gin.go 13 KB

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