Merge branch 'master' into develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conflicts: README.md gin.go routergroup.go
authored by Manu Mtz-Almeida · committed by Manu Mtz-Almeida · parents 5f56db5, a97c239 · Browse files · 27 files·+789 added−244 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
27 files+789 added−244 removed
- other:+789 added−244 removed
Provenance
- Commit
e8bc8f4- Tree
5c58bbb- Author
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Committer
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Parent 1
5f56db5- Parent 2
a97c239
27 files changed+789 added−244 removed
modified:binding/binding_test.go+39 added
4 unmodified lines5 package binding6 7 import (8 "bytes"9+ "mime/multipart"10 "net/http"11 "testing"12 13 "github.com/stretchr/testify/assert"50 unmodified lines64 "/", "/",65 "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")66 }67 68+func createFormPostRequest() *http.Request {69+ req, _ := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", bytes.NewBufferString("foo=bar&bar=foo"))70+ req.Header.Set("Content-Type", MIMEPOSTForm)71+ return req72+}73+74+func createFormMultipartRequest() *http.Request {75+ boundary := "--testboundary"76+ body := new(bytes.Buffer)77+ mw := multipart.NewWriter(body)78+ defer mw.Close()79+80+ mw.SetBoundary(boundary)81+ mw.WriteField("foo", "bar")82+ mw.WriteField("bar", "foo")83+ req, _ := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)84+ req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)85+ return req86+}87+88+func TestBindingFormPost(t *testing.T) {89+ req := createFormPostRequest()90+ var obj FooBarStruct91+ FormPost.Bind(req, &obj)92+93+ assert.Equal(t, obj.Foo, "bar")94+ assert.Equal(t, obj.Bar, "foo")95+}96+97+func TestBindingFormMultipart(t *testing.T) {98+ req := createFormMultipartRequest()99+ var obj FooBarStruct100+ FormMultipart.Bind(req, &obj)101+102+ assert.Equal(t, obj.Foo, "bar")103+ assert.Equal(t, obj.Bar, "foo")104+}105+106 func TestValidationFails(t *testing.T) {107 var obj FooStruct108 req := requestWithBody("POST", "/", `{"bar": "foo"}`)109 err := JSON.Bind(req, &obj)53 unmodified linesmodified:binding/binding.go+5 added-3 removed
31 unmodified lines32 33 var Validator StructValidator = &defaultValidator{}34 35 var (36- JSON = jsonBinding{}37- XML = xmlBinding{}38- Form = formBinding{}36+ JSON = jsonBinding{}37+ XML = xmlBinding{}38+ Form = formBinding{}39+ FormPost = formPostBinding{}40+ FormMultipart = formMultipartBinding{}41 )42 43 func Default(method, contentType string) Binding {44 if method == "GET" {19 unmodified linesmodified:binding/form_mapping.go-1 removed
54 unmodified lines55 if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {56 return err57 }58 }59-59 }60 return nil61 }62 88 unmodified linesmodified:binding/form.go+32 added-2 removed
5 unmodified lines6 7 import "net/http"8 9 type formBinding struct{}10+type formPostBinding struct{}11+type formMultipartBinding struct{}12 11-func (_ formBinding) Name() string {13+func (formBinding) Name() string {14 return "form"15 }16 15-func (_ formBinding) Bind(req *http.Request, obj interface{}) error {17+func (formBinding) Bind(req *http.Request, obj interface{}) error {18 if err := req.ParseForm(); err != nil {19 return err20 }21 req.ParseMultipartForm(32 << 10) // 32 MB1 unmodified line23 return err24 }25 return validate(obj)26 }27+28+func (formPostBinding) Name() string {29+ return "form-urlencoded"30+}31+32+func (formPostBinding) Bind(req *http.Request, obj interface{}) error {33+ if err := req.ParseForm(); err != nil {34+ return err35+ }36+ if err := mapForm(obj, req.PostForm); err != nil {37+ return err38+ }39+ return validate(obj)40+}41+42+func (formMultipartBinding) Name() string {43+ return "multipart/form-data"44+}45+46+func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error {47+ if err := req.ParseMultipartForm(32 << 10); err != nil {48+ return err49+ }50+ if err := mapForm(obj, req.MultipartForm.Value); err != nil {51+ return err52+ }53+ return validate(obj)54+}modified:binding/json.go+2 added-2 removed
10 unmodified lines11 )12 13 type jsonBinding struct{}14 15-func (_ jsonBinding) Name() string {15+func (jsonBinding) Name() string {16 return "json"17 }18 19-func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {19+func (jsonBinding) Bind(req *http.Request, obj interface{}) error {20 decoder := json.NewDecoder(req.Body)21 if err := decoder.Decode(obj); err != nil {22 return err23 }2 unmodified linesmodified:binding/xml.go+2 added-2 removed
9 unmodified lines10 )11 12 type xmlBinding struct{}13 14-func (_ xmlBinding) Name() string {14+func (xmlBinding) Name() string {15 return "xml"16 }17 18-func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {18+func (xmlBinding) Bind(req *http.Request, obj interface{}) error {19 decoder := xml.NewDecoder(req.Body)20 if err := decoder.Decode(obj); err != nil {21 return err22 }2 unmodified linesmodified:auth.go+7 added-9 removed
8 unmodified lines9 "encoding/base64"10 "strconv"11 )12 13-const (14- AuthUserKey = "user"13+const AuthUserKey = "user"15-)14 15 type (16 Accounts map[string]string17 authPair struct {14 unmodified lines32 }33 return "", false34 }35 38-// Implements a basic Basic HTTP Authorization. It takes as arguments a map[string]string where39-// the key is the user name and the value is the password, as well as the name of the Realm36+// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where37+// the key is the user name and the value is the password, as well as the name of the Realm.38+// If the realm is empty, "Authorization Required" will be used by default.39 // (see http://tools.ietf.org/html/rfc2617#section-1.2)40 func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {41 if realm == "" {42 realm = "Authorization Required"14 unmodified lines57 }58 }59 }60 62-// Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where61+// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where62 // the key is the user name and the value is the password.63 func BasicAuth(accounts Accounts) HandlerFunc {64 return BasicAuthForRealm(accounts, "")65 }23 unmodified lines89 90 func secureCompare(given, actual string) bool {91 if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {92 return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 194- } else {95- /* Securely compare actual to itself to keep constant time, but always return false */96- return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false93 }94+ /* Securely compare actual to itself to keep constant time, but always return false */95+ return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false96 }modified:CHANGELOG.md+10 added-1 removed
10 unmodified lines1112131415161718192021222324252627282930313237 unmodified lines7071727365747576777872 unmodified lines10 unmodified lines- [PERFORMANCE] Much faster SSE implementation- [NEW] Benchmarks suite- [NEW] Bind validation can be disabled and replaced with custom validators.- [NEW] More flexible HTML render- [NEW] Multipart and PostForm bindings- [NEW] Adds method to return all the registered routes- [NEW] Context.HandlerName() returns the main handler's name- [NEW] Adds Error.IsType() helper- [FIX] Binding multipart form- [FIX] Integration tests- [FIX] Crash when binding non struct object in Context.- [FIX] RunTLS() implementation- [FIX] Logger() unit tests- [FIX] Adds SetHTMLTemplate() warning- [FIX] Context.IsAborted()- [FIX] More unit tests- [FIX] JSON, XML, HTML renders accept custom content-types- [FIX] gin.AbortIndex is unexported- [FIX] Better approach to avoid directory listing in StaticFS()- [FIX] Context.ClientIP() always returns the IP with trimmed spaces.- [FIX] Better warning when running in debug mode.- [FIX] Google App Engine integration. debugPrint does not use os.Stdout37 unmodified lines- [FIX] Context.Engine renamed to Context.engine- [FIX] Better debugging messages- [FIX] ErrorLogger- [FIX] Debug HTTP render- [FIX] Refactored binding and render modules - [FIX] Refactored binding and render modules- [FIX] Refactored Context initialization- [FIX] Refactored BasicAuth()- [FIX] NoMethod/NoRoute handlers- [FIX] Hijacking http72 unmodified linesmodified:context_test.go+65 added-13 removed
40 unmodified lines41 42 must(mw.SetBoundary(boundary))43 must(mw.WriteField("foo", "bar"))44 must(mw.WriteField("bar", "foo"))45+ must(mw.WriteField("bar", "foo2"))46+ must(mw.WriteField("array", "first"))47+ must(mw.WriteField("array", "second"))48 req, err := http.NewRequest("POST", "/", body)49 must(err)50 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)51 return req27 unmodified lines79 assert.EqualValues(t, c.index, -1)80 assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)81 }82 83+func TestContextHandlers(t *testing.T) {84+ c, _, _ := createTestContext()85+ assert.Nil(t, c.handlers)86+ assert.Nil(t, c.handlers.Last())87+88+ c.handlers = HandlersChain{}89+ assert.NotNil(t, c.handlers)90+ assert.Nil(t, c.handlers.Last())91+92+ f := func(c *Context) {}93+ g := func(c *Context) {}94+95+ c.handlers = HandlersChain{f}96+ compareFunc(t, f, c.handlers.Last())97+98+ c.handlers = HandlersChain{f, g}99+ compareFunc(t, g, c.handlers.Last())100+}101+102 // TestContextSetGet tests that a parameter is set correctly on the103 // current context and can be retrieved using Get.104 func TestContextSetGet(t *testing.T) {105 c, _, _ := createTestContext()44 unmodified lines150 assert.Nil(t, cp.handlers)151 assert.Nil(t, cp.writermem.ResponseWriter)152 assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))153 assert.Equal(t, cp.Request, c.Request)132- assert.Equal(t, cp.index, AbortIndex)154+ assert.Equal(t, cp.index, abortIndex)155 assert.Equal(t, cp.Keys, c.Keys)156 assert.Equal(t, cp.engine, c.engine)157 assert.Equal(t, cp.Params, c.Params)158 }159 160+func TestContextHandlerName(t *testing.T) {161+ c, _, _ := createTestContext()162+ c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}163+164+ assert.Equal(t, c.HandlerName(), "github.com/gin-gonic/gin.handlerNameTest")165+}166+167+func handlerNameTest(c *Context) {168+169+}170+171 func TestContextQuery(t *testing.T) {172 c, _, _ := createTestContext()173 c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)174 11 unmodified lines186 }187 188 func TestContextQueryAndPostForm(t *testing.T) {189 c, _, _ := createTestContext()157- body := bytes.NewBufferString("foo=bar&page=11&both=POST")158- c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main", body)190+ body := bytes.NewBufferString("foo=bar&page=11&both=POST&foo=second")191+ c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body)192 c.Request.Header.Add("Content-Type", MIMEPOSTForm)193 194 assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")195 assert.Equal(t, c.PostForm("foo"), "bar")14 unmodified lines210 assert.Empty(t, c.PostForm("NoKey"))211 assert.Empty(t, c.Query("NoKey"))212 213 var obj struct {181- Foo string `form:"foo"`182- Id string `form:"id"`183- Page string `form:"page"`184- Both string `form:"both"`214+ Foo string `form:"foo"`215+ ID string `form:"id"`216+ Page string `form:"page"`217+ Both string `form:"both"`218+ Array []string `form:"array[]"`219 }220 assert.NoError(t, c.Bind(&obj))221 assert.Equal(t, obj.Foo, "bar")188- assert.Equal(t, obj.Id, "main")222+ assert.Equal(t, obj.ID, "main")223 assert.Equal(t, obj.Page, "11")224 assert.Equal(t, obj.Both, "POST")225+ assert.Equal(t, obj.Array, []string{"first", "second"})226 }227 228 func TestContextPostFormMultipart(t *testing.T) {229 c, _, _ := createTestContext()230 c.Request = createMultipartRequest()231 232 var obj struct {198- Foo string `form:"foo"`199- Bar string `form:"bar"`233+ Foo string `form:"foo"`234+ Bar string `form:"bar"`235+ Array []string `form:"array"`236 }237 assert.NoError(t, c.Bind(&obj))238 assert.Equal(t, obj.Bar, "foo")239 assert.Equal(t, obj.Foo, "bar")240+ assert.Equal(t, obj.Array, []string{"first", "second"})241 242 assert.Empty(t, c.Query("foo"))243 assert.Empty(t, c.Query("bar"))244 assert.Equal(t, c.PostForm("foo"), "bar")245+ assert.Equal(t, c.PostForm("array"), "first")246 assert.Equal(t, c.PostForm("bar"), "foo")247 }248 249 // Tests that the response is serialized as JSON100 unmodified lines350 "foo": "bar",351 "bar": "foo",352 })353 316- assert.Equal(t, w.Body.String(), "event: float\ndata: 1.5\n\nid: 123\ndata: text\n\nevent: chat\ndata: {\"bar\":\"foo\",\"foo\":\"bar\"}\n\n")354+ assert.Equal(t, w.Body.String(), "event:float\ndata:1.5\n\nid:123\ndata:text\n\nevent:chat\ndata:{\"bar\":\"foo\",\"foo\":\"bar\"}\n\n")355 }356 357 func TestContextRenderFile(t *testing.T) {358 c, w, _ := createTestContext()75 unmodified lines434 assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)435 assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)436 }437 438+func TestContextIsAborted(t *testing.T) {439+ c, _, _ := createTestContext()440+ assert.False(t, c.IsAborted())441+442+ c.Abort()443+ assert.True(t, c.IsAborted())444+445+ c.Next()446+ assert.True(t, c.IsAborted())447+448+ c.index++449+ assert.True(t, c.IsAborted())450+}451+452 // TestContextData tests that the response can be written from `bytesting`453 // with specified MIME type454 func TestContextAbortWithStatus(t *testing.T) {455 c, w, _ := createTestContext()456 c.index = 4457 c.AbortWithStatus(401)458 c.Writer.WriteHeaderNow()459 408- assert.Equal(t, c.index, AbortIndex)460+ assert.Equal(t, c.index, abortIndex)461 assert.Equal(t, c.Writer.Status(), 401)462 assert.Equal(t, w.Code, 401)463 assert.True(t, c.IsAborted())464 }43 unmodified lines508 c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")509 c.Writer.WriteHeaderNow()510 511 assert.Equal(t, w.Code, 401)460- assert.Equal(t, c.index, AbortIndex)512+ assert.Equal(t, c.index, abortIndex)513 assert.True(t, c.IsAborted())514 }515 516 func TestContextClientIP(t *testing.T) {91 unmodified linesmodified:context.go+58 added-30 removed
16 unmodified lines17 "github.com/manucorporat/sse"18 "golang.org/x/net/context"19 )20 21+// Content-Type MIME of the most common data formats22 const (23 MIMEJSON = binding.MIMEJSON24 MIMEHTML = binding.MIMEHTML25 MIMEXML = binding.MIMEXML2 unmodified lines28 MIMEPOSTForm = binding.MIMEPOSTForm29 MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm30 )31 31-const AbortIndex int8 = math.MaxInt8 / 232+const abortIndex int8 = math.MaxInt8 / 233 34 // Context is the most important part of gin. It allows us to pass variables between middleware,35 // manage the flow, validate the JSON of a request and render a JSON response for example.36 type Context struct {26 unmodified lines63 c.Errors = c.Errors[0:0]64 c.Accepted = nil65 }66 67+// Copy returns a copy of the current context that can be safely used outside the request's scope.68+// This have to be used then the context has to be passed to a goroutine.69 func (c *Context) Copy() *Context {70 var cp Context = *c71 cp.writermem.ResponseWriter = nil72 cp.Writer = &cp.writermem70- cp.index = AbortIndex73+ cp.index = abortIndex74 cp.handlers = nil75 return &cp76 }77 78+// HandlerName returns the main handle's name. For example if the handler is "handleGetUsers()", this79+// function will return "main.handleGetUsers"80+func (c *Context) HandlerName() string {81+ return nameOfFunction(c.handlers.Last())82+}83+84 /************************************/85 /*********** FLOW CONTROL ***********/86 /************************************/87 7 unmodified lines95 c.handlers[c.index](c)96 }97 }98 90-// Returns if the currect context was aborted.99+// IsAborted returns true if the currect context was aborted.100 func (c *Context) IsAborted() bool {92- return c.index == AbortIndex101+ return c.index >= abortIndex102 }103 95-// Stops the system to continue calling the pending handlers in the chain.104+// Abort stops the system to continue calling the pending handlers in the chain.105 // Let's say you have an authorization middleware that validates if the request is authorized106 // if the authorization fails (the password does not match). This method (Abort()) should be called107 // in order to stop the execution of the actual handler.108 func (c *Context) Abort() {100- c.index = AbortIndex109+ c.index = abortIndex110 }111 103-// It calls Abort() and writes the headers with the specified status code.112+// AbortWithStatus calls `Abort()` and writes the headers with the specified status code.113 // For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).114 func (c *Context) AbortWithStatus(code int) {115 c.Writer.WriteHeader(code)116 c.Abort()117 }118 110-// It calls AbortWithStatus() and Error() internally. This method stops the chain, writes the status code and119+// AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and120 // pushes the specified error to `c.Errors`.121 // See Context.Error() for more details.122 func (c *Context) AbortWithError(code int, err error) *Error {123 c.AbortWithStatus(code)5 unmodified lines129 /************************************/130 131 // Attaches an error to the current context. The error is pushed to a list of errors.132 // It's a good idea to call Error for each error that occurred during the resolution of a request.124-// 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.133+// A middleware can be used to collect all the errors134+// and push them to a database together, print a log, or append it in the HTTP response.135 func (c *Context) Error(err error) *Error {136 var parsedError *Error137 switch err.(type) {138 case *Error:11 unmodified lines150 /************************************/151 /******** METADATA MANAGEMENT********/152 /************************************/153 144-// Sets a new pair key/value just for this context.145-// It also lazy initializes the hashmap if it was not used previously.154+// Set is used to store a new key/value pair exclusivelly for this context.155+// It also lazy initializes c.Keys if it was not used previously.156 func (c *Context) Set(key string, value interface{}) {157 if c.Keys == nil {158 c.Keys = make(map[string]interface{})159 }160 c.Keys[key] = value161 }162 153-// Returns the value for the given key, ie: (value, true).163+// Get returns the value for the given key, ie: (value, true).164 // If the value does not exists it returns (nil, false)165 func (c *Context) Get(key string) (value interface{}, exists bool) {166 if c.Keys != nil {167 value, exists = c.Keys[key]12 unmodified lines180 /************************************/181 /************ INPUT DATA ************/182 /************************************/183 174-// Shortcut for c.Request.URL.Query().Get(key)184+// Query is a shortcut for c.Request.URL.Query().Get(key)185+// It is used to return the url query values.186+// ?id=1234&name=Manu187+// c.Query("id") == "1234"188+// c.Query("name") == "Manu"189+// c.Query("wtf") == ""190 func (c *Context) Query(key string) (va string) {191 va, _ = c.query(key)192 return193 }194 180-// Shortcut for c.Request.PostFormValue(key)195+// PostForm is a shortcut for c.Request.PostFormValue(key)196 func (c *Context) PostForm(key string) (va string) {197 va, _ = c.postForm(key)198 return199 }200 186-// Shortcut for c.Params.ByName(key)201+// Param is a shortcut for c.Params.ByName(key)202 func (c *Context) Param(key string) string {203 return c.Params.ByName(key)204 }205 3 unmodified lines209 }210 return defaultValue211 }212 213+// DefaultQuery returns the keyed url query value if it exists, othewise it returns the214+// specified defaultValue.215+// ```216+// /?name=Manu217+// c.DefaultQuery("name", "unknown") == "Manu"218+// c.DefaultQuery("id", "none") == "none"219+// ```220 func (c *Context) DefaultQuery(key, defaultValue string) string {221 if va, ok := c.query(key); ok {222 return va223 }21 unmodified lines245 }246 return "", false247 }248 227-// This function checks the Content-Type to select a binding engine automatically,249+// Bind checks the Content-Type to select a binding engine automatically,250 // Depending the "Content-Type" header different bindings are used:251 // "application/json" --> JSON binding252 // "application/xml" --> XML binding231-// else --> returns an error232-// if Parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer.Like ParseBody() but this method also writes a 400 error if the json is not valid.253+// otherwise --> returns an error254+// If Parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.255+// It decodes the json payload into the struct specified as a pointer.256+// Like ParseBody() but this method also writes a 400 error if the json is not valid.257 func (c *Context) Bind(obj interface{}) error {258 b := binding.Default(c.Request.Method, c.ContentType())259 return c.BindWith(obj, b)260 }261 238-// Shortcut for c.BindWith(obj, binding.JSON)262+// BindJSON is a shortcut for c.BindWith(obj, binding.JSON)263 func (c *Context) BindJSON(obj interface{}) error {264 return c.BindWith(obj, binding.JSON)265 }266 267+// BindWith binds the passed struct pointer using the specified binding engine.268+// See the binding package.269 func (c *Context) BindWith(obj interface{}, b binding.Binding) error {270 if err := b.Bind(c.Request, obj); err != nil {271 c.AbortWithError(400, err).SetType(ErrorTypeBind)272 return err273 }274 return nil275 }276 251-// Best effort algoritm to return the real client IP, it parses277+// ClientIP implements a best effort algorithm to return the real client IP, it parses278 // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.279 func (c *Context) ClientIP() string {280 if c.engine.ForwardedByClientIP {281 clientIP := strings.TrimSpace(c.requestHeader("X-Real-Ip"))11 unmodified lines293 }294 return strings.TrimSpace(c.Request.RemoteAddr)295 }296 297+// ContentType returns the Content-Type header of the request.298 func (c *Context) ContentType() string {299 return filterFlags(c.requestHeader("Content-Type"))300 }301 7 unmodified lines309 /************************************/310 /******** RESPONSE RENDERING ********/311 /************************************/312 286-// Intelligent shortcut for c.Writer.Header().Set(key, value)287-// it writes a header in the response.313+// Header is a intelligent shortcut for c.Writer.Header().Set(key, value)314+// It writes a header in the response.315 // If value == "", this method removes the header `c.Writer.Header().Del(key)`316 func (c *Context) Header(key, value string) {317 if len(value) == 0 {318 c.Writer.Header().Del(key)13 unmodified lines332 debugPrintError(err)333 c.AbortWithError(500, err).SetType(ErrorTypeRender)334 }335 309-// Renders the HTTP template specified by its file name.336+// HTML renders the HTTP template specified by its file name.337 // It also updates the HTTP code and sets the Content-Type as "text/html".338 // See http://golang.org/doc/articles/wiki/339 func (c *Context) HTML(code int, name string, obj interface{}) {340 instance := c.engine.HTMLRender.Instance(name, obj)341 c.Render(code, instance)342 }343 317-// Serializes the given struct as pretty JSON (indented + endlines) into the response body.344+// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.345 // It also sets the Content-Type as "application/json".346 // WARNING: we recommend to use this only for development propuses since printing pretty JSON is347 // more CPU and bandwidth consuming. Use Context.JSON() instead.348 func (c *Context) IndentedJSON(code int, obj interface{}) {349 c.Render(code, render.IndentedJSON{Data: obj})350 }351 325-// Serializes the given struct as JSON into the response body.352+// JSON serializes the given struct as JSON into the response body.353 // It also sets the Content-Type as "application/json".354 func (c *Context) JSON(code int, obj interface{}) {355 c.writermem.WriteHeader(code)356 if err := render.WriteJSON(c.Writer, obj); err != nil {357 c.renderError(err)358 }359 }360 334-// Serializes the given struct as XML into the response body.361+// XML serializes the given struct as XML into the response body.362 // It also sets the Content-Type as "application/xml".363 func (c *Context) XML(code int, obj interface{}) {364 c.Render(code, render.XML{Data: obj})365 }366 340-// Writes the given string into the response body.367+// String writes the given string into the response body.368 func (c *Context) String(code int, format string, values ...interface{}) {369 c.writermem.WriteHeader(code)370 render.WriteString(c.Writer, format, values)371 }372 346-// Returns a HTTP redirect to the specific location.373+// Redirect returns a HTTP redirect to the specific location.374 func (c *Context) Redirect(code int, location string) {375 c.Render(-1, render.Redirect{376 Code: code,377 Location: location,378 Request: c.Request,379 })380 }381 355-// Writes some data into the body stream and updates the HTTP code.382+// Data writes some data into the body stream and updates the HTTP code.383 func (c *Context) Data(code int, contentType string, data []byte) {384 c.Render(code, render.Data{385 ContentType: contentType,386 Data: data,387 })388 }389 363-// Writes the specified file into the body stream in a efficient way.390+// File writes the specified file into the body stream in a efficient way.391 func (c *Context) File(filepath string) {392 http.ServeFile(c.Writer, c.Request, filepath)393 }394 395+// SSEvent writes a Server-Sent Event into the body stream.396 func (c *Context) SSEvent(name string, message interface{}) {397 c.Render(-1, sse.Event{398 Event: name,399 Data: message,102 unmodified linesmodified:debug_test.go+9 added
55 unmodified lines56 debugPrintError(errors.New("this is an error"))57 assert.Equal(t, w.String(), "[GIN-debug] [ERROR] this is an error\n")58 }59 60+func TestDebugPrintRoutes(t *testing.T) {61+ var w bytes.Buffer62+ setup(&w)63+ defer teardown()64+65+ debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest})66+ assert.Equal(t, w.String(), "[GIN-debug] GET /path/to/route/:param --> github.com/gin-gonic/gin.handlerNameTest (2 handlers)\n")67+}68+69 func setup(w io.Writer) {70 SetMode(DebugMode)71 log.SetOutput(w)72 }5 unmodified linesmodified:debug.go+32 added-3 removed
2 unmodified lines3 // license that can be found in the LICENSE file.4 5 package gin6 7-import "log"7+import (8+ "bytes"9+ "html/template"10+ "log"11+)12 13 func init() {14 log.SetFlags(0)15 }16+17+// IsDebugging returns true if the framework is running in debug mode.18+// Use SetMode(gin.Release) to switch to disable the debug mode.19 func IsDebugging() bool {20 return ginMode == debugCode21 }22 23 func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {24 if IsDebugging() {25 nuHandlers := len(handlers)19- handlerName := nameOfFunction(handlers[nuHandlers-1])26+ handlerName := nameOfFunction(handlers.Last())27 debugPrint("%-5s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)28 }29 }30 31+func debugPrintLoadTemplate(tmpl *template.Template) {32+ if IsDebugging() {33+ var buf bytes.Buffer34+ for _, tmpl := range tmpl.Templates() {35+ buf.WriteString("\t- ")36+ buf.WriteString(tmpl.Name())37+ buf.WriteString("\n")38+ }39+ debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String())40+ }41+}42+43 func debugPrint(format string, values ...interface{}) {44 if IsDebugging() {45 log.Printf("[GIN-debug] "+format, values...)46 }47 }48 30-func debugPrintWARNING() {49+func debugPrintWARNINGNew() {50 debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production.51 - using env: export GIN_MODE=release52 - using code: gin.SetMode(gin.ReleaseMode)53 54 `)55 }56 57+func debugPrintWARNINGSetHTMLTemplate() {58+ debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called59+at initialization. ie. before any route is registered or the router is listening in a socket:60+61+ router := gin.Default()62+ router.SetHTMLTemplate(template) // << good place63+64+`)65+}66+67 func debugPrintError(err error) {68 if err != nil {69 debugPrint("[ERROR] %v\n", err)70 }1 unmodified linemodified:errors_test.go+1 added
61 unmodified lines62 {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"},63 {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}},64 }65 66+ assert.Equal(t, errs, errs.ByType(ErrorTypeAny))67 assert.Equal(t, errs.Last().Error(), "third")68 assert.Equal(t, errs.Errors(), []string{"first", "second", "third"})69 assert.Equal(t, errs.ByType(ErrorTypePublic).Errors(), []string{"third"})70 assert.Equal(t, errs.ByType(ErrorTypePrivate).Errors(), []string{"first", "second"})29 unmodified linesmodified:errors.go+3 added-3 removed
100 unmodified lines101 // Returns the last error in the slice. It returns nil if the array is empty.102 // Shortcut for errors[len(errors)-1]103 func (a errorMsgs) Last() *Error {104 length := len(a)105- if length == 0 {106- return nil105+ if length > 0 {106+ return a[length-1]107 }108- return a[length-1]108+ return nil109 }110 111 // Returns an array will all the error messages.112 // Example49 unmodified linesmodified:fs.go+2 added-3 removed
12 unmodified lines13 http.File14 }15 )16 17-// It returns a http.Filesystem that can be used by http.FileServer(). It is used interally17+// Dir returns a http.Filesystem that can be used by http.FileServer(). It is used interally18 // in router.Static().19 // if listDirectory == true, then it works the same as http.Dir() otherwise it returns20 // a filesystem that prevents http.FileServer() to list the directory files.21 func Dir(root string, listDirectory bool) http.FileSystem {22 fs := http.Dir(root)23 if listDirectory {24 return fs25- } else {26- return &onlyfilesFS{fs}25 }26+ return &onlyfilesFS{fs}27 }28 29 // Conforms to http.Filesystem30 func (fs onlyfilesFS) Open(name string) (http.File, error) {12 unmodified linesmodified:gin_integration_test.go+53 added-16 removed
1 package gin2 3 import (4 "bufio"5- "bytes"5 "fmt"6 "io/ioutil"7 "net"8 "net/http"9+ "os"10 "testing"11 "time"12 13 "github.com/stretchr/testify/assert"14 )15 16-func TestRun(t *testing.T) {17- buffer := new(bytes.Buffer)16+func testRequest(t *testing.T, url string) {17+ resp, err := http.Get(url)18+ defer resp.Body.Close()19+ assert.NoError(t, err)20+21+ body, ioerr := ioutil.ReadAll(resp.Body)22+ assert.NoError(t, ioerr)23+ assert.Equal(t, "it worked", string(body), "resp body should match")24+ assert.Equal(t, "200 OK", resp.Status, "should get a 200")25+}26+27+func TestRunEmpty(t *testing.T) {28+ SetMode(DebugMode)29+ os.Setenv("PORT", "")30 router := New()31 go func() {20- router.Use(LoggerWithWriter(buffer))32 router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })22- router.Run(":5150")33+ assert.NoError(t, router.Run())34 }()35 // have to wait for the goroutine to start and run the server36 // otherwise the main thread will complete37 time.Sleep(5 * time.Millisecond)38 28- assert.Error(t, router.Run(":5150"))39+ assert.Error(t, router.Run(":8080"))40+ testRequest(t, "http://localhost:8080/example")41+}42 30- resp, err := http.Get("http://localhost:5150/example")31- defer resp.Body.Close()32- assert.NoError(t, err)43+func TestRunEmptyWithEnv(t *testing.T) {44+ os.Setenv("PORT", "3123")45+ router := New()46+ go func() {47+ router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })48+ assert.NoError(t, router.Run())49+ }()50+ // have to wait for the goroutine to start and run the server51+ // otherwise the main thread will complete52+ time.Sleep(5 * time.Millisecond)53 34- body, ioerr := ioutil.ReadAll(resp.Body)35- assert.NoError(t, ioerr)36- assert.Equal(t, "it worked", string(body[:]), "resp body should match")37- assert.Equal(t, "200 OK", resp.Status, "should get a 200")54+ assert.Error(t, router.Run(":3123"))55+ testRequest(t, "http://localhost:3123/example")56 }57 58+func TestRunTooMuchParams(t *testing.T) {59+ router := New()60+ assert.Panics(t, func() {61+ router.Run("2", "2")62+ })63+}64+65+func TestRunWithPort(t *testing.T) {66+ router := New()67+ go func() {68+ router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })69+ assert.NoError(t, router.Run(":5150"))70+ }()71+ // have to wait for the goroutine to start and run the server72+ // otherwise the main thread will complete73+ time.Sleep(5 * time.Millisecond)74+75+ assert.Error(t, router.Run(":5150"))76+ testRequest(t, "http://localhost:5150/example")77+}78+79 func TestUnixSocket(t *testing.T) {41- buffer := new(bytes.Buffer)80 router := New()81 82 go func() {45- router.Use(LoggerWithWriter(buffer))83 router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })47- router.RunUnix("/tmp/unix_unit_test")84+ assert.NoError(t, router.RunUnix("/tmp/unix_unit_test"))85 }()86 // have to wait for the goroutine to start and run the server87 // otherwise the main thread will complete88 time.Sleep(5 * time.Millisecond)18 unmodified linesmodified:gin_test.go+65 added-2 removed
12 unmodified lines13 14 //TODO15 // func (engine *Engine) LoadHTMLGlob(pattern string) {16 // func (engine *Engine) LoadHTMLFiles(files ...string) {17-// func (engine *Engine) Run(addr string) error {17 // func (engine *Engine) RunTLS(addr string, cert string, key string) error {18 19 func init() {20 SetMode(TestMode)21 }22 23 func TestCreateEngine(t *testing.T) {24 router := New()26- assert.Equal(t, "/", router.BasePath)25+ assert.Equal(t, "/", router.basePath)26 assert.Equal(t, router.engine, router)27 assert.Empty(t, router.Handlers)28 }29 30+// func TestLoadHTMLDebugMode(t *testing.T) {31+// router := New()32+// SetMode(DebugMode)33+// router.LoadHTMLGlob("*.testtmpl")34+// r := router.HTMLRender.(render.HTMLDebug)35+// assert.Empty(t, r.Files)36+// assert.Equal(t, r.Glob, "*.testtmpl")37+//38+// router.LoadHTMLFiles("index.html.testtmpl", "login.html.testtmpl")39+// r = router.HTMLRender.(render.HTMLDebug)40+// assert.Empty(t, r.Glob)41+// assert.Equal(t, r.Files, []string{"index.html", "login.html"})42+// SetMode(TestMode)43+// }44+45+func TestLoadHTMLReleaseMode(t *testing.T) {46+47+}48+49 func TestAddRoute(t *testing.T) {50 router := New()51 router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})52 144 unmodified lines197 if sf1.Pointer() != sf2.Pointer() {198 t.Error("different functions")199 }200 }201+202+func TestListOfRoutes(t *testing.T) {203+ router := New()204+ router.GET("/favicon.ico", handler_test1)205+ router.GET("/", handler_test1)206+ group := router.Group("/users")207+ {208+ group.GET("/", handler_test2)209+ group.GET("/:id", handler_test1)210+ group.POST("/:id", handler_test2)211+ }212+ router.Static("/static", ".")213+214+ list := router.Routes()215+216+ assert.Len(t, list, 7)217+ assert.Contains(t, list, RouteInfo{218+ Method: "GET",219+ Path: "/favicon.ico",220+ Handler: "github.com/gin-gonic/gin.handler_test1",221+ })222+ assert.Contains(t, list, RouteInfo{223+ Method: "GET",224+ Path: "/",225+ Handler: "github.com/gin-gonic/gin.handler_test1",226+ })227+ assert.Contains(t, list, RouteInfo{228+ Method: "GET",229+ Path: "/users/",230+ Handler: "github.com/gin-gonic/gin.handler_test2",231+ })232+ assert.Contains(t, list, RouteInfo{233+ Method: "GET",234+ Path: "/users/:id",235+ Handler: "github.com/gin-gonic/gin.handler_test1",236+ })237+ assert.Contains(t, list, RouteInfo{238+ Method: "POST",239+ Path: "/users/:id",240+ Handler: "github.com/gin-gonic/gin.handler_test2",241+ })242+}243+244+func handler_test1(c *Context) {}245+func handler_test2(c *Context) {}modified:gin.go+68 added-23 removed
12 unmodified lines13 14 "github.com/gin-gonic/gin/render"15 )16 17+// Framework's version18 const Version = "v1.0rc2"19 20 var default404Body = []byte("404 page not found")21 var default405Body = []byte("405 method not allowed")22 23+type HandlerFunc func(*Context)24+type HandlersChain []HandlerFunc25+26+// Last returns the last handler in the chain. ie. the last handler is the main own.27+func (c HandlersChain) Last() HandlerFunc {28+ length := len(c)29+ if length > 0 {30+ return c[length-1]31+ }32+ return nil33+}34+35 type (23- HandlerFunc func(*Context)24- HandlersChain []HandlerFunc36+ RoutesInfo []RouteInfo37+ RouteInfo struct {38+ Method string39+ Path string40+ Handler string41+ }42 26- // Represents the web framework, it wraps the blazing fast httprouter multiplexer and a list of global middleware.43+ // Engine is the framework's instance, it contains the muxer, middleware and configuration settings.44+ // Create an instance of Engine, by using New() or Default()45 Engine struct {46 RouterGroup47 HTMLRender render.HTMLRender48 allNoRoute HandlersChain31 unmodified lines80 ForwardedByClientIP bool81 }82 )83 84+var _ IRouter = &Engine{}85+66-// Returns a new blank Engine instance without any middleware attached.67-// The most basic configuration86+// New returns a new blank Engine instance without any middleware attached.87+// By default the configuration is:88+// - RedirectTrailingSlash: true89+// - RedirectFixedPath: false90+// - HandleMethodNotAllowed: false91+// - ForwardedByClientIP: true92 func New() *Engine {69- debugPrintWARNING()93+ debugPrintWARNINGNew()94 engine := &Engine{95 RouterGroup: RouterGroup{96 Handlers: nil,73- BasePath: "/",97+ basePath: "/",98 root: true,99 },100 RedirectTrailingSlash: true,101 RedirectFixedPath: false,7 unmodified lines109 }110 return engine111 }112 89-// Returns a Engine instance with the Logger and Recovery already attached.113+// Default returns an Engine instance with the Logger and Recovery middleware already attached.114 func Default() *Engine {115 engine := New()116 engine.Use(Recovery(), Logger())117 return engine4 unmodified lines122 }123 124 func (engine *Engine) LoadHTMLGlob(pattern string) {125 if IsDebugging() {126+ debugPrintLoadTemplate(template.Must(template.ParseGlob(pattern)))127 engine.HTMLRender = render.HTMLDebug{Glob: pattern}128 } else {129 templ := template.Must(template.ParseGlob(pattern))130 engine.SetHTMLTemplate(templ)10 unmodified lines141 }142 143 func (engine *Engine) SetHTMLTemplate(templ *template.Template) {144 if len(engine.trees) > 0 {120- debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called121-at initialization. ie. before any route is registered or the router is listening in a socket:122-123- router := gin.Default()124- router.SetHTMLTemplate(template) // << good place125-`)145+ debugPrintWARNINGSetHTMLTemplate()146 }147 engine.HTMLRender = render.HTMLProduction{Template: templ}148 }149 11 unmodified lines161 162 // Attachs a global middleware to the router. ie. the middleware attached though Use() will be163 // included in the handlers chain for every single request. Even 404, 405, static files...164 // For example, this is the right place for a logger or error management middleware.145-func (engine *Engine) Use(middleware ...HandlerFunc) routesInterface {165+func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {166 engine.RouterGroup.Use(middleware...)167 engine.rebuild404Handlers()168 engine.rebuild405Handlers()169 return engine30 unmodified lines200 }201 root.addRoute(path, handlers)202 }203 204+// Routes returns a slice of registered routes, including some useful information, such as:205+// the http method, path and the handler name.206+func (engine *Engine) Routes() (routes RoutesInfo) {207+ for _, tree := range engine.trees {208+ routes = iterate("", tree.method, routes, tree.root)209+ }210+ return routes211+}212+213+func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {214+ path += root.path215+ if len(root.handlers) > 0 {216+ routes = append(routes, RouteInfo{217+ Method: method,218+ Path: path,219+ Handler: nameOfFunction(root.handlers.Last()),220+ })221+ }222+ for _, child := range root.children {223+ routes = iterate(path, method, routes, child)224+ }225+ return routes226+}227+184-// The router is attached to a http.Server and starts listening and serving HTTP requests.228+// Run attaches the router to a http.Server and starts listening and serving HTTP requests.229 // It is a shortcut for http.ListenAndServe(addr, router)230 // Note: this method will block the calling goroutine undefinitelly unless an error happens.187-func (engine *Engine) Run(addr string) (err error) {188- debugPrint("Listening and serving HTTP on %s\n", addr)231+func (engine *Engine) Run(addr ...string) (err error) {232 defer func() { debugPrintError(err) }()233 234+ address := resolveAddress(addr)235+ debugPrint("Listening and serving HTTP on %s\n", address)191- err = http.ListenAndServe(addr, engine)236+ err = http.ListenAndServe(address, engine)237 return238 }239 195-// The router is attached to a http.Server and starts listening and serving HTTPS requests.240+// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.241 // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)242 // Note: this method will block the calling goroutine undefinitelly unless an error happens.243 func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {244 debugPrint("Listening and serving HTTPS on %s\n", addr)2 unmodified lines247 err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)248 return249 }250 206-// The router is attached to a http.Server and starts listening and serving HTTP requests207-// through the specified unix socket (ie. a file)251+// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests252+// through the specified unix socket (ie. a file).253 // Note: this method will block the calling goroutine undefinitelly unless an error happens.254 func (engine *Engine) RunUnix(file string) (err error) {255 debugPrint("Listening and serving HTTP on unix:/%s", file)256 defer func() { debugPrintError(err) }()38 unmodified lines295 context.writermem.WriteHeaderNow()296 return297 298 } else if httpMethod != "CONNECT" && path != "/" {254- if tsr && engine.RedirectFixedPath {299+ if tsr && engine.RedirectTrailingSlash {300 redirectTrailingSlash(context)301 return302 }303 if engine.RedirectFixedPath && redirectFixedPath(context, root, engine.RedirectFixedPath) {77 unmodified linesmodified:logger_test.go+28 added
4 unmodified lines5 package gin6 7 import (8 "bytes"9+ "errors"10 "testing"11 12 "github.com/stretchr/testify/assert"13 )82 unmodified lines96 assert.Equal(t, colorForStatus(301), string([]byte{27, 91, 57, 48, 59, 52, 55, 109}), "3xx should be white")97 assert.Equal(t, colorForStatus(404), string([]byte{27, 91, 57, 55, 59, 52, 51, 109}), "4xx should be yellow")98 assert.Equal(t, colorForStatus(2), string([]byte{27, 91, 57, 55, 59, 52, 49, 109}), "other things should be red")99 }100+101+func TestErrorLogger(t *testing.T) {102+ router := New()103+ router.Use(ErrorLogger())104+ router.GET("/error", func(c *Context) {105+ c.Error(errors.New("this is an error"))106+ })107+ router.GET("/abort", func(c *Context) {108+ c.AbortWithError(401, errors.New("no authorized"))109+ })110+ router.GET("/print", func(c *Context) {111+ c.Error(errors.New("this is an error"))112+ c.String(500, "hola!")113+ })114+115+ w := performRequest(router, "GET", "/error")116+ assert.Equal(t, w.Code, 200)117+ assert.Equal(t, w.Body.String(), "{\"error\":\"this is an error\"}\n")118+119+ w = performRequest(router, "GET", "/abort")120+ assert.Equal(t, w.Code, 401)121+ assert.Equal(t, w.Body.String(), "{\"error\":\"no authorized\"}\n")122+123+ w = performRequest(router, "GET", "/print")124+ assert.Equal(t, w.Code, 500)125+ assert.Equal(t, w.Body.String(), "hola!")126+}modified:middleware_test.go+2 added-2 removed
246 unmodified lines247 assert.Equal(t, w.Code, 400)248 assert.Equal(t, w.Body.String(), `hola249 <map><foo>bar</foo></map>{"foo":"bar"}250 {"foo":"bar"}251-event: test252-data: message251+event:test252+data:message253 254 `)255 }modified:README.md+101 added-69 removed
1-#Gin Web Framework [](https://travis-ci.org/gin-gonic/gin) [](https://coveralls.io/r/gin-gonic/gin?branch=master) 1 2+#Gin Web Framework3+<img align="right" src="https://s3.amazonaws.com/uploads.hipchat.com/36744/1498287/JVR32LgyEGCiy01/path4201%20copy%202.png">4+[](https://travis-ci.org/gin-gonic/gin)5+[](https://coveralls.io/r/gin-gonic/gin?branch=master)6+[](https://godoc.org/github.com/gin-gonic/gin)3- [](https://godoc.org/github.com/gin-gonic/gin) [](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)7+[](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)8 9 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.10 11+12+13 14 15 ```16 $ cat test.go18 unmodified lines35 36 [See all benchmarks](/BENCHMARKS.md)37 38 33-```34-BenchmarkAce_GithubAll 10000 109482 ns/op 13792 B/op 167 allocs/op35-BenchmarkBear_GithubAll 10000 287490 ns/op 79952 B/op 943 allocs/op36-BenchmarkBeego_GithubAll 3000 562184 ns/op 146272 B/op 2092 allocs/op37-BenchmarkBone_GithubAll 500 2578716 ns/op 648016 B/op 8119 allocs/op38-BenchmarkDenco_GithubAll 20000 94955 ns/op 20224 B/op 167 allocs/op39-BenchmarkEcho_GithubAll 30000 58705 ns/op 0 B/op 0 allocs/op40-BenchmarkGin_GithubAll 30000 50991 ns/op 0 B/op 0 allocs/op41-BenchmarkGocraftWeb_GithubAll 5000 449648 ns/op 133280 B/op 1889 allocs/op42-BenchmarkGoji_GithubAll 2000 689748 ns/op 56113 B/op 334 allocs/op43-BenchmarkGoJsonRest_GithubAll 5000 537769 ns/op 135995 B/op 2940 allocs/op44-BenchmarkGoRestful_GithubAll 100 18410628 ns/op 797236 B/op 7725 allocs/op45-BenchmarkGorillaMux_GithubAll 200 8036360 ns/op 153137 B/op 1791 allocs/op46-BenchmarkHttpRouter_GithubAll 20000 63506 ns/op 13792 B/op 167 allocs/op47-BenchmarkHttpTreeMux_GithubAll 10000 165927 ns/op 56112 B/op 334 allocs/op48-BenchmarkKocha_GithubAll 10000 171362 ns/op 23304 B/op 843 allocs/op49-BenchmarkMacaron_GithubAll 2000 817008 ns/op 224960 B/op 2315 allocs/op50-BenchmarkMartini_GithubAll 100 12609209 ns/op 237952 B/op 2686 allocs/op51-BenchmarkPat_GithubAll 300 4830398 ns/op 1504101 B/op 32222 allocs/op52-BenchmarkPossum_GithubAll 10000 301716 ns/op 97440 B/op 812 allocs/op53-BenchmarkR2router_GithubAll 10000 270691 ns/op 77328 B/op 1182 allocs/op54-BenchmarkRevel_GithubAll 1000 1491919 ns/op 345553 B/op 5918 allocs/op55-BenchmarkRivet_GithubAll 10000 283860 ns/op 84272 B/op 1079 allocs/op56-BenchmarkTango_GithubAll 5000 473821 ns/op 87078 B/op 2470 allocs/op57-BenchmarkTigerTonic_GithubAll 2000 1120131 ns/op 241088 B/op 6052 allocs/op58-BenchmarkTraffic_GithubAll 200 8708979 ns/op 2664762 B/op 22390 allocs/op59-BenchmarkVulcan_GithubAll 5000 353392 ns/op 19894 B/op 609 allocs/op60-BenchmarkZeus_GithubAll 2000 944234 ns/op 300688 B/op 2648 allocs/op61-```39+Benchmark name | (1) | (2) | (3) | (4)40+--------------------------------|----------:|----------:|----------:|------:41+BenchmarkAce_GithubAll | 10000 | 109482 | 13792 | 16742+BenchmarkBear_GithubAll | 10000 | 287490 | 79952 | 94343+BenchmarkBeego_GithubAll | 3000 | 562184 | 146272 | 209244+BenchmarkBone_GithubAll | 500 | 2578716 | 648016 | 811945+BenchmarkDenco_GithubAll | 20000 | 94955 | 20224 | 16746+BenchmarkEcho_GithubAll | 30000 | 58705 | 0 | 047+**BenchmarkGin_GithubAll** | **30000** | **50991** | **0** | **0**48+BenchmarkGocraftWeb_GithubAll | 5000 | 449648 | 133280 | 188949+BenchmarkGoji_GithubAll | 2000 | 689748 | 56113 | 33450+BenchmarkGoJsonRest_GithubAll | 5000 | 537769 | 135995 | 294051+BenchmarkGoRestful_GithubAll | 100 | 18410628 | 797236 | 772552+BenchmarkGorillaMux_GithubAll | 200 | 8036360 | 153137 | 179153+BenchmarkHttpRouter_GithubAll | 20000 | 63506 | 13792 | 16754+BenchmarkHttpTreeMux_GithubAll | 10000 | 165927 | 56112 | 33455+BenchmarkKocha_GithubAll | 10000 | 171362 | 23304 | 84356+BenchmarkMacaron_GithubAll | 2000 | 817008 | 224960 | 231557+BenchmarkMartini_GithubAll | 100 | 12609209 | 237952 | 268658+BenchmarkPat_GithubAll | 300 | 4830398 | 1504101 | 3222259+BenchmarkPossum_GithubAll | 10000 | 301716 | 97440 | 81260+BenchmarkR2router_GithubAll | 10000 | 270691 | 77328 | 118261+BenchmarkRevel_GithubAll | 1000 | 1491919 | 345553 | 591862+BenchmarkRivet_GithubAll | 10000 | 283860 | 84272 | 107963+BenchmarkTango_GithubAll | 5000 | 473821 | 87078 | 247064+BenchmarkTigerTonic_GithubAll | 2000 | 1120131 | 241088 | 605265+BenchmarkTraffic_GithubAll | 200 | 8708979 | 2664762 | 2239066+BenchmarkVulcan_GithubAll | 5000 | 353392 | 19894 | 60967+BenchmarkZeus_GithubAll | 2000 | 944234 | 300688 | 264868 69+(1): Total Repetitions 70+(2): Single Repetition Duration (ns/op) 71+(3): Heap Memory (B/op) 72+(4): Average Allocations per Repetition (allocs/op) 73 74 ##Gin v1. stable75 76 - [x] Zero allocation router.98 unmodified lines175 router.Run(":8080")176 }177 ```178 179+### Another example: query + post form180+181+```182+POST /post?id=1234&page=1 HTTP/1.1183+Content-Type: application/x-www-form-urlencoded184+185+name=manu&message=this_is_great186+```187+188+```go189+func main() {190+ router := gin.Default()191+192+ router.POST("/post", func(c *gin.Context) {193+ id := c.Query("id")194+ page := c.DefaultQuery("id", "0")195+ name := c.PostForm("name")196+ message := c.PostForm("message")197+198+ fmt.Println("id: %s; page: %s; name: %s; message: %s", id, page, name, message)199+ })200+ router.Run(":8080")201+}202+```203+204+```205+id: 1234; page: 0; name: manu; message: this_is_great206+```207+208+209 #### Grouping routes210 ```go211 func main() {212 router := gin.Default()79 unmodified lines292 You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, the current request will fail with an error.293 294 ```go295 // Binding from JSON256-type LoginJSON struct {257- User string `json:"user" binding:"required"`258- Password string `json:"password" binding:"required"`296+type Login struct {297+ User string `form:"user" json:"user" binding:"required"`298+ Password string `form:"password" json:"password" binding:"required"`299 }300 261-// Binding from form values262-type LoginForm struct {263- User string `form:"user" binding:"required"`264- Password string `form:"password" binding:"required"`265-}266-301 func main() {268- r := gin.Default()302+ router := gin.Default()303 304 // Example for binding JSON ({"user": "manu", "password": "123"})271- r.POST("/loginJSON", func(c *gin.Context) {272- var json LoginJSON273-274- c.Bind(&json) // This will infer what binder to use depending on the content-type header.275- if json.User == "manu" && json.Password == "123" {276- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})277- } else {278- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})305+ router.POST("/loginJSON", func(c *gin.Context) {306+ var json Login307+ if c.BindJSON(&json) == nil {308+ if json.User == "manu" && json.Password == "123" {309+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})310+ } else {311+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})312+ }313 }314 })315 316 // Example for binding a HTML form (user=manu&password=123)283- r.POST("/loginHTML", func(c *gin.Context) {284- var form LoginForm285-286- c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML.287- if form.User == "manu" && form.Password == "123" {288- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})289- } else {290- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})317+ router.POST("/loginForm", func(c *gin.Context) {318+ var form Login319+ // This will infer what binder to use depending on the content-type header.320+ if c.Bind(&form) == nil {321+ if form.User == "manu" && form.Password == "123" {322+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})323+ } else {324+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})325+ }326 }327 })328 329 // Listen and server on 0.0.0.0:8080295- r.Run(":8080")330+ router.Run(":8080")331 }332 ```333 334 11 unmodified lines346 Password string `form:"password" binding:"required"`347 }348 349 func main() {315-350 router := gin.Default()317-351 router.POST("/login", func(c *gin.Context) {352 // you can bind multipart form with explicit binding declaration:353 // c.BindWith(&form, binding.Form)354 // or you can simply use autobinding with Bind method:355 var form LoginForm323- c.Bind(&form) // in this case proper binding will be automatically selected324-325- if form.User == "user" && form.Password == "password" {326- c.JSON(200, gin.H{"status": "you are logged in"})327- } else {328- c.JSON(401, gin.H{"status": "unauthorized"})329- }356+ // in this case proper binding will be automatically selected357+ if c.Bind(&form) == nil {358+ if form.User == "user" && form.Password == "password" {359+ c.JSON(200, gin.H{"status": "you are logged in"})360+ } else {361+ c.JSON(401, gin.H{"status": "unauthorized"})362+ }363+ }364 })331-365 router.Run(":8080")333-366 }367 ```368 369 Test it with:242 unmodified linesmodified:response_writer.go+10 added
21 unmodified lines22 http.Hijacker23 http.Flusher24 http.CloseNotifier25 26+ // Returns the HTTP response status code of the current request.27 Status() int28+29+ // Returns the number of bytes already written into the response http body.30+ // See Written()31 Size() int32+33+ // Writes the string into the response body.34 WriteString(string) (int, error)35+36+ // Returns true if the response body was already written.37 Written() bool38+39+ // Forces to write the http header (status code + headers).40 WriteHeaderNow()41 }42 43 responseWriter struct {73 unmodified linesmodified:routergroup_test.go+5 added-5 removed
18 unmodified lines19 group := router.Group("/hola", func(c *Context) {})20 group.Use(func(c *Context) {})21 22 assert.Len(t, group.Handlers, 2)23- assert.Equal(t, group.BasePath, "/hola")23+ assert.Equal(t, group.BasePath(), "/hola")24 assert.Equal(t, group.engine, router)25 26 group2 := group.Group("manu")27 group2.Use(func(c *Context) {}, func(c *Context) {})28 29 assert.Len(t, group2.Handlers, 4)30- assert.Equal(t, group2.BasePath, "/hola/manu")30+ assert.Equal(t, group2.BasePath(), "/hola/manu")31 assert.Equal(t, group2.engine, router)32 }33 34 func TestRouterGroupBasicHandle(t *testing.T) {8 unmodified lines43 44 func performRequestInGroup(t *testing.T, method string) {45 router := New()46 v1 := router.Group("v1", func(c *Context) {})47- assert.Equal(t, v1.BasePath, "/v1")47+ assert.Equal(t, v1.BasePath(), "/v1")48 49 login := v1.Group("/login/", func(c *Context) {}, func(c *Context) {})50- assert.Equal(t, login.BasePath, "/v1/login/")50+ assert.Equal(t, login.BasePath(), "/v1/login/")51 52 handler := func(c *Context) {53 c.String(400, "the method was %s and index %d", c.Request.Method, c.index)54 }101 unmodified lines156 v1 := router.Group("/v1")157 testRoutesInterface(t, v1)158 }159 160-func testRoutesInterface(t *testing.T, r routesInterface) {160+func testRoutesInterface(t *testing.T, r IRoutes) {161 handler := func(c *Context) {}162 assert.Equal(t, r, r.Use(handler))163 164 assert.Equal(t, r, r.Handle("GET", "/handler", handler))13 unmodified linesmodified:routergroup.go+69 added-52 removed
9 unmodified lines10 "regexp"11 "strings"12 )13 14-type routesInterface interface {15- Use(...HandlerFunc) routesInterface14+type (15+ IRouter interface {16+ IRoutes17+ Group(string, ...HandlerFunc) *RouterGroup18+ }19 17- Handle(string, string, ...HandlerFunc) routesInterface18- Any(string, ...HandlerFunc) routesInterface19- GET(string, ...HandlerFunc) routesInterface20- POST(string, ...HandlerFunc) routesInterface21- DELETE(string, ...HandlerFunc) routesInterface22- PATCH(string, ...HandlerFunc) routesInterface23- PUT(string, ...HandlerFunc) routesInterface24- OPTIONS(string, ...HandlerFunc) routesInterface25- HEAD(string, ...HandlerFunc) routesInterface20+ IRoutes interface {21+ Use(...HandlerFunc) IRoutes22 27- StaticFile(string, string) routesInterface28- Static(string, string) routesInterface29- StaticFS(string, http.FileSystem) routesInterface30-}23+ Handle(string, string, ...HandlerFunc) IRoutes24+ Any(string, ...HandlerFunc) IRoutes25+ GET(string, ...HandlerFunc) IRoutes26+ POST(string, ...HandlerFunc) IRoutes27+ DELETE(string, ...HandlerFunc) IRoutes28+ PATCH(string, ...HandlerFunc) IRoutes29+ PUT(string, ...HandlerFunc) IRoutes30+ OPTIONS(string, ...HandlerFunc) IRoutes31+ HEAD(string, ...HandlerFunc) IRoutes32 32-// Used internally to configure router, a RouterGroup is associated with a prefix33-// and an array of handlers (middleware)34-type RouterGroup struct {35- Handlers HandlersChain36- BasePath string37- engine *Engine38- root bool39-}33+ StaticFile(string, string) IRoutes34+ Static(string, string) IRoutes35+ StaticFS(string, http.FileSystem) IRoutes36+ }37 38+ // RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix39+ // and an array of handlers (middleware)40+ RouterGroup struct {41+ Handlers HandlersChain42+ basePath string43+ engine *Engine44+ root bool45+ }46+)47+48+var _ IRouter = &RouterGroup{}49+41-// Adds middleware to the group, see example code in github.42-func (group *RouterGroup) Use(middleware ...HandlerFunc) routesInterface {50+// Use adds middleware to the group, see example code in github.51+func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {52 group.Handlers = append(group.Handlers, middleware...)53 return group.returnObj()54 }55 47-// Creates a new router group. You should add all the routes that have common middlwares or the same path prefix.56+// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.57 // For example, all the routes that use a common middlware for authorization could be grouped.58 func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {59 return &RouterGroup{60 Handlers: group.combineHandlers(handlers),52- BasePath: group.calculateAbsolutePath(relativePath),61+ basePath: group.calculateAbsolutePath(relativePath),62 engine: group.engine,63 }64 }65 66+func (group *RouterGroup) BasePath() string {67+ return group.basePath68+}69+70+func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {71+ absolutePath := group.calculateAbsolutePath(relativePath)72+ handlers = group.combineHandlers(handlers)73+ group.engine.addRoute(httpMethod, absolutePath, handlers)74+ return group.returnObj()75+}76+77 // Handle registers a new request handle and middleware with the given path and method.78 // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.79 // See the example code in github.80 //2 unmodified lines83 //84 // This function is intended for bulk loading and to allow the usage of less85 // frequently used, non-standardized or custom methods (e.g. for internal86 // communication with a proxy).67-func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) routesInterface {68- absolutePath := group.calculateAbsolutePath(relativePath)69- handlers = group.combineHandlers(handlers)70- group.engine.addRoute(httpMethod, absolutePath, handlers)71- return group.returnObj()72-}73-74-func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) routesInterface {87+func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {88 if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {89 panic("http method " + httpMethod + " is not valid")90 }91 return group.handle(httpMethod, relativePath, handlers)92 }93 94 // POST is a shortcut for router.Handle("POST", path, handle)82-func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) routesInterface {95+func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {96 return group.handle("POST", relativePath, handlers)97 }98 99 // GET is a shortcut for router.Handle("GET", path, handle)87-func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) routesInterface {100+func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {101 return group.handle("GET", relativePath, handlers)102 }103 104 // DELETE is a shortcut for router.Handle("DELETE", path, handle)92-func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) routesInterface {105+func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {106 return group.handle("DELETE", relativePath, handlers)107 }108 109 // PATCH is a shortcut for router.Handle("PATCH", path, handle)97-func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) routesInterface {110+func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {111 return group.handle("PATCH", relativePath, handlers)112 }113 114 // PUT is a shortcut for router.Handle("PUT", path, handle)102-func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) routesInterface {115+func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {116 return group.handle("PUT", relativePath, handlers)117 }118 119 // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)107-func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) routesInterface {120+func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {121 return group.handle("OPTIONS", relativePath, handlers)122 }123 124 // HEAD is a shortcut for router.Handle("HEAD", path, handle)112-func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) routesInterface {125+func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {126 return group.handle("HEAD", relativePath, handlers)127 }128 116-func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) routesInterface {117- // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE129+// Any registers a route that matches all the HTTP methods.130+// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE131+func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {132 group.handle("GET", relativePath, handlers)133 group.handle("POST", relativePath, handlers)134 group.handle("PUT", relativePath, handlers)135 group.handle("PATCH", relativePath, handlers)4 unmodified lines140 group.handle("TRACE", relativePath, handlers)141 return group.returnObj()142 }143 144+// StaticFile registers a single route in order to server a single file of the local filesystem.145+// router.StaticFile("favicon.ico", "./resources/favicon.ico")130-func (group *RouterGroup) StaticFile(relativePath, filepath string) routesInterface {146+func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {147 if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {148 panic("URL parameters can not be used when serving a static file")149 }150 handler := func(c *Context) {9 unmodified lines160 // of the Router's NotFound handler.161 // To use the operating system's file system implementation,162 // use :163 // router.Static("/static", "/var/www")148-func (group *RouterGroup) Static(relativePath, root string) routesInterface {164+func (group *RouterGroup) Static(relativePath, root string) IRoutes {165 return group.StaticFS(relativePath, Dir(root, false))166 }167 168+// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.169+// Gin by default user: gin.Dir()152-func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) routesInterface {170+func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {171 if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {172 panic("URL parameters can not be used when serving a static folder")173 }174 handler := group.createStaticHandler(relativePath, fs)18 unmodified lines193 }194 195 func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {196 finalSize := len(group.Handlers) + len(handlers)179- if finalSize >= int(AbortIndex) {197+ if finalSize >= int(abortIndex) {198 panic("too many handlers")199 }200 mergedHandlers := make(HandlersChain, finalSize)201 copy(mergedHandlers, group.Handlers)1 unmodified line203 return mergedHandlers204 }205 206 func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {189- return joinPaths(group.BasePath, relativePath)207+ return joinPaths(group.basePath, relativePath)208 }209 192-func (group *RouterGroup) returnObj() routesInterface {210+func (group *RouterGroup) returnObj() IRoutes {211 if group.root {212 return group.engine195- } else {196- return group213 }214+ return group215 }modified:routes_test.go+76 added-3 removed
38 unmodified lines39 assert.Equal(t, w.Code, http.StatusOK)40 41 performRequest(r, method, "/test2")42 assert.True(t, passedAny)43-43 }44 45 // TestSingleRouteOK tests that POST route is correctly invoked.46 func testRouteNotOK(method string, t *testing.T) {61 unmodified lines108 testRouteOK("CONNECT", t)109 testRouteOK("TRACE", t)110 }111 113-// TestSingleRouteOK tests that POST route is correctly invoked.112 func TestRouteNotOK(t *testing.T) {113 testRouteNotOK("GET", t)114 testRouteNotOK("POST", t)115 testRouteNotOK("PUT", t)4 unmodified lines120 testRouteNotOK("CONNECT", t)121 testRouteNotOK("TRACE", t)122 }123 126-// TestSingleRouteOK tests that POST route is correctly invoked.124 func TestRouteNotOK2(t *testing.T) {125 testRouteNotOK2("GET", t)126 testRouteNotOK2("POST", t)127 testRouteNotOK2("PUT", t)4 unmodified lines132 testRouteNotOK2("CONNECT", t)133 testRouteNotOK2("TRACE", t)134 }135 136+func TestRouteRedirectTrailingSlash(t *testing.T) {137+ router := New()138+ router.RedirectFixedPath = false139+ router.RedirectTrailingSlash = true140+ router.GET("/path", func(c *Context) {})141+ router.GET("/path2/", func(c *Context) {})142+ router.POST("/path3", func(c *Context) {})143+ router.PUT("/path4/", func(c *Context) {})144+145+ w := performRequest(router, "GET", "/path/")146+ assert.Equal(t, w.Header().Get("Location"), "/path")147+ assert.Equal(t, w.Code, 301)148+149+ w = performRequest(router, "GET", "/path2")150+ assert.Equal(t, w.Header().Get("Location"), "/path2/")151+ assert.Equal(t, w.Code, 301)152+153+ w = performRequest(router, "POST", "/path3/")154+ assert.Equal(t, w.Header().Get("Location"), "/path3")155+ assert.Equal(t, w.Code, 307)156+157+ w = performRequest(router, "PUT", "/path4")158+ assert.Equal(t, w.Header().Get("Location"), "/path4/")159+ assert.Equal(t, w.Code, 307)160+161+ w = performRequest(router, "GET", "/path")162+ assert.Equal(t, w.Code, 200)163+164+ w = performRequest(router, "GET", "/path2/")165+ assert.Equal(t, w.Code, 200)166+167+ w = performRequest(router, "POST", "/path3")168+ assert.Equal(t, w.Code, 200)169+170+ w = performRequest(router, "PUT", "/path4/")171+ assert.Equal(t, w.Code, 200)172+173+ router.RedirectTrailingSlash = false174+175+ w = performRequest(router, "GET", "/path/")176+ assert.Equal(t, w.Code, 404)177+ w = performRequest(router, "GET", "/path2")178+ assert.Equal(t, w.Code, 404)179+ w = performRequest(router, "POST", "/path3/")180+ assert.Equal(t, w.Code, 404)181+ w = performRequest(router, "PUT", "/path4")182+ assert.Equal(t, w.Code, 404)183+}184+185+func TestRouteRedirectFixedPath(t *testing.T) {186+ router := New()187+ router.RedirectFixedPath = true188+ router.RedirectTrailingSlash = false189+190+ router.GET("/path", func(c *Context) {})191+ router.GET("/Path2", func(c *Context) {})192+ router.POST("/PATH3", func(c *Context) {})193+ router.POST("/Path4/", func(c *Context) {})194+195+ w := performRequest(router, "GET", "/PATH")196+ assert.Equal(t, w.Header().Get("Location"), "/path")197+ assert.Equal(t, w.Code, 301)198+199+ w = performRequest(router, "GET", "/path2")200+ assert.Equal(t, w.Header().Get("Location"), "/Path2")201+ assert.Equal(t, w.Code, 301)202+203+ w = performRequest(router, "POST", "/path3")204+ assert.Equal(t, w.Header().Get("Location"), "/PATH3")205+ assert.Equal(t, w.Code, 307)206+207+ w = performRequest(router, "POST", "/path4")208+ assert.Equal(t, w.Header().Get("Location"), "/Path4/")209+ assert.Equal(t, w.Code, 307)210+}211+212 // TestContextParamsGet tests that a parameter can be parsed from the URL.213 func TestRouteParamsByName(t *testing.T) {214 name := ""215 lastName := ""187 unmodified linesmodified:utils_test.go+27 added
95 unmodified lines96 assert.Equal(t, joinPaths("/a/", "/hola"), "/a/hola")97 assert.Equal(t, joinPaths("/a/", "/hola/"), "/a/hola/")98 assert.Equal(t, joinPaths("/a/", "/hola//"), "/a/hola/")99 }100+101+type bindTestStruct struct {102+ Foo string `form:"foo" binding:"required"`103+ Bar int `form:"bar" binding:"min=4"`104+}105+106+func TestBindMiddleware(t *testing.T) {107+ var value *bindTestStruct108+ var called bool109+ router := New()110+ router.GET("/", Bind(bindTestStruct{}), func(c *Context) {111+ called = true112+ value = c.MustGet(BindKey).(*bindTestStruct)113+ })114+ performRequest(router, "GET", "/?foo=hola&bar=10")115+ assert.True(t, called)116+ assert.Equal(t, value.Foo, "hola")117+ assert.Equal(t, value.Bar, 10)118+119+ called = false120+ performRequest(router, "GET", "/?foo=hola&bar=1")121+ assert.False(t, called)122+123+ assert.Panics(t, func() {124+ Bind(&bindTestStruct{})125+ })126+}modified:utils.go+18 added
5 unmodified lines6 7 import (8 "encoding/xml"9 "net/http"10+ "os"11 "path"12 "reflect"13 "runtime"14 "strings"114 unmodified lines129 return finalPath + "/"130 }131 return finalPath132 }133+134+func resolveAddress(addr []string) string {135+ switch len(addr) {136+ case 0:137+ if port := os.Getenv("PORT"); len(port) > 0 {138+ debugPrint("Environment variable PORT=\"%s\"", port)139+ return ":" + port140+ } else {141+ debugPrint("Environment variable PORT is undefined. Using port :8080 by default")142+ return ":8080"143+ }144+ case 1:145+ return addr[0]146+ default:147+ panic("too much parameters")148+ }149+}