暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

router_service.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package router
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "git.x2erp.com/qdy/go-base/ctx"
  10. )
  11. // WebService 路由服务
  12. type RouterService struct {
  13. router *http.ServeMux
  14. middlewares []func(http.Handler) http.Handler
  15. handlers map[string]http.Handler // key: method + " " + path
  16. registeredPaths map[string]bool // 路径是否已注册通用处理器
  17. mu sync.RWMutex
  18. }
  19. // NewWebService 创建WebService
  20. func NewWebService(router *http.ServeMux) *RouterService {
  21. ws := &RouterService{
  22. router: router,
  23. handlers: make(map[string]http.Handler),
  24. registeredPaths: make(map[string]bool),
  25. }
  26. return ws
  27. }
  28. // Use 添加全局中间件
  29. func (ws *RouterService) Use(middleware func(http.Handler) http.Handler) *RouterService {
  30. ws.middlewares = append(ws.middlewares, middleware)
  31. return ws
  32. }
  33. // GET 注册GET请求
  34. func (ws *RouterService) GET(path string, handler interface{}) *RouteBuilder {
  35. return ws.handle("GET", path, handler)
  36. }
  37. // POST 注册POST请求
  38. func (ws *RouterService) POST(path string, handler interface{}) *RouteBuilder {
  39. return ws.handle("POST", path, handler)
  40. }
  41. // PUT 注册PUT请求
  42. func (ws *RouterService) PUT(path string, handler interface{}) *RouteBuilder {
  43. return ws.handle("PUT", path, handler)
  44. }
  45. // DELETE 注册DELETE请求
  46. func (ws *RouterService) DELETE(path string, handler interface{}) *RouteBuilder {
  47. return ws.handle("DELETE", path, handler)
  48. }
  49. // handle 统一处理方法
  50. func (ws *RouterService) handle(method, path string, handler interface{}) *RouteBuilder {
  51. // 解析路径参数名
  52. paramNames := extractPathParams(path)
  53. // 获取处理器函数信息
  54. handlerValue := reflect.ValueOf(handler)
  55. handlerType := handlerValue.Type()
  56. // 验证处理器函数
  57. if handlerType.Kind() != reflect.Func {
  58. panic("handler must be a function")
  59. }
  60. // 验证返回值
  61. if handlerType.NumOut() != 2 {
  62. panic("handler must return exactly 2 values: (T, error)")
  63. }
  64. return &RouteBuilder{
  65. ws: ws,
  66. method: method,
  67. path: path,
  68. handlerFunc: handlerValue,
  69. paramNames: paramNames,
  70. }
  71. }
  72. // RouteBuilder 路由构建器
  73. type RouteBuilder struct {
  74. ws *RouterService
  75. method string
  76. path string
  77. handlerFunc reflect.Value
  78. paramNames []string
  79. middlewares []func(http.Handler) http.Handler
  80. description string
  81. }
  82. // Use 添加路由级中间件
  83. func (rb *RouteBuilder) Use(middleware ...func(http.Handler) http.Handler) *RouteBuilder {
  84. rb.middlewares = append(rb.middlewares, middleware...)
  85. return rb
  86. }
  87. // Desc 添加描述
  88. func (rb *RouteBuilder) Desc(description string) *RouteBuilder {
  89. rb.description = description
  90. return rb
  91. }
  92. // registerPathIfNeeded 注册路径通用处理器(如果尚未注册)
  93. func (ws *RouterService) registerPathIfNeeded(path string) {
  94. ws.mu.Lock()
  95. defer ws.mu.Unlock()
  96. if ws.registeredPaths[path] {
  97. return
  98. }
  99. // 创建通用处理器,根据方法分发
  100. genericHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  101. key := r.Method + " " + path
  102. ws.mu.RLock()
  103. handler, ok := ws.handlers[key]
  104. ws.mu.RUnlock()
  105. if !ok {
  106. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  107. return
  108. }
  109. handler.ServeHTTP(w, r)
  110. })
  111. ws.router.Handle(path, genericHandler)
  112. ws.registeredPaths[path] = true
  113. }
  114. // Register 注册路由
  115. func (rb *RouteBuilder) Register() {
  116. // 创建适配器
  117. adapter := &handlerAdapter{
  118. ws: rb.ws,
  119. method: rb.method,
  120. pathPattern: rb.path,
  121. paramNames: rb.paramNames,
  122. handlerFunc: rb.handlerFunc,
  123. }
  124. // 构建处理链:全局中间件 → 路由中间件 → 处理器
  125. var handler http.Handler = adapter
  126. // 1. 应用路由级中间件(从后往前)
  127. for i := len(rb.middlewares) - 1; i >= 0; i-- {
  128. handler = rb.middlewares[i](handler)
  129. }
  130. // 2. 应用全局中间件(从后往前)
  131. for i := len(rb.ws.middlewares) - 1; i >= 0; i-- {
  132. handler = rb.ws.middlewares[i](handler)
  133. }
  134. // 存储处理器到映射
  135. key := rb.method + " " + rb.path
  136. rb.ws.mu.Lock()
  137. rb.ws.handlers[key] = handler
  138. rb.ws.mu.Unlock()
  139. // 确保路径已注册通用处理器
  140. rb.ws.registerPathIfNeeded(rb.path)
  141. }
  142. // handlerAdapter 处理器适配器
  143. type handlerAdapter struct {
  144. ws *RouterService
  145. method string
  146. pathPattern string
  147. paramNames []string
  148. handlerFunc reflect.Value
  149. }
  150. func (ha *handlerAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  151. // 只处理指定方法的请求
  152. if r.Method != ha.method {
  153. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  154. return
  155. }
  156. // 1. 解析路径参数
  157. pathParams := ha.parsePathParams(r.URL.Path)
  158. // 2. 构建函数参数
  159. args := ha.buildArgs(w, r, pathParams)
  160. if args == nil {
  161. http.Error(w, "Invalid parameters", http.StatusBadRequest)
  162. return
  163. }
  164. // 3. 调用处理器函数
  165. results := ha.handlerFunc.Call(args)
  166. // 4. 处理返回结果
  167. ha.handleResponse(w, results)
  168. }
  169. // parsePathParams 解析路径参数
  170. func (ha *handlerAdapter) parsePathParams(requestPath string) map[string]string {
  171. params := make(map[string]string)
  172. pattern := strings.Trim(ha.pathPattern, "/")
  173. request := strings.Trim(requestPath, "/")
  174. patternParts := strings.Split(pattern, "/")
  175. requestParts := strings.Split(request, "/")
  176. for i, patternPart := range patternParts {
  177. if strings.HasPrefix(patternPart, "{") && strings.HasSuffix(patternPart, "}") {
  178. paramName := patternPart[1 : len(patternPart)-1]
  179. if i < len(requestParts) {
  180. params[paramName] = requestParts[i]
  181. }
  182. }
  183. }
  184. return params
  185. }
  186. func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
  187. handlerType := ha.handlerFunc.Type()
  188. numIn := handlerType.NumIn()
  189. args := make([]reflect.Value, numIn)
  190. for i := 0; i < numIn; i++ {
  191. paramType := handlerType.In(i)
  192. paramName := getParamName(i, handlerType, ha.paramNames)
  193. // 1. 检查是否是特殊类型
  194. if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
  195. args[i] = arg
  196. continue
  197. }
  198. // 2. 检查是否是 *ctx.RequestContext 类型
  199. if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
  200. reqCtx := ctx.GetContext(r)
  201. args[i] = reflect.ValueOf(reqCtx)
  202. continue
  203. }
  204. // 3. 只按名称匹配路径参数
  205. if value, ok := pathParams[paramName]; ok {
  206. args[i] = convertToType(value, paramType)
  207. continue
  208. }
  209. // 4. 尝试从查询参数获取
  210. if queryValue := r.URL.Query().Get(paramName); queryValue != "" {
  211. args[i] = convertToType(queryValue, paramType)
  212. continue
  213. }
  214. // 5. 尝试从JSON body获取(POST/PUT请求)
  215. if (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH") &&
  216. (paramType.Kind() == reflect.Struct ||
  217. (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct)) {
  218. if arg := ha.parseBody(r, paramType); arg.IsValid() {
  219. args[i] = arg
  220. continue
  221. }
  222. }
  223. // 6. 返回零值
  224. args[i] = reflect.Zero(paramType)
  225. }
  226. return args
  227. }
  228. // bindSpecialType 绑定特殊类型
  229. func (ha *handlerAdapter) bindSpecialType(paramType reflect.Type, w http.ResponseWriter, r *http.Request) reflect.Value {
  230. switch paramType {
  231. case reflect.TypeOf((*http.ResponseWriter)(nil)).Elem():
  232. return reflect.ValueOf(w)
  233. case reflect.TypeOf((*http.Request)(nil)):
  234. return reflect.ValueOf(r)
  235. }
  236. return reflect.Value{}
  237. }
  238. // getParamName 获取参数名
  239. func getParamName(index int, handlerType reflect.Type, pathParamNames []string) string {
  240. // 如果有路径参数名,优先使用
  241. if index < len(pathParamNames) {
  242. return pathParamNames[index]
  243. }
  244. // 使用类型名的蛇形格式
  245. paramType := handlerType.In(index)
  246. typeName := paramType.Name()
  247. if typeName == "" {
  248. return strconv.Itoa(index)
  249. }
  250. // 转换为蛇形格式:MyInterface -> my_interface
  251. var result []rune
  252. for i, r := range typeName {
  253. if i > 0 && 'A' <= r && r <= 'Z' {
  254. result = append(result, '_')
  255. }
  256. result = append(result, r)
  257. }
  258. return strings.ToLower(string(result))
  259. }
  260. // convertToType 字符串转换为指定类型
  261. func convertToType(str string, targetType reflect.Type) reflect.Value {
  262. switch targetType.Kind() {
  263. case reflect.String:
  264. return reflect.ValueOf(str)
  265. case reflect.Int:
  266. if i, err := strconv.Atoi(str); err == nil {
  267. return reflect.ValueOf(i)
  268. }
  269. case reflect.Int64:
  270. if i, err := strconv.ParseInt(str, 10, 64); err == nil {
  271. return reflect.ValueOf(i)
  272. }
  273. case reflect.Bool:
  274. if b, err := strconv.ParseBool(str); err == nil {
  275. return reflect.ValueOf(b)
  276. }
  277. case reflect.Float64:
  278. if f, err := strconv.ParseFloat(str, 64); err == nil {
  279. return reflect.ValueOf(f)
  280. }
  281. }
  282. return reflect.Value{}
  283. }
  284. // parseBody 解析请求体
  285. func (ha *handlerAdapter) parseBody(r *http.Request, paramType reflect.Type) reflect.Value {
  286. // 创建参数实例
  287. var paramValue reflect.Value
  288. if paramType.Kind() == reflect.Ptr {
  289. paramValue = reflect.New(paramType.Elem())
  290. } else {
  291. paramValue = reflect.New(paramType)
  292. }
  293. // 解析JSON
  294. if err := json.NewDecoder(r.Body).Decode(paramValue.Interface()); err != nil {
  295. return reflect.Value{}
  296. }
  297. defer r.Body.Close()
  298. // 如果是非指针类型,需要解引用
  299. if paramType.Kind() != reflect.Ptr {
  300. paramValue = paramValue.Elem()
  301. }
  302. return paramValue
  303. }
  304. // handleResponse 处理响应
  305. func (ha *handlerAdapter) handleResponse(w http.ResponseWriter, results []reflect.Value) {
  306. // 第一个返回值是数据
  307. data := results[0].Interface()
  308. // 第二个返回值是error
  309. errVal := results[1].Interface()
  310. if errVal != nil {
  311. err := errVal.(error)
  312. http.Error(w, err.Error(), http.StatusInternalServerError)
  313. return
  314. }
  315. // 检查是否是 []byte 类型
  316. if bytes, ok := data.([]byte); ok {
  317. // 如果是 []byte,直接写入响应,不进行 JSON 编码
  318. w.Write(bytes)
  319. return
  320. }
  321. // 返回JSON响应
  322. w.Header().Set("Content-Type", "application/json")
  323. json.NewEncoder(w).Encode(data)
  324. }
  325. // extractPathParams 从路径中提取参数名
  326. func extractPathParams(path string) []string {
  327. var params []string
  328. parts := strings.Split(strings.Trim(path, "/"), "/")
  329. for _, part := range parts {
  330. if strings.HasPrefix(part, "{") && strings.HasSuffix(part, "}") {
  331. paramName := part[1 : len(part)-1]
  332. params = append(params, paramName)
  333. }
  334. }
  335. return params
  336. }