gin.go 14 KB

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