SoFunction
Updated on 2025-03-04

Detailed explanation of the use of HttpRouter routing in Golang

httprouter

httprouter is a high-performance, scalable HTTP route. The shortcomings of the net/http default routes we listed above are implemented by httprouter. Let’s first use an example to understand the powerful HTTP route of httprouter.

Install:

go get -u /julienschmidt/httprouter

In this example, first, a *Router routing pointer is generated through (), and then a GET method is used to register an index function that is adapted/path, and finally, *Router is passed to the ListenAndServe function as a parameter to start the HTTP service.

package main
 
import (
    "log"
    "net/http"
 
    "/julienschmidt/httprouter"
)
 
func Index(w , r *, _ ) {
    ([]byte("Index"))
}
 
func main() {
    router := ()
    ("/", Index)
    ((":8080", router))
}

httprouter provides a quick way to use all HTTP methods, just call the corresponding method.

func (r *Router) GET(path string, handle Handle) {
    ("GET", path, handle)
}
func (r *Router) HEAD(path string, handle Handle) {
    ("HEAD", path, handle)
}
func (r *Router) OPTIONS(path string, handle Handle) {
    ("OPTIONS", path, handle)
}
func (r *Router) POST(path string, handle Handle) {
    ("POST", path, handle)
}
func (r *Router) PUT(path string, handle Handle) {
    ("PUT", path, handle)
}
func (r *Router) PATCH(path string, handle Handle) {
    ("PATCH", path, handle)
}
func (r *Router) DELETE(path string, handle Handle) {
    ("DELETE", path, handle)
}

Modern APIs are basically Restful APIs, and the naming parameters provided by httprouter can help us develop Restful APIs very conveniently. For example, the API/user/flysnow we designed, can view the information of the user flysnow. If you want to view other users, such as zhangsan, we only need to access API/user/zhangsan.

The URL includes two matching patterns: /user/:name exact match, and /user/*name matches all patterns.

package main
 
import (
  "/julienschmidt/httprouter"
  "net/http"
  "log"
  "fmt"
)
 
 
func main()  {
  router:=()
  ("/MainData", func (w ,r *,_ )  {
    ([]byte("default get"))
  })
  ("/MainData",func (w ,r *,_ )  {
    ([]byte("default post"))
  })
  //Exact match  ("/user/name",func (w ,r *,p )  {
    ([]byte("user name:"+("name")))
  })
  //Match all  ("/employee/*name",func (w ,r *,p )  {
    ([]byte("employee name:"+("name")))
  })
  (":8081", router)
}

Handler processing chain processing different secondary domain names

package main
 
import (
    "fmt"
    "log"
    "net/http"
 
    "/julienschmidt/httprouter"
)
 
type HostMap map[string]
 
func (hs HostMap) ServeHTTP(w , r *) {
    ("222")
    //Get the corresponding Handler route according to the domain name, and then call the processing (distribution mechanism)    if handler := hs[]; handler != nil {
        (w, r)
    } else {
        (w, "Forbidden", 403)
    }
}
 
func main() {
    userRouter := ()
    ("/", func(w , r *, p ) {
        ([]byte("play"))
    })
 
    dataRouter := ()
    ("/", func(w , r *, _ ) {
        ([]byte("tool"))
    })
 
    // Used to handle different secondary domain names respectively    hs := make(HostMap)
    hs[":12345"] = userRouter
    hs[":12345"] = dataRouter
 
    ((":12345", hs))
}

httprouter provides a very convenient static file service, which allows you to host a directory on the server for access.

("/static/*filepath",("./"))

It should be noted that the first parameter path must be /*filepath because we want to obtain the path information we want to access.

func (r *Router) ServeFiles(path string, root ) {
    if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
        panic("path must end with /*filepath in path '" + path + "'")
    }
    fileServer := (root)
    (path, func(w , req *, ps Params) {
         = ("filepath")
        (w, req)
    })
}

example:

package main
import (
    "log"
    "net/http"
    "/julienschmidt/httprouter"
)
func main() {
    router := ()
  //Access static files    ("/static/*filepath", ("./files"))
    ((":8080", router))
}

httprouter exception capture, httprouter allows users to set PanicHandler to handle panics that occur in HTTP requests.

package main
import (
    "fmt"
    "log"
    "net/http"
    "/julienschmidt/httprouter"
)
func Index(w , r *, _ ) {
    panic("error")
}
func main() {
    router := ()
    ("/", Index)
  //Catch exception     = func(w , r *, v interface{}) {
        ()
        (w, "error:%s", v)
    }
    ((":8080", router))
}

httprouter also has many useful small functions, such as processing 404. We can implement it through settings. Let’s look at the configuration of the Router structure and find more useful functions.

type Router struct {
    //Whether to add a slash to the path through redirection    RedirectTrailingSlash bool
    // Whether to automatically repair the path through redirection, such as double slashes, etc., automatically repair it to a single slash, etc.    RedirectFixedPath bool
    //Whether to detect the current requested method is allowed    HandleMethodNotAllowed bool
    //Do you need to reply to OPTION requests in a custom way    HandleOPTIONS bool
    //404 default processing    NotFound 
    //Uns allowed methods are processed by default    MethodNotAllowed 
    //Unexceptions are handled uniformly    PanicHandler func(, *, interface{})
}

This is the end of this article about the detailed explanation of the use of HttpRouter routing in Golang. For more information about Golang HttpRouter routing, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!