要实现自定义的golang http server,关键要实现http.Hanlder这个接口,这个接口只有一个方法:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
直接上代码:
package main
import (
"fmt"
"net/http"
)
//处理请求的函数类型
type HandleFunc func(http.ResponseWriter, *http.Request)
//自定义的请求处理器,类似gin的Engine
type MyHandler struct{
Routers map[string]HandleFunc//用于存放路由与处理函数的map
}
//实现http.Handler接口的ServeHTTP方法,有请求到来时就会调用这个方法
func (h *MyHandler) ServeHTTP (w http.ResponseWriter, r *http.Request) {
path:=r.URL.Path
if f,ok := h.Routers[path]; ok{//判断路由是否存在
f(w,r)//调用处理函数
}else{
fmt.Fprintf(w, "404 not found")
}
}
//添加路由与处理函数
func (h *MyHandler) AddRoute(path string,handleFunc HandleFunc) {
h.Routers[path] = handleFunc
}
func NewHandle() *MyHandler {
engine:=&MyHandler{}
engine.Routers = make(map[string]HandleFunc)
return engine
}
func main() {
engine:=NewHandle()