gin.go 11 KB

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