Go HTTP server

Posted on Aug 2, 2020

Go makes it very easy to create HTTP servers using the standard library net/http package.

First we create a new ServeMux object, also known as a request multiplexer, muxer or router. Using the HandleFunc() method we then register a function to handle requests for the "/hello" pattern. Finally, we start a local server on port 3000 and pass the mux object as its handler.

package main

import "net/http"

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello World!"))
    })

    http.ListenAndServe("localhost:3000", mux)
}

ServeMux implements the Handler interface and is the main entry point for requests accepted by the server.

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

HandleFunc() is just a convenient method to turn a function into a Handler by wrapping it with a ServeHTTP() method. It then registers it to handle the "/hello" pattern, so our muxer can route requests to the appropriate handlers.

comments powered by Disqus