How to make an HTTP server in Go
In this shot, we will use the standard net/http package to make a simple HTTP web server.
Implementation
We will be writing an HTTP web server that listens on the port 8080. The net/http package provides the function ListenAndServe. The first argument is the port number and the second is the handler, which is mainly used for HTTP/2 servers. However, we won’t be using this parameter in this shot, so we pass nil for the default router:
func main() {
http.ListenAndServe(":8080", nil)
}
Next, we will add a handler. A handler is a function that implements the http.Handler interface – the handler takes an http.ResponseWriter and an http.Request as arguments.
Our hello handler responds using the http.ResponseWriter w with a, “Hello from the server!” message:
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello from the server!\n")
}
We finally register our hello handler on the server routes using the http.HandleFunc function, which sets up the default router in the net/http package and takes a function as an argument.
http.HandleFunc("/hello", hello)
Once all the pieces are put together, we will get the following HTTP server in Go.
package mainimport ("fmt""net/http")// A handler for "/hello" routefunc hello(w http.ResponseWriter, req *http.Request) {fmt.Fprintf(w, "Hello from the server!\n")}func main() {// Registering the hello handlerhttp.HandleFunc("/hello", hello)// Listening on port 8080http.ListenAndServe(":8080", nil)}
You can run the server on localhost. Accessing localhost:8080/hello route will return the response "Hello from the server!\n", as expected.
Free Resources