Writing Custom HTTP Router in Golang

Its this article we will create a simple router to server request in golang server

As stated in the title of this article, we are going to build a router (also known as a mux) in Go.

Now you might be asking why? There are a plethora of great routers out there so why "reinvent the wheel"? As a mentor of mine use to say "to learn how wheels
work". So without further ado, let's jump in.
. . .

Creating Router

package router import ( "fmt" "net/http" ) // Router serves http type Router struct { handlers map[string]func(http.ResponseWriter, *http.Request) } // NewRouter creates instance of Router func NewRouter() *Router { router := new(Router) router.handlers = make(map[string]func(http.ResponseWriter, *http.Request)) return router } // ServeHTTP is called for every connection func (s *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { f, ok := s.handlers[key(r.Method, r.URL.Path)] if !ok { bad(w) return } f(w, r) }
After implenting the handler lets build our GET, POST handler that will handle our request. You can extend it furter by adding more methods if required.
// GET sets get handler func (s *Router) GET(path string, f http.HandlerFunc) { s.handlers[key("GET", path)] = f } // POST sets post handler func (s *Router) POST(path string, f http.HandlerFunc) { s.handlers[key("POST", path)] = f } // DELETE sets delete handler func (s *Router) DELETE(path string, f http.HandlerFunc) { s.handlers[key("DELETE", path)] = f } // PUT sets put handler func (s *Router) PUT(path string, f http.HandlerFunc) { s.handlers[key("PUT", path)] = f } func key(method, path string) string { return fmt.Sprintf("%s:%s", method, path) } func bad(w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"error":"not found"}`)) }

. . .


Its time to use our router
package main
import( mux "github.com/gufranmirza/go-router" "net/http" "log" )

func boo(w http.ResponseWriter, r *http.Request){ // do something }

func foo(w http.ResponseWriter, r *http.Request){ // do something }
func main() { router := mux.NewRouter() router.GET("/boo", boo) router.POST("/foo", foo) log.Fatal(http.ListenAndServe(":8080", router)) }

. . .

On a mission to build Next-Gen Community Platform for Developers