gin.go 14 KB

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