1 Star 0 Fork 0

leminewx / gokit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
router.go 1015 Bytes
一键复制 编辑 原始数据 按行查看 历史
wenxian 提交于 2023-12-21 17:52 . 优化httpserver的优雅退出
package httpserver
import (
"fmt"
"log/slog"
"net/http"
)
// router 定义路由器的数据类型
type router map[string]HandleFunc
// addRoute 添加路由处理器到路由器中
func (own router) addRoute(method, path string, handler HandleFunc) {
key := method + "-" + path
if _, ok := own[key]; ok {
slog.Error(fmt.Sprintf("Add route failed: %s - %s already exist", method, path))
return
}
slog.Info(fmt.Sprintf("Add route success: %s - %s", method, path))
own[key] = handler
}
// handleContext 处理HTTP请求
func (own router) handleContext(ctx *Context) {
key := ctx.Method + "-" + ctx.Path
handler, ok := own[key]
if !ok {
if ctx.staticMiddleware != nil {
handler = ctx.staticMiddleware
} else {
handler = func(ctx *Context) {
ctx.ResponseString(http.StatusNotFound, ERR_NOT_FOUND)
}
}
}
// 将请求路由对应的处理器添加到上下文的中间件中,并最后一个执行
ctx.middlewares = append(ctx.middlewares, handler)
ctx.RunNext()
}
Go
1
https://gitee.com/leminewx/gokit.git
git@gitee.com:leminewx/gokit.git
leminewx
gokit
gokit
d2d37884a85f

搜索帮助