1 Star 0 Fork 0

Souki/go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server_http_router.go 1.84 KB
一键复制 编辑 原始数据 按行查看 历史
王少奇 提交于 2021-08-28 09:27 +08:00 . 去除 log
package httpserver
import (
"context"
"fmt"
"gitee.com/scottq/go-framework/src/utils"
"github.com/julienschmidt/httprouter"
"net/http"
"strings"
)
type Router struct {
Path string
Method string
RouteHandler HttpRouteFunc
Middleware []Middleware
HttpHandler http.Handler
}
func (r *Router) hash() string {
return r.Method + "_" + r.Path
}
func (r *Router) invokeRegister(router *httprouter.Router, c *ServerConfig) {
handler := r.handler(c)
if handler != nil {
method := strings.ToUpper(r.Method)
switch method {
case "GET":
router.GET(r.Path, handler)
case "POST":
router.POST(r.Path, handler)
case "OPTIONS":
router.OPTIONS(r.Path, handler)
case "DELETE":
router.DELETE(r.Path, handler)
case "PUT":
router.PUT(r.Path, handler)
default:
fmt.Printf("not support router method:%s\n", method)
}
}
}
func (r *Router) handler(c *ServerConfig) func(http.ResponseWriter, *http.Request, httprouter.Params) {
genCtx := func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) *Ctx {
ctx := NewCtx(writer, request)
ctx._setRouterParams(params)
if c.requestId {
ctx.httpContext = context.WithValue(ctx.httpContext, c.requestIdField, utils.NewRequestId())
}
return ctx
}
if r.HttpHandler != nil {
handler := handlerMiddleware(func(ctx *Ctx) {
r.HttpHandler.ServeHTTP(ctx.Writer(), ctx.Request())
}, r.Middleware)
return func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
ctx := genCtx(writer, request, params)
handler(ctx)
}
}
if r.RouteHandler != nil {
handler := handlerMiddleware(r.RouteHandler, r.Middleware)
return func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
ctx := genCtx(writer, request, params)
handler(ctx)
}
}
return nil
}
type HttpRouteFunc = func(ctx *Ctx)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.21

搜索帮助