HttpRouter provides a New() function to create a router instance. You can register routes for specific HTTP methods (like GET) using patterns. The most efficient way to use it is with the 3-argument Handle API, which provides httprouter.Params directly to your handler.
Note: Because HttpRouter uses explicit matches, you cannot register a static route and a parameter route for the same path segment and method (e.g., you cannot have both /user/new and /user/:user for GET).
package main
import (
"fmt"
"net/http"
"log"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
}