点击上方蓝色“polarisxu”关注我,设个星标,不会让你失望
说起 HTTP 路由器,Go 中还真不少,这是每个 Web 框架不可缺少的,有些框架自己实现,有些使用其他的库。就路由库来说,https://github.com/julienschmidt/httprouter 是比较知名的一个,Gin 就用的它。
如果你对路由库的实现感兴趣,推荐你可以看下这个库,这几天刚开源的,代码一共才 200+ 行。
项目地址:https://github.com/majidsajadi/sariaf。
它兼容 net/http,支持中间件、URL 参数等。
一个例子看这个小巧的库:
package mainimport (
"fmt"
"log"
"net/http"
"github.com/majidsajadi/sariaf"
)
func main() {
router := sariaf.New()
router.SetNotFound(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Not Found")
})
router.SetPanicHandler(func(w http.ResponseWriter, r *http.Request, err interface{}) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Println("error:", err)
fmt.Fprint(w, "Internal Server Error")
})
router.GET("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
})
router.GET("/posts", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("GET: Get All Posts"))
})
router.GET("/posts/:id", func(w http.ResponseWriter, r *http.Request) {
params, _ := sariaf.GetParams(r)
w.Write([]byte("GET: Get Post With ID:" + params["id"]))
})
router.POST("/posts", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("POST: Create New Post"))
})
router.PATCH("/posts/:id", func(w http.ResponseWriter, r *http.Request) {
params, _ := sariaf.GetParams(r)
w.Write([]byte("PATCH: Update Post With ID:" + params["id"]))
})
router.PUT("/posts/:id", func(w http.ResponseWriter, r *http.Request) {
params, _ := sariaf.GetParams(r)
w.Write([]byte("PUT: Update Post With ID:" + params["id"]))
})
router.DELETE("/posts/:id", func(w http.ResponseWriter, r *http.Request) {
params, _ := sariaf.GetParams(r)
w.Write([]byte("DELETE: Delete Post With ID:" + params["id"]))
})
router.GET("/error", func(w http.ResponseWriter, r *http.Request) {
panic("Some Error Message")
})
log.Fatal(http.ListenAndServe(":8181", router))
}
往期推荐
觉得不错,欢迎关注:
点个赞、在看和转发是最大的支持