gin.go 14 KB

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