gin.go 11 KB

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