gin.go 14 KB

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