gin.go 13 KB

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