gin.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package gin
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "errors"
  7. "fmt"
  8. "github.com/gin-gonic/gin/binding"
  9. "github.com/julienschmidt/httprouter"
  10. "html/template"
  11. "log"
  12. "math"
  13. "net/http"
  14. "path"
  15. "sync"
  16. )
  17. const (
  18. AbortIndex = math.MaxInt8 / 2
  19. MIMEJSON = "application/json"
  20. MIMEHTML = "text/html"
  21. MIMEXML = "application/xml"
  22. MIMEXML2 = "text/xml"
  23. MIMEPlain = "text/plain"
  24. MIMEPOSTForm = "application/x-www-form-urlencoded"
  25. )
  26. const (
  27. ErrorTypeInternal = 1 << iota
  28. ErrorTypeExternal = 1 << iota
  29. ErrorTypeAll = 0xffffffff
  30. )
  31. type (
  32. HandlerFunc func(*Context)
  33. H map[string]interface{}
  34. // Used internally to collect errors that occurred during an http request.
  35. errorMsg struct {
  36. Err string `json:"error"`
  37. Type uint32 `json:"-"`
  38. Meta interface{} `json:"meta"`
  39. }
  40. errorMsgs []errorMsg
  41. // Context is the most important part of gin. It allows us to pass variables between middleware,
  42. // manage the flow, validate the JSON of a request and render a JSON response for example.
  43. Context struct {
  44. Req *http.Request
  45. Writer ResponseWriter
  46. Keys map[string]interface{}
  47. Errors errorMsgs
  48. Params httprouter.Params
  49. Engine *Engine
  50. handlers []HandlerFunc
  51. index int8
  52. }
  53. // Used internally to configure router, a RouterGroup is associated with a prefix
  54. // and an array of handlers (middlewares)
  55. RouterGroup struct {
  56. Handlers []HandlerFunc
  57. prefix string
  58. parent *RouterGroup
  59. engine *Engine
  60. }
  61. // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.
  62. Engine struct {
  63. *RouterGroup
  64. HTMLTemplates *template.Template
  65. cache sync.Pool
  66. handlers404 []HandlerFunc
  67. router *httprouter.Router
  68. }
  69. )
  70. // Allows type H to be used with xml.Marshal
  71. func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  72. start.Name = xml.Name{"", "map"}
  73. if err := e.EncodeToken(start); err != nil {
  74. return err
  75. }
  76. for key, value := range h {
  77. elem := xml.StartElement{
  78. xml.Name{"", key},
  79. []xml.Attr{},
  80. }
  81. if err := e.EncodeElement(value, elem); err != nil {
  82. return err
  83. }
  84. }
  85. if err := e.EncodeToken(xml.EndElement{start.Name}); err != nil {
  86. return err
  87. }
  88. return nil
  89. }
  90. func (a errorMsgs) ByType(typ uint32) errorMsgs {
  91. if len(a) == 0 {
  92. return a
  93. }
  94. result := make(errorMsgs, 0, len(a))
  95. for _, msg := range a {
  96. if msg.Type&typ > 0 {
  97. result = append(result, msg)
  98. }
  99. }
  100. return result
  101. }
  102. func (a errorMsgs) String() string {
  103. var buffer bytes.Buffer
  104. for i, msg := range a {
  105. text := fmt.Sprintf("Error #%02d: %s \n Meta: %v\n", (i + 1), msg.Err, msg.Meta)
  106. buffer.WriteString(text)
  107. }
  108. return buffer.String()
  109. }
  110. // Returns a new blank Engine instance without any middleware attached.
  111. // The most basic configuration
  112. func New() *Engine {
  113. engine := &Engine{}
  114. engine.RouterGroup = &RouterGroup{nil, "/", nil, engine}
  115. engine.router = httprouter.New()
  116. engine.router.NotFound = engine.handle404
  117. engine.cache.New = func() interface{} {
  118. return &Context{Engine: engine, Writer: &responseWriter{}}
  119. }
  120. return engine
  121. }
  122. // Returns a Engine instance with the Logger and Recovery already attached.
  123. func Default() *Engine {
  124. engine := New()
  125. engine.Use(Recovery(), Logger())
  126. return engine
  127. }
  128. func (engine *Engine) LoadHTMLTemplates(pattern string) {
  129. engine.HTMLTemplates = template.Must(template.ParseGlob(pattern))
  130. }
  131. // Adds handlers for NotFound. It return a 404 code by default.
  132. func (engine *Engine) NotFound404(handlers ...HandlerFunc) {
  133. engine.handlers404 = handlers
  134. }
  135. func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {
  136. handlers := engine.combineHandlers(engine.handlers404)
  137. c := engine.createContext(w, req, nil, handlers)
  138. c.Writer.setStatus(404)
  139. c.Next()
  140. if !c.Writer.Written() {
  141. c.Data(404, MIMEPlain, []byte("404 page not found"))
  142. }
  143. engine.cache.Put(c)
  144. }
  145. // ServeHTTP makes the router implement the http.Handler interface.
  146. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  147. engine.router.ServeHTTP(w, req)
  148. }
  149. func (engine *Engine) Run(addr string) {
  150. if err := http.ListenAndServe(addr, engine); err != nil {
  151. panic(err)
  152. }
  153. }
  154. func (engine *Engine) RunTLS(addr string, cert string, key string) {
  155. if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {
  156. panic(err)
  157. }
  158. }
  159. /************************************/
  160. /********** ROUTES GROUPING *********/
  161. /************************************/
  162. func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
  163. c := engine.cache.Get().(*Context)
  164. c.Writer.reset(w)
  165. c.Req = req
  166. c.Params = params
  167. c.handlers = handlers
  168. c.Keys = nil
  169. c.index = -1
  170. return c
  171. }
  172. // Adds middlewares to the group, see example code in github.
  173. func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
  174. group.Handlers = append(group.Handlers, middlewares...)
  175. }
  176. // Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
  177. // For example, all the routes that use a common middlware for authorization could be grouped.
  178. func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {
  179. prefix := path.Join(group.prefix, component)
  180. return &RouterGroup{
  181. Handlers: group.combineHandlers(handlers),
  182. parent: group,
  183. prefix: prefix,
  184. engine: group.engine,
  185. }
  186. }
  187. // Handle registers a new request handle and middlewares with the given path and method.
  188. // The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.
  189. // See the example code in github.
  190. //
  191. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  192. // functions can be used.
  193. //
  194. // This function is intended for bulk loading and to allow the usage of less
  195. // frequently used, non-standardized or custom methods (e.g. for internal
  196. // communication with a proxy).
  197. func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
  198. p = path.Join(group.prefix, p)
  199. handlers = group.combineHandlers(handlers)
  200. group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  201. c := group.engine.createContext(w, req, params, handlers)
  202. c.Next()
  203. group.engine.cache.Put(c)
  204. })
  205. }
  206. // POST is a shortcut for router.Handle("POST", path, handle)
  207. func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {
  208. group.Handle("POST", path, handlers)
  209. }
  210. // GET is a shortcut for router.Handle("GET", path, handle)
  211. func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {
  212. group.Handle("GET", path, handlers)
  213. }
  214. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  215. func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {
  216. group.Handle("DELETE", path, handlers)
  217. }
  218. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  219. func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {
  220. group.Handle("PATCH", path, handlers)
  221. }
  222. // PUT is a shortcut for router.Handle("PUT", path, handle)
  223. func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {
  224. group.Handle("PUT", path, handlers)
  225. }
  226. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  227. func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {
  228. group.Handle("OPTIONS", path, handlers)
  229. }
  230. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  231. func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {
  232. group.Handle("HEAD", path, handlers)
  233. }
  234. // Static serves files from the given file system root.
  235. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  236. // of the Router's NotFound handler.
  237. // To use the operating system's file system implementation,
  238. // use :
  239. // router.Static("/static", "/var/www")
  240. func (group *RouterGroup) Static(p, root string) {
  241. p = path.Join(p, "/*filepath")
  242. fileServer := http.FileServer(http.Dir(root))
  243. group.GET(p, func(c *Context) {
  244. original := c.Req.URL.Path
  245. c.Req.URL.Path = c.Params.ByName("filepath")
  246. fileServer.ServeHTTP(c.Writer, c.Req)
  247. c.Req.URL.Path = original
  248. })
  249. }
  250. func (group *RouterGroup) combineHandlers(handlers []HandlerFunc) []HandlerFunc {
  251. s := len(group.Handlers) + len(handlers)
  252. h := make([]HandlerFunc, 0, s)
  253. h = append(h, group.Handlers...)
  254. h = append(h, handlers...)
  255. return h
  256. }
  257. /************************************/
  258. /****** FLOW AND ERROR MANAGEMENT****/
  259. /************************************/
  260. func (c *Context) Copy() *Context {
  261. var cp Context = *c
  262. cp.index = AbortIndex
  263. cp.handlers = nil
  264. return &cp
  265. }
  266. // Next should be used only in the middlewares.
  267. // It executes the pending handlers in the chain inside the calling handler.
  268. // See example in github.
  269. func (c *Context) Next() {
  270. c.index++
  271. s := int8(len(c.handlers))
  272. for ; c.index < s; c.index++ {
  273. c.handlers[c.index](c)
  274. }
  275. }
  276. // Forces the system to do not continue calling the pending handlers.
  277. // For example, the first handler checks if the request is authorized. If it's not, context.Abort(401) should be called.
  278. // The rest of pending handlers would never be called for that request.
  279. func (c *Context) Abort(code int) {
  280. if code >= 0 {
  281. c.Writer.WriteHeader(code)
  282. }
  283. c.index = AbortIndex
  284. }
  285. // Fail is the same as Abort plus an error message.
  286. // Calling `context.Fail(500, err)` is equivalent to:
  287. // ```
  288. // context.Error("Operation aborted", err)
  289. // context.Abort(500)
  290. // ```
  291. func (c *Context) Fail(code int, err error) {
  292. c.Error(err, "Operation aborted")
  293. c.Abort(code)
  294. }
  295. func (c *Context) ErrorTyped(err error, typ uint32, meta interface{}) {
  296. c.Errors = append(c.Errors, errorMsg{
  297. Err: err.Error(),
  298. Type: typ,
  299. Meta: meta,
  300. })
  301. }
  302. // Attaches an error to the current context. The error is pushed to a list of errors.
  303. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  304. // A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response.
  305. func (c *Context) Error(err error, meta interface{}) {
  306. c.ErrorTyped(err, ErrorTypeExternal, meta)
  307. }
  308. func (c *Context) LastError() error {
  309. s := len(c.Errors)
  310. if s > 0 {
  311. return errors.New(c.Errors[s-1].Err)
  312. } else {
  313. return nil
  314. }
  315. }
  316. /************************************/
  317. /******** METADATA MANAGEMENT********/
  318. /************************************/
  319. // Sets a new pair key/value just for the specified context.
  320. // It also lazy initializes the hashmap.
  321. func (c *Context) Set(key string, item interface{}) {
  322. if c.Keys == nil {
  323. c.Keys = make(map[string]interface{})
  324. }
  325. c.Keys[key] = item
  326. }
  327. // Get returns the value for the given key or an error if the key does not exist.
  328. func (c *Context) Get(key string) (interface{}, error) {
  329. if c.Keys != nil {
  330. item, ok := c.Keys[key]
  331. if ok {
  332. return item, nil
  333. }
  334. }
  335. return nil, errors.New("Key does not exist.")
  336. }
  337. // MustGet returns the value for the given key or panics if the value doesn't exist.
  338. func (c *Context) MustGet(key string) interface{} {
  339. value, err := c.Get(key)
  340. if err != nil || value == nil {
  341. log.Panicf("Key %s doesn't exist", key)
  342. }
  343. return value
  344. }
  345. /************************************/
  346. /******** ENCOGING MANAGEMENT********/
  347. /************************************/
  348. func filterFlags(content string) string {
  349. for i, a := range content {
  350. if a == ' ' || a == ';' {
  351. return content[:i]
  352. }
  353. }
  354. return content
  355. }
  356. // This function checks the Content-Type to select a binding engine automatically,
  357. // Depending the "Content-Type" header different bindings are used:
  358. // "application/json" --> JSON binding
  359. // "application/xml" --> XML binding
  360. // else --> returns an error
  361. // if Parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer.Like ParseBody() but this method also writes a 400 error if the json is not valid.
  362. func (c *Context) Bind(obj interface{}) bool {
  363. var b binding.Binding
  364. ctype := filterFlags(c.Req.Header.Get("Content-Type"))
  365. switch {
  366. case c.Req.Method == "GET" || ctype == MIMEPOSTForm:
  367. b = binding.Form
  368. case ctype == MIMEJSON:
  369. b = binding.JSON
  370. case ctype == MIMEXML || ctype == MIMEXML2:
  371. b = binding.XML
  372. default:
  373. c.Fail(400, errors.New("unknown content-type: "+ctype))
  374. return false
  375. }
  376. return c.BindWith(obj, b)
  377. }
  378. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  379. if err := b.Bind(c.Req, obj); err != nil {
  380. c.Fail(400, err)
  381. return false
  382. }
  383. return true
  384. }
  385. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  386. // It also sets the Content-Type as "application/json".
  387. func (c *Context) JSON(code int, obj interface{}) {
  388. c.Writer.Header().Set("Content-Type", MIMEJSON)
  389. if code >= 0 {
  390. c.Writer.WriteHeader(code)
  391. }
  392. encoder := json.NewEncoder(c.Writer)
  393. if err := encoder.Encode(obj); err != nil {
  394. c.ErrorTyped(err, ErrorTypeInternal, obj)
  395. c.Abort(500)
  396. }
  397. }
  398. // Serializes the given struct as XML into the response body in a fast and efficient way.
  399. // It also sets the Content-Type as "application/xml".
  400. func (c *Context) XML(code int, obj interface{}) {
  401. c.Writer.Header().Set("Content-Type", MIMEXML)
  402. if code >= 0 {
  403. c.Writer.WriteHeader(code)
  404. }
  405. encoder := xml.NewEncoder(c.Writer)
  406. if err := encoder.Encode(obj); err != nil {
  407. c.ErrorTyped(err, ErrorTypeInternal, obj)
  408. c.Abort(500)
  409. }
  410. }
  411. // Renders the HTTP template specified by its file name.
  412. // It also updates the HTTP code and sets the Content-Type as "text/html".
  413. // See http://golang.org/doc/articles/wiki/
  414. func (c *Context) HTML(code int, name string, data interface{}) {
  415. c.Writer.Header().Set("Content-Type", MIMEHTML)
  416. if code >= 0 {
  417. c.Writer.WriteHeader(code)
  418. }
  419. if err := c.Engine.HTMLTemplates.ExecuteTemplate(c.Writer, name, data); err != nil {
  420. c.ErrorTyped(err, ErrorTypeInternal, H{
  421. "name": name,
  422. "data": data,
  423. })
  424. c.Abort(500)
  425. }
  426. }
  427. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  428. func (c *Context) String(code int, format string, values ...interface{}) {
  429. c.Writer.Header().Set("Content-Type", MIMEPlain)
  430. if code >= 0 {
  431. c.Writer.WriteHeader(code)
  432. }
  433. c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
  434. }
  435. // Writes some data into the body stream and updates the HTTP code.
  436. func (c *Context) Data(code int, contentType string, data []byte) {
  437. if len(contentType) > 0 {
  438. c.Writer.Header().Set("Content-Type", contentType)
  439. }
  440. if code >= 0 {
  441. c.Writer.WriteHeader(code)
  442. }
  443. c.Writer.Write(data)
  444. }