httprouter是一个高可用的http路由请求库。路由器通过请求方法和路径来匹配传入的请求。如果为该路径和方法注册了句柄,路由器会将请求委托给该函数。对于方法GET、POST、PUT、PATCH、DELETE和OPTIONS,存在注册句柄的快捷功能,对于所有其他方法路由器。可以使用手柄。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package main
import ( "fmt" "github.com/julienschmidt/httprouter" "net/http" "log" )
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)) }
|