gin.go 14 KB

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