gin.go 11 KB

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