Açıklama Yok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

router_service.go 10KB

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