gin.go 11 KB

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