gin.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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.String(404, "404 page not found")
  127. }
  128. engine.reuseContext(c)
  129. }
  130. // ServeFiles serves files from the given file system root.
  131. // The path must end with "/*filepath", files are then served from the local
  132. // path /defined/root/dir/*filepath.
  133. // For example if root is "/etc" and *filepath is "passwd", the local file
  134. // "/etc/passwd" would be served.
  135. // Internally a http.FileServer is used, therefore http.NotFound is used instead
  136. // of the Router's NotFound handler.
  137. // To use the operating system's file system implementation,
  138. // use http.Dir:
  139. // router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
  140. func (engine *Engine) ServeFiles(path string, root http.FileSystem) {
  141. engine.router.ServeFiles(path, root)
  142. }
  143. // ServeHTTP makes the router implement the http.Handler interface.
  144. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  145. engine.router.ServeHTTP(w, req)
  146. }
  147. func (engine *Engine) Run(addr string) {
  148. if err := http.ListenAndServe(addr, engine); err != nil {
  149. panic(err)
  150. }
  151. }
  152. /************************************/
  153. /********** ROUTES GROUPING *********/
  154. /************************************/
  155. func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
  156. select {
  157. case c := <-engine.cache:
  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. default:
  166. return &Context{
  167. Writer: &responseWriter{w, -1, false},
  168. Req: req,
  169. Params: params,
  170. handlers: handlers,
  171. index: -1,
  172. Engine: engine,
  173. }
  174. }
  175. }
  176. func (engine *Engine) reuseContext(c *Context) {
  177. select {
  178. case engine.cache <- c:
  179. default:
  180. }
  181. }
  182. // Adds middlewares to the group, see example code in github.
  183. func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
  184. group.Handlers = append(group.Handlers, middlewares...)
  185. }
  186. // Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
  187. // For example, all the routes that use a common middlware for authorization could be grouped.
  188. func (group *RouterGroup) Group(component string, handlers ...HandlerFunc) *RouterGroup {
  189. prefix := path.Join(group.prefix, component)
  190. return &RouterGroup{
  191. Handlers: group.combineHandlers(handlers),
  192. parent: group,
  193. prefix: prefix,
  194. engine: group.engine,
  195. }
  196. }
  197. // Handle registers a new request handle and middlewares with the given path and method.
  198. // The last handler should be the real handler, the other ones should be middlewares that can and should be shared among different routes.
  199. // See the example code in github.
  200. //
  201. // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
  202. // functions can be used.
  203. //
  204. // This function is intended for bulk loading and to allow the usage of less
  205. // frequently used, non-standardized or custom methods (e.g. for internal
  206. // communication with a proxy).
  207. func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
  208. p = path.Join(group.prefix, p)
  209. handlers = group.combineHandlers(handlers)
  210. group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
  211. c := group.engine.createContext(w, req, params, handlers)
  212. c.Next()
  213. group.engine.reuseContext(c)
  214. })
  215. }
  216. // POST is a shortcut for router.Handle("POST", path, handle)
  217. func (group *RouterGroup) POST(path string, handlers ...HandlerFunc) {
  218. group.Handle("POST", path, handlers)
  219. }
  220. // GET is a shortcut for router.Handle("GET", path, handle)
  221. func (group *RouterGroup) GET(path string, handlers ...HandlerFunc) {
  222. group.Handle("GET", path, handlers)
  223. }
  224. // DELETE is a shortcut for router.Handle("DELETE", path, handle)
  225. func (group *RouterGroup) DELETE(path string, handlers ...HandlerFunc) {
  226. group.Handle("DELETE", path, handlers)
  227. }
  228. // PATCH is a shortcut for router.Handle("PATCH", path, handle)
  229. func (group *RouterGroup) PATCH(path string, handlers ...HandlerFunc) {
  230. group.Handle("PATCH", path, handlers)
  231. }
  232. // PUT is a shortcut for router.Handle("PUT", path, handle)
  233. func (group *RouterGroup) PUT(path string, handlers ...HandlerFunc) {
  234. group.Handle("PUT", path, handlers)
  235. }
  236. // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
  237. func (group *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc) {
  238. group.Handle("OPTIONS", path, handlers)
  239. }
  240. // HEAD is a shortcut for router.Handle("HEAD", path, handle)
  241. func (group *RouterGroup) HEAD(path string, handlers ...HandlerFunc) {
  242. group.Handle("HEAD", path, handlers)
  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. // Attaches an error to the current context. The error is pushed to a list of errors.
  290. // It's a good idea to call Error for each error that occurred during the resolution of a request.
  291. // 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.
  292. func (c *Context) Error(err error, meta interface{}) {
  293. c.Errors = append(c.Errors, ErrorMsg{
  294. Err: err.Error(),
  295. Meta: meta,
  296. })
  297. }
  298. func (c *Context) LastError() error {
  299. s := len(c.Errors)
  300. if s > 0 {
  301. return errors.New(c.Errors[s-1].Err)
  302. } else {
  303. return nil
  304. }
  305. }
  306. /************************************/
  307. /******** METADATA MANAGEMENT********/
  308. /************************************/
  309. // Sets a new pair key/value just for the specified context.
  310. // It also lazy initializes the hashmap.
  311. func (c *Context) Set(key string, item interface{}) {
  312. if c.Keys == nil {
  313. c.Keys = make(map[string]interface{})
  314. }
  315. c.Keys[key] = item
  316. }
  317. // Get returns the value for the given key or an error if the key does not exist.
  318. func (c *Context) Get(key string) (interface{}, error) {
  319. if c.Keys != nil {
  320. item, ok := c.Keys[key]
  321. if ok {
  322. return item, nil
  323. }
  324. }
  325. return nil, errors.New("Key does not exist.")
  326. }
  327. // MustGet returns the value for the given key or panics if the value doesn't exist.
  328. func (c *Context) MustGet(key string) interface{} {
  329. value, err := c.Get(key)
  330. if err != nil || value == nil {
  331. log.Panicf("Key %s doesn't exist", key)
  332. }
  333. return value
  334. }
  335. /************************************/
  336. /******** ENCOGING MANAGEMENT********/
  337. /************************************/
  338. func filterFlags(content string) string {
  339. for i, a := range content {
  340. if a == ' ' || a == ';' {
  341. return content[:i]
  342. }
  343. }
  344. return content
  345. }
  346. // This function checks the Content-Type to select a binding engine automatically,
  347. // Depending the "Content-Type" header different bindings are used:
  348. // "application/json" --> JSON binding
  349. // "application/xml" --> XML binding
  350. // else --> returns an error
  351. // 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.
  352. func (c *Context) Bind(obj interface{}) bool {
  353. var b binding.Binding
  354. ctype := filterFlags(c.Req.Header.Get("Content-Type"))
  355. switch {
  356. case c.Req.Method == "GET":
  357. b = binding.Form
  358. case ctype == MIMEJSON:
  359. b = binding.JSON
  360. case ctype == MIMEXML || ctype == MIMEXML2:
  361. b = binding.XML
  362. default:
  363. c.Fail(400, errors.New("unknown content-type: "+ctype))
  364. return false
  365. }
  366. return c.BindWith(obj, b)
  367. }
  368. func (c *Context) BindWith(obj interface{}, b binding.Binding) bool {
  369. if err := b.Bind(c.Req, obj); err != nil {
  370. c.Fail(400, err)
  371. return false
  372. }
  373. return true
  374. }
  375. // Serializes the given struct as JSON into the response body in a fast and efficient way.
  376. // It also sets the Content-Type as "application/json".
  377. func (c *Context) JSON(code int, obj interface{}) {
  378. c.Writer.Header().Set("Content-Type", MIMEJSON)
  379. if code >= 0 {
  380. c.Writer.WriteHeader(code)
  381. }
  382. encoder := json.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. // Serializes the given struct as XML into the response body in a fast and efficient way.
  389. // It also sets the Content-Type as "application/xml".
  390. func (c *Context) XML(code int, obj interface{}) {
  391. c.Writer.Header().Set("Content-Type", MIMEXML)
  392. if code >= 0 {
  393. c.Writer.WriteHeader(code)
  394. }
  395. encoder := xml.NewEncoder(c.Writer)
  396. if err := encoder.Encode(obj); err != nil {
  397. c.Error(err, obj)
  398. http.Error(c.Writer, err.Error(), 500)
  399. }
  400. }
  401. // Renders the HTTP template specified by its file name.
  402. // It also updates the HTTP code and sets the Content-Type as "text/html".
  403. // See http://golang.org/doc/articles/wiki/
  404. func (c *Context) HTML(code int, name string, data interface{}) {
  405. c.Writer.Header().Set("Content-Type", MIMEHTML)
  406. if code >= 0 {
  407. c.Writer.WriteHeader(code)
  408. }
  409. if err := c.Engine.HTMLTemplates.ExecuteTemplate(c.Writer, name, data); err != nil {
  410. c.Error(err, map[string]interface{}{
  411. "name": name,
  412. "data": data,
  413. })
  414. http.Error(c.Writer, err.Error(), 500)
  415. }
  416. }
  417. // Writes the given string into the response body and sets the Content-Type to "text/plain".
  418. func (c *Context) String(code int, msg string) {
  419. c.Writer.Header().Set("Content-Type", MIMEPlain)
  420. if code >= 0 {
  421. c.Writer.WriteHeader(code)
  422. }
  423. c.Writer.Write([]byte(msg))
  424. }
  425. // Writes some data into the body stream and updates the HTTP code.
  426. func (c *Context) Data(code int, contentType string, data []byte) {
  427. if len(contentType) > 0 {
  428. c.Writer.Header().Set("Content-Type", contentType)
  429. }
  430. if code >= 0 {
  431. c.Writer.WriteHeader(code)
  432. }
  433. c.Writer.Write(data)
  434. }