| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538 |
- package webx
-
- import (
- "encoding/json"
- "net/http"
- "reflect"
- "strconv"
- "strings"
-
- "git.x2erp.com/qdy/go-base/ctx"
- )
-
- // WebService 路由服务
- type WebService struct {
- router *http.ServeMux
- middlewares []func(http.Handler) http.Handler
- }
-
- // NewWebService 创建WebService
- func NewWebService(router *http.ServeMux) *WebService {
- ws := &WebService{
- router: router,
- }
-
- return ws
- }
-
- // Use 添加全局中间件
- func (ws *WebService) Use(middleware func(http.Handler) http.Handler) *WebService {
- ws.middlewares = append(ws.middlewares, middleware)
- return ws
- }
-
- // GET 注册GET请求
- func (ws *WebService) GET(path string, handler interface{}) *RouteBuilder {
- return ws.handle("GET", path, handler)
- }
-
- // POST 注册POST请求
- func (ws *WebService) POST(path string, handler interface{}) *RouteBuilder {
- return ws.handle("POST", path, handler)
- }
-
- // PUT 注册PUT请求
- func (ws *WebService) PUT(path string, handler interface{}) *RouteBuilder {
- return ws.handle("PUT", path, handler)
- }
-
- // DELETE 注册DELETE请求
- func (ws *WebService) DELETE(path string, handler interface{}) *RouteBuilder {
- return ws.handle("DELETE", path, handler)
- }
-
- // handle 统一处理方法
- func (ws *WebService) handle(method, path string, handler interface{}) *RouteBuilder {
- // 解析路径参数名
- paramNames := extractPathParams(path)
-
- // 获取处理器函数信息
- handlerValue := reflect.ValueOf(handler)
- handlerType := handlerValue.Type()
-
- // 验证处理器函数
- if handlerType.Kind() != reflect.Func {
- panic("handler must be a function")
- }
-
- // 验证返回值
- if handlerType.NumOut() != 2 {
- panic("handler must return exactly 2 values: (T, error)")
- }
-
- return &RouteBuilder{
- ws: ws,
- method: method,
- path: path,
- handlerFunc: handlerValue,
- paramNames: paramNames,
- }
- }
-
- // // 上下文中间件
- // func (ws *WebService) contextMiddleware() func(http.Handler) http.Handler {
- // return func(next http.Handler) http.Handler {
- // return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // // 自动创建 RequestContext
- // reqCtx := ws.createRequestContext(r)
-
- // // 保存到请求中
- // r = ctx.SaveContext(r, *reqCtx)
- // next.ServeHTTP(w, r)
- // })
- // }
- // }
-
- // // 创建 RequestContext
- // func (ws *WebService) createRequestContext(r *http.Request) *ctx.RequestContext {
- // return &ctx.RequestContext{
- // TraceID: generateTraceID(),
- // ServiceName: getServiceName(r),
- // InstanceName: getInstanceName(),
- // TenantID: r.Header.Get("X-Tenant-ID"),
- // UserID: extractUserID(r),
- // }
- // }
-
- // // 辅助函数
- // func generateTraceID() string {
- // return "trace-" + strconv.FormatInt(time.Now().UnixNano(), 36)
- // }
-
- // func getServiceName(r *http.Request) string {
- // if serviceName := r.Header.Get("X-Service-Name"); serviceName != "" {
- // return serviceName
- // }
- // return "unknown-service"
- // }
-
- // func getInstanceName() string {
- // // 获取主机名
- // hostname, _ := os.Hostname()
- // if hostname != "" {
- // return hostname
- // }
- // return "instance-1"
- // }
-
- // func extractUserID(r *http.Request) string {
- // if auth := r.Header.Get("Authorization"); auth != "" {
- // // 简单示例:从 Authorization 头提取
- // if strings.HasPrefix(auth, "Bearer ") {
- // // 这里可以解析 JWT token 获取用户ID
- // // 暂时返回示例值
- // return "user-from-token"
- // }
- // }
- // return ""
- // }
-
- // RouteBuilder 路由构建器
- type RouteBuilder struct {
- ws *WebService
- method string
- path string
- handlerFunc reflect.Value
- paramNames []string
- middlewares []func(http.Handler) http.Handler
- description string
- }
-
- // Use 添加路由级中间件
- func (rb *RouteBuilder) Use(middleware ...func(http.Handler) http.Handler) *RouteBuilder {
- rb.middlewares = append(rb.middlewares, middleware...)
- return rb
- }
-
- // Desc 添加描述
- func (rb *RouteBuilder) Desc(description string) *RouteBuilder {
- rb.description = description
- return rb
- }
-
- // Register 注册路由
- func (rb *RouteBuilder) Register() {
- // 创建适配器
- adapter := &handlerAdapter{
- ws: rb.ws,
- method: rb.method,
- pathPattern: rb.path,
- paramNames: rb.paramNames,
- handlerFunc: rb.handlerFunc,
- }
-
- // 构建处理链:全局中间件 → 路由中间件 → 处理器
- var handler http.Handler = adapter
-
- // 1. 应用路由级中间件(从后往前)
- for i := len(rb.middlewares) - 1; i >= 0; i-- {
- handler = rb.middlewares[i](handler)
- }
-
- // 2. 应用全局中间件(从后往前)
- for i := len(rb.ws.middlewares) - 1; i >= 0; i-- {
- handler = rb.ws.middlewares[i](handler)
- }
-
- // 注册到路由器
- rb.ws.router.Handle(rb.path, handler)
- }
-
- // handlerAdapter 处理器适配器
- type handlerAdapter struct {
- ws *WebService
- method string
- pathPattern string
- paramNames []string
- handlerFunc reflect.Value
- }
-
- func (ha *handlerAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // 只处理指定方法的请求
- if r.Method != ha.method {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- // 1. 解析路径参数
- pathParams := ha.parsePathParams(r.URL.Path)
-
- // 2. 构建函数参数
- args := ha.buildArgs(w, r, pathParams)
- if args == nil {
- http.Error(w, "Invalid parameters", http.StatusBadRequest)
- return
- }
-
- // 3. 调用处理器函数
- results := ha.handlerFunc.Call(args)
-
- // 4. 处理返回结果
- ha.handleResponse(w, results)
- }
-
- // parsePathParams 解析路径参数
- func (ha *handlerAdapter) parsePathParams(requestPath string) map[string]string {
- params := make(map[string]string)
-
- pattern := strings.Trim(ha.pathPattern, "/")
- request := strings.Trim(requestPath, "/")
-
- patternParts := strings.Split(pattern, "/")
- requestParts := strings.Split(request, "/")
-
- for i, patternPart := range patternParts {
- if strings.HasPrefix(patternPart, "{") && strings.HasSuffix(patternPart, "}") {
- paramName := patternPart[1 : len(patternPart)-1]
- if i < len(requestParts) {
- params[paramName] = requestParts[i]
- }
- }
- }
-
- return params
- }
- func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
- handlerType := ha.handlerFunc.Type()
- numIn := handlerType.NumIn()
- args := make([]reflect.Value, numIn)
-
- for i := 0; i < numIn; i++ {
- paramType := handlerType.In(i)
- paramName := getParamName(i, handlerType, ha.paramNames)
-
- // 1. 检查是否是特殊类型
- if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
- args[i] = arg
- continue
- }
-
- // 2. 检查是否是 *ctx.RequestContext 类型
- if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
- reqCtx := ctx.GetContext(r)
- args[i] = reflect.ValueOf(reqCtx)
- continue
- }
-
- // 3. 只按名称匹配路径参数
- if value, ok := pathParams[paramName]; ok {
- args[i] = convertToType(value, paramType)
- continue
- }
-
- // 4. 尝试从查询参数获取
- if queryValue := r.URL.Query().Get(paramName); queryValue != "" {
- args[i] = convertToType(queryValue, paramType)
- continue
- }
-
- // 5. 尝试从JSON body获取(POST/PUT请求)
- if (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH") &&
- (paramType.Kind() == reflect.Struct ||
- (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct)) {
- if arg := ha.parseBody(r, paramType); arg.IsValid() {
- args[i] = arg
- continue
- }
- }
-
- // 6. 返回零值
- args[i] = reflect.Zero(paramType)
- }
-
- return args
- }
-
- // func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
- // handlerType := ha.handlerFunc.Type()
- // numIn := handlerType.NumIn()
- // args := make([]reflect.Value, numIn)
-
- // // 收集所有 string 类型的参数索引
- // var stringParamIndices []int
- // for i := 0; i < numIn; i++ {
- // paramType := handlerType.In(i)
- // if paramType.Kind() == reflect.String &&
- // paramType != reflect.TypeOf((*ctx.RequestContext)(nil)) {
- // stringParamIndices = append(stringParamIndices, i)
- // }
- // }
-
- // // 处理每个参数
- // stringParamIndex := 0
- // for i := 0; i < numIn; i++ {
- // paramType := handlerType.In(i)
- // paramName := getParamName(i, handlerType, ha.paramNames)
-
- // // 1. 检查是否是特殊类型
- // if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
- // args[i] = arg
- // continue
- // }
-
- // // 2. 检查是否是 *ctx.RequestContext 类型
- // if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
- // reqCtx := ctx.GetContext(r)
- // args[i] = reflect.ValueOf(reqCtx)
- // continue
- // }
-
- // // 3. 处理路径参数
- // matched := false
-
- // // 如果有对应的路径参数名,直接匹配
- // if value, ok := pathParams[paramName]; ok && paramType.Kind() == reflect.String {
- // args[i] = convertToType(value, paramType)
- // matched = true
- // }
-
- // // 如果是 string 类型但没有匹配到名称,按顺序分配路径参数
- // if !matched && paramType.Kind() == reflect.String {
- // // 使用 stringParamIndices 中的位置来匹配 pathParamNames
- // if stringParamIndex < len(ha.paramNames) && stringParamIndex < len(stringParamIndices) {
- // paramName := ha.paramNames[stringParamIndex]
- // if value, ok := pathParams[paramName]; ok {
- // args[i] = convertToType(value, paramType)
- // matched = true
- // stringParamIndex++
- // }
- // }
- // }
-
- // if matched {
- // continue
- // }
-
- // // 4. 其他绑定逻辑...
- // // 查询参数、JSON body 等
- // }
-
- // return args
- // }
-
- // // buildArgs 构建函数参数
- // func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
- // handlerType := ha.handlerFunc.Type()
- // numIn := handlerType.NumIn()
- // args := make([]reflect.Value, numIn)
-
- // for i := 0; i < numIn; i++ {
- // paramType := handlerType.In(i)
- // paramName := getParamName(i, handlerType, ha.paramNames)
-
- // // 1. 检查是否是特殊类型
- // if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
- // args[i] = arg
- // continue
- // }
-
- // // 2. 检查是否是 *ctx.RequestContext 类型
- // if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
- // reqCtx := ctx.GetContext(r)
- // if logger.IsDebug() {
- // logger.DebugC(reqCtx, "requestContext: %+v", reqCtx)
- // }
- // args[i] = reflect.ValueOf(reqCtx)
- // continue
- // }
-
- // // 3. 尝试从路径参数获取
- // if value, ok := pathParams[paramName]; ok {
- // if arg := convertToType(value, paramType); arg.IsValid() {
- // args[i] = arg
- // continue
- // }
- // }
-
- // // 4. 尝试从查询参数获取
- // if queryValue := r.URL.Query().Get(paramName); queryValue != "" {
- // if arg := convertToType(queryValue, paramType); arg.IsValid() {
- // args[i] = arg
- // continue
- // }
- // }
-
- // // 5. 尝试从JSON body获取
- // if (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH") &&
- // (paramType.Kind() == reflect.Struct ||
- // (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct)) {
- // if arg := ha.parseBody(r, paramType); arg.IsValid() {
- // args[i] = arg
- // continue
- // }
- // }
-
- // // 6. 返回零值
- // args[i] = reflect.Zero(paramType)
- // }
-
- // return args
- // }
-
- // bindSpecialType 绑定特殊类型
- func (ha *handlerAdapter) bindSpecialType(paramType reflect.Type, w http.ResponseWriter, r *http.Request) reflect.Value {
- switch paramType {
- case reflect.TypeOf((*http.ResponseWriter)(nil)).Elem():
- return reflect.ValueOf(w)
- case reflect.TypeOf((*http.Request)(nil)):
- return reflect.ValueOf(r)
- }
- return reflect.Value{}
- }
-
- // getParamName 获取参数名
- func getParamName(index int, handlerType reflect.Type, pathParamNames []string) string {
- // 如果有路径参数名,优先使用
- if index < len(pathParamNames) {
- return pathParamNames[index]
- }
-
- // 使用类型名的蛇形格式
- paramType := handlerType.In(index)
- typeName := paramType.Name()
- if typeName == "" {
- return strconv.Itoa(index)
- }
-
- // 转换为蛇形格式:MyInterface -> my_interface
- var result []rune
- for i, r := range typeName {
- if i > 0 && 'A' <= r && r <= 'Z' {
- result = append(result, '_')
- }
- result = append(result, r)
- }
- return strings.ToLower(string(result))
- }
-
- // convertToType 字符串转换为指定类型
- func convertToType(str string, targetType reflect.Type) reflect.Value {
- switch targetType.Kind() {
- case reflect.String:
- return reflect.ValueOf(str)
- case reflect.Int:
- if i, err := strconv.Atoi(str); err == nil {
- return reflect.ValueOf(i)
- }
- case reflect.Int64:
- if i, err := strconv.ParseInt(str, 10, 64); err == nil {
- return reflect.ValueOf(i)
- }
- case reflect.Bool:
- if b, err := strconv.ParseBool(str); err == nil {
- return reflect.ValueOf(b)
- }
- case reflect.Float64:
- if f, err := strconv.ParseFloat(str, 64); err == nil {
- return reflect.ValueOf(f)
- }
- }
- return reflect.Value{}
- }
-
- // parseBody 解析请求体
- func (ha *handlerAdapter) parseBody(r *http.Request, paramType reflect.Type) reflect.Value {
- // 创建参数实例
- var paramValue reflect.Value
- if paramType.Kind() == reflect.Ptr {
- paramValue = reflect.New(paramType.Elem())
- } else {
- paramValue = reflect.New(paramType)
- }
-
- // 解析JSON
- if err := json.NewDecoder(r.Body).Decode(paramValue.Interface()); err != nil {
- return reflect.Value{}
- }
- defer r.Body.Close()
-
- // 如果是非指针类型,需要解引用
- if paramType.Kind() != reflect.Ptr {
- paramValue = paramValue.Elem()
- }
-
- return paramValue
- }
-
- // handleResponse 处理响应
- func (ha *handlerAdapter) handleResponse(w http.ResponseWriter, results []reflect.Value) {
- // 第一个返回值是数据
- data := results[0].Interface()
-
- // 第二个返回值是error
- errVal := results[1].Interface()
- if errVal != nil {
- err := errVal.(error)
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-
- // 返回JSON响应
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(data)
- }
-
- // extractPathParams 从路径中提取参数名
- func extractPathParams(path string) []string {
- var params []string
- parts := strings.Split(strings.Trim(path, "/"), "/")
-
- for _, part := range parts {
- if strings.HasPrefix(part, "{") && strings.HasSuffix(part, "}") {
- paramName := part[1 : len(part)-1]
- params = append(params, paramName)
- }
- }
-
- return params
- }
|