context.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package engines
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "math"
  11. "mime/multipart"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "os"
  16. "strings"
  17. "sync"
  18. "time"
  19. "git.shuncheng.lu/bigthing/gocommon/pkg/net/engines/binding"
  20. "git.shuncheng.lu/bigthing/gocommon/pkg/net/engines/contrib/sse"
  21. "git.shuncheng.lu/bigthing/gocommon/pkg/net/engines/render"
  22. )
  23. // Content-Type MIME of the most common data formats.
  24. const (
  25. MIMEJSON = binding.MIMEJSON
  26. //MIMEHTML = binding.MIMEHTML
  27. MIMEXML = binding.MIMEXML
  28. MIMEXML2 = binding.MIMEXML2
  29. MIMEPlain = binding.MIMEPlain
  30. MIMEPOSTForm = binding.MIMEPOSTForm
  31. MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
  32. MIMEYAML = binding.MIMEYAML
  33. //BodyBytesKey = "_/gin/bodybyteskey"
  34. )
  35. const abortIndex int8 = math.MaxInt8 / 2
  36. // Context is the most important part of gin. It allows us to pass variables between middleware,
  37. // manage the flow, validate the JSON of a request and render a JSON response for example.
  38. type Context struct {
  39. writermem responseWriter
  40. Request *http.Request
  41. Writer ResponseWriter
  42. Params Params
  43. handlers HandlersChain
  44. index int8
  45. fullPath string
  46. engine *Engine
  47. // Keys is a key/value pair exclusively for the context of each request.
  48. Keys map[string]interface{}
  49. // This mutex protect Keys map
  50. mu sync.RWMutex
  51. // Errors is a list of errors attached to all the handlers/middlewares who used this context.
  52. Errors errorMsgs
  53. // Accepted defines a list of manually accepted formats for content negotiation.
  54. Accepted []string
  55. // queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()
  56. queryCache url.Values
  57. // formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,
  58. // or PUT body parameters.
  59. formCache url.Values
  60. }
  61. /************************************/
  62. /********** CONTEXT CREATION ********/
  63. /************************************/
  64. func (c *Context) reset() {
  65. c.Writer = &c.writermem
  66. c.Params = c.Params[0:0]
  67. c.handlers = nil
  68. c.index = -1
  69. c.fullPath = ""
  70. c.Keys = nil
  71. c.Errors = c.Errors[0:0]
  72. c.Accepted = nil
  73. c.queryCache = nil
  74. c.formCache = nil
  75. }
  76. // Copy returns a copy of the current context that can be safely used outside the request's scope.
  77. // This has to be used when the context has to be passed to a goroutine.
  78. func (c *Context) Copy() *Context {
  79. var cp = *c
  80. cp.writermem.ResponseWriter = nil
  81. cp.Writer = &cp.writermem
  82. cp.index = abortIndex
  83. cp.handlers = nil
  84. cp.Keys = map[string]interface{}{}
  85. for k, v := range c.Keys {
  86. cp.Keys[k] = v
  87. }
  88. paramCopy := make([]Param, len(cp.Params))
  89. copy(paramCopy, cp.Params)
  90. cp.Params = paramCopy
  91. return &cp
  92. }
  93. // HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()",
  94. // this function will return "main.handleGetUsers".
  95. func (c *Context) HandlerName() string {
  96. return nameOfFunction(c.handlers.Last())
  97. }
  98. // HandlerNames returns a list of all registered handlers for this context in descending order,
  99. // following the semantics of HandlerName()
  100. func (c *Context) HandlerNames() []string {
  101. hn := make([]string, 0, len(c.handlers))
  102. for _, val := range c.handlers {
  103. hn = append(hn, nameOfFunction(val))
  104. }
  105. return hn
  106. }
  107. // Handler returns the main handler.
  108. func (c *Context) Handler() HandlerFunc {
  109. return c.handlers.Last()
  110. }
  111. // FullPath returns a matched route full path. For not found routes
  112. // returns an empty string.
  113. // router.GET("/user/:id", func(c *gin.Context) {
  114. // c.FullPath() == "/user/:id" // true
  115. // })
  116. func (c *Context) FullPath() string {
  117. return c.fullPath
  118. }
  119. /************************************/
  120. /*********** FLOW CONTROL ***********/
  121. /************************************/
  122. // Next should be used only inside middleware.
  123. // It executes the pending handlers in the chain inside the calling handler.
  124. // See example in GitHub.
  125. func (c *Context) Next() {
  126. c.index++
  127. for c.index < int8(len(c.handlers)) {
  128. c.handlers[c.index](c)
  129. c.index++
  130. }
  131. }
  132. // IsAborted returns true if the current context was aborted.
  133. func (c *Context) IsAborted() bool {
  134. return c.index >= abortIndex
  135. }
  136. // Abort prevents pending handlers from being called. Note that this will not stop the current handler.
  137. // Let's say you have an authorization middleware that validates that the current request is authorized.
  138. // If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
  139. // for this request are not called.
  140. func (c *Context) Abort() {
  141. c.index = abortIndex
  142. }
  143. // AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
  144. // For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
  145. func (c *Context) AbortWithStatus(code int) {
  146. c.Status(code)
  147. c.Writer.WriteHeaderNow()
  148. c.Abort()
  149. }
  150. // AbortWithStatusJSON calls `Abort()` and then `JSON` internally.
  151. // This method stops the chain, writes the status code and return a JSON body.
  152. // It also sets the Content-Type as "application/json".
  153. func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {
  154. c.Abort()
  155. c.JSON(code, jsonObj)
  156. }
  157. // AbortWithError calls `AbortWithStatus()` and `Error()` internally.
  158. // This method stops the chain, writes the status code and pushes the specified error to `c.Errors`.
  159. // See Context.Error() for more details.
  160. func (c *Context) AbortWithError(code int, err error) *Error {
  161. c.AbortWithStatus(code)
  162. return c.Error(err)
  163. }
  164. /************************************/
  165. /********* ERROR MANAGEMENT *********/
  166. /************************************/
  167. // Error attaches an error to the current context. The error is pushed to a list of errors.
  168. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  169. // A middleware can be used to collect all the errors and push them to a database together,
  170. // print a log, or append it in the HTTP response.
  171. // Error will panic if err is nil.
  172. func (c *Context) Error(err error) *Error {
  173. if err == nil {
  174. panic("err is nil")
  175. }
  176. parsedError, ok := err.(*Error)
  177. if !ok {
  178. parsedError = &Error{
  179. Err: err,
  180. Type: ErrorTypePrivate,
  181. }
  182. }
  183. c.Errors = append(c.Errors, parsedError)
  184. return parsedError
  185. }
  186. /************************************/
  187. /******** METADATA MANAGEMENT********/
  188. /************************************/
  189. // Set is used to store a new key/value pair exclusively for this context.
  190. // It also lazy initializes c.Keys if it was not used previously.
  191. func (c *Context) Set(key string, value interface{}) {
  192. c.mu.Lock()
  193. if c.Keys == nil {
  194. c.Keys = make(map[string]interface{})
  195. }
  196. c.Keys[key] = value
  197. c.mu.Unlock()
  198. }
  199. // Get returns the value for the given key, ie: (value, true).
  200. // If the value does not exists it returns (nil, false)
  201. func (c *Context) Get(key string) (interface{}, bool) {
  202. c.mu.RLock()
  203. value, exists := c.Keys[key]
  204. c.mu.RUnlock()
  205. return value, exists
  206. }
  207. // MustGet returns the value for the given key if it exists, otherwise it panics.
  208. //func (c *Context) MustGet(key string) interface{} {
  209. // if value, exists := c.Get(key); exists {
  210. // return value
  211. // }
  212. // panic("Key \"" + key + "\" does not exist")
  213. //}
  214. // GetString returns the value associated with the key as a string.
  215. func (c *Context) GetString(key string) (s string) {
  216. if val, ok := c.Get(key); ok && val != nil {
  217. s, _ = val.(string)
  218. }
  219. return
  220. }
  221. // GetBool returns the value associated with the key as a boolean.
  222. func (c *Context) GetBool(key string) (b bool) {
  223. if val, ok := c.Get(key); ok && val != nil {
  224. b, _ = val.(bool)
  225. }
  226. return
  227. }
  228. // GetInt returns the value associated with the key as an integer.
  229. func (c *Context) GetInt(key string) (i int) {
  230. if val, ok := c.Get(key); ok && val != nil {
  231. i, _ = val.(int)
  232. }
  233. return
  234. }
  235. // GetInt64 returns the value associated with the key as an integer.
  236. func (c *Context) GetInt64(key string) (i64 int64) {
  237. if val, ok := c.Get(key); ok && val != nil {
  238. i64, _ = val.(int64)
  239. }
  240. return
  241. }
  242. // GetFloat64 returns the value associated with the key as a float64.
  243. func (c *Context) GetFloat64(key string) (f64 float64) {
  244. if val, ok := c.Get(key); ok && val != nil {
  245. f64, _ = val.(float64)
  246. }
  247. return
  248. }
  249. // GetTime returns the value associated with the key as time.
  250. func (c *Context) GetTime(key string) (t time.Time) {
  251. if val, ok := c.Get(key); ok && val != nil {
  252. t, _ = val.(time.Time)
  253. }
  254. return
  255. }
  256. // GetDuration returns the value associated with the key as a duration.
  257. func (c *Context) GetDuration(key string) (d time.Duration) {
  258. if val, ok := c.Get(key); ok && val != nil {
  259. d, _ = val.(time.Duration)
  260. }
  261. return
  262. }
  263. // GetStringSlice returns the value associated with the key as a slice of strings.
  264. func (c *Context) GetStringSlice(key string) (ss []string) {
  265. if val, ok := c.Get(key); ok && val != nil {
  266. ss, _ = val.([]string)
  267. }
  268. return
  269. }
  270. // GetStringMap returns the value associated with the key as a map of interfaces.
  271. func (c *Context) GetStringMap(key string) (sm map[string]interface{}) {
  272. if val, ok := c.Get(key); ok && val != nil {
  273. sm, _ = val.(map[string]interface{})
  274. }
  275. return
  276. }
  277. // GetStringMapString returns the value associated with the key as a map of strings.
  278. func (c *Context) GetStringMapString(key string) (sms map[string]string) {
  279. if val, ok := c.Get(key); ok && val != nil {
  280. sms, _ = val.(map[string]string)
  281. }
  282. return
  283. }
  284. // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
  285. func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) {
  286. if val, ok := c.Get(key); ok && val != nil {
  287. smss, _ = val.(map[string][]string)
  288. }
  289. return
  290. }
  291. /************************************/
  292. /************ INPUT DATA ************/
  293. /************************************/
  294. // Param returns the value of the URL param.
  295. // It is a shortcut for c.Params.ByName(key)
  296. // router.GET("/user/:id", func(c *gin.Context) {
  297. // // a GET request to /user/john
  298. // id := c.Param("id") // id == "john"
  299. // })
  300. func (c *Context) Param(key string) string {
  301. return c.Params.ByName(key)
  302. }
  303. // Query returns the keyed url query value if it exists,
  304. // otherwise it returns an empty string `("")`.
  305. // It is shortcut for `c.Request.URL.Query().Get(key)`
  306. // GET /path?id=1234&name=Manu&value=
  307. // c.Query("id") == "1234"
  308. // c.Query("name") == "Manu"
  309. // c.Query("value") == ""
  310. // c.Query("wtf") == ""
  311. func (c *Context) Query(key string) string {
  312. value, _ := c.GetQuery(key)
  313. return value
  314. }
  315. // DefaultQuery returns the keyed url query value if it exists,
  316. // otherwise it returns the specified defaultValue string.
  317. // See: Query() and GetQuery() for further information.
  318. // GET /?name=Manu&lastname=
  319. // c.DefaultQuery("name", "unknown") == "Manu"
  320. // c.DefaultQuery("id", "none") == "none"
  321. // c.DefaultQuery("lastname", "none") == ""
  322. func (c *Context) DefaultQuery(key, defaultValue string) string {
  323. if value, ok := c.GetQuery(key); ok {
  324. return value
  325. }
  326. return defaultValue
  327. }
  328. // GetQuery is like Query(), it returns the keyed url query value
  329. // if it exists `(value, true)` (even when the value is an empty string),
  330. // otherwise it returns `("", false)`.
  331. // It is shortcut for `c.Request.URL.Query().Get(key)`
  332. // GET /?name=Manu&lastname=
  333. // ("Manu", true) == c.GetQuery("name")
  334. // ("", false) == c.GetQuery("id")
  335. // ("", true) == c.GetQuery("lastname")
  336. func (c *Context) GetQuery(key string) (string, bool) {
  337. if values, ok := c.GetQueryArray(key); ok {
  338. return values[0], ok
  339. }
  340. return "", false
  341. }
  342. // QueryArray returns a slice of strings for a given query key.
  343. // The length of the slice depends on the number of params with the given key.
  344. func (c *Context) QueryArray(key string) []string {
  345. values, _ := c.GetQueryArray(key)
  346. return values
  347. }
  348. func (c *Context) getQueryCache() {
  349. if c.queryCache == nil {
  350. c.queryCache = c.Request.URL.Query()
  351. }
  352. }
  353. // GetQueryArray returns a slice of strings for a given query key, plus
  354. // a boolean value whether at least one value exists for the given key.
  355. func (c *Context) GetQueryArray(key string) ([]string, bool) {
  356. c.getQueryCache()
  357. if values, ok := c.queryCache[key]; ok && len(values) > 0 {
  358. return values, true
  359. }
  360. return []string{}, false
  361. }
  362. // QueryMap returns a map for a given query key.
  363. func (c *Context) QueryMap(key string) map[string]string {
  364. dicts, _ := c.GetQueryMap(key)
  365. return dicts
  366. }
  367. // GetQueryMap returns a map for a given query key, plus a boolean value
  368. // whether at least one value exists for the given key.
  369. func (c *Context) GetQueryMap(key string) (map[string]string, bool) {
  370. c.getQueryCache()
  371. return c.get(c.queryCache, key)
  372. }
  373. // PostForm returns the specified key from a POST urlencoded form or multipart form
  374. // when it exists, otherwise it returns an empty string `("")`.
  375. func (c *Context) PostForm(key string) string {
  376. value, _ := c.GetPostForm(key)
  377. return value
  378. }
  379. // DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
  380. // when it exists, otherwise it returns the specified defaultValue string.
  381. // See: PostForm() and GetPostForm() for further information.
  382. func (c *Context) DefaultPostForm(key, defaultValue string) string {
  383. if value, ok := c.GetPostForm(key); ok {
  384. return value
  385. }
  386. return defaultValue
  387. }
  388. // GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
  389. // form or multipart form when it exists `(value, true)` (even when the value is an empty string),
  390. // otherwise it returns ("", false).
  391. // For example, during a PATCH request to update the user's email:
  392. // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
  393. // email= --> ("", true) := GetPostForm("email") // set email to ""
  394. // --> ("", false) := GetPostForm("email") // do nothing with email
  395. func (c *Context) GetPostForm(key string) (string, bool) {
  396. if values, ok := c.GetPostFormArray(key); ok {
  397. return values[0], ok
  398. }
  399. return "", false
  400. }
  401. // PostFormArray returns a slice of strings for a given form key.
  402. // The length of the slice depends on the number of params with the given key.
  403. func (c *Context) PostFormArray(key string) []string {
  404. values, _ := c.GetPostFormArray(key)
  405. return values
  406. }
  407. func (c *Context) getFormCache() {
  408. if c.formCache == nil {
  409. c.formCache = make(url.Values)
  410. req := c.Request
  411. if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
  412. if err != http.ErrNotMultipart {
  413. debugPrint("error on parse multipart form array: %v", err)
  414. }
  415. }
  416. c.formCache = req.PostForm
  417. }
  418. }
  419. // GetPostFormArray returns a slice of strings for a given form key, plus
  420. // a boolean value whether at least one value exists for the given key.
  421. func (c *Context) GetPostFormArray(key string) ([]string, bool) {
  422. c.getFormCache()
  423. if values := c.formCache[key]; len(values) > 0 {
  424. return values, true
  425. }
  426. return []string{}, false
  427. }
  428. // PostFormMap returns a map for a given form key.
  429. func (c *Context) PostFormMap(key string) map[string]string {
  430. dicts, _ := c.GetPostFormMap(key)
  431. return dicts
  432. }
  433. // GetPostFormMap returns a map for a given form key, plus a boolean value
  434. // whether at least one value exists for the given key.
  435. func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {
  436. c.getFormCache()
  437. return c.get(c.formCache, key)
  438. }
  439. // get is an internal method and returns a map which satisfy conditions.
  440. func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) {
  441. dicts := make(map[string]string)
  442. exist := false
  443. for k, v := range m {
  444. if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {
  445. if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {
  446. exist = true
  447. dicts[k[i+1:][:j]] = v[0]
  448. }
  449. }
  450. }
  451. return dicts, exist
  452. }
  453. // FormFile returns the first file for the provided form key.
  454. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
  455. if c.Request.MultipartForm == nil {
  456. if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
  457. return nil, err
  458. }
  459. }
  460. f, fh, err := c.Request.FormFile(name)
  461. if err != nil {
  462. return nil, err
  463. }
  464. f.Close()
  465. return fh, err
  466. }
  467. // MultipartForm is the parsed multipart form, including file uploads.
  468. func (c *Context) MultipartForm() (*multipart.Form, error) {
  469. err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
  470. return c.Request.MultipartForm, err
  471. }
  472. // SaveUploadedFile uploads the form file to specific dst.
  473. func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
  474. src, err := file.Open()
  475. if err != nil {
  476. return err
  477. }
  478. defer src.Close()
  479. out, err := os.Create(dst)
  480. if err != nil {
  481. return err
  482. }
  483. defer out.Close()
  484. _, err = io.Copy(out, src)
  485. return err
  486. }
  487. // Bind checks the Content-Type to select a binding engine automatically,
  488. // Depending the "Content-Type" header different bindings are used:
  489. // "application/json" --> JSON binding
  490. // "application/xml" --> XML binding
  491. // otherwise --> returns an error.
  492. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
  493. // It decodes the json payload into the struct specified as a pointer.
  494. // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
  495. func (c *Context) Bind(obj interface{}) error {
  496. b := binding.Default(c.Request.Method, c.ContentType())
  497. return c.MustBindWith(obj, b)
  498. }
  499. // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
  500. func (c *Context) BindJSON(obj interface{}) error {
  501. return c.MustBindWith(obj, binding.JSON)
  502. }
  503. // BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).
  504. func (c *Context) BindXML(obj interface{}) error {
  505. return c.MustBindWith(obj, binding.XML)
  506. }
  507. // BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).
  508. func (c *Context) BindQuery(obj interface{}) error {
  509. return c.MustBindWith(obj, binding.Query)
  510. }
  511. // BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML).
  512. func (c *Context) BindYAML(obj interface{}) error {
  513. return c.MustBindWith(obj, binding.YAML)
  514. }
  515. // BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).
  516. func (c *Context) BindHeader(obj interface{}) error {
  517. return c.MustBindWith(obj, binding.Header)
  518. }
  519. // BindUri binds the passed struct pointer using binding.Uri.
  520. // It will abort the request with HTTP 400 if any error occurs.
  521. func (c *Context) BindUri(obj interface{}) error {
  522. if err := c.ShouldBindUri(obj); err != nil {
  523. c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
  524. return err
  525. }
  526. return nil
  527. }
  528. // MustBindWith binds the passed struct pointer using the specified binding engine.
  529. // It will abort the request with HTTP 400 if any error occurs.
  530. // See the binding package.
  531. func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {
  532. if err := c.ShouldBindWith(obj, b); err != nil {
  533. c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
  534. return err
  535. }
  536. return nil
  537. }
  538. // ShouldBind checks the Content-Type to select a binding engine automatically,
  539. // Depending the "Content-Type" header different bindings are used:
  540. // "application/json" --> JSON binding
  541. // "application/xml" --> XML binding
  542. // otherwise --> returns an error
  543. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
  544. // It decodes the json payload into the struct specified as a pointer.
  545. // Like c.Bind() but this method does not set the response status code to 400 and abort if the json is not valid.
  546. func (c *Context) ShouldBind(obj interface{}) error {
  547. b := binding.Default(c.Request.Method, c.ContentType())
  548. return c.ShouldBindWith(obj, b)
  549. }
  550. // ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
  551. func (c *Context) ShouldBindJSON(obj interface{}) error {
  552. return c.ShouldBindWith(obj, binding.JSON)
  553. }
  554. // ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).
  555. func (c *Context) ShouldBindXML(obj interface{}) error {
  556. return c.ShouldBindWith(obj, binding.XML)
  557. }
  558. // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).
  559. func (c *Context) ShouldBindQuery(obj interface{}) error {
  560. return c.ShouldBindWith(obj, binding.Query)
  561. }
  562. // ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).
  563. func (c *Context) ShouldBindYAML(obj interface{}) error {
  564. return c.ShouldBindWith(obj, binding.YAML)
  565. }
  566. // ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).
  567. func (c *Context) ShouldBindHeader(obj interface{}) error {
  568. return c.ShouldBindWith(obj, binding.Header)
  569. }
  570. // ShouldBindUri binds the passed struct pointer using the specified binding engine.
  571. func (c *Context) ShouldBindUri(obj interface{}) error {
  572. m := make(map[string][]string)
  573. for _, v := range c.Params {
  574. m[v.Key] = []string{v.Value}
  575. }
  576. return binding.Uri.BindUri(m, obj)
  577. }
  578. // ShouldBindWith binds the passed struct pointer using the specified binding engine.
  579. // See the binding package.
  580. func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
  581. return b.Bind(c.Request, obj)
  582. }
  583. // ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
  584. // body into the context, and reuse when it is called again.
  585. //
  586. // NOTE: This method reads the body before binding. So you should use
  587. // ShouldBindWith for better performance if you need to call only once.
  588. //func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) {
  589. // var body []byte
  590. // if cb, ok := c.Get(BodyBytesKey); ok {
  591. // if cbb, ok := cb.([]byte); ok {
  592. // body = cbb
  593. // }
  594. // }
  595. // if body == nil {
  596. // body, err = ioutil.ReadAll(c.Request.Body)
  597. // if err != nil {
  598. // return err
  599. // }
  600. // c.Set(BodyBytesKey, body)
  601. // }
  602. // return bb.BindBody(body, obj)
  603. //}
  604. // ClientIP implements a best effort algorithm to return the real client IP, it parses
  605. // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
  606. // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
  607. func (c *Context) ClientIP() string {
  608. if c.engine.ForwardedByClientIP {
  609. clientIP := c.requestHeader("X-Forwarded-For")
  610. clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
  611. if clientIP == "" {
  612. clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
  613. }
  614. if clientIP != "" {
  615. return clientIP
  616. }
  617. }
  618. if c.engine.AppEngine {
  619. if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {
  620. return addr
  621. }
  622. }
  623. if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
  624. return ip
  625. }
  626. return ""
  627. }
  628. // ContentType returns the Content-Type header of the request.
  629. func (c *Context) ContentType() string {
  630. return filterFlags(c.requestHeader("Content-Type"))
  631. }
  632. // IsWebsocket returns true if the request headers indicate that a websocket
  633. // handshake is being initiated by the client.
  634. func (c *Context) IsWebsocket() bool {
  635. if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
  636. strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {
  637. return true
  638. }
  639. return false
  640. }
  641. func (c *Context) requestHeader(key string) string {
  642. return c.Request.Header.Get(key)
  643. }
  644. /************************************/
  645. /******** RESPONSE RENDERING ********/
  646. /************************************/
  647. // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
  648. func bodyAllowedForStatus(status int) bool {
  649. switch {
  650. case status >= 100 && status <= 199:
  651. return false
  652. case status == http.StatusNoContent:
  653. return false
  654. case status == http.StatusNotModified:
  655. return false
  656. }
  657. return true
  658. }
  659. // Status sets the HTTP response code.
  660. func (c *Context) Status(code int) {
  661. c.Writer.WriteHeader(code)
  662. }
  663. // Header is a intelligent shortcut for c.Writer.Header().Set(key, value).
  664. // It writes a header in the response.
  665. // If value == "", this method removes the header `c.Writer.Header().Del(key)`
  666. func (c *Context) Header(key, value string) {
  667. if value == "" {
  668. c.Writer.Header().Del(key)
  669. return
  670. }
  671. c.Writer.Header().Set(key, value)
  672. }
  673. // GetHeader returns value from request headers.
  674. func (c *Context) GetHeader(key string) string {
  675. return c.requestHeader(key)
  676. }
  677. // GetRawData return stream data.
  678. func (c *Context) GetRawData() ([]byte, error) {
  679. return ioutil.ReadAll(c.Request.Body)
  680. }
  681. // SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
  682. // The provided cookie must have a valid Name. Invalid cookies may be
  683. // silently dropped.
  684. func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
  685. if path == "" {
  686. path = "/"
  687. }
  688. http.SetCookie(c.Writer, &http.Cookie{
  689. Name: name,
  690. Value: url.QueryEscape(value),
  691. MaxAge: maxAge,
  692. Path: path,
  693. Domain: domain,
  694. Secure: secure,
  695. HttpOnly: httpOnly,
  696. })
  697. }
  698. // Cookie returns the named cookie provided in the request or
  699. // ErrNoCookie if not found. And return the named cookie is unescaped.
  700. // If multiple cookies match the given name, only one cookie will
  701. // be returned.
  702. func (c *Context) Cookie(name string) (string, error) {
  703. cookie, err := c.Request.Cookie(name)
  704. if err != nil {
  705. return "", err
  706. }
  707. val, _ := url.QueryUnescape(cookie.Value)
  708. return val, nil
  709. }
  710. // Render writes the response headers and calls render.Render to render data.
  711. func (c *Context) RenderWithError(code int, r render.Render) error {
  712. c.Status(code)
  713. if !bodyAllowedForStatus(code) {
  714. r.WriteContentType(c.Writer)
  715. c.Writer.WriteHeaderNow()
  716. return nil
  717. }
  718. if err := r.Render(c.Writer); err != nil {
  719. return err
  720. }
  721. return nil
  722. }
  723. // Render writes the response headers and calls render.Render to render data.
  724. func (c *Context) Render(code int, r render.Render) {
  725. c.Status(code)
  726. if !bodyAllowedForStatus(code) {
  727. r.WriteContentType(c.Writer)
  728. c.Writer.WriteHeaderNow()
  729. return
  730. }
  731. if err := r.Render(c.Writer); err != nil {
  732. panic(err)
  733. }
  734. }
  735. // HTML renders the HTTP template specified by its file name.
  736. // It also updates the HTTP code and sets the Content-Type as "text/html".
  737. // See http://golang.org/doc/articles/wiki/
  738. //func (c *Context) HTML(code int, name string, obj interface{}) {
  739. // instance := c.engine.HTMLRender.Instance(name, obj)
  740. // c.Render(code, instance)
  741. //}
  742. // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
  743. // It also sets the Content-Type as "application/json".
  744. // WARNING: we recommend to use this only for development purposes since printing pretty JSON is
  745. // more CPU and bandwidth consuming. Use Context.JSON() instead.
  746. func (c *Context) IndentedJSON(code int, obj interface{}) {
  747. c.Render(code, render.IndentedJSON{Data: obj})
  748. }
  749. // SecureJSON serializes the given struct as Secure JSON into the response body.
  750. // Default prepends "while(1)," to response body if the given struct is array values.
  751. // It also sets the Content-Type as "application/json".
  752. func (c *Context) SecureJSON(code int, obj interface{}) {
  753. c.Render(code, render.SecureJSON{Prefix: c.engine.secureJsonPrefix, Data: obj})
  754. }
  755. // JSONP serializes the given struct as JSON into the response body.
  756. // It add padding to response body to request data from a server residing in a different domain than the client.
  757. // It also sets the Content-Type as "application/javascript".
  758. func (c *Context) JSONP(code int, obj interface{}) error {
  759. callback := c.DefaultQuery("callback", "")
  760. if callback == "" {
  761. return c.RenderWithError(code, render.JSON{Data: obj})
  762. }
  763. return c.RenderWithError(code, render.JsonpJSON{Callback: callback, Data: obj})
  764. }
  765. // JSON serializes the given struct as JSON into the response body.
  766. // It also sets the Content-Type as "application/json".
  767. func (c *Context) JSON(code int, obj interface{}) error {
  768. return c.RenderWithError(code, render.JSON{Data: obj})
  769. }
  770. // AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.
  771. // It also sets the Content-Type as "application/json".
  772. func (c *Context) AsciiJSON(code int, obj interface{}) {
  773. c.Render(code, render.AsciiJSON{Data: obj})
  774. }
  775. // PureJSON serializes the given struct as JSON into the response body.
  776. // PureJSON, unlike JSON, does not replace special html characters with their unicode entities.
  777. func (c *Context) PureJSON(code int, obj interface{}) {
  778. c.Render(code, render.PureJSON{Data: obj})
  779. }
  780. // XML serializes the given struct as XML into the response body.
  781. // It also sets the Content-Type as "application/xml".
  782. func (c *Context) XML(code int, obj interface{}) {
  783. c.Render(code, render.XML{Data: obj})
  784. }
  785. // YAML serializes the given struct as YAML into the response body.
  786. func (c *Context) YAML(code int, obj interface{}) {
  787. c.Render(code, render.YAML{Data: obj})
  788. }
  789. // ProtoBuf serializes the given struct as ProtoBuf into the response body.
  790. func (c *Context) ProtoBuf(code int, obj interface{}) {
  791. c.Render(code, render.ProtoBuf{Data: obj})
  792. }
  793. // String writes the given string into the response body.
  794. func (c *Context) String(code int, format string, values ...interface{}) {
  795. c.Render(code, render.String{Format: format, Data: values})
  796. }
  797. // Redirect returns a HTTP redirect to the specific location.
  798. func (c *Context) Redirect(code int, location string) {
  799. c.Render(-1, render.Redirect{
  800. Code: code,
  801. Location: location,
  802. Request: c.Request,
  803. })
  804. }
  805. // Data writes some data into the body stream and updates the HTTP code.
  806. func (c *Context) Data(code int, contentType string, data []byte) {
  807. c.Render(code, render.Data{
  808. ContentType: contentType,
  809. Data: data,
  810. })
  811. }
  812. // DataFromReader writes the specified reader into the body stream and updates the HTTP code.
  813. func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {
  814. c.Render(code, render.Reader{
  815. Headers: extraHeaders,
  816. ContentType: contentType,
  817. ContentLength: contentLength,
  818. Reader: reader,
  819. })
  820. }
  821. // File writes the specified file into the body stream in a efficient way.
  822. func (c *Context) File(filepath string) {
  823. http.ServeFile(c.Writer, c.Request, filepath)
  824. }
  825. // FileAttachment writes the specified file into the body stream in an efficient way
  826. // On the client side, the file will typically be downloaded with the given filename
  827. func (c *Context) FileAttachment(filepath, filename string) {
  828. c.Writer.Header().Set("content-disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  829. http.ServeFile(c.Writer, c.Request, filepath)
  830. }
  831. // SSEvent writes a Server-Sent Event into the body stream.
  832. func (c *Context) SSEvent(name string, message interface{}) {
  833. c.Render(-1, sse.Event{
  834. Event: name,
  835. Data: message,
  836. })
  837. }
  838. // Stream sends a streaming response and returns a boolean
  839. // indicates "Is client disconnected in middle of stream"
  840. func (c *Context) Stream(step func(w io.Writer) bool) bool {
  841. w := c.Writer
  842. clientGone := w.CloseNotify()
  843. for {
  844. select {
  845. case <-clientGone:
  846. return true
  847. default:
  848. keepOpen := step(w)
  849. w.Flush()
  850. if !keepOpen {
  851. return false
  852. }
  853. }
  854. }
  855. }
  856. /************************************/
  857. /******** CONTENT NEGOTIATION *******/
  858. /************************************/
  859. // Negotiate contains all negotiations data.
  860. type Negotiate struct {
  861. Offered []string
  862. HTMLName string
  863. HTMLData interface{}
  864. JSONData interface{}
  865. XMLData interface{}
  866. Data interface{}
  867. }
  868. // Negotiate calls different Render according acceptable Accept format.
  869. func (c *Context) Negotiate(code int, config Negotiate) {
  870. switch c.NegotiateFormat(config.Offered...) {
  871. case binding.MIMEJSON:
  872. data := chooseData(config.JSONData, config.Data)
  873. c.JSON(code, data)
  874. //case binding.MIMEHTML:
  875. // data := chooseData(config.HTMLData, config.Data)
  876. // c.HTML(code, config.HTMLName, data)
  877. case binding.MIMEXML:
  878. data := chooseData(config.XMLData, config.Data)
  879. c.XML(code, data)
  880. default:
  881. c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck
  882. }
  883. }
  884. // NegotiateFormat returns an acceptable Accept format.
  885. func (c *Context) NegotiateFormat(offered ...string) string {
  886. assert1(len(offered) > 0, "you must provide at least one offer")
  887. if c.Accepted == nil {
  888. c.Accepted = parseAccept(c.requestHeader("Accept"))
  889. }
  890. if len(c.Accepted) == 0 {
  891. return offered[0]
  892. }
  893. for _, accepted := range c.Accepted {
  894. for _, offert := range offered {
  895. // According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,
  896. // therefore we can just iterate over the string without casting it into []rune
  897. i := 0
  898. for ; i < len(accepted); i++ {
  899. if accepted[i] == '*' || offert[i] == '*' {
  900. return offert
  901. }
  902. if accepted[i] != offert[i] {
  903. break
  904. }
  905. }
  906. if i == len(accepted) {
  907. return offert
  908. }
  909. }
  910. }
  911. return ""
  912. }
  913. // SetAccepted sets Accept header data.
  914. func (c *Context) SetAccepted(formats ...string) {
  915. c.Accepted = formats
  916. }
  917. /************************************/
  918. /***** GOLANG.ORG/X/NET/CONTEXT *****/
  919. /************************************/
  920. // Deadline returns the time when work done on behalf of this context
  921. // should be canceled. Deadline returns ok==false when no deadline is
  922. // set. Successive calls to Deadline return the same results.
  923. func (c *Context) Deadline() (deadline time.Time, ok bool) {
  924. return
  925. }
  926. // Done returns a channel that's closed when work done on behalf of this
  927. // context should be canceled. Done may return nil if this context can
  928. // never be canceled. Successive calls to Done return the same value.
  929. func (c *Context) Done() <-chan struct{} {
  930. return nil
  931. }
  932. // Err returns a non-nil error value after Done is closed,
  933. // successive calls to Err return the same error.
  934. // If Done is not yet closed, Err returns nil.
  935. // If Done is closed, Err returns a non-nil error explaining why:
  936. // Canceled if the context was canceled
  937. // or DeadlineExceeded if the context's deadline passed.
  938. func (c *Context) Err() error {
  939. return nil
  940. }
  941. // Value returns the value associated with this context for key, or nil
  942. // if no value is associated with key. Successive calls to Value with
  943. // the same key returns the same result.
  944. func (c *Context) Value(key interface{}) interface{} {
  945. if key == 0 {
  946. return c.Request
  947. }
  948. if keyAsString, ok := key.(string); ok {
  949. val, _ := c.Get(keyAsString)
  950. return val
  951. }
  952. return nil
  953. }