Skip to content
Myr

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

27 files+789 added−244 removed

modified:binding/binding_test.go+39 added
4 unmodified lines
5package binding67import (8 "bytes"9 "mime/multipart"10 "net/http"11 "testing"1213 "github.com/stretchr/testify/assert"
50 unmodified lines
64 "/", "/",65 "<map><foo>bar</foo></map>", "<map><bar>foo</bar></map>")66}6768func 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}7374func createFormMultipartRequest() *http.Request {75 boundary := "--testboundary"76 body := new(bytes.Buffer)77 mw := multipart.NewWriter(body)78 defer mw.Close()7980 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}8788func TestBindingFormPost(t *testing.T) {89 req := createFormPostRequest()90 var obj FooBarStruct91 FormPost.Bind(req, &obj)9293 assert.Equal(t, obj.Foo, "bar")94 assert.Equal(t, obj.Bar, "foo")95}9697func TestBindingFormMultipart(t *testing.T) {98 req := createFormMultipartRequest()99 var obj FooBarStruct100 FormMultipart.Bind(req, &obj)101102 assert.Equal(t, obj.Foo, "bar")103 assert.Equal(t, obj.Bar, "foo")104}105106func TestValidationFails(t *testing.T) {107 var obj FooStruct108 req := requestWithBody("POST", "/", `{"bar": "foo"}`)109 err := JSON.Bind(req, &obj)
53 unmodified lines
modified:binding/binding.go+5 added-3 removed
31 unmodified lines
3233var Validator StructValidator = &defaultValidator{}3435var (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)4243func Default(method, contentType string) Binding {44 if method == "GET" {
19 unmodified lines
modified:binding/form_mapping.go-1 removed
54 unmodified lines
55 if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {56 return err57 }58 }5959 }60 return nil61}62
88 unmodified lines
modified:binding/form.go+32 added-2 removed
5 unmodified lines
67import "net/http"89type formBinding struct{}10type formPostBinding struct{}11type formMultipartBinding struct{}1211func (_ formBinding) Name() string {13func (formBinding) Name() string {14 return "form"15}1615func (_ formBinding) Bind(req *http.Request, obj interface{}) error {17func (formBinding) Bind(req *http.Request, obj interface{}) error {18 if err := req.ParseForm(); err != nil {19 return err20 }21 req.ParseMultipartForm(32 << 10) // 32 MB
1 unmodified line
23 return err24 }25 return validate(obj)26}2728func (formPostBinding) Name() string {29 return "form-urlencoded"30}3132func (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}4142func (formMultipartBinding) Name() string {43 return "multipart/form-data"44}4546func (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 lines
11)1213type jsonBinding struct{}1415func (_ jsonBinding) Name() string {15func (jsonBinding) Name() string {16 return "json"17}1819func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {19func (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 lines
modified:binding/xml.go+2 added-2 removed
9 unmodified lines
10)1112type xmlBinding struct{}1314func (_ xmlBinding) Name() string {14func (xmlBinding) Name() string {15 return "xml"16}1718func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {18func (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 lines
modified:auth.go+7 added-9 removed
8 unmodified lines
9 "encoding/base64"10 "strconv"11)1213const (14 AuthUserKey = "user"13const AuthUserKey = "user"15)1415type (16 Accounts map[string]string17 authPair struct {
14 unmodified lines
32 }33 return "", false34}3538// 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)40func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {41 if realm == "" {42 realm = "Authorization Required"
14 unmodified lines
57 }58 }59}6062// 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.63func BasicAuth(accounts Accounts) HandlerFunc {64 return BasicAuthForRealm(accounts, "")65}
23 unmodified lines
8990func 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
modified:context_test.go+65 added-13 removed
40 unmodified lines
4142 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 req
27 unmodified lines
79 assert.EqualValues(t, c.index, -1)80 assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)81}8283func TestContextHandlers(t *testing.T) {84 c, _, _ := createTestContext()85 assert.Nil(t, c.handlers)86 assert.Nil(t, c.handlers.Last())8788 c.handlers = HandlersChain{}89 assert.NotNil(t, c.handlers)90 assert.Nil(t, c.handlers.Last())9192 f := func(c *Context) {}93 g := func(c *Context) {}9495 c.handlers = HandlersChain{f}96 compareFunc(t, f, c.handlers.Last())9798 c.handlers = HandlersChain{f, g}99 compareFunc(t, g, c.handlers.Last())100}101102// TestContextSetGet tests that a parameter is set correctly on the103// current context and can be retrieved using Get.104func TestContextSetGet(t *testing.T) {105 c, _, _ := createTestContext()
44 unmodified lines
150 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}159160func TestContextHandlerName(t *testing.T) {161 c, _, _ := createTestContext()162 c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}163164 assert.Equal(t, c.HandlerName(), "github.com/gin-gonic/gin.handlerNameTest")165}166167func handlerNameTest(c *Context) {168169}170171func TestContextQuery(t *testing.T) {172 c, _, _ := createTestContext()173 c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)174
11 unmodified lines
186}187188func 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)193194 assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")195 assert.Equal(t, c.PostForm("foo"), "bar")
14 unmodified lines
210 assert.Empty(t, c.PostForm("NoKey"))211 assert.Empty(t, c.Query("NoKey"))212213 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}227228func TestContextPostFormMultipart(t *testing.T) {229 c, _, _ := createTestContext()230 c.Request = createMultipartRequest()231232 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"})241242 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}248249// Tests that the response is serialized as JSON
100 unmodified lines
350 "foo": "bar",351 "bar": "foo",352 })353316 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}356357func TestContextRenderFile(t *testing.T) {358 c, w, _ := createTestContext()
75 unmodified lines
434 assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)435 assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)436}437438func TestContextIsAborted(t *testing.T) {439 c, _, _ := createTestContext()440 assert.False(t, c.IsAborted())441442 c.Abort()443 assert.True(t, c.IsAborted())444445 c.Next()446 assert.True(t, c.IsAborted())447448 c.index++449 assert.True(t, c.IsAborted())450}451452// TestContextData tests that the response can be written from `bytesting`453// with specified MIME type454func TestContextAbortWithStatus(t *testing.T) {455 c, w, _ := createTestContext()456 c.index = 4457 c.AbortWithStatus(401)458 c.Writer.WriteHeaderNow()459408 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 lines
508 c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")509 c.Writer.WriteHeaderNow()510511 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}515516func TestContextClientIP(t *testing.T) {
91 unmodified lines
modified:context.go+58 added-30 removed
16 unmodified lines
17 "github.com/manucorporat/sse"18 "golang.org/x/net/context"19)2021// Content-Type MIME of the most common data formats22const (23 MIMEJSON = binding.MIMEJSON24 MIMEHTML = binding.MIMEHTML25 MIMEXML = binding.MIMEXML
2 unmodified lines
28 MIMEPOSTForm = binding.MIMEPOSTForm29 MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm30)3131const AbortIndex int8 = math.MaxInt8 / 232const abortIndex int8 = math.MaxInt8 / 23334// 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.36type Context struct {
26 unmodified lines
63 c.Errors = c.Errors[0:0]64 c.Accepted = nil65}6667// 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.69func (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}7778// HandlerName returns the main handle's name. For example if the handler is "handleGetUsers()", this79// function will return "main.handleGetUsers"80func (c *Context) HandlerName() string {81 return nameOfFunction(c.handlers.Last())82}8384/************************************/85/*********** FLOW CONTROL ***********/86/************************************/87
7 unmodified lines
95 c.handlers[c.index](c)96 }97}9890// Returns if the currect context was aborted.99// IsAborted returns true if the currect context was aborted.100func (c *Context) IsAborted() bool {92 return c.index == AbortIndex101 return c.index >= abortIndex102}10395// 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.108func (c *Context) Abort() {100 c.index = AbortIndex109 c.index = abortIndex110}111103// 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).114func (c *Context) AbortWithStatus(code int) {115 c.Writer.WriteHeader(code)116 c.Abort()117}118110// 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.122func (c *Context) AbortWithError(code int, err error) *Error {123 c.AbortWithStatus(code)
5 unmodified lines
129/************************************/130131// 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.135func (c *Context) Error(err error) *Error {136 var parsedError *Error137 switch err.(type) {138 case *Error:
11 unmodified lines
150/************************************/151/******** METADATA MANAGEMENT********/152/************************************/153144// 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.156func (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}162153// 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)165func (c *Context) Get(key string) (value interface{}, exists bool) {166 if c.Keys != nil {167 value, exists = c.Keys[key]
12 unmodified lines
180/************************************/181/************ INPUT DATA ************/182/************************************/183174// 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") == ""190func (c *Context) Query(key string) (va string) {191 va, _ = c.query(key)192 return193}194180// Shortcut for c.Request.PostFormValue(key)195// PostForm is a shortcut for c.Request.PostFormValue(key)196func (c *Context) PostForm(key string) (va string) {197 va, _ = c.postForm(key)198 return199}200186// Shortcut for c.Params.ByName(key)201// Param is a shortcut for c.Params.ByName(key)202func (c *Context) Param(key string) string {203 return c.Params.ByName(key)204}205
3 unmodified lines
209 }210 return defaultValue211}212213// 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// ```220func (c *Context) DefaultQuery(key, defaultValue string) string {221 if va, ok := c.query(key); ok {222 return va223 }
21 unmodified lines
245 }246 return "", false247}248227// 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.257func (c *Context) Bind(obj interface{}) error {258 b := binding.Default(c.Request.Method, c.ContentType())259 return c.BindWith(obj, b)260}261238// Shortcut for c.BindWith(obj, binding.JSON)262// BindJSON is a shortcut for c.BindWith(obj, binding.JSON)263func (c *Context) BindJSON(obj interface{}) error {264 return c.BindWith(obj, binding.JSON)265}266267// BindWith binds the passed struct pointer using the specified binding engine.268// See the binding package.269func (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}276251// 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.279func (c *Context) ClientIP() string {280 if c.engine.ForwardedByClientIP {281 clientIP := strings.TrimSpace(c.requestHeader("X-Real-Ip"))
11 unmodified lines
293 }294 return strings.TrimSpace(c.Request.RemoteAddr)295}296297// ContentType returns the Content-Type header of the request.298func (c *Context) ContentType() string {299 return filterFlags(c.requestHeader("Content-Type"))300}301
7 unmodified lines
309/************************************/310/******** RESPONSE RENDERING ********/311/************************************/312286// 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)`316func (c *Context) Header(key, value string) {317 if len(value) == 0 {318 c.Writer.Header().Del(key)
13 unmodified lines
332 debugPrintError(err)333 c.AbortWithError(500, err).SetType(ErrorTypeRender)334}335309// 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/339func (c *Context) HTML(code int, name string, obj interface{}) {340 instance := c.engine.HTMLRender.Instance(name, obj)341 c.Render(code, instance)342}343317// 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.348func (c *Context) IndentedJSON(code int, obj interface{}) {349 c.Render(code, render.IndentedJSON{Data: obj})350}351325// 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".354func (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}360334// 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".363func (c *Context) XML(code int, obj interface{}) {364 c.Render(code, render.XML{Data: obj})365}366340// Writes the given string into the response body.367// String writes the given string into the response body.368func (c *Context) String(code int, format string, values ...interface{}) {369 c.writermem.WriteHeader(code)370 render.WriteString(c.Writer, format, values)371}372346// Returns a HTTP redirect to the specific location.373// Redirect returns a HTTP redirect to the specific location.374func (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}381355// 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.383func (c *Context) Data(code int, contentType string, data []byte) {384 c.Render(code, render.Data{385 ContentType: contentType,386 Data: data,387 })388}389363// 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.391func (c *Context) File(filepath string) {392 http.ServeFile(c.Writer, c.Request, filepath)393}394395// SSEvent writes a Server-Sent Event into the body stream.396func (c *Context) SSEvent(name string, message interface{}) {397 c.Render(-1, sse.Event{398 Event: name,399 Data: message,
102 unmodified lines
modified:debug_test.go+9 added
55 unmodified lines
56 debugPrintError(errors.New("this is an error"))57 assert.Equal(t, w.String(), "[GIN-debug] [ERROR] this is an error\n")58}5960func TestDebugPrintRoutes(t *testing.T) {61 var w bytes.Buffer62 setup(&w)63 defer teardown()6465 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}6869func setup(w io.Writer) {70 SetMode(DebugMode)71 log.SetOutput(w)72}
5 unmodified lines
modified:debug.go+32 added-3 removed
2 unmodified lines
3// license that can be found in the LICENSE file.45package gin67import "log"7import (8 "bytes"9 "html/template"10 "log"11)1213func init() {14 log.SetFlags(0)15}1617// IsDebugging returns true if the framework is running in debug mode.18// Use SetMode(gin.Release) to switch to disable the debug mode.19func IsDebugging() bool {20 return ginMode == debugCode21}2223func 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}3031func 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}4243func debugPrint(format string, values ...interface{}) {44 if IsDebugging() {45 log.Printf("[GIN-debug] "+format, values...)46 }47}4830func debugPrintWARNING() {49func 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)5354`)55}5657func debugPrintWARNINGSetHTMLTemplate() {58 debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called59at initialization. ie. before any route is registered or the router is listening in a socket:6061 router := gin.Default()62 router.SetHTMLTemplate(template) // << good place6364`)65}6667func debugPrintError(err error) {68 if err != nil {69 debugPrint("[ERROR] %v\n", err)70 }
1 unmodified line
modified:errors_test.go+1 added
61 unmodified lines
62 {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"},63 {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}},64 }6566 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 lines
modified:errors.go+3 added-3 removed
100 unmodified lines
101// Returns the last error in the slice. It returns nil if the array is empty.102// Shortcut for errors[len(errors)-1]103func (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}110111// Returns an array will all the error messages.112// Example
49 unmodified lines
modified:fs.go+2 added-3 removed
12 unmodified lines
13 http.File14 }15)1617// 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.21func 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}2829// Conforms to http.Filesystem30func (fs onlyfilesFS) Open(name string) (http.File, error) {
12 unmodified lines
modified:gin_integration_test.go+53 added-16 removed
1package gin23import (4 "bufio"5 "bytes"5 "fmt"6 "io/ioutil"7 "net"8 "net/http"9 "os"10 "testing"11 "time"1213 "github.com/stretchr/testify/assert"14)1516func TestRun(t *testing.T) {17 buffer := new(bytes.Buffer)16func testRequest(t *testing.T, url string) {17 resp, err := http.Get(url)18 defer resp.Body.Close()19 assert.NoError(t, err)2021 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}2627func 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)3828 assert.Error(t, router.Run(":5150"))39 assert.Error(t, router.Run(":8080"))40 testRequest(t, "http://localhost:8080/example")41}4230 resp, err := http.Get("http://localhost:5150/example")31 defer resp.Body.Close()32 assert.NoError(t, err)43func 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)5334 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}5758func TestRunTooMuchParams(t *testing.T) {59 router := New()60 assert.Panics(t, func() {61 router.Run("2", "2")62 })63}6465func 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)7475 assert.Error(t, router.Run(":5150"))76 testRequest(t, "http://localhost:5150/example")77}7879func TestUnixSocket(t *testing.T) {41 buffer := new(bytes.Buffer)80 router := New()8182 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 lines
modified:gin_test.go+65 added-2 removed
12 unmodified lines
1314//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 {1819func init() {20 SetMode(TestMode)21}2223func 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}2930// 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// }4445func TestLoadHTMLReleaseMode(t *testing.T) {4647}4849func TestAddRoute(t *testing.T) {50 router := New()51 router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})52
144 unmodified lines
197 if sf1.Pointer() != sf2.Pointer() {198 t.Error("different functions")199 }200}201202func 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", ".")213214 list := router.Routes()215216 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}243244func handler_test1(c *Context) {}245func handler_test2(c *Context) {}
modified:gin.go+68 added-23 removed
12 unmodified lines
1314 "github.com/gin-gonic/gin/render"15)1617// Framework's version18const Version = "v1.0rc2"1920var default404Body = []byte("404 page not found")21var default405Body = []byte("405 method not allowed")2223type HandlerFunc func(*Context)24type HandlersChain []HandlerFunc2526// Last returns the last handler in the chain. ie. the last handler is the main own.27func (c HandlersChain) Last() HandlerFunc {28 length := len(c)29 if length > 0 {30 return c[length-1]31 }32 return nil33}3435type (23 HandlerFunc func(*Context)24 HandlersChain []HandlerFunc36 RoutesInfo []RouteInfo37 RouteInfo struct {38 Method string39 Path string40 Handler string41 }4226 // 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 HandlersChain
31 unmodified lines
80 ForwardedByClientIP bool81 }82)8384var _ IRouter = &Engine{}8566// 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: true92func 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 lines
109 }110 return engine111}11289// 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.114func Default() *Engine {115 engine := New()116 engine.Use(Recovery(), Logger())117 return engine
4 unmodified lines
122}123124func (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 lines
141}142143func (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 called121at initialization. ie. before any route is registered or the router is listening in a socket:122123 router := gin.Default()124 router.SetHTMLTemplate(template) // << good place125`)145 debugPrintWARNINGSetHTMLTemplate()146 }147 engine.HTMLRender = render.HTMLProduction{Template: templ}148}149
11 unmodified lines
161162// 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.145func (engine *Engine) Use(middleware ...HandlerFunc) routesInterface {165func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {166 engine.RouterGroup.Use(middleware...)167 engine.rebuild404Handlers()168 engine.rebuild405Handlers()169 return engine
30 unmodified lines
200 }201 root.addRoute(path, handlers)202}203204// Routes returns a slice of registered routes, including some useful information, such as:205// the http method, path and the handler name.206func (engine *Engine) Routes() (routes RoutesInfo) {207 for _, tree := range engine.trees {208 routes = iterate("", tree.method, routes, tree.root)209 }210 return routes211}212213func 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}227184// 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.187func (engine *Engine) Run(addr string) (err error) {188 debugPrint("Listening and serving HTTP on %s\n", addr)231func (engine *Engine) Run(addr ...string) (err error) {232 defer func() { debugPrintError(err) }()233234 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}239195// 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.243func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {244 debugPrint("Listening and serving HTTPS on %s\n", addr)
2 unmodified lines
247 err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)248 return249}250206// 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.254func (engine *Engine) RunUnix(file string) (err error) {255 debugPrint("Listening and serving HTTP on unix:/%s", file)256 defer func() { debugPrintError(err) }()
38 unmodified lines
295 context.writermem.WriteHeaderNow()296 return297298 } 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 lines
modified:logger_test.go+28 added
4 unmodified lines
5package gin67import (8 "bytes"9 "errors"10 "testing"1112 "github.com/stretchr/testify/assert"13)
82 unmodified lines
96 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}100101func 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 })114115 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")118119 w = performRequest(router, "GET", "/abort")120 assert.Equal(t, w.Code, 401)121 assert.Equal(t, w.Body.String(), "{\"error\":\"no authorized\"}\n")122123 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 lines
247 assert.Equal(t, w.Code, 400)248 assert.Equal(t, w.Body.String(), `hola249<map><foo>bar</foo></map>{"foo":"bar"}250{"foo":"bar"}251event: test252data: message251event:test252data:message253254`)255}
modified:README.md+101 added-69 removed
1#Gin Web Framework [![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin) [![Coverage Status](https://coveralls.io/repos/gin-gonic/gin/badge.svg?branch=master)](https://coveralls.io/r/gin-gonic/gin?branch=master) 12#Gin Web Framework3<img align="right" src="https://s3.amazonaws.com/uploads.hipchat.com/36744/1498287/JVR32LgyEGCiy01/path4201%20copy%202.png">4[![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin)5[![Coverage Status](https://coveralls.io/repos/gin-gonic/gin/badge.svg?branch=master)](https://coveralls.io/r/gin-gonic/gin?branch=master)6[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin)3 [![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin) [![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)7[![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)89Gin 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.10111213![Gin console logger](https://gin-gonic.github.io/gin/other/console.png)1415```16$ cat test.go
18 unmodified lines
3536[See all benchmarks](/BENCHMARKS.md)373833```34BenchmarkAce_GithubAll 10000 109482 ns/op 13792 B/op 167 allocs/op35BenchmarkBear_GithubAll 10000 287490 ns/op 79952 B/op 943 allocs/op36BenchmarkBeego_GithubAll 3000 562184 ns/op 146272 B/op 2092 allocs/op37BenchmarkBone_GithubAll 500 2578716 ns/op 648016 B/op 8119 allocs/op38BenchmarkDenco_GithubAll 20000 94955 ns/op 20224 B/op 167 allocs/op39BenchmarkEcho_GithubAll 30000 58705 ns/op 0 B/op 0 allocs/op40BenchmarkGin_GithubAll 30000 50991 ns/op 0 B/op 0 allocs/op41BenchmarkGocraftWeb_GithubAll 5000 449648 ns/op 133280 B/op 1889 allocs/op42BenchmarkGoji_GithubAll 2000 689748 ns/op 56113 B/op 334 allocs/op43BenchmarkGoJsonRest_GithubAll 5000 537769 ns/op 135995 B/op 2940 allocs/op44BenchmarkGoRestful_GithubAll 100 18410628 ns/op 797236 B/op 7725 allocs/op45BenchmarkGorillaMux_GithubAll 200 8036360 ns/op 153137 B/op 1791 allocs/op46BenchmarkHttpRouter_GithubAll 20000 63506 ns/op 13792 B/op 167 allocs/op47BenchmarkHttpTreeMux_GithubAll 10000 165927 ns/op 56112 B/op 334 allocs/op48BenchmarkKocha_GithubAll 10000 171362 ns/op 23304 B/op 843 allocs/op49BenchmarkMacaron_GithubAll 2000 817008 ns/op 224960 B/op 2315 allocs/op50BenchmarkMartini_GithubAll 100 12609209 ns/op 237952 B/op 2686 allocs/op51BenchmarkPat_GithubAll 300 4830398 ns/op 1504101 B/op 32222 allocs/op52BenchmarkPossum_GithubAll 10000 301716 ns/op 97440 B/op 812 allocs/op53BenchmarkR2router_GithubAll 10000 270691 ns/op 77328 B/op 1182 allocs/op54BenchmarkRevel_GithubAll 1000 1491919 ns/op 345553 B/op 5918 allocs/op55BenchmarkRivet_GithubAll 10000 283860 ns/op 84272 B/op 1079 allocs/op56BenchmarkTango_GithubAll 5000 473821 ns/op 87078 B/op 2470 allocs/op57BenchmarkTigerTonic_GithubAll 2000 1120131 ns/op 241088 B/op 6052 allocs/op58BenchmarkTraffic_GithubAll 200 8708979 ns/op 2664762 B/op 22390 allocs/op59BenchmarkVulcan_GithubAll 5000 353392 ns/op 19894 B/op 609 allocs/op60BenchmarkZeus_GithubAll 2000 944234 ns/op 300688 B/op 2648 allocs/op61```39Benchmark name | (1) | (2) | (3) | (4)40--------------------------------|----------:|----------:|----------:|------:41BenchmarkAce_GithubAll | 10000 | 109482 | 13792 | 16742BenchmarkBear_GithubAll | 10000 | 287490 | 79952 | 94343BenchmarkBeego_GithubAll | 3000 | 562184 | 146272 | 209244BenchmarkBone_GithubAll | 500 | 2578716 | 648016 | 811945BenchmarkDenco_GithubAll | 20000 | 94955 | 20224 | 16746BenchmarkEcho_GithubAll | 30000 | 58705 | 0 | 047**BenchmarkGin_GithubAll** | **30000** | **50991** | **0** | **0**48BenchmarkGocraftWeb_GithubAll | 5000 | 449648 | 133280 | 188949BenchmarkGoji_GithubAll | 2000 | 689748 | 56113 | 33450BenchmarkGoJsonRest_GithubAll | 5000 | 537769 | 135995 | 294051BenchmarkGoRestful_GithubAll | 100 | 18410628 | 797236 | 772552BenchmarkGorillaMux_GithubAll | 200 | 8036360 | 153137 | 179153BenchmarkHttpRouter_GithubAll | 20000 | 63506 | 13792 | 16754BenchmarkHttpTreeMux_GithubAll | 10000 | 165927 | 56112 | 33455BenchmarkKocha_GithubAll | 10000 | 171362 | 23304 | 84356BenchmarkMacaron_GithubAll | 2000 | 817008 | 224960 | 231557BenchmarkMartini_GithubAll | 100 | 12609209 | 237952 | 268658BenchmarkPat_GithubAll | 300 | 4830398 | 1504101 | 3222259BenchmarkPossum_GithubAll | 10000 | 301716 | 97440 | 81260BenchmarkR2router_GithubAll | 10000 | 270691 | 77328 | 118261BenchmarkRevel_GithubAll | 1000 | 1491919 | 345553 | 591862BenchmarkRivet_GithubAll | 10000 | 283860 | 84272 | 107963BenchmarkTango_GithubAll | 5000 | 473821 | 87078 | 247064BenchmarkTigerTonic_GithubAll | 2000 | 1120131 | 241088 | 605265BenchmarkTraffic_GithubAll | 200 | 8708979 | 2664762 | 2239066BenchmarkVulcan_GithubAll | 5000 | 353392 | 19894 | 60967BenchmarkZeus_GithubAll | 2000 | 944234 | 300688 | 26486869(1): Total Repetitions 70(2): Single Repetition Duration (ns/op) 71(3): Heap Memory (B/op) 72(4): Average Allocations per Repetition (allocs/op) 7374##Gin v1. stable7576- [x] Zero allocation router.
98 unmodified lines
175 router.Run(":8080")176}177```178179### Another example: query + post form180181```182POST /post?id=1234&page=1 HTTP/1.1183Content-Type: application/x-www-form-urlencoded184185name=manu&message=this_is_great186```187188```go189func main() {190 router := gin.Default()191192 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")197198 fmt.Println("id: %s; page: %s; name: %s; message: %s", id, page, name, message)199 })200 router.Run(":8080")201}202```203204```205id: 1234; page: 0; name: manu; message: this_is_great206```207208209#### Grouping routes210```go211func main() {212 router := gin.Default()
79 unmodified lines
292You 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.293294```go295// Binding from JSON256type LoginJSON struct {257 User string `json:"user" binding:"required"`258 Password string `json:"password" binding:"required"`296type Login struct {297 User string `form:"user" json:"user" binding:"required"`298 Password string `form:"password" json:"password" binding:"required"`299}300261// Binding from form values262type LoginForm struct {263 User string `form:"user" binding:"required"`264 Password string `form:"password" binding:"required"`265}266301func main() {268 r := gin.Default()302 router := gin.Default()303304 // Example for binding JSON ({"user": "manu", "password": "123"})271 r.POST("/loginJSON", func(c *gin.Context) {272 var json LoginJSON273274 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 })315316 // Example for binding a HTML form (user=manu&password=123)283 r.POST("/loginHTML", func(c *gin.Context) {284 var form LoginForm285286 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 })328329 // Listen and server on 0.0.0.0:8080295 r.Run(":8080")330 router.Run(":8080")331}332```333334
11 unmodified lines
346 Password string `form:"password" binding:"required"`347}348349func main() {315350 router := gin.Default()317351 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 selected324325 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 })331365 router.Run(":8080")333366}367```368369Test it with:
242 unmodified lines
modified:response_writer.go+10 added
21 unmodified lines
22 http.Hijacker23 http.Flusher24 http.CloseNotifier2526 // Returns the HTTP response status code of the current request.27 Status() int2829 // Returns the number of bytes already written into the response http body.30 // See Written()31 Size() int3233 // Writes the string into the response body.34 WriteString(string) (int, error)3536 // Returns true if the response body was already written.37 Written() bool3839 // Forces to write the http header (status code + headers).40 WriteHeaderNow()41 }4243 responseWriter struct {
73 unmodified lines
modified:routergroup_test.go+5 added-5 removed
18 unmodified lines
19 group := router.Group("/hola", func(c *Context) {})20 group.Use(func(c *Context) {})2122 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)2526 group2 := group.Group("manu")27 group2.Use(func(c *Context) {}, func(c *Context) {})2829 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}3334func TestRouterGroupBasicHandle(t *testing.T) {
8 unmodified lines
4344func 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")4849 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/")5152 handler := func(c *Context) {53 c.String(400, "the method was %s and index %d", c.Request.Method, c.index)54 }
101 unmodified lines
156 v1 := router.Group("/v1")157 testRoutesInterface(t, v1)158}159160func testRoutesInterface(t *testing.T, r routesInterface) {160func testRoutesInterface(t *testing.T, r IRoutes) {161 handler := func(c *Context) {}162 assert.Equal(t, r, r.Use(handler))163164 assert.Equal(t, r, r.Handle("GET", "/handler", handler))
13 unmodified lines
modified:routergroup.go+69 added-52 removed
9 unmodified lines
10 "regexp"11 "strings"12)1314type routesInterface interface {15 Use(...HandlerFunc) routesInterface14type (15 IRouter interface {16 IRoutes17 Group(string, ...HandlerFunc) *RouterGroup18 }1917 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) IRoutes2227 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) IRoutes3232// Used internally to configure router, a RouterGroup is associated with a prefix33// and an array of handlers (middleware)34type 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 }3738 // 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)4748var _ IRouter = &RouterGroup{}4941// Adds middleware to the group, see example code in github.42func (group *RouterGroup) Use(middleware ...HandlerFunc) routesInterface {50// Use adds middleware to the group, see example code in github.51func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {52 group.Handlers = append(group.Handlers, middleware...)53 return group.returnObj()54}5547// 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.58func (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}6566func (group *RouterGroup) BasePath() string {67 return group.basePath68}6970func (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}7677// 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 lines
83//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).67func (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}7374func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) routesInterface {87func (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}9394// POST is a shortcut for router.Handle("POST", path, handle)82func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) routesInterface {95func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {96 return group.handle("POST", relativePath, handlers)97}9899// GET is a shortcut for router.Handle("GET", path, handle)87func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) routesInterface {100func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {101 return group.handle("GET", relativePath, handlers)102}103104// DELETE is a shortcut for router.Handle("DELETE", path, handle)92func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) routesInterface {105func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {106 return group.handle("DELETE", relativePath, handlers)107}108109// PATCH is a shortcut for router.Handle("PATCH", path, handle)97func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) routesInterface {110func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {111 return group.handle("PATCH", relativePath, handlers)112}113114// PUT is a shortcut for router.Handle("PUT", path, handle)102func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) routesInterface {115func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {116 return group.handle("PUT", relativePath, handlers)117}118119// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)107func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) routesInterface {120func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {121 return group.handle("OPTIONS", relativePath, handlers)122}123124// HEAD is a shortcut for router.Handle("HEAD", path, handle)112func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) routesInterface {125func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {126 return group.handle("HEAD", relativePath, handlers)127}128116func (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, TRACE131func (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 lines
140 group.handle("TRACE", relativePath, handlers)141 return group.returnObj()142}143144// StaticFile registers a single route in order to server a single file of the local filesystem.145// router.StaticFile("favicon.ico", "./resources/favicon.ico")130func (group *RouterGroup) StaticFile(relativePath, filepath string) routesInterface {146func (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 lines
160// of the Router's NotFound handler.161// To use the operating system's file system implementation,162// use :163// router.Static("/static", "/var/www")148func (group *RouterGroup) Static(relativePath, root string) routesInterface {164func (group *RouterGroup) Static(relativePath, root string) IRoutes {165 return group.StaticFS(relativePath, Dir(root, false))166}167168// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.169// Gin by default user: gin.Dir()152func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) routesInterface {170func (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 lines
193}194195func (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 line
203 return mergedHandlers204}205206func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {189 return joinPaths(group.BasePath, relativePath)207 return joinPaths(group.basePath, relativePath)208}209192func (group *RouterGroup) returnObj() routesInterface {210func (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 lines
39 assert.Equal(t, w.Code, http.StatusOK)4041 performRequest(r, method, "/test2")42 assert.True(t, passedAny)4343}4445// TestSingleRouteOK tests that POST route is correctly invoked.46func testRouteNotOK(method string, t *testing.T) {
61 unmodified lines
108 testRouteOK("CONNECT", t)109 testRouteOK("TRACE", t)110}111113// TestSingleRouteOK tests that POST route is correctly invoked.112func TestRouteNotOK(t *testing.T) {113 testRouteNotOK("GET", t)114 testRouteNotOK("POST", t)115 testRouteNotOK("PUT", t)
4 unmodified lines
120 testRouteNotOK("CONNECT", t)121 testRouteNotOK("TRACE", t)122}123126// TestSingleRouteOK tests that POST route is correctly invoked.124func TestRouteNotOK2(t *testing.T) {125 testRouteNotOK2("GET", t)126 testRouteNotOK2("POST", t)127 testRouteNotOK2("PUT", t)
4 unmodified lines
132 testRouteNotOK2("CONNECT", t)133 testRouteNotOK2("TRACE", t)134}135136func 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) {})144145 w := performRequest(router, "GET", "/path/")146 assert.Equal(t, w.Header().Get("Location"), "/path")147 assert.Equal(t, w.Code, 301)148149 w = performRequest(router, "GET", "/path2")150 assert.Equal(t, w.Header().Get("Location"), "/path2/")151 assert.Equal(t, w.Code, 301)152153 w = performRequest(router, "POST", "/path3/")154 assert.Equal(t, w.Header().Get("Location"), "/path3")155 assert.Equal(t, w.Code, 307)156157 w = performRequest(router, "PUT", "/path4")158 assert.Equal(t, w.Header().Get("Location"), "/path4/")159 assert.Equal(t, w.Code, 307)160161 w = performRequest(router, "GET", "/path")162 assert.Equal(t, w.Code, 200)163164 w = performRequest(router, "GET", "/path2/")165 assert.Equal(t, w.Code, 200)166167 w = performRequest(router, "POST", "/path3")168 assert.Equal(t, w.Code, 200)169170 w = performRequest(router, "PUT", "/path4/")171 assert.Equal(t, w.Code, 200)172173 router.RedirectTrailingSlash = false174175 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}184185func TestRouteRedirectFixedPath(t *testing.T) {186 router := New()187 router.RedirectFixedPath = true188 router.RedirectTrailingSlash = false189190 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) {})194195 w := performRequest(router, "GET", "/PATH")196 assert.Equal(t, w.Header().Get("Location"), "/path")197 assert.Equal(t, w.Code, 301)198199 w = performRequest(router, "GET", "/path2")200 assert.Equal(t, w.Header().Get("Location"), "/Path2")201 assert.Equal(t, w.Code, 301)202203 w = performRequest(router, "POST", "/path3")204 assert.Equal(t, w.Header().Get("Location"), "/PATH3")205 assert.Equal(t, w.Code, 307)206207 w = performRequest(router, "POST", "/path4")208 assert.Equal(t, w.Header().Get("Location"), "/Path4/")209 assert.Equal(t, w.Code, 307)210}211212// TestContextParamsGet tests that a parameter can be parsed from the URL.213func TestRouteParamsByName(t *testing.T) {214 name := ""215 lastName := ""
187 unmodified lines
modified:utils_test.go+27 added
95 unmodified lines
96 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}100101type bindTestStruct struct {102 Foo string `form:"foo" binding:"required"`103 Bar int `form:"bar" binding:"min=4"`104}105106func 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)118119 called = false120 performRequest(router, "GET", "/?foo=hola&bar=1")121 assert.False(t, called)122123 assert.Panics(t, func() {124 Bind(&bindTestStruct{})125 })126}
modified:utils.go+18 added
5 unmodified lines
67import (8 "encoding/xml"9 "net/http"10 "os"11 "path"12 "reflect"13 "runtime"14 "strings"
114 unmodified lines
129 return finalPath + "/"130 }131 return finalPath132}133134func 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}