200 行 Go 代码实现一个快速,简单,轻巧的 HTTP 路由器
2020-12-10 19:12:00 Author: mp.weixin.qq.com(查看原文) 阅读量:43 收藏

点击上方蓝色“polarisxu”关注我,设个星标,不会让你失望

说起 HTTP 路由器,Go 中还真不少,这是每个 Web 框架不可缺少的,有些框架自己实现,有些使用其他的库。就路由库来说,https://github.com/julienschmidt/httprouter 是比较知名的一个,Gin 就用的它。

如果你对路由库的实现感兴趣,推荐你可以看下这个库,这几天刚开源的,代码一共才 200+ 行。

项目地址:https://github.com/majidsajadi/sariaf。

它兼容 net/http,支持中间件、URL 参数等。

一个例子看这个小巧的库:

package main

import (
 "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))
}


往期推荐

觉得不错,欢迎关注:

点个赞、在看和转发是最大的支持


文章来源: http://mp.weixin.qq.com/s?__biz=MzAxNzY0NDE3NA==&mid=2247485505&idx=2&sn=0f67dc64c267b96bfeb5cca448c36451&chksm=9be327a0ac94aeb6519c893cf578eb924f73007a49c52076a4b13bf3515f14aa3ef4847e2f97#rd
如有侵权请联系:admin#unsafe.sh