55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
|
package gee
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"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
|
||
|
// 对比和匹配路由
|
||
|
if handler, ok := engine.router[key]; ok {
|
||
|
handler(w, r)
|
||
|
} else {
|
||
|
w.WriteHeader(http.StatusNotFound)
|
||
|
_, _ = fmt.Fprintf(w, "404 NOT FOUND: %s", r.URL)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 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
|
||
|
}
|
||
|
|
||
|
// 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)}
|
||
|
}
|