Ingen beskrivning
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

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