context.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package mux
  2. import (
  3. "bytes"
  4. stdCtx "context"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "sync"
  10. "git.bvbej.com/bvbej/base-golang/pkg/errno"
  11. "git.bvbej.com/bvbej/base-golang/pkg/trace"
  12. "github.com/gin-gonic/gin"
  13. "github.com/gin-gonic/gin/binding"
  14. "go.uber.org/zap"
  15. )
  16. type HandlerFunc func(c Context)
  17. type Trace = trace.T
  18. const (
  19. _Alias = "_alias_"
  20. _TraceName = "_trace_"
  21. _LoggerName = "_logger_"
  22. _BodyName = "_body_"
  23. _PayloadName = "_payload_"
  24. _GraphPayloadName = "_graph_payload_"
  25. _AbortErrorName = "_abort_error_"
  26. _Auth = "_auth_"
  27. )
  28. var contextPool = &sync.Pool{
  29. New: func() any {
  30. return new(context)
  31. },
  32. }
  33. func newContext(ctx *gin.Context) Context {
  34. getContext := contextPool.Get().(*context)
  35. getContext.ctx = ctx
  36. return getContext
  37. }
  38. func releaseContext(ctx Context) {
  39. c := ctx.(*context)
  40. c.ctx = nil
  41. contextPool.Put(c)
  42. }
  43. var _ Context = (*context)(nil)
  44. type Context interface {
  45. init()
  46. Context() *gin.Context
  47. // ShouldBindQuery 反序列化 query
  48. // tag: `form:"xxx"` (注:不要写成 query)
  49. ShouldBindQuery(obj any) error
  50. // ShouldBindPostForm 反序列化 x-www-from-urlencoded
  51. // tag: `form:"xxx"`
  52. ShouldBindPostForm(obj any) error
  53. // ShouldBindForm 同时反序列化 form-data;
  54. // tag: `form:"xxx"`
  55. ShouldBindForm(obj any) error
  56. // ShouldBindJSON 反序列化 post-json
  57. // tag: `json:"xxx"`
  58. ShouldBindJSON(obj any) error
  59. // ShouldBindURI 反序列化 path 参数(如路由路径为 /user/:name)
  60. // tag: `uri:"xxx"`
  61. ShouldBindURI(obj any) error
  62. // Redirect 重定向
  63. Redirect(code int, location string)
  64. // Trace 获取 Trace 对象
  65. Trace() Trace
  66. setTrace(trace Trace)
  67. disableTrace()
  68. // Logger 获取 Logger 对象
  69. Logger() *zap.Logger
  70. setLogger(logger *zap.Logger)
  71. // Payload 正确返回
  72. Payload(payload any)
  73. getPayload() any
  74. // GraphPayload GraphQL返回值 与 api 返回结构不同
  75. GraphPayload(payload any)
  76. getGraphPayload() any
  77. // HTML 返回界面
  78. HTML(name string, obj any)
  79. // AbortWithError 错误返回
  80. AbortWithError(err errno.Error)
  81. abortError() errno.Error
  82. // Header 获取 Header 对象
  83. Header() http.Header
  84. // GetHeader 获取 Header
  85. GetHeader(key string) string
  86. // SetHeader 设置 Header
  87. SetHeader(key, value string)
  88. Auth() any
  89. SetAuth(auth any)
  90. // Authorization 获取请求认证信息
  91. Authorization() string
  92. // Alias 设置路由别名 for metrics uri
  93. Alias() string
  94. setAlias(path string)
  95. // RequestInputParams 获取所有参数
  96. RequestInputParams() url.Values
  97. // RequestQueryParams 获取 Query 参数
  98. RequestQueryParams() url.Values
  99. // RequestPostFormParams 获取 PostForm 参数
  100. RequestPostFormParams() url.Values
  101. // Request 获取 Request 对象
  102. Request() *http.Request
  103. // RawData 获取 Request.Body
  104. RawData() []byte
  105. // Method 获取 Request.Method
  106. Method() string
  107. // Host 获取 Request.Host
  108. Host() string
  109. // Path 获取 请求的路径 Request.URL.Path (不附带 querystring)
  110. Path() string
  111. // URI 获取 unescape 后的 Request.URL.RequestURI()
  112. URI() string
  113. // RequestContext 获取请求的 context (当 client 关闭后,会自动 canceled)
  114. RequestContext() StdContext
  115. // ResponseWriter 获取 ResponseWriter 对象
  116. ResponseWriter() gin.ResponseWriter
  117. }
  118. type context struct {
  119. ctx *gin.Context
  120. }
  121. type StdContext struct {
  122. stdCtx.Context
  123. Trace
  124. *zap.Logger
  125. }
  126. func (c *context) init() {
  127. body, err := c.ctx.GetRawData()
  128. if err != nil {
  129. panic(err)
  130. }
  131. c.ctx.Set(_BodyName, body) // cache body是为了trace使用
  132. c.ctx.Request.Body = io.NopCloser(bytes.NewBuffer(body)) // re-construct req body
  133. }
  134. func (c *context) Context() *gin.Context {
  135. return c.ctx
  136. }
  137. // ShouldBindQuery 反序列化querystring
  138. // tag: `form:"xxx"` (注:不要写成query)
  139. func (c *context) ShouldBindQuery(obj any) error {
  140. return c.ctx.ShouldBindWith(obj, binding.Query)
  141. }
  142. // ShouldBindPostForm 反序列化 postform (querystring 会被忽略)
  143. // tag: `form:"xxx"`
  144. func (c *context) ShouldBindPostForm(obj any) error {
  145. return c.ctx.ShouldBindWith(obj, binding.FormPost)
  146. }
  147. // ShouldBindForm 同时反序列化querystring和postform;
  148. // 当querystring和postform存在相同字段时,postform优先使用。
  149. // tag: `form:"xxx"`
  150. func (c *context) ShouldBindForm(obj any) error {
  151. return c.ctx.ShouldBindWith(obj, binding.Form)
  152. }
  153. // ShouldBindJSON 反序列化postjson
  154. // tag: `json:"xxx"`
  155. func (c *context) ShouldBindJSON(obj any) error {
  156. return c.ctx.ShouldBindWith(obj, binding.JSON)
  157. }
  158. // ShouldBindURI 反序列化path参数(如路由路径为 /user/:name)
  159. // tag: `uri:"xxx"`
  160. func (c *context) ShouldBindURI(obj any) error {
  161. return c.ctx.ShouldBindUri(obj)
  162. }
  163. // Redirect 重定向
  164. func (c *context) Redirect(code int, location string) {
  165. c.ctx.Redirect(code, location)
  166. }
  167. func (c *context) Trace() Trace {
  168. t, ok := c.ctx.Get(_TraceName)
  169. if !ok || t == nil {
  170. return nil
  171. }
  172. return t.(Trace)
  173. }
  174. func (c *context) setTrace(trace Trace) {
  175. c.ctx.Set(_TraceName, trace)
  176. }
  177. func (c *context) disableTrace() {
  178. c.setTrace(nil)
  179. }
  180. func (c *context) Logger() *zap.Logger {
  181. logger, ok := c.ctx.Get(_LoggerName)
  182. if !ok {
  183. return nil
  184. }
  185. return logger.(*zap.Logger)
  186. }
  187. func (c *context) setLogger(logger *zap.Logger) {
  188. c.ctx.Set(_LoggerName, logger)
  189. }
  190. func (c *context) getPayload() any {
  191. if payload, ok := c.ctx.Get(_PayloadName); ok != false {
  192. return payload
  193. }
  194. return nil
  195. }
  196. func (c *context) Payload(payload any) {
  197. c.ctx.Set(_PayloadName, payload)
  198. }
  199. func (c *context) getGraphPayload() any {
  200. if payload, ok := c.ctx.Get(_GraphPayloadName); ok != false {
  201. return payload
  202. }
  203. return nil
  204. }
  205. func (c *context) GraphPayload(payload any) {
  206. c.ctx.Set(_GraphPayloadName, payload)
  207. }
  208. func (c *context) HTML(name string, obj any) {
  209. c.ctx.HTML(200, name+".html", obj)
  210. }
  211. func (c *context) Header() http.Header {
  212. header := c.ctx.Request.Header
  213. clone := make(http.Header, len(header))
  214. for k, v := range header {
  215. value := make([]string, len(v))
  216. copy(value, v)
  217. clone[k] = value
  218. }
  219. return clone
  220. }
  221. func (c *context) GetHeader(key string) string {
  222. return c.ctx.GetHeader(key)
  223. }
  224. func (c *context) SetHeader(key, value string) {
  225. c.ctx.Header(key, value)
  226. }
  227. func (c *context) Auth() any {
  228. val, ok := c.ctx.Get(_Auth)
  229. if !ok {
  230. return nil
  231. }
  232. return val
  233. }
  234. func (c *context) SetAuth(auth any) {
  235. c.ctx.Set(_Auth, auth)
  236. }
  237. func (c *context) Authorization() string {
  238. return c.ctx.GetHeader("Authorization")
  239. }
  240. func (c *context) AbortWithError(err errno.Error) {
  241. if err != nil {
  242. httpCode := err.GetHttpCode()
  243. if httpCode == 0 {
  244. httpCode = http.StatusInternalServerError
  245. }
  246. c.ctx.AbortWithStatus(httpCode)
  247. c.ctx.Set(_AbortErrorName, err)
  248. }
  249. }
  250. func (c *context) abortError() errno.Error {
  251. err, _ := c.ctx.Get(_AbortErrorName)
  252. return err.(errno.Error)
  253. }
  254. func (c *context) Alias() string {
  255. path, ok := c.ctx.Get(_Alias)
  256. if !ok {
  257. return ""
  258. }
  259. return path.(string)
  260. }
  261. func (c *context) setAlias(path string) {
  262. if path = strings.TrimSpace(path); path != "" {
  263. c.ctx.Set(_Alias, path)
  264. }
  265. }
  266. // RequestInputParams 获取所有参数
  267. func (c *context) RequestInputParams() url.Values {
  268. _ = c.ctx.Request.ParseForm()
  269. return c.ctx.Request.Form
  270. }
  271. // RequestQueryParams 获取Query参数
  272. func (c *context) RequestQueryParams() url.Values {
  273. query, _ := url.ParseQuery(c.ctx.Request.URL.RawQuery)
  274. return query
  275. }
  276. // RequestPostFormParams 获取 PostForm 参数
  277. func (c *context) RequestPostFormParams() url.Values {
  278. _ = c.ctx.Request.ParseForm()
  279. return c.ctx.Request.PostForm
  280. }
  281. // Request 获取 Request
  282. func (c *context) Request() *http.Request {
  283. return c.ctx.Request
  284. }
  285. func (c *context) RawData() []byte {
  286. body, ok := c.ctx.Get(_BodyName)
  287. if !ok {
  288. return nil
  289. }
  290. return body.([]byte)
  291. }
  292. // Method 请求的method
  293. func (c *context) Method() string {
  294. return c.ctx.Request.Method
  295. }
  296. // Host 请求的host
  297. func (c *context) Host() string {
  298. return c.ctx.Request.Host
  299. }
  300. // Path 请求的路径(不附带querystring)
  301. func (c *context) Path() string {
  302. return c.ctx.Request.URL.Path
  303. }
  304. // URI unescape后的uri
  305. func (c *context) URI() string {
  306. uri, _ := url.QueryUnescape(c.ctx.Request.URL.RequestURI())
  307. return uri
  308. }
  309. // RequestContext (包装 Trace + Logger) 获取请求的 context (当client关闭后,会自动canceled)
  310. func (c *context) RequestContext() StdContext {
  311. return StdContext{
  312. //c.ctx.Request.Context(),
  313. stdCtx.Background(),
  314. c.Trace(),
  315. c.Logger(),
  316. }
  317. }
  318. // ResponseWriter 获取 ResponseWriter
  319. func (c *context) ResponseWriter() gin.ResponseWriter {
  320. return c.ctx.Writer
  321. }