# router **Repository Path**: lichenxin/router ## Basic Information - **Project Name**: router - **Description**: golang router 简单实现,学习使用 - **Primary Language**: Go - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2018-11-07 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README golang router 简单实现, 支持中间件 ``` package main import ( "fmt" "log" "net/http" "router" ) // middleware func Logger(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(w, r) log.Println("method:", r.Method, "path:", r.URL.Path) }) } func Recover(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := recover(); err != nil { log.Fatal(err) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(http.StatusText(http.StatusInternalServerError))) } h.ServeHTTP(w, r) }) } func main() { r := router.NewRouter() r.Use(Recover) r.Use(Logger) r.Get("/", Index) r.Get("/panic", Panic) r.Get("/demo/{name:int}/{age:int}", ParamInt) r.Get("/demo/{name:string}", ParamString) http.ListenAndServe(":8989", r) } func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Home") } func Panic(w http.ResponseWriter, r *http.Request) { panic("panic error") } func ParamInt(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "param int ", r.Context().Value("name"), r.Context().Value("age")) } func ParamString(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "param string ", r.Context().Value("name")) } ```