61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
package gee
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
// HandlerFunc 路由匹配到后的具体函数
|
|
type HandlerFunc func(w http.ResponseWriter, r *http.Request)
|
|
|
|
// Engine 路由表 实现了ServeHTTP接口
|
|
type Engine struct {
|
|
router map[string]HandlerFunc
|
|
}
|
|
|
|
// ServeHTTP 实现了ServeHTTP接口
|
|
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
// 获取连接的请求方式和路径
|
|
key := r.Method + "-" + r.URL.Path
|
|
// 对比和匹配路由
|
|
handler, ok := engine.router[key]
|
|
if ok {
|
|
handler(w, r)
|
|
} else {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
_, _ = fmt.Fprintf(w, "404 NOT FOUND: %s", r.URL)
|
|
}
|
|
// 这里我们加上时间,容易理解
|
|
log.Println("请求方式:", r.Method, r.URL.Path, "对应:", key, "是否对应上:", ok)
|
|
}
|
|
|
|
// Run 启动服务
|
|
func (engine *Engine) Run(addr string) (err error) {
|
|
return http.ListenAndServe(addr, engine)
|
|
}
|
|
|
|
// 封装路由规则和具体的处理函数
|
|
// addRoute 添加路由规则
|
|
func (engine *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
|
|
key := method + "-" + pattern
|
|
engine.router[key] = handler
|
|
// 打印对应的 key
|
|
fmt.Println("请求方式:", method, pattern, " 对应: ", key)
|
|
}
|
|
|
|
// GET 添加GET路由规则
|
|
func (engine *Engine) GET(pattern string, handler HandlerFunc) {
|
|
engine.addRoute("GET", pattern, handler)
|
|
}
|
|
|
|
// POST 添加POST路由规则
|
|
func (engine *Engine) POST(pattern string, handler HandlerFunc) {
|
|
engine.addRoute("POST", pattern, handler)
|
|
}
|
|
|
|
// New 实例化Engine
|
|
func New() *Engine {
|
|
return &Engine{router: make(map[string]HandlerFunc)}
|
|
}
|