net/http:
This is available out of the box in Go language. Package "net/http" provides HTTP client and server implementations which can be used to make common HTTP requests like GET, POST, PUT, DELETE e.t.c..
While building REST Api's with Go using net/http, here are few methods and interfaces we should understand:
type Handler
type Handler
type Handler interface { ServeHTTP(ResponseWriter, *Request) }
- A Handler is responsible for responding to HTTP requests. This interface has only one method ServeHTTP(ResponserWriter, *Request)
- You can define your own struct as a Handler which implements ServeHTTP method with ResponseWriter and pointer to Request as arguments
package main import ( "net/http" ) type server struct{} func (s *server) ServeHTTP(writer http.ResponseWriter, req *http.Request) { writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(http.StatusOK) writer.Write([]byte(`{"message": "Go world"}`)) }
func main() { s := &server{} http.Handle("/", s) http.ListenAndServe(":9780", nil) }
ListenAndServe
func ListenAndServe(addr string, handler Handler) error
- Starts an HTTP server to serve the requests with a given address and handler
Handle
- Handle registers the handler for given pattern in DefaultServeMux
- ServeMux matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL. In our main(), we can see passing our own handler for the given pattern
HandleFunc
- HandlerFunc registers the handler function for the given pattern in DefaultServerMuxHandle
func Handle(pattern string, handler Handler)
- ServeMux matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL. In our main(), we can see passing our own handler for the given pattern
HandleFunc
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
- The problem with Handle is you have to write an empty struct and implement ServeHTTP your struct does nothing other than that, so to eliminate that dumb struct and simplify your code you can use HandleFunc
- Above code can be refactored as below, notice that we removed struct and ServeHTTP instead defined a new handler function and registered it
func helloGo(writer http.ResponseWriter, req *http.Request) { writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(http.StatusOK) writer.Write([]byte(`{"message": "Go world"}`)) } func main() { http.HandleFunc("/", helloGo) http.ListenAndServe(":9780", nil) }
Though net/http is a great package for our REST api needs. It comes with few limitations like only two keep-alive connections, not easy to handle path/ query params e.t.c.. you can read more about limitations here so to solve some of these problems most real world applications use gorilla mux or gin-gonic. I'll try to cover them both in my future posts.
Happy Coding 🤖
Comments
Post a Comment