gin.go 12 KB

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