gin.go 13 KB

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