暫無描述
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.

web_service.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. package webx
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "git.x2erp.com/qdy/go-base/ctx"
  9. )
  10. // WebService 路由服务
  11. type WebService struct {
  12. router *http.ServeMux
  13. middlewares []func(http.Handler) http.Handler
  14. }
  15. // NewWebService 创建WebService
  16. func NewWebService(router *http.ServeMux) *WebService {
  17. ws := &WebService{
  18. router: router,
  19. }
  20. return ws
  21. }
  22. // Use 添加全局中间件
  23. func (ws *WebService) Use(middleware func(http.Handler) http.Handler) *WebService {
  24. ws.middlewares = append(ws.middlewares, middleware)
  25. return ws
  26. }
  27. // GET 注册GET请求
  28. func (ws *WebService) GET(path string, handler interface{}) *RouteBuilder {
  29. return ws.handle("GET", path, handler)
  30. }
  31. // POST 注册POST请求
  32. func (ws *WebService) POST(path string, handler interface{}) *RouteBuilder {
  33. return ws.handle("POST", path, handler)
  34. }
  35. // PUT 注册PUT请求
  36. func (ws *WebService) PUT(path string, handler interface{}) *RouteBuilder {
  37. return ws.handle("PUT", path, handler)
  38. }
  39. // DELETE 注册DELETE请求
  40. func (ws *WebService) DELETE(path string, handler interface{}) *RouteBuilder {
  41. return ws.handle("DELETE", path, handler)
  42. }
  43. // handle 统一处理方法
  44. func (ws *WebService) handle(method, path string, handler interface{}) *RouteBuilder {
  45. // 解析路径参数名
  46. paramNames := extractPathParams(path)
  47. // 获取处理器函数信息
  48. handlerValue := reflect.ValueOf(handler)
  49. handlerType := handlerValue.Type()
  50. // 验证处理器函数
  51. if handlerType.Kind() != reflect.Func {
  52. panic("handler must be a function")
  53. }
  54. // 验证返回值
  55. if handlerType.NumOut() != 2 {
  56. panic("handler must return exactly 2 values: (T, error)")
  57. }
  58. return &RouteBuilder{
  59. ws: ws,
  60. method: method,
  61. path: path,
  62. handlerFunc: handlerValue,
  63. paramNames: paramNames,
  64. }
  65. }
  66. // // 上下文中间件
  67. // func (ws *WebService) contextMiddleware() func(http.Handler) http.Handler {
  68. // return func(next http.Handler) http.Handler {
  69. // return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  70. // // 自动创建 RequestContext
  71. // reqCtx := ws.createRequestContext(r)
  72. // // 保存到请求中
  73. // r = ctx.SaveContext(r, *reqCtx)
  74. // next.ServeHTTP(w, r)
  75. // })
  76. // }
  77. // }
  78. // // 创建 RequestContext
  79. // func (ws *WebService) createRequestContext(r *http.Request) *ctx.RequestContext {
  80. // return &ctx.RequestContext{
  81. // TraceID: generateTraceID(),
  82. // ServiceName: getServiceName(r),
  83. // InstanceName: getInstanceName(),
  84. // TenantID: r.Header.Get("X-Tenant-ID"),
  85. // UserID: extractUserID(r),
  86. // }
  87. // }
  88. // // 辅助函数
  89. // func generateTraceID() string {
  90. // return "trace-" + strconv.FormatInt(time.Now().UnixNano(), 36)
  91. // }
  92. // func getServiceName(r *http.Request) string {
  93. // if serviceName := r.Header.Get("X-Service-Name"); serviceName != "" {
  94. // return serviceName
  95. // }
  96. // return "unknown-service"
  97. // }
  98. // func getInstanceName() string {
  99. // // 获取主机名
  100. // hostname, _ := os.Hostname()
  101. // if hostname != "" {
  102. // return hostname
  103. // }
  104. // return "instance-1"
  105. // }
  106. // func extractUserID(r *http.Request) string {
  107. // if auth := r.Header.Get("Authorization"); auth != "" {
  108. // // 简单示例:从 Authorization 头提取
  109. // if strings.HasPrefix(auth, "Bearer ") {
  110. // // 这里可以解析 JWT token 获取用户ID
  111. // // 暂时返回示例值
  112. // return "user-from-token"
  113. // }
  114. // }
  115. // return ""
  116. // }
  117. // RouteBuilder 路由构建器
  118. type RouteBuilder struct {
  119. ws *WebService
  120. method string
  121. path string
  122. handlerFunc reflect.Value
  123. paramNames []string
  124. middlewares []func(http.Handler) http.Handler
  125. description string
  126. }
  127. // Use 添加路由级中间件
  128. func (rb *RouteBuilder) Use(middleware ...func(http.Handler) http.Handler) *RouteBuilder {
  129. rb.middlewares = append(rb.middlewares, middleware...)
  130. return rb
  131. }
  132. // Desc 添加描述
  133. func (rb *RouteBuilder) Desc(description string) *RouteBuilder {
  134. rb.description = description
  135. return rb
  136. }
  137. // Register 注册路由
  138. func (rb *RouteBuilder) Register() {
  139. // 创建适配器
  140. adapter := &handlerAdapter{
  141. ws: rb.ws,
  142. method: rb.method,
  143. pathPattern: rb.path,
  144. paramNames: rb.paramNames,
  145. handlerFunc: rb.handlerFunc,
  146. }
  147. // 构建处理链:全局中间件 → 路由中间件 → 处理器
  148. var handler http.Handler = adapter
  149. // 1. 应用路由级中间件(从后往前)
  150. for i := len(rb.middlewares) - 1; i >= 0; i-- {
  151. handler = rb.middlewares[i](handler)
  152. }
  153. // 2. 应用全局中间件(从后往前)
  154. for i := len(rb.ws.middlewares) - 1; i >= 0; i-- {
  155. handler = rb.ws.middlewares[i](handler)
  156. }
  157. // 注册到路由器
  158. rb.ws.router.Handle(rb.path, handler)
  159. }
  160. // handlerAdapter 处理器适配器
  161. type handlerAdapter struct {
  162. ws *WebService
  163. method string
  164. pathPattern string
  165. paramNames []string
  166. handlerFunc reflect.Value
  167. }
  168. func (ha *handlerAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  169. // 只处理指定方法的请求
  170. if r.Method != ha.method {
  171. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  172. return
  173. }
  174. // 1. 解析路径参数
  175. pathParams := ha.parsePathParams(r.URL.Path)
  176. // 2. 构建函数参数
  177. args := ha.buildArgs(w, r, pathParams)
  178. if args == nil {
  179. http.Error(w, "Invalid parameters", http.StatusBadRequest)
  180. return
  181. }
  182. // 3. 调用处理器函数
  183. results := ha.handlerFunc.Call(args)
  184. // 4. 处理返回结果
  185. ha.handleResponse(w, results)
  186. }
  187. // parsePathParams 解析路径参数
  188. func (ha *handlerAdapter) parsePathParams(requestPath string) map[string]string {
  189. params := make(map[string]string)
  190. pattern := strings.Trim(ha.pathPattern, "/")
  191. request := strings.Trim(requestPath, "/")
  192. patternParts := strings.Split(pattern, "/")
  193. requestParts := strings.Split(request, "/")
  194. for i, patternPart := range patternParts {
  195. if strings.HasPrefix(patternPart, "{") && strings.HasSuffix(patternPart, "}") {
  196. paramName := patternPart[1 : len(patternPart)-1]
  197. if i < len(requestParts) {
  198. params[paramName] = requestParts[i]
  199. }
  200. }
  201. }
  202. return params
  203. }
  204. func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
  205. handlerType := ha.handlerFunc.Type()
  206. numIn := handlerType.NumIn()
  207. args := make([]reflect.Value, numIn)
  208. for i := 0; i < numIn; i++ {
  209. paramType := handlerType.In(i)
  210. paramName := getParamName(i, handlerType, ha.paramNames)
  211. // 1. 检查是否是特殊类型
  212. if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
  213. args[i] = arg
  214. continue
  215. }
  216. // 2. 检查是否是 *ctx.RequestContext 类型
  217. if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
  218. reqCtx := ctx.GetContext(r)
  219. args[i] = reflect.ValueOf(reqCtx)
  220. continue
  221. }
  222. // 3. 只按名称匹配路径参数
  223. if value, ok := pathParams[paramName]; ok {
  224. args[i] = convertToType(value, paramType)
  225. continue
  226. }
  227. // 4. 尝试从查询参数获取
  228. if queryValue := r.URL.Query().Get(paramName); queryValue != "" {
  229. args[i] = convertToType(queryValue, paramType)
  230. continue
  231. }
  232. // 5. 尝试从JSON body获取(POST/PUT请求)
  233. if (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH") &&
  234. (paramType.Kind() == reflect.Struct ||
  235. (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct)) {
  236. if arg := ha.parseBody(r, paramType); arg.IsValid() {
  237. args[i] = arg
  238. continue
  239. }
  240. }
  241. // 6. 返回零值
  242. args[i] = reflect.Zero(paramType)
  243. }
  244. return args
  245. }
  246. // func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
  247. // handlerType := ha.handlerFunc.Type()
  248. // numIn := handlerType.NumIn()
  249. // args := make([]reflect.Value, numIn)
  250. // // 收集所有 string 类型的参数索引
  251. // var stringParamIndices []int
  252. // for i := 0; i < numIn; i++ {
  253. // paramType := handlerType.In(i)
  254. // if paramType.Kind() == reflect.String &&
  255. // paramType != reflect.TypeOf((*ctx.RequestContext)(nil)) {
  256. // stringParamIndices = append(stringParamIndices, i)
  257. // }
  258. // }
  259. // // 处理每个参数
  260. // stringParamIndex := 0
  261. // for i := 0; i < numIn; i++ {
  262. // paramType := handlerType.In(i)
  263. // paramName := getParamName(i, handlerType, ha.paramNames)
  264. // // 1. 检查是否是特殊类型
  265. // if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
  266. // args[i] = arg
  267. // continue
  268. // }
  269. // // 2. 检查是否是 *ctx.RequestContext 类型
  270. // if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
  271. // reqCtx := ctx.GetContext(r)
  272. // args[i] = reflect.ValueOf(reqCtx)
  273. // continue
  274. // }
  275. // // 3. 处理路径参数
  276. // matched := false
  277. // // 如果有对应的路径参数名,直接匹配
  278. // if value, ok := pathParams[paramName]; ok && paramType.Kind() == reflect.String {
  279. // args[i] = convertToType(value, paramType)
  280. // matched = true
  281. // }
  282. // // 如果是 string 类型但没有匹配到名称,按顺序分配路径参数
  283. // if !matched && paramType.Kind() == reflect.String {
  284. // // 使用 stringParamIndices 中的位置来匹配 pathParamNames
  285. // if stringParamIndex < len(ha.paramNames) && stringParamIndex < len(stringParamIndices) {
  286. // paramName := ha.paramNames[stringParamIndex]
  287. // if value, ok := pathParams[paramName]; ok {
  288. // args[i] = convertToType(value, paramType)
  289. // matched = true
  290. // stringParamIndex++
  291. // }
  292. // }
  293. // }
  294. // if matched {
  295. // continue
  296. // }
  297. // // 4. 其他绑定逻辑...
  298. // // 查询参数、JSON body 等
  299. // }
  300. // return args
  301. // }
  302. // // buildArgs 构建函数参数
  303. // func (ha *handlerAdapter) buildArgs(w http.ResponseWriter, r *http.Request, pathParams map[string]string) []reflect.Value {
  304. // handlerType := ha.handlerFunc.Type()
  305. // numIn := handlerType.NumIn()
  306. // args := make([]reflect.Value, numIn)
  307. // for i := 0; i < numIn; i++ {
  308. // paramType := handlerType.In(i)
  309. // paramName := getParamName(i, handlerType, ha.paramNames)
  310. // // 1. 检查是否是特殊类型
  311. // if arg := ha.bindSpecialType(paramType, w, r); arg.IsValid() {
  312. // args[i] = arg
  313. // continue
  314. // }
  315. // // 2. 检查是否是 *ctx.RequestContext 类型
  316. // if paramType == reflect.TypeOf((*ctx.RequestContext)(nil)) {
  317. // reqCtx := ctx.GetContext(r)
  318. // if logger.IsDebug() {
  319. // logger.DebugC(reqCtx, "requestContext: %+v", reqCtx)
  320. // }
  321. // args[i] = reflect.ValueOf(reqCtx)
  322. // continue
  323. // }
  324. // // 3. 尝试从路径参数获取
  325. // if value, ok := pathParams[paramName]; ok {
  326. // if arg := convertToType(value, paramType); arg.IsValid() {
  327. // args[i] = arg
  328. // continue
  329. // }
  330. // }
  331. // // 4. 尝试从查询参数获取
  332. // if queryValue := r.URL.Query().Get(paramName); queryValue != "" {
  333. // if arg := convertToType(queryValue, paramType); arg.IsValid() {
  334. // args[i] = arg
  335. // continue
  336. // }
  337. // }
  338. // // 5. 尝试从JSON body获取
  339. // if (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH") &&
  340. // (paramType.Kind() == reflect.Struct ||
  341. // (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() == reflect.Struct)) {
  342. // if arg := ha.parseBody(r, paramType); arg.IsValid() {
  343. // args[i] = arg
  344. // continue
  345. // }
  346. // }
  347. // // 6. 返回零值
  348. // args[i] = reflect.Zero(paramType)
  349. // }
  350. // return args
  351. // }
  352. // bindSpecialType 绑定特殊类型
  353. func (ha *handlerAdapter) bindSpecialType(paramType reflect.Type, w http.ResponseWriter, r *http.Request) reflect.Value {
  354. switch paramType {
  355. case reflect.TypeOf((*http.ResponseWriter)(nil)).Elem():
  356. return reflect.ValueOf(w)
  357. case reflect.TypeOf((*http.Request)(nil)):
  358. return reflect.ValueOf(r)
  359. }
  360. return reflect.Value{}
  361. }
  362. // getParamName 获取参数名
  363. func getParamName(index int, handlerType reflect.Type, pathParamNames []string) string {
  364. // 如果有路径参数名,优先使用
  365. if index < len(pathParamNames) {
  366. return pathParamNames[index]
  367. }
  368. // 使用类型名的蛇形格式
  369. paramType := handlerType.In(index)
  370. typeName := paramType.Name()
  371. if typeName == "" {
  372. return strconv.Itoa(index)
  373. }
  374. // 转换为蛇形格式:MyInterface -> my_interface
  375. var result []rune
  376. for i, r := range typeName {
  377. if i > 0 && 'A' <= r && r <= 'Z' {
  378. result = append(result, '_')
  379. }
  380. result = append(result, r)
  381. }
  382. return strings.ToLower(string(result))
  383. }
  384. // convertToType 字符串转换为指定类型
  385. func convertToType(str string, targetType reflect.Type) reflect.Value {
  386. switch targetType.Kind() {
  387. case reflect.String:
  388. return reflect.ValueOf(str)
  389. case reflect.Int:
  390. if i, err := strconv.Atoi(str); err == nil {
  391. return reflect.ValueOf(i)
  392. }
  393. case reflect.Int64:
  394. if i, err := strconv.ParseInt(str, 10, 64); err == nil {
  395. return reflect.ValueOf(i)
  396. }
  397. case reflect.Bool:
  398. if b, err := strconv.ParseBool(str); err == nil {
  399. return reflect.ValueOf(b)
  400. }
  401. case reflect.Float64:
  402. if f, err := strconv.ParseFloat(str, 64); err == nil {
  403. return reflect.ValueOf(f)
  404. }
  405. }
  406. return reflect.Value{}
  407. }
  408. // parseBody 解析请求体
  409. func (ha *handlerAdapter) parseBody(r *http.Request, paramType reflect.Type) reflect.Value {
  410. // 创建参数实例
  411. var paramValue reflect.Value
  412. if paramType.Kind() == reflect.Ptr {
  413. paramValue = reflect.New(paramType.Elem())
  414. } else {
  415. paramValue = reflect.New(paramType)
  416. }
  417. // 解析JSON
  418. if err := json.NewDecoder(r.Body).Decode(paramValue.Interface()); err != nil {
  419. return reflect.Value{}
  420. }
  421. defer r.Body.Close()
  422. // 如果是非指针类型,需要解引用
  423. if paramType.Kind() != reflect.Ptr {
  424. paramValue = paramValue.Elem()
  425. }
  426. return paramValue
  427. }
  428. // handleResponse 处理响应
  429. func (ha *handlerAdapter) handleResponse(w http.ResponseWriter, results []reflect.Value) {
  430. // 第一个返回值是数据
  431. data := results[0].Interface()
  432. // 第二个返回值是error
  433. errVal := results[1].Interface()
  434. if errVal != nil {
  435. err := errVal.(error)
  436. http.Error(w, err.Error(), http.StatusInternalServerError)
  437. return
  438. }
  439. // 返回JSON响应
  440. w.Header().Set("Content-Type", "application/json")
  441. json.NewEncoder(w).Encode(data)
  442. }
  443. // extractPathParams 从路径中提取参数名
  444. func extractPathParams(path string) []string {
  445. var params []string
  446. parts := strings.Split(strings.Trim(path, "/"), "/")
  447. for _, part := range parts {
  448. if strings.HasPrefix(part, "{") && strings.HasSuffix(part, "}") {
  449. paramName := part[1 : len(part)-1]
  450. params = append(params, paramName)
  451. }
  452. }
  453. return params
  454. }