第三十篇:httpserver练习:自定义路由、支持GET/POST访问
一:自定义路由
有三个元素
1:request method :常见的有 Get/Post/Put/Delete
2:请求路径,如 /
3:http.HandlerFunc
于是我们定义一个二维的map
map[string]map[string]http.HandlerFunc
用来保存上述3个元素
譬如:
map["/"]=func(......)
map["GET"]=map["/"]
1.1:定义核心文件

代码如下:
package core
import "net/http"
type MyRouter struct {
Mapping map[string]map[string]http.HandlerFunc
}
//获取统一的对象,使用指针返回方式
func DefaultRouter() *MyRouter {
//结构体参数为map 类型,所以也要初始化;
return &MyRouter{make(map[string]map[string]http.HandlerFunc)}
}
func (this *MyRouter)Get(path string,f http.HandlerFunc){
if this.Mapping["GET"]==nil{
this.Mapping["GET"]=make(map[string]http.HandlerFunc)
}
this.Mapping["GET"][path]=f
}
func (this *MyRouter)Post(path string,f http.HandlerFunc){
if this.Mapping["POST"]==nil{
this.Mapping["POST"]=make(map[string]http.HandlerFunc)
}
this.Mapping["POST"][path]=f
}
func (this *MyRouter) ServeHTTP(writer http.ResponseWriter, request *http.Request){
f:=this.Mapping[request.Method][request.URL.Path]
f(writer,request)
}
main主函数代码如下:
package main
import (
"com.pizixu.net/myhttpserver/core"
"net/http"
)
type MyHandler struct {
}
func main() {
router:=core.DefaultRouter()
router.Get("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("get abc"))
})
router.Post("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("post abc"))
})
http.ListenAndServe(":8099",router)
}

浙公网安备 33010602011771号