1 Star 0 Fork 0

Wsage/go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server_http_router.go 2.50 KB
一键复制 编辑 原始数据 按行查看 历史
Wsage 提交于 2022-12-03 10:50 . modify
package httpserver
import (
"context"
"gitee.com/scottq/go-framework/src/utils"
"github.com/gin-gonic/gin"
"github.com/julienschmidt/httprouter"
"net/http"
)
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 := r.Method
router.Handle(method, r.Path, handler)
}
}
func (r *Router) handlerGin(c *ServerConfig) gin.HandlerFunc {
genCtx := func(writer http.ResponseWriter, request *http.Request, params gin.Params) *Ctx {
ctx := NewCtx(writer, request)
var rParams httprouter.Params
for _, v := range params {
rParams = append(rParams, httprouter.Param{v.Key, v.Value})
}
ctx._setRouterParams(rParams)
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(c *gin.Context) {
ctx := genCtx(c.Writer, c.Request, c.Params)
handler(ctx)
}
}
if r.RouteHandler != nil {
handler := handlerMiddleware(r.RouteHandler, r.Middleware)
return func(c *gin.Context) {
ctx := genCtx(c.Writer, c.Request, c.Params)
handler(ctx)
}
}
return func(c *gin.Context) {
}
}
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)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.46

搜索帮助