Creating a HTTP server with go

2019-06-10

Cookbook: Creating a HTTP server with Go

In this lesson, we will build a simple HTTP server using the net/http built in library

The Recipe

First create the directory and file

mkdir HttpServer
cd HttpServer
touch main.go

Then, use the following Go code. The code explination is below.

package main

import (
	"fmt"
	"log"
	"net/http"
)

const HOST = "localhost:3000"

func GetRequest(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World")
}

func main() {
	http.HandleFunc("/", GetRequest)

	err := http.ListenAndServe(HOST, nil)

	if err != nil {
		log.Fatal("Error Starting Servier ", err)
		return
	}
}

And run the code with the following command.

go run main.go

The Explanation

We start with some set up. We simply import some needed libraries (most noteabley net/http). And, we declare a constant where we will have go serve requests.

package main

import (
	"fmt"
	"log"
	"net/http"
)

const HOST = "localhost:3000"

Next, we create a function that will accept a Get http request. We have two parameters w http.ResponseWriter and r *http.Request which are built into the net/http pacakge. We use the w http.ResponseWriter with the fmt library to output our text.

func GetRequest(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World")
}

Finally, we declare a route to our request using the following.

http.HandleFunc("/", GetRequest)

This says that when a useer goes to our base url (the const HOST variable), serve them using our GetRequest function.

Finally, we turn the server on and check for an error.

err := http.ListenAndServe(HOST, nil)

if err != nil {
  log.Fatal("Error Starting Servier ", err)
  return
}