Merge branch 'develop' | v0.5 release
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Javier Provecho Fernandez · committed by Javier Provecho Fernandez · parents 50e7e42, 2b85363 · Browse files · 13 files·+402 added−64 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+402 added−64 removed
- other:+402 added−64 removed
Provenance
- Commit
e2fa897- Tree
dc20755- Author
Javier Provecho Fernandez <javiertitan@gmail.com>- Committer
Javier Provecho Fernandez <javiertitan@gmail.com>- Parent 1
50e7e42- Parent 2
2b85363
13 files changed+402 added−64 removed
modified:binding/binding.go+82 added-14 removed
23 unmodified lines24 25 // XML binding26 xmlBinding struct{}27 28- // // form binding28+ // form binding29 formBinding struct{}30+31+ // multipart form binding32+ multipartFormBinding struct{}33 )34 35+const MAX_MEMORY = 1 * 1024 * 102436+37 var (33- JSON = jsonBinding{}34- XML = xmlBinding{}35- Form = formBinding{} // todo38+ JSON = jsonBinding{}39+ XML = xmlBinding{}40+ Form = formBinding{} // todo41+ MultipartForm = multipartFormBinding{}42 )43 44 func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {45 decoder := json.NewDecoder(req.Body)22 unmodified lines68 }69 return Validate(obj)70 }71 72+func (_ multipartFormBinding) Bind(req *http.Request, obj interface{}) error {73+ if err := req.ParseMultipartForm(MAX_MEMORY); err != nil {74+ return err75+ }76+ if err := mapForm(obj, req.Form); err != nil {77+ return err78+ }79+ return Validate(obj)80+}81+82 func mapForm(ptr interface{}, form map[string][]string) error {83 typ := reflect.TypeOf(ptr).Elem()84 formStruct := reflect.ValueOf(ptr).Elem()85 for i := 0; i < typ.NumField(); i++ {27 unmodified lines113 }114 return nil115 }116 117+func setIntField(val string, bitSize int, structField reflect.Value) error {118+ if val == "" {119+ val = "0"120+ }121+122+ intVal, err := strconv.ParseInt(val, 10, bitSize)123+ if err == nil {124+ structField.SetInt(intVal)125+ }126+127+ return err128+}129+130+func setUintField(val string, bitSize int, structField reflect.Value) error {131+ if val == "" {132+ val = "0"133+ }134+135+ uintVal, err := strconv.ParseUint(val, 10, bitSize)136+ if err == nil {137+ structField.SetUint(uintVal)138+ }139+140+ return err141+}142+143 func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {144 switch valueKind {103- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:104- if val == "" {105- val = "0"106- }107- intVal, err := strconv.Atoi(val)108- if err != nil {109- return err110- } else {111- structField.SetInt(int64(intVal))112- }145+ case reflect.Int:146+ return setIntField(val, 0, structField)147+ case reflect.Int8:148+ return setIntField(val, 8, structField)149+ case reflect.Int16:150+ return setIntField(val, 16, structField)151+ case reflect.Int32:152+ return setIntField(val, 32, structField)153+ case reflect.Int64:154+ return setIntField(val, 64, structField)155+ case reflect.Uint:156+ return setUintField(val, 0, structField)157+ case reflect.Uint8:158+ return setUintField(val, 8, structField)159+ case reflect.Uint16:160+ return setUintField(val, 16, structField)161+ case reflect.Uint32:162+ return setUintField(val, 32, structField)163+ case reflect.Uint64:164+ return setUintField(val, 64, structField)165 case reflect.Bool:166 if val == "" {167 val = "false"168 }81 unmodified lines250 if err != nil {251 return err252 }253 }254+ } else {255+ fieldType := field.Type.Kind()256+ if fieldType == reflect.Struct {257+ if reflect.DeepEqual(zero, fieldValue) {258+ continue259+ }260+ err := Validate(fieldValue, field.Name)261+ if err != nil {262+ return err263+ }264+ } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {265+ err := Validate(fieldValue, field.Name)266+ if err != nil {267+ return err268+ }269+ }270 }271 }272 case reflect.Slice:273 for i := 0; i < val.Len(); i++ {11 unmodified linesmodified:Godeps/Godeps.json+1 added-1 removed
2 unmodified lines34567789102 unmodified lines "GoVersion": "go1.3", "Deps": [ { "ImportPath": "github.com/julienschmidt/httprouter", "Rev": "00ce1c6a267162792c367acc43b1681a884e1872" "Rev": "b428fda53bb0a764fea9c76c9413512eda291dec" } ]}modified:render/render.go+17 added
24 unmodified lines25 26 // Plain text27 plainRender struct{}28 29+ // HTML Plain text30+ htmlPlainRender struct{}31+32 // Redirects33 redirectRender struct{}34 35 // Redirects11 unmodified lines47 var (48 JSON = jsonRender{}49 XML = xmlRender{}50 Plain = plainRender{}51+ HTMLPlain = htmlPlainRender{}52 Redirect = redirectRender{}53 HTMLDebug = &htmlDebugRender{}54 )55 32 unmodified lines88 }89 return err90 }91 92+func (_ htmlPlainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {93+ writeHeader(w, code, "text/html")94+ format := data[0].(string)95+ args := data[1].([]interface{})96+ var err error97+ if len(args) > 0 {98+ _, err = w.Write([]byte(fmt.Sprintf(format, args...)))99+ } else {100+ _, err = w.Write([]byte(format))101+ }102+ return err103+}104+105 func (r *htmlDebugRender) AddGlob(pattern string) {106 r.globs = append(r.globs, pattern)107 }108 32 unmodified linesmodified:auth_test.go+24 added
57 unmodified lines58 if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {59 t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))60 }61 }62+63+func TestBasicAuth401WithCustomRealm(t *testing.T) {64+ req, _ := http.NewRequest("GET", "/login", nil)65+ w := httptest.NewRecorder()66+67+ r := New()68+ accounts := Accounts{"foo": "bar"}69+ r.Use(BasicAuthForRealm(accounts, "My Custom Realm"))70+71+ r.GET("/login", func(c *Context) {72+ c.String(200, "autorized")73+ })74+75+ req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))76+ r.ServeHTTP(w, req)77+78+ if w.Code != 401 {79+ t.Errorf("Response code should be Not autorized, was: %s", w.Code)80+ }81+82+ if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"My Custom Realm\"" {83+ t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))84+ }85+}modified:auth.go+15 added-4 removed
6 unmodified lines7 import (8 "crypto/subtle"9 "encoding/base64"10 "errors"11+ "fmt"12 "sort"13 )14 15 const (12 unmodified lines28 func (a authPairs) Len() int { return len(a) }29 func (a authPairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }30 func (a authPairs) Less(i, j int) bool { return a[i].Value < a[j].Value }31 31-// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where32-// the key is the user name and the value is the password.33-func BasicAuth(accounts Accounts) HandlerFunc {32+// Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where33+// the key is the user name and the value is the password, as well as the name of the Realm34+// (see http://tools.ietf.org/html/rfc2617#section-1.2)35+func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {36 pairs, err := processAccounts(accounts)37 if err != nil {38 panic(err)39 }1 unmodified line41 // Search user in the slice of allowed credentials42 user, ok := searchCredential(pairs, c.Request.Header.Get("Authorization"))43 if !ok {44 // Credentials doesn't match, we return 401 Unauthorized and abort request.45+ if realm == "" {46+ realm = "Authorization Required"47+ }43- c.Writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")48+ c.Writer.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", realm))49 c.Fail(401, errors.New("Unauthorized"))50 } else {51 // user is allowed, set UserId to key "user" in this context, the userId can be read later using52 // c.Get(gin.AuthUserKey)1 unmodified line54 }55 }56 }57 58+// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where59+// the key is the user name and the value is the password.60+func BasicAuth(accounts Accounts) HandlerFunc {61+ return BasicAuthForRealm(accounts, "")62+}63+64 func processAccounts(accounts Accounts) (authPairs, error) {65 if len(accounts) == 0 {66 return nil, errors.New("Empty list of authorized credentials")67 }38 unmodified linesmodified:AUTHORS.md+56 added
7 unmodified lines8 **Long-term Maintainer:** Javier Provecho (@javierprovecho)9 10 People and companies, who have contributed, in alphabetical order.11 12+**@858806258 (杰哥)**13+- Fix typo in example14+15+16 **@achedeuzot (Klemen Sever)**17 - Fix newline debug printing18 19 4 unmodified lines24 **@AlexanderChen1989 (Alexander)**25 - Typos in README26 27 28+**@alexanderdidenko (Aleksandr Didenko)**29+- Add support multipart/form-data30+31+32 **@alexandernyquist (Alexander Nyquist)**33 - Using template.Must to fix multiple return issue34 - ★ Added support for OPTIONS verb35 - ★ Setting response headers before calling WriteHeader26 unmodified lines62 - Typos in README63 - Add example about serving static files64 65 66+**@donileo (Adonis)**67+- Add NoMethod handler68+69+70 **@dutchcoders (DutchCoders)**71 - ★ Fix security bug that allows client to spoof ip72 - Fix typo. r.HTMLTemplates -> SetHTMLTemplate73 74 75+**@el3ctro- (Joshua Loper)**76+- Fix typo in example77+78+79+**@ethankan (Ethan Kan)**80+- Unsigned integers in binding81+82+83+**(Evgeny Persienko)**84+- Validate sub structures85+86+87+**@frankbille (Frank Bille)**88+- Add support for HTTP Realm Auth89+90+91 **@fmd (Fareed Dudhia)**92 - Fix typo. SetHTTPTemplate -> SetHTMLTemplate93 94 95+**@ironiridis (Christopher Harrington)**96+- Remove old reference97+98+99 **@jammie-stackhouse (Jamie Stackhouse)**100 - Add more shortcuts for router methods101 102 32 unmodified lines135 **@lucas-clemente (Lucas Clemente)**136 - ★ work around path.Join removing trailing slashes from routes137 138 139+**@mattn (Yasuhiro Matsumoto)**140+- Improve color logger141+142+143 **@mdigger (Dmitry Sedykh)**144 - Fixes Form binding when content-type is x-www-form-urlencoded145 - No repeat call c.Writer.Status() in gin.Logger146 - Fixes Content-Type for json render26 unmodified lines173 **@r8k (Rajiv Kilaparti)**174 - Fix Port usage in README.175 176 177+**@rayrod2030 (Ray Rodriguez)**178+- Fix typo in example179+180+181+**@rns**182+- Fix typo in example183+184+185 **@RobAWilkinson (Robert Wilkinson)**186 - Add example of forms and params187 188 189+**@rogierlommers (Rogier Lommers)**190+- Add updated static serve example191+192+193 **@se77en (Damon Zhao)**194 - Improve color logging195 196 16 unmodified lines213 **@superalsrk (SRK.Lyu)**214 - Update httprouter godeps215 216 217+**@tebeka (Miki Tebeka)**218+- Use net/http constants instead of numeric values219+220+221+**@techjanitor**222+- Update context.go reserved IPs223+224+225 **@yosssi (Keiji Yoshida)**226 - Fix link in README227 228 2 unmodified linesmodified:CHANGELOG.md+8 added-1 removed
12334567891011121314151655 unmodified lines#Changelog
###Gin 0.6 (Mar 7, 2015)###Gin 0.6 (Mar 9, 2015)
- [ADD] Support multipart/form-data- [ADD] NoMethod handler- [ADD] Validate sub structures- [ADD] Support for HTTP Realm Auth- [FIX] Unsigned integers in binding- [FIX] Improve color logger
###Gin 0.5 (Feb 7, 2015)
- [NEW] Content Negotiation- [FIX] Solved security bug that allow a client to spoof ip55 unmodified linesmodified:context_test.go+36 added
439 unmodified lines440 t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))441 }442 }443 444+func TestBindingForm(t *testing.T) {445+446+ body := bytes.NewBuffer([]byte("foo=bar&num=123&unum=1234567890"))447+448+ r := New()449+ r.POST("/binding/form", func(c *Context) {450+ var body struct {451+ Foo string `form:"foo"`452+ Num int `form:"num"`453+ Unum uint `form:"unum"`454+ }455+ if c.Bind(&body) {456+ c.JSON(200, H{"foo": body.Foo, "num": body.Num, "unum": body.Unum})457+ }458+ })459+460+ req, _ := http.NewRequest("POST", "/binding/form", body)461+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")462+ w := httptest.NewRecorder()463+464+ r.ServeHTTP(w, req)465+466+ if w.Code != 200 {467+ t.Errorf("Response code should be Ok, was: %d", w.Code)468+ }469+470+ expected := "{\"foo\":\"bar\",\"num\":123,\"unum\":1234567890}\n"471+ if w.Body.String() != expected {472+ t.Errorf("Response should be %s, was %s", expected, w.Body.String())473+ }474+475+ if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {476+ t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))477+ }478+}479+480 func TestClientIP(t *testing.T) {481 r := New()482 483 var clientIP string = ""36 unmodified linesmodified:context.go+8 added-1 removed
228 unmodified lines229 // the real client ip.230 func ForwardedFor(proxies ...interface{}) HandlerFunc {231 if len(proxies) == 0 {232 // default to local ips233- var reservedLocalIps = []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}233+ var reservedLocalIps = []string{"10.0.0.0/8", "127.0.0.1/32", "172.16.0.0/12", "192.168.0.0/16"}234 235 proxies = make([]interface{}, len(reservedLocalIps))236 237 for i, v := range reservedLocalIps {56 unmodified lines294 ctype := filterFlags(c.Request.Header.Get("Content-Type"))295 switch {296 case c.Request.Method == "GET" || ctype == MIMEPOSTForm:297 b = binding.Form298+ case ctype == MIMEMultipartPOSTForm:299+ b = binding.MultipartForm300 case ctype == MIMEJSON:301 b = binding.JSON302 case ctype == MIMEXML || ctype == MIMEXML2:303 b = binding.XML46 unmodified lines350 func (c *Context) String(code int, format string, values ...interface{}) {351 c.Render(code, render.Plain, format, values)352 }353 354+// Writes the given string into the response body and sets the Content-Type to "text/html" without template.355+func (c *Context) HTMLString(code int, format string, values ...interface{}) {356+ c.Render(code, render.HTMLPlain, format, values)357+}358+359 // Returns a HTTP redirect to the specific location.360 func (c *Context) Redirect(code int, location string) {361 if code >= 300 && code <= 308 {362 c.Render(code, render.Redirect, location)79 unmodified linesmodified:gin.go+45 added-15 removed
12 unmodified lines13 "sync"14 )15 16 const (17- AbortIndex = math.MaxInt8 / 218- MIMEJSON = "application/json"19- MIMEHTML = "text/html"20- MIMEXML = "application/xml"21- MIMEXML2 = "text/xml"22- MIMEPlain = "text/plain"23- MIMEPOSTForm = "application/x-www-form-urlencoded"17+ AbortIndex = math.MaxInt8 / 218+ MIMEJSON = "application/json"19+ MIMEHTML = "text/html"20+ MIMEXML = "application/xml"21+ MIMEXML2 = "text/xml"22+ MIMEPlain = "text/plain"23+ MIMEPOSTForm = "application/x-www-form-urlencoded"24+ MIMEMultipartPOSTForm = "multipart/form-data"25 )26 27 type (28 HandlerFunc func(*Context)29 30 // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middlewares.31 Engine struct {32 *RouterGroup32- HTMLRender render.Render33- Default404Body []byte34- pool sync.Pool35- allNoRoute []HandlerFunc36- noRoute []HandlerFunc37- router *httprouter.Router33+ HTMLRender render.Render34+ Default404Body []byte35+ Default405Body []byte36+ pool sync.Pool37+ allNoRouteNoMethod []HandlerFunc38+ noRoute []HandlerFunc39+ noMethod []HandlerFunc40+ router *httprouter.Router41 }42 )43 44 // Returns a new blank Engine instance without any middleware attached.6 unmodified lines51 engine: engine,52 }53 engine.router = httprouter.New()54 engine.Default404Body = []byte("404 page not found")55+ engine.Default405Body = []byte("405 method not allowed")56 engine.router.NotFound = engine.handle40457+ engine.router.MethodNotAllowed = engine.handle40558 engine.pool.New = func() interface{} {59 c := &Context{Engine: engine}60 c.Writer = &c.writermem61 return c39 unmodified lines101 engine.noRoute = handlers102 engine.rebuild404Handlers()103 }104 105+func (engine *Engine) NoMethod(handlers ...HandlerFunc) {106+ engine.noMethod = handlers107+ engine.rebuild405Handlers()108+}109+110 func (engine *Engine) Use(middlewares ...HandlerFunc) {111 engine.RouterGroup.Use(middlewares...)112 engine.rebuild404Handlers()113+ engine.rebuild405Handlers()114 }115 116 func (engine *Engine) rebuild404Handlers() {106- engine.allNoRoute = engine.combineHandlers(engine.noRoute)117+ engine.allNoRouteNoMethod = engine.combineHandlers(engine.noRoute)118 }119 120+func (engine *Engine) rebuild405Handlers() {121+ engine.allNoRouteNoMethod = engine.combineHandlers(engine.noMethod)122+}123+124 func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {110- c := engine.createContext(w, req, nil, engine.allNoRoute)125+ c := engine.createContext(w, req, nil, engine.allNoRouteNoMethod)126 // set 404 by default, useful for logging127 c.Writer.WriteHeader(404)128 c.Next()129 if !c.Writer.Written() {5 unmodified lines135 }136 engine.reuseContext(c)137 }138 139+func (engine *Engine) handle405(w http.ResponseWriter, req *http.Request) {140+ c := engine.createContext(w, req, nil, engine.allNoRouteNoMethod)141+ // set 405 by default, useful for logging142+ c.Writer.WriteHeader(405)143+ c.Next()144+ if !c.Writer.Written() {145+ if c.Writer.Status() == 405 {146+ c.Data(-1, MIMEPlain, engine.Default405Body)147+ } else {148+ c.Writer.WriteHeaderNow()149+ }150+ }151+ engine.reuseContext(c)152+}153+154 // ServeHTTP makes the router implement the http.Handler interface.155 func (engine *Engine) ServeHTTP(writer http.ResponseWriter, request *http.Request) {156 engine.router.ServeHTTP(writer, request)157 }16 unmodified linesmodified:logger.go+2 added-2 removed
3 unmodified lines4 5 package gin6 7 import (8+ "github.com/mattn/go-colorable"9 "log"9- "os"10 "time"11 )12 13 var (23 unmodified lines37 }38 }39 40 func Logger() HandlerFunc {41- stdlogger := log.New(os.Stdout, "", 0)41+ stdlogger := log.New(colorable.NewColorableStdout(), "", 0)42 //errlogger := log.New(os.Stderr, "", 0)43 44 return func(c *Context) {45 // Start timer60 unmodified linesmodified:README.md+107 added-25 removed
1 #Gin Web Framework [](https://godoc.org/github.com/gin-gonic/gin) [](https://travis-ci.org/gin-gonic/gin)2 3+[](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)4+5 Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin. 6 7 8 2 unmodified lines11 ```12 ```go13 package main14 15+import (16+ "net/http"13-import "github.com/gin-gonic/gin"17+ "github.com/gin-gonic/gin"18+)19 20 func main() {21 router := gin.Default()22 router.GET("/", func(c *gin.Context) {18- c.String(200, "hello world")23+ c.String(http.StatusOK, "hello world")24 })25 router.GET("/ping", func(c *gin.Context) {21- c.String(200, "pong")26+ c.String(http.StatusOK, "pong")27 })28 router.POST("/submit", func(c *gin.Context) {24- c.String(401, "not authorized")29+ c.String(http.StatusUnauthorized, "not authorized")30 })31 router.PUT("/error", func(c *gin.Context) {27- c.String(500, "and error hapenned :(")32+ c.String(http.StatusInternalServerError, "and error happened :(")33 })34 router.Run(":8080")35 }36 ```52 unmodified lines89 #### Create most basic PING/PONG HTTP endpoint90 ```go 91 package main92 93+import (94+ "net/http"88-import "github.com/gin-gonic/gin"95+ "github.com/gin-gonic/gin"96+)97 98 func main() {99 r := gin.Default()100 r.GET("/ping", func(c *gin.Context) {93- c.String(200, "pong")101+ c.String(http.StatusOK, "pong")102 })103 96- // Listen and server on 0.0.0.0:8080104+ // Listen and serve on 0.0.0.0:8080105 r.Run(":8080")106 }107 ```108 26 unmodified lines135 // This handler will match /user/john but will not match neither /user/ or /user136 r.GET("/user/:name", func(c *gin.Context) {137 name := c.Params.ByName("name")138 message := "Hello "+name131- c.String(200, message)139+ c.String(http.StatusOK, message)140 })141 142 // However, this one will match /user/john/ and also /user/john/send143 // If no other routers match /user/john, it will redirect to /user/join/144 r.GET("/user/:name/*action", func(c *gin.Context) {145 name := c.Params.ByName("name")146 action := c.Params.ByName("action")147 message := name + " is " + action140- c.String(200, message)148+ c.String(http.StatusOK, message)149 })150 151 // Listen and server on 0.0.0.0:8080152 r.Run(":8080")9 unmodified lines162 // You need to call ParseForm() on the request to receive url and form params first163 c.Request.ParseForm()164 165 firstname := c.Request.Form.Get("firstname")158- lastname := c.Request.Form.get("lastname")166+ lastname := c.Request.Form.Get("lastname")167 168 message := "Hello "+ firstname + lastname161- c.String(200, message)169+ c.String(http.StatusOK, message)170 })171 r.Run(":8080")172 }173 ```174 175+###Multipart Form176+```go177+package main178+179+import (180+ "github.com/gin-gonic/gin"181+ "github.com/gin-gonic/gin/binding"182+)183+184+type LoginForm struct {185+ User string `form:"user" binding:"required"`186+ Password string `form:"password" binding:"required"`187+}188+189+func main() {190+191+ r := gin.Default()192+193+ r.POST("/login", func(c *gin.Context) {194+195+ var form LoginForm196+ c.BindWith(&form, binding.MultipartForm)197+198+ if form.User == "user" && form.Password == "password" {199+ c.JSON(200, gin.H{"status": "you are logged in"})200+ } else {201+ c.JSON(401, gin.H{"status": "unauthorized"})202+ }203+204+ })205+206+ r.Run(":8080")207+208+}209+```210+211+Test it with:212+```bash213+$ curl -v --form user=user --form password=password http://localhost:8080/login214+```215+216 #### Grouping routes217 ```go218 func main() {219 r := gin.Default()100 unmodified lines320 var json LoginJSON321 322 c.Bind(&json) // This will infer what binder to use depending on the content-type header.323 if json.User == "manu" && json.Password == "123" {275- c.JSON(200, gin.H{"status": "you are logged in"})324+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})325 } else {277- c.JSON(401, gin.H{"status": "unauthorized"})326+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})327 }328 })329 330 // Example for binding a HTML form (user=manu&password=123)1 unmodified line332 var form LoginForm333 334 c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML.335 if form.User == "manu" && form.Password == "123" {287- c.JSON(200, gin.H{"status": "you are logged in"})336+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})337 } else {289- c.JSON(401, gin.H{"status": "unauthorized"})338+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})339 }340 })341 342 // Listen and server on 0.0.0.0:80808 unmodified lines351 r := gin.Default()352 353 // gin.H is a shortcut for map[string]interface{}354 r.GET("/someJSON", func(c *gin.Context) {306- c.JSON(200, gin.H{"message": "hey", "status": 200})355+ c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})356 })357 358 r.GET("/moreJSON", func(c *gin.Context) {359 // You also can use a struct6 unmodified lines366 msg.Message = "hey"367 msg.Number = 123368 // Note that msg.Name becomes "user" in the JSON369 // Will output : {"user": "Lena", "Message": "hey", "Number": 123}321- c.JSON(200, msg)370+ c.JSON(http.StatusOK, msg)371 })372 373 r.GET("/someXML", func(c *gin.Context) {325- c.XML(200, gin.H{"message": "hey", "status": 200})374+ c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})375 })376 377 // Listen and server on 0.0.0.0:8080378 r.Run(":8080")379 }380 ```381 382 ####Serving static files334-383 Use Engine.ServeFiles(path string, root http.FileSystem):384 385 ```go386 func main() {4 unmodified lines391 r.Run(":8080")392 }393 ```394 395+Use the following example to serve static files at top level route of your domain. Files are being served from directory ./html.396+397+```398+r := gin.Default()399+r.Use(static.Serve("/", static.LocalFile("html", false)))400+```401+402 Note: this will use `httpNotFound` instead of the Router's `NotFound` handler.403 404 ####HTML rendering405 4 unmodified lines410 r := gin.Default()411 r.LoadHTMLGlob("templates/*")412 r.GET("/index", func(c *gin.Context) {413 obj := gin.H{"title": "Main website"}359- c.HTML(200, "index.tmpl", obj)414+ c.HTML(http.StatusOK, "index.tmpl", obj)415 })416 417 // Listen and server on 0.0.0.0:8080418 r.Run(":8080")19 unmodified lines438 r.Run(":8080")439 }440 ```441 442+#####Using layout files with templates443+```go444+var baseTemplate = "main.tmpl"445+446+r.GET("/", func(c *gin.Context) {447+ r.SetHTMLTemplate(template.Must(template.ParseFiles(baseTemplate, "whatever.tmpl")))448+ c.HTML(200, "base", data)449+})450+```451+main.tmpl452+```html453+{{define "base"}}454+<html>455+ <head></head>456+ <body>457+ {{template "content" .}}458+ </body>459+</html>460+{{end}}461+```462+whatever.tmpl463+```html464+{{define "content"}}465+<h1>Hello World!</h1>466+{{end}}467+```468+469 #### Redirects470 471 Issuing a HTTP redirect is easy:472 473 ```go474 r.GET("/test", func(c *gin.Context) {393- c.Redirect(301, "http://www.google.com/")475+ c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")476 })477 ```478 Both internal and external locations are supported.479 39 unmodified lines519 ```520 521 #### Using BasicAuth() middleware522 ```go441-// similate some private data523+// simulate some private data524 var secrets = gin.H{525 "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},526 "austin": gin.H{"email": "austin@example.com", "phone": "666"},527 "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},16 unmodified lines544 authorized.GET("/secrets", func(c *gin.Context) {545 // get user, it was setted by the BasicAuth middleware546 user := c.MustGet(gin.AuthUserKey).(string)547 if secret, ok := secrets[user]; ok {466- c.JSON(200, gin.H{"user": user, "secret": secret})548+ c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})549 } else {468- c.JSON(200, gin.H{"user": user, "secret": "NO SECRET :("})550+ c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})551 }552 })553 554 // Listen and server on 0.0.0.0:808064 unmodified linesmodified:recovery.go+1 added-1 removed
80 unmodified lines81 return name82 }83 84 // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.85-// While Martini is in development mode, Recovery will also output the panic as HTML.85+// While Gin is in development mode, Recovery will also output the panic as HTML.86 func Recovery() HandlerFunc {87 return func(c *Context) {88 defer func() {89 if err := recover(); err != nil {9 unmodified lines