context.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package blademaster
  2. import (
  3. "context"
  4. "math"
  5. "net/http"
  6. "strconv"
  7. "go-common/library/ecode"
  8. "go-common/library/net/http/blademaster/binding"
  9. "go-common/library/net/http/blademaster/render"
  10. "github.com/gogo/protobuf/proto"
  11. "github.com/gogo/protobuf/types"
  12. "github.com/pkg/errors"
  13. )
  14. const (
  15. _abortIndex int8 = math.MaxInt8 / 2
  16. )
  17. var (
  18. _openParen = []byte("(")
  19. _closeParen = []byte(")")
  20. )
  21. // Context is the most important part. It allows us to pass variables between
  22. // middleware, manage the flow, validate the JSON of a request and render a
  23. // JSON response for example.
  24. type Context struct {
  25. context.Context
  26. Request *http.Request
  27. Writer http.ResponseWriter
  28. // flow control
  29. index int8
  30. handlers []HandlerFunc
  31. // Keys is a key/value pair exclusively for the context of each request.
  32. Keys map[string]interface{}
  33. Error error
  34. method string
  35. engine *Engine
  36. }
  37. /************************************/
  38. /*********** FLOW CONTROL ***********/
  39. /************************************/
  40. // Next should be used only inside middleware.
  41. // It executes the pending handlers in the chain inside the calling handler.
  42. // See example in godoc.
  43. func (c *Context) Next() {
  44. c.index++
  45. s := int8(len(c.handlers))
  46. for ; c.index < s; c.index++ {
  47. // only check method on last handler, otherwise middlewares
  48. // will never be effected if request method is not matched
  49. if c.index == s-1 && c.method != c.Request.Method {
  50. code := http.StatusMethodNotAllowed
  51. c.Error = ecode.MethodNotAllowed
  52. http.Error(c.Writer, http.StatusText(code), code)
  53. return
  54. }
  55. c.handlers[c.index](c)
  56. }
  57. }
  58. // Abort prevents pending handlers from being called. Note that this will not stop the current handler.
  59. // Let's say you have an authorization middleware that validates that the current request is authorized.
  60. // If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
  61. // for this request are not called.
  62. func (c *Context) Abort() {
  63. c.index = _abortIndex
  64. }
  65. // AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
  66. // For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
  67. func (c *Context) AbortWithStatus(code int) {
  68. c.Status(code)
  69. c.Abort()
  70. }
  71. // IsAborted returns true if the current context was aborted.
  72. func (c *Context) IsAborted() bool {
  73. return c.index >= _abortIndex
  74. }
  75. /************************************/
  76. /******** METADATA MANAGEMENT********/
  77. /************************************/
  78. // Set is used to store a new key/value pair exclusively for this context.
  79. // It also lazy initializes c.Keys if it was not used previously.
  80. func (c *Context) Set(key string, value interface{}) {
  81. if c.Keys == nil {
  82. c.Keys = make(map[string]interface{})
  83. }
  84. c.Keys[key] = value
  85. }
  86. // Get returns the value for the given key, ie: (value, true).
  87. // If the value does not exists it returns (nil, false)
  88. func (c *Context) Get(key string) (value interface{}, exists bool) {
  89. value, exists = c.Keys[key]
  90. return
  91. }
  92. /************************************/
  93. /******** RESPONSE RENDERING ********/
  94. /************************************/
  95. // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
  96. func bodyAllowedForStatus(status int) bool {
  97. switch {
  98. case status >= 100 && status <= 199:
  99. return false
  100. case status == 204:
  101. return false
  102. case status == 304:
  103. return false
  104. }
  105. return true
  106. }
  107. // Status sets the HTTP response code.
  108. func (c *Context) Status(code int) {
  109. c.Writer.WriteHeader(code)
  110. }
  111. // Render http response with http code by a render instance.
  112. func (c *Context) Render(code int, r render.Render) {
  113. r.WriteContentType(c.Writer)
  114. if code > 0 {
  115. c.Status(code)
  116. }
  117. if !bodyAllowedForStatus(code) {
  118. return
  119. }
  120. params := c.Request.Form
  121. cb := params.Get("callback")
  122. jsonp := cb != "" && params.Get("jsonp") == "jsonp"
  123. if jsonp {
  124. c.Writer.Write([]byte(cb))
  125. c.Writer.Write(_openParen)
  126. }
  127. if err := r.Render(c.Writer); err != nil {
  128. c.Error = err
  129. return
  130. }
  131. if jsonp {
  132. if _, err := c.Writer.Write(_closeParen); err != nil {
  133. c.Error = errors.WithStack(err)
  134. }
  135. }
  136. }
  137. // JSON serializes the given struct as JSON into the response body.
  138. // It also sets the Content-Type as "application/json".
  139. func (c *Context) JSON(data interface{}, err error) {
  140. code := http.StatusOK
  141. c.Error = err
  142. bcode := ecode.Cause(err)
  143. // TODO app allow 5xx?
  144. /*
  145. if bcode.Code() == -500 {
  146. code = http.StatusServiceUnavailable
  147. }
  148. */
  149. writeStatusCode(c.Writer, bcode.Code())
  150. c.Render(code, render.JSON{
  151. Code: bcode.Code(),
  152. Message: bcode.Message(),
  153. Data: data,
  154. })
  155. }
  156. // JSONMap serializes the given map as map JSON into the response body.
  157. // It also sets the Content-Type as "application/json".
  158. func (c *Context) JSONMap(data map[string]interface{}, err error) {
  159. code := http.StatusOK
  160. c.Error = err
  161. bcode := ecode.Cause(err)
  162. // TODO app allow 5xx?
  163. /*
  164. if bcode.Code() == -500 {
  165. code = http.StatusServiceUnavailable
  166. }
  167. */
  168. writeStatusCode(c.Writer, bcode.Code())
  169. data["code"] = bcode.Code()
  170. if _, ok := data["message"]; !ok {
  171. data["message"] = bcode.Message()
  172. }
  173. c.Render(code, render.MapJSON(data))
  174. }
  175. // XML serializes the given struct as XML into the response body.
  176. // It also sets the Content-Type as "application/xml".
  177. func (c *Context) XML(data interface{}, err error) {
  178. code := http.StatusOK
  179. c.Error = err
  180. bcode := ecode.Cause(err)
  181. // TODO app allow 5xx?
  182. /*
  183. if bcode.Code() == -500 {
  184. code = http.StatusServiceUnavailable
  185. }
  186. */
  187. writeStatusCode(c.Writer, bcode.Code())
  188. c.Render(code, render.XML{
  189. Code: bcode.Code(),
  190. Message: bcode.Message(),
  191. Data: data,
  192. })
  193. }
  194. // Protobuf serializes the given struct as PB into the response body.
  195. // It also sets the ContentType as "application/x-protobuf".
  196. func (c *Context) Protobuf(data proto.Message, err error) {
  197. var (
  198. bytes []byte
  199. )
  200. code := http.StatusOK
  201. c.Error = err
  202. bcode := ecode.Cause(err)
  203. any := new(types.Any)
  204. if data != nil {
  205. if bytes, err = proto.Marshal(data); err != nil {
  206. c.Error = errors.WithStack(err)
  207. return
  208. }
  209. any.TypeUrl = "type.googleapis.com/" + proto.MessageName(data)
  210. any.Value = bytes
  211. }
  212. writeStatusCode(c.Writer, bcode.Code())
  213. c.Render(code, render.PB{
  214. Code: int64(bcode.Code()),
  215. Message: bcode.Message(),
  216. Data: any,
  217. })
  218. }
  219. // Bytes writes some data into the body stream and updates the HTTP code.
  220. func (c *Context) Bytes(code int, contentType string, data ...[]byte) {
  221. c.Render(code, render.Data{
  222. ContentType: contentType,
  223. Data: data,
  224. })
  225. }
  226. // String writes the given string into the response body.
  227. func (c *Context) String(code int, format string, values ...interface{}) {
  228. c.Render(code, render.String{Format: format, Data: values})
  229. }
  230. // Redirect returns a HTTP redirect to the specific location.
  231. func (c *Context) Redirect(code int, location string) {
  232. c.Render(-1, render.Redirect{
  233. Code: code,
  234. Location: location,
  235. Request: c.Request,
  236. })
  237. }
  238. // BindWith bind req arg with parser.
  239. func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
  240. return c.mustBindWith(obj, b)
  241. }
  242. // Bind bind req arg with defult form binding.
  243. func (c *Context) Bind(obj interface{}) error {
  244. return c.mustBindWith(obj, binding.Form)
  245. }
  246. // mustBindWith binds the passed struct pointer using the specified binding engine.
  247. // It will abort the request with HTTP 400 if any error ocurrs.
  248. // See the binding package.
  249. func (c *Context) mustBindWith(obj interface{}, b binding.Binding) (err error) {
  250. if err = b.Bind(c.Request, obj); err != nil {
  251. c.Error = ecode.RequestErr
  252. c.Render(http.StatusOK, render.JSON{
  253. Code: ecode.RequestErr.Code(),
  254. Message: err.Error(),
  255. Data: nil,
  256. })
  257. c.Abort()
  258. }
  259. return
  260. }
  261. func writeStatusCode(w http.ResponseWriter, ecode int) {
  262. header := w.Header()
  263. header.Set("bili-status-code", strconv.FormatInt(int64(ecode), 10))
  264. }