手把手教媳婦-封裝簡易的http路由(一)
2020-07-23 本文已影响0人
牛空空
午休睡不着,教我媳婦頓修封裝個簡易的http路由,實現簡單的GET,POST,DELETE,PUT方法了
package main
import (
"fmt"
"log"
"net/http"
)
type route interface {
GET(string, http.HandlerFunc)
POST(string, http.HandlerFunc)
DELETE(string, http.HandlerFunc)
PUT(string, http.HandlerFunc)
}
type Test struct {
handlers map[string]map[string]http.HandlerFunc
}
func NewTest() *Test {
return &Test{
handlers: make(map[string]map[string]http.HandlerFunc),
}
}
func (t *Test) GET(path string, f http.HandlerFunc) {
if _, ok := t.handlers["GET"]; ok {
t.handlers["GET"][path] = f
} else {
t.handlers["GET"] = make(map[string]http.HandlerFunc)
t.handlers["GET"][path] = f
}
}
func (t *Test) POST(path string, f http.HandlerFunc) {
if _, ok := t.handlers["POST"]; ok {
t.handlers["POST"][path] = f
} else {
t.handlers["POST"] = make(map[string]http.HandlerFunc)
t.handlers["POST"][path] = f
}
}
func (t *Test) DELETE(path string, f http.HandlerFunc) {
if _, ok := t.handlers["DELETE"]; ok {
t.handlers["DELETE"][path] = f
} else {
t.handlers["DELETE"] = make(map[string]http.HandlerFunc)
t.handlers["DELETE"][path] = f
}
}
func (t *Test) PUT(path string, f http.HandlerFunc) {
if _, ok := t.handlers["PUT"]; ok {
t.handlers["PUT"][path] = f
} else {
t.handlers["PUT"] = make(map[string]http.HandlerFunc)
t.handlers["PUT"][path] = f
}
}
func (t *Test) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method)
fmt.Println(r.RequestURI)
if f, ok := t.handlers[r.Method][r.RequestURI]; ok {
f(w, r)
} else {
w.WriteHeader(404)
w.Write([]byte("not found"))
}
}
func (t *Test) Run(addr string) {
err := http.ListenAndServe(addr, t)
if err != nil {
log.Fatal(err)
panic(err)
}
}
測試
t := NewTest()
t.GET("/todo", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("todo"))
})
t.POST("/foo", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("foo"))
})
t.Run(":8080")
ps:功能比較單一,也不支持路徑參數,參數驗證等,以後再去自行擴展了