Merge branch 'develop'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Manu Mtz-Almeida · committed by Manu Mtz-Almeida · parents c3abaf9, a3a5753 · Browse files · 14 files·+970 added−56 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+970 added−56 removed
- other:+970 added−56 removed
Provenance
- Commit
2d94e27- Tree
6d9eba9- Author
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Committer
Manu Mtz-Almeida <manu.valladolid@gmail.com>- Parent 1
c3abaf9- Parent 2
a3a5753
14 files changed+970 added−56 removed
modified:render/render.go+37 added-14 removed
20 unmodified lines21 22 // Plain text23 plainRender struct{}24 25+ // Redirects26+ redirectRender struct{}27+28+ // Redirects29+ htmlDebugRender struct{}30+31 // form binding32 HTMLRender struct {33 Template *template.Template34 }35 )36 37 var (32- JSON = jsonRender{}33- XML = xmlRender{}34- Plain = plainRender{}38+ JSON = jsonRender{}39+ XML = xmlRender{}40+ Plain = plainRender{}41+ Redirect = redirectRender{}42+ HTMLDebug = htmlDebugRender{}43 )44 45 func writeHeader(w http.ResponseWriter, code int, contentType string) {38- if code >= 0 {39- w.Header().Set("Content-Type", contentType)40- w.WriteHeader(code)46+ w.Header().Set("Content-Type", contentType)47+ w.WriteHeader(code)41- }48 }49 50 func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {51 writeHeader(w, code, "application/json")52 encoder := json.NewEncoder(w)53 return encoder.Encode(data[0])54 }55 56+func (_ redirectRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {57+ w.Header().Set("Location", data[0].(string))58+ w.WriteHeader(code)59+ return nil60+}61+62 func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {63 writeHeader(w, code, "application/xml")64 encoder := xml.NewEncoder(w)65 return encoder.Encode(data[0])66 }67 56-func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {57- writeHeader(w, code, "text/html")58- file := data[0].(string)59- obj := data[1]60- return html.Template.ExecuteTemplate(w, file, obj)61-}62-68 func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {69 writeHeader(w, code, "text/plain")70 format := data[0].(string)71 args := data[1].([]interface{})4 unmodified lines76 _, err = w.Write([]byte(format))77 }78 return err79 }80+81+func (_ htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {82+ writeHeader(w, code, "text/html")83+ file := data[0].(string)84+ obj := data[1]85+ t, err := template.ParseFiles(file)86+ if err != nil {87+ return err88+ }89+ return t.ExecuteTemplate(w, file, obj)90+}91+92+func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {93+ writeHeader(w, code, "text/html")94+ file := data[0].(string)95+ obj := data[1]96+ return html.Template.ExecuteTemplate(w, file, obj)97+}added:auth_test.go+57 added
1+package gin2+3+import (4+ "encoding/base64"5+ "net/http"6+ "net/http/httptest"7+ "testing"8+)9+10+func TestBasicAuthSucceed(t *testing.T) {11+ req, _ := http.NewRequest("GET", "/login", nil)12+ w := httptest.NewRecorder()13+14+ r := New()15+ accounts := Accounts{"admin": "password"}16+ r.Use(BasicAuth(accounts))17+18+ r.GET("/login", func(c *Context) {19+ c.String(200, "autorized")20+ })21+22+ req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))23+ r.ServeHTTP(w, req)24+25+ if w.Code != 200 {26+ t.Errorf("Response code should be Ok, was: %s", w.Code)27+ }28+ bodyAsString := w.Body.String()29+30+ if bodyAsString != "autorized" {31+ t.Errorf("Response body should be `autorized`, was %s", bodyAsString)32+ }33+}34+35+func TestBasicAuth401(t *testing.T) {36+ req, _ := http.NewRequest("GET", "/login", nil)37+ w := httptest.NewRecorder()38+39+ r := New()40+ accounts := Accounts{"foo": "bar"}41+ r.Use(BasicAuth(accounts))42+43+ r.GET("/login", func(c *Context) {44+ c.String(200, "autorized")45+ })46+47+ req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))48+ r.ServeHTTP(w, req)49+50+ if w.Code != 401 {51+ t.Errorf("Response code should be Not autorized, was: %s", w.Code)52+ }53+54+ if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {55+ t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))56+ }57+}modified:AUTHORS.md+16 added-6 removed
3 unmodified lines45678891011128 unmodified lines2122232425262728293028313233343533 unmodified lines697071727073747576777879778081798283848586878889909192936 unmodified lines100101102103981041051061071083 unmodified lines
##gin 0.x series authors
**Lead Developer:** Manu Martinez-Almeida (@manucorporat) **Stuff:****Staff:**Javier Provecho (@javierprovecho)
People and companies, who have contributed, in alphabetical order.
8 unmodified lines**@alexandernyquist (Alexander Nyquist)**- Using template.Must to fix multiple return issue- ★ Added support for OPTIONS verb- ★ Setting response headers before calling WriteHeader- Improved documentation for model binding- ★ Added Content.Redirect()- ★ Added tons of Unit tests
**@austinheap (Austin Heap)**- Adds travis CI integration- Added travis CI integration
**@bluele (Jun Kimura)**- Fixes code examples in README33 unmodified lines
**@mdigger (Dmitry Sedykh)**- Fixes Form binding when content-type is x-www-form-urlencoded- No repeat call c.Writer.Status() in gin.Logger- Fixed Content-Type for json render- Fixes Content-Type for json render
**@mopemope (Yutaka Matsubara)**- ★ Adds Godep support (Dependencies Manager)- Fix variadic parameter in the flexible render API- Fix Corrupted plain render- Fix variadic parameter in new flexible render API
**@msemenistyi (Mykyta Semenistyi)**- update Readme.md. Add code to String method
**@msoedov (Sasha Myasoedov)**- ★ Adds tons of unit tests.
**@ngerakines (Nick Gerakines)**- ★ Improves API, c.GET() doesn't panic- Adds MustGet() method
6 unmodified lines- Fixing quotes in README
**@SkuliOskarsson (Skuli Oskarsson)**- Fixes some texts in README IINo newline at end of file- Fixes some texts in README II
**@yuyabee**- Fixed READMENo newline at end of filemodified:CHANGELOG.md+8 added-2 removed
1123345678910111213141539 unmodified lines##Changelog#Changelog
###Gin 0.4 (??)###Gin 0.4 (Aug 21, 2014)
- [NEW] Development mode- [NEW] Unit tests- [NEW] Add Content.Redirect()- [FIX] Deferring WriteHeader()- [FIX] Improved documentation for model binding
###Gin 0.3 (Jul 18, 2014)
- [PERFORMANCE] Normal log and error log are printed in the same call.- [PERFORMANCE] Improve performance of NoRouter()39 unmodified linesadded:context_test.go+438 added
1+package gin2+3+import (4+ "bytes"5+ "errors"6+ "html/template"7+ "net/http"8+ "net/http/httptest"9+ "testing"10+)11+12+// TestContextParamsGet tests that a parameter can be parsed from the URL.13+func TestContextParamsByName(t *testing.T) {14+ req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil)15+ w := httptest.NewRecorder()16+ name := ""17+18+ r := New()19+ r.GET("/test/:name", func(c *Context) {20+ name = c.Params.ByName("name")21+ })22+23+ r.ServeHTTP(w, req)24+25+ if name != "alexandernyquist" {26+ t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name)27+ }28+}29+30+// TestContextSetGet tests that a parameter is set correctly on the31+// current context and can be retrieved using Get.32+func TestContextSetGet(t *testing.T) {33+ req, _ := http.NewRequest("GET", "/test", nil)34+ w := httptest.NewRecorder()35+36+ r := New()37+ r.GET("/test", func(c *Context) {38+ // Key should be lazily created39+ if c.Keys != nil {40+ t.Error("Keys should be nil")41+ }42+43+ // Set44+ c.Set("foo", "bar")45+46+ v, err := c.Get("foo")47+ if err != nil {48+ t.Errorf("Error on exist key")49+ }50+ if v != "bar" {51+ t.Errorf("Value should be bar, was %s", v)52+ }53+ })54+55+ r.ServeHTTP(w, req)56+}57+58+// TestContextJSON tests that the response is serialized as JSON59+// and Content-Type is set to application/json60+func TestContextJSON(t *testing.T) {61+ req, _ := http.NewRequest("GET", "/test", nil)62+ w := httptest.NewRecorder()63+64+ r := New()65+ r.GET("/test", func(c *Context) {66+ c.JSON(200, H{"foo": "bar"})67+ })68+69+ r.ServeHTTP(w, req)70+71+ if w.Body.String() != "{\"foo\":\"bar\"}\n" {72+ t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String())73+ }74+75+ if w.HeaderMap.Get("Content-Type") != "application/json" {76+ t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))77+ }78+}79+80+// TestContextHTML tests that the response executes the templates81+// and responds with Content-Type set to text/html82+func TestContextHTML(t *testing.T) {83+ req, _ := http.NewRequest("GET", "/test", nil)84+ w := httptest.NewRecorder()85+86+ r := New()87+ templ, _ := template.New("t").Parse(`Hello {{.Name}}`)88+ r.SetHTMLTemplate(templ)89+90+ type TestData struct{ Name string }91+92+ r.GET("/test", func(c *Context) {93+ c.HTML(200, "t", TestData{"alexandernyquist"})94+ })95+96+ r.ServeHTTP(w, req)97+98+ if w.Body.String() != "Hello alexandernyquist" {99+ t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String())100+ }101+102+ if w.HeaderMap.Get("Content-Type") != "text/html" {103+ t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type"))104+ }105+}106+107+// TestContextString tests that the response is returned108+// with Content-Type set to text/plain109+func TestContextString(t *testing.T) {110+ req, _ := http.NewRequest("GET", "/test", nil)111+ w := httptest.NewRecorder()112+113+ r := New()114+ r.GET("/test", func(c *Context) {115+ c.String(200, "test")116+ })117+118+ r.ServeHTTP(w, req)119+120+ if w.Body.String() != "test" {121+ t.Errorf("Response should be test, was: %s", w.Body.String())122+ }123+124+ if w.HeaderMap.Get("Content-Type") != "text/plain" {125+ t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))126+ }127+}128+129+// TestContextXML tests that the response is serialized as XML130+// and Content-Type is set to application/xml131+func TestContextXML(t *testing.T) {132+ req, _ := http.NewRequest("GET", "/test", nil)133+ w := httptest.NewRecorder()134+135+ r := New()136+ r.GET("/test", func(c *Context) {137+ c.XML(200, H{"foo": "bar"})138+ })139+140+ r.ServeHTTP(w, req)141+142+ if w.Body.String() != "<map><foo>bar</foo></map>" {143+ t.Errorf("Response should be <map><foo>bar</foo></map>, was: %s", w.Body.String())144+ }145+146+ if w.HeaderMap.Get("Content-Type") != "application/xml" {147+ t.Errorf("Content-Type should be application/xml, was %s", w.HeaderMap.Get("Content-Type"))148+ }149+}150+151+// TestContextData tests that the response can be written from `bytesting`152+// with specified MIME type153+func TestContextData(t *testing.T) {154+ req, _ := http.NewRequest("GET", "/test/csv", nil)155+ w := httptest.NewRecorder()156+157+ r := New()158+ r.GET("/test/csv", func(c *Context) {159+ c.Data(200, "text/csv", []byte(`foo,bar`))160+ })161+162+ r.ServeHTTP(w, req)163+164+ if w.Body.String() != "foo,bar" {165+ t.Errorf("Response should be foo&bar, was: %s", w.Body.String())166+ }167+168+ if w.HeaderMap.Get("Content-Type") != "text/csv" {169+ t.Errorf("Content-Type should be text/csv, was %s", w.HeaderMap.Get("Content-Type"))170+ }171+}172+173+func TestContextFile(t *testing.T) {174+ req, _ := http.NewRequest("GET", "/test/file", nil)175+ w := httptest.NewRecorder()176+177+ r := New()178+ r.GET("/test/file", func(c *Context) {179+ c.File("./gin.go")180+ })181+182+ r.ServeHTTP(w, req)183+184+ bodyAsString := w.Body.String()185+186+ if len(bodyAsString) == 0 {187+ t.Errorf("Got empty body instead of file data")188+ }189+190+ if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {191+ t.Errorf("Content-Type should be text/plain; charset=utf-8, was %s", w.HeaderMap.Get("Content-Type"))192+ }193+}194+195+// TestHandlerFunc - ensure that custom middleware works properly196+func TestHandlerFunc(t *testing.T) {197+198+ req, _ := http.NewRequest("GET", "/", nil)199+ w := httptest.NewRecorder()200+201+ r := New()202+ var stepsPassed int = 0203+204+ r.Use(func(context *Context) {205+ stepsPassed += 1206+ context.Next()207+ stepsPassed += 1208+ })209+210+ r.ServeHTTP(w, req)211+212+ if w.Code != 404 {213+ t.Errorf("Response code should be Not found, was: %s", w.Code)214+ }215+216+ if stepsPassed != 2 {217+ t.Errorf("Falied to switch context in handler function: %s", stepsPassed)218+ }219+}220+221+// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers222+func TestBadAbortHandlersChain(t *testing.T) {223+ // SETUP224+ var stepsPassed int = 0225+ r := New()226+ r.Use(func(c *Context) {227+ stepsPassed += 1228+ c.Next()229+ stepsPassed += 1230+ // after check and abort231+ c.Abort(409)232+ })233+ r.Use(func(c *Context) {234+ stepsPassed += 1235+ c.Next()236+ stepsPassed += 1237+ c.Abort(403)238+ })239+240+ // RUN241+ w := PerformRequest(r, "GET", "/")242+243+ // TEST244+ if w.Code != 409 {245+ t.Errorf("Response code should be Forbiden, was: %d", w.Code)246+ }247+ if stepsPassed != 4 {248+ t.Errorf("Falied to switch context in handler function: %d", stepsPassed)249+ }250+}251+252+// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order253+func TestAbortHandlersChain(t *testing.T) {254+ // SETUP255+ var stepsPassed int = 0256+ r := New()257+ r.Use(func(context *Context) {258+ stepsPassed += 1259+ context.Abort(409)260+ })261+ r.Use(func(context *Context) {262+ stepsPassed += 1263+ context.Next()264+ stepsPassed += 1265+ })266+267+ // RUN268+ w := PerformRequest(r, "GET", "/")269+270+ // TEST271+ if w.Code != 409 {272+ t.Errorf("Response code should be Conflict, was: %d", w.Code)273+ }274+ if stepsPassed != 1 {275+ t.Errorf("Falied to switch context in handler function: %d", stepsPassed)276+ }277+}278+279+// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as280+// as well as Abort281+func TestFailHandlersChain(t *testing.T) {282+ // SETUP283+ var stepsPassed int = 0284+ r := New()285+ r.Use(func(context *Context) {286+ stepsPassed += 1287+ context.Fail(500, errors.New("foo"))288+ })289+ r.Use(func(context *Context) {290+ stepsPassed += 1291+ context.Next()292+ stepsPassed += 1293+ })294+295+ // RUN296+ w := PerformRequest(r, "GET", "/")297+298+ // TEST299+ if w.Code != 500 {300+ t.Errorf("Response code should be Server error, was: %d", w.Code)301+ }302+ if stepsPassed != 1 {303+ t.Errorf("Falied to switch context in handler function: %d", stepsPassed)304+ }305+}306+307+func TestBindingJSON(t *testing.T) {308+309+ body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))310+311+ r := New()312+ r.POST("/binding/json", func(c *Context) {313+ var body struct {314+ Foo string `json:"foo"`315+ }316+ if c.Bind(&body) {317+ c.JSON(200, H{"parsed": body.Foo})318+ }319+ })320+321+ req, _ := http.NewRequest("POST", "/binding/json", body)322+ req.Header.Set("Content-Type", "application/json")323+ w := httptest.NewRecorder()324+325+ r.ServeHTTP(w, req)326+327+ if w.Code != 200 {328+ t.Errorf("Response code should be Ok, was: %s", w.Code)329+ }330+331+ if w.Body.String() != "{\"parsed\":\"bar\"}\n" {332+ t.Errorf("Response should be {\"parsed\":\"bar\"}, was: %s", w.Body.String())333+ }334+335+ if w.HeaderMap.Get("Content-Type") != "application/json" {336+ t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))337+ }338+}339+340+func TestBindingJSONEncoding(t *testing.T) {341+342+ body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}"))343+344+ r := New()345+ r.POST("/binding/json", func(c *Context) {346+ var body struct {347+ Foo string `json:"foo"`348+ }349+ if c.Bind(&body) {350+ c.JSON(200, H{"parsed": body.Foo})351+ }352+ })353+354+ req, _ := http.NewRequest("POST", "/binding/json", body)355+ req.Header.Set("Content-Type", "application/json; charset=utf-8")356+ w := httptest.NewRecorder()357+358+ r.ServeHTTP(w, req)359+360+ if w.Code != 200 {361+ t.Errorf("Response code should be Ok, was: %s", w.Code)362+ }363+364+ if w.Body.String() != "{\"parsed\":\"嘉\"}\n" {365+ t.Errorf("Response should be {\"parsed\":\"嘉\"}, was: %s", w.Body.String())366+ }367+368+ if w.HeaderMap.Get("Content-Type") != "application/json" {369+ t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))370+ }371+}372+373+func TestBindingJSONNoContentType(t *testing.T) {374+375+ body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))376+377+ r := New()378+ r.POST("/binding/json", func(c *Context) {379+ var body struct {380+ Foo string `json:"foo"`381+ }382+ if c.Bind(&body) {383+ c.JSON(200, H{"parsed": body.Foo})384+ }385+386+ })387+388+ req, _ := http.NewRequest("POST", "/binding/json", body)389+ w := httptest.NewRecorder()390+391+ r.ServeHTTP(w, req)392+393+ if w.Code != 400 {394+ t.Errorf("Response code should be Bad request, was: %s", w.Code)395+ }396+397+ if w.Body.String() == "{\"parsed\":\"bar\"}\n" {398+ t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())399+ }400+401+ if w.HeaderMap.Get("Content-Type") == "application/json" {402+ t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))403+ }404+}405+406+func TestBindingJSONMalformed(t *testing.T) {407+408+ body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n"))409+410+ r := New()411+ r.POST("/binding/json", func(c *Context) {412+ var body struct {413+ Foo string `json:"foo"`414+ }415+ if c.Bind(&body) {416+ c.JSON(200, H{"parsed": body.Foo})417+ }418+419+ })420+421+ req, _ := http.NewRequest("POST", "/binding/json", body)422+ req.Header.Set("Content-Type", "application/json")423+424+ w := httptest.NewRecorder()425+426+ r.ServeHTTP(w, req)427+428+ if w.Code != 400 {429+ t.Errorf("Response code should be Bad request, was: %s", w.Code)430+ }431+ if w.Body.String() == "{\"parsed\":\"bar\"}\n" {432+ t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())433+ }434+435+ if w.HeaderMap.Get("Content-Type") == "application/json" {436+ t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))437+ }438+}modified:context.go+9 added
245 unmodified lines246 func (c *Context) String(code int, format string, values ...interface{}) {247 c.Render(code, render.Plain, format, values)248 }249 250+// Returns a HTTP redirect to the specific location.251+func (c *Context) Redirect(code int, location string) {252+ if code >= 300 && code <= 308 {253+ c.Render(code, render.Redirect, location)254+ } else {255+ panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))256+ }257+}258+259 // Writes some data into the body stream and updates the HTTP code.260 func (c *Context) Data(code int, contentType string, data []byte) {261 if len(contentType) > 0 {262 c.Writer.Header().Set("Content-Type", contentType)11 unmodified linesadded:gin_test.go+203 added
1+package gin2+3+import (4+ "io/ioutil"5+ "net/http"6+ "net/http/httptest"7+ "os"8+ "path"9+ "strings"10+ "testing"11+)12+13+func init() {14+ SetMode(TestMode)15+}16+17+func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {18+ req, _ := http.NewRequest(method, path, nil)19+ w := httptest.NewRecorder()20+ r.ServeHTTP(w, req)21+ return w22+}23+24+// TestSingleRouteOK tests that POST route is correctly invoked.25+func testRouteOK(method string, t *testing.T) {26+ // SETUP27+ passed := false28+ r := New()29+ r.Handle(method, "/test", []HandlerFunc{func(c *Context) {30+ passed = true31+ }})32+33+ // RUN34+ w := PerformRequest(r, method, "/test")35+36+ // TEST37+ if passed == false {38+ t.Errorf(method + " route handler was not invoked.")39+ }40+ if w.Code != http.StatusOK {41+ t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)42+ }43+}44+func TestRouterGroupRouteOK(t *testing.T) {45+ testRouteOK("POST", t)46+ testRouteOK("DELETE", t)47+ testRouteOK("PATCH", t)48+ testRouteOK("PUT", t)49+ testRouteOK("OPTIONS", t)50+ testRouteOK("HEAD", t)51+}52+53+// TestSingleRouteOK tests that POST route is correctly invoked.54+func testRouteNotOK(method string, t *testing.T) {55+ // SETUP56+ passed := false57+ r := New()58+ r.Handle(method, "/test_2", []HandlerFunc{func(c *Context) {59+ passed = true60+ }})61+62+ // RUN63+ w := PerformRequest(r, method, "/test")64+65+ // TEST66+ if passed == true {67+ t.Errorf(method + " route handler was invoked, when it should not")68+ }69+ if w.Code != http.StatusNotFound {70+ // If this fails, it's because httprouter needs to be updated to at least f78f58a0db71+ t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))72+ }73+}74+75+// TestSingleRouteOK tests that POST route is correctly invoked.76+func TestRouteNotOK(t *testing.T) {77+ testRouteNotOK("POST", t)78+ testRouteNotOK("DELETE", t)79+ testRouteNotOK("PATCH", t)80+ testRouteNotOK("PUT", t)81+ testRouteNotOK("OPTIONS", t)82+ testRouteNotOK("HEAD", t)83+}84+85+// TestSingleRouteOK tests that POST route is correctly invoked.86+func testRouteNotOK2(method string, t *testing.T) {87+ // SETUP88+ passed := false89+ r := New()90+ var methodRoute string91+ if method == "POST" {92+ methodRoute = "GET"93+ } else {94+ methodRoute = "POST"95+ }96+ r.Handle(methodRoute, "/test", []HandlerFunc{func(c *Context) {97+ passed = true98+ }})99+100+ // RUN101+ w := PerformRequest(r, method, "/test")102+103+ // TEST104+ if passed == true {105+ t.Errorf(method + " route handler was invoked, when it should not")106+ }107+ if w.Code != http.StatusNotFound {108+ // If this fails, it's because httprouter needs to be updated to at least f78f58a0db109+ t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))110+ }111+}112+113+// TestSingleRouteOK tests that POST route is correctly invoked.114+func TestRouteNotOK2(t *testing.T) {115+ testRouteNotOK2("POST", t)116+ testRouteNotOK2("DELETE", t)117+ testRouteNotOK2("PATCH", t)118+ testRouteNotOK2("PUT", t)119+ testRouteNotOK2("OPTIONS", t)120+ testRouteNotOK2("HEAD", t)121+}122+123+// TestHandleStaticFile - ensure the static file handles properly124+func TestHandleStaticFile(t *testing.T) {125+ // SETUP file126+ testRoot, _ := os.Getwd()127+ f, err := ioutil.TempFile(testRoot, "")128+ if err != nil {129+ t.Error(err)130+ }131+ defer os.Remove(f.Name())132+ filePath := path.Join("/", path.Base(f.Name()))133+ f.WriteString("Gin Web Framework")134+ f.Close()135+136+ // SETUP gin137+ r := New()138+ r.Static("./", testRoot)139+140+ // RUN141+ w := PerformRequest(r, "GET", filePath)142+143+ // TEST144+ if w.Code != 200 {145+ t.Errorf("Response code should be Ok, was: %s", w.Code)146+ }147+ if w.Body.String() != "Gin Web Framework" {148+ t.Errorf("Response should be test, was: %s", w.Body.String())149+ }150+ if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {151+ t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))152+ }153+}154+155+// TestHandleStaticDir - ensure the root/sub dir handles properly156+func TestHandleStaticDir(t *testing.T) {157+ // SETUP158+ r := New()159+ r.Static("/", "./")160+161+ // RUN162+ w := PerformRequest(r, "GET", "/")163+164+ // TEST165+ bodyAsString := w.Body.String()166+ if w.Code != 200 {167+ t.Errorf("Response code should be Ok, was: %s", w.Code)168+ }169+ if len(bodyAsString) == 0 {170+ t.Errorf("Got empty body instead of file tree")171+ }172+ if !strings.Contains(bodyAsString, "gin.go") {173+ t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)174+ }175+ if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {176+ t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))177+ }178+}179+180+// TestHandleHeadToDir - ensure the root/sub dir handles properly181+func TestHandleHeadToDir(t *testing.T) {182+ // SETUP183+ r := New()184+ r.Static("/", "./")185+186+ // RUN187+ w := PerformRequest(r, "HEAD", "/")188+189+ // TEST190+ bodyAsString := w.Body.String()191+ if w.Code != 200 {192+ t.Errorf("Response code should be Ok, was: %s", w.Code)193+ }194+ if len(bodyAsString) == 0 {195+ t.Errorf("Got empty body instead of file tree")196+ }197+ if !strings.Contains(bodyAsString, "gin.go") {198+ t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)199+ }200+ if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {201+ t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))202+ }203+}modified:gin.go+32 added-6 removed
1 package gin2 3 import (4+ "fmt"5 "github.com/gin-gonic/gin/render"6 "github.com/julienschmidt/httprouter"7 "html/template"8 "math"36 unmodified lines45 )46 47 func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {48 c := engine.createContext(w, req, nil, engine.finalNoRoute)49+ // set 404 by default, useful for logging48- c.Writer.setStatus(404)50+ c.Writer.WriteHeader(404)51 c.Next()52 if !c.Writer.Written() {53+ if c.Writer.Status() == 404 {51- c.Data(404, MIMEPlain, []byte("404 page not found"))54+ c.Data(-1, MIMEPlain, []byte("404 page not found"))55+ } else {56+ c.Writer.WriteHeaderNow()57+ }58 }59 engine.cache.Put(c)60 }61 19 unmodified lines81 return engine82 }83 84 func (engine *Engine) LoadHTMLGlob(pattern string) {85+ if gin_mode == debugCode {86+ engine.HTMLRender = render.HTMLDebug87+ } else {79- templ := template.Must(template.ParseGlob(pattern))80- engine.SetHTMLTemplate(templ)88+ templ := template.Must(template.ParseGlob(pattern))89+ engine.SetHTMLTemplate(templ)90+ }91 }92 93 func (engine *Engine) LoadHTMLFiles(files ...string) {94+ if gin_mode == debugCode {95+ engine.HTMLRender = render.HTMLDebug96+ } else {84- templ := template.Must(template.ParseFiles(files...))85- engine.SetHTMLTemplate(templ)97+ templ := template.Must(template.ParseFiles(files...))98+ engine.SetHTMLTemplate(templ)99+ }100 }101 102 func (engine *Engine) SetHTMLTemplate(templ *template.Template) {103 engine.HTMLRender = render.HTMLRender{17 unmodified lines121 engine.router.ServeHTTP(w, req)122 }123 124 func (engine *Engine) Run(addr string) {125+ if gin_mode == debugCode {126+ fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr)127+ }128 if err := http.ListenAndServe(addr, engine); err != nil {129 panic(err)130 }131 }132 133 func (engine *Engine) RunTLS(addr string, cert string, key string) {134+ if gin_mode == debugCode {135+ fmt.Println("[GIN-debug] Listening and serving HTTPS on " + addr)136+ }137 if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {138 panic(err)139 }140 }41 unmodified lines182 // communication with a proxy).183 func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {184 p = group.pathFor(p)185 handlers = group.combineHandlers(handlers)186+ if gin_mode == debugCode {187+ nuHandlers := len(handlers)188+ name := funcName(handlers[nuHandlers-1])189+ fmt.Printf("[GIN-debug] %-5s %-25s --> %s (%d handlers)\n", method, p, name, nuHandlers)190+ }191 group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {192 c := group.engine.createContext(w, req, params, handlers)193 c.Next()194+ c.Writer.WriteHeaderNow()195 group.engine.cache.Put(c)196 })197 }198 60 unmodified linesmodified:logger.go+2 added-3 removed
42 unmodified lines43 44 // save the IP of the requester45 requester := c.Request.Header.Get("X-Real-IP")46 // if the requester-header is empty, check the forwarded-header47- if requester == "" {47+ if len(requester) == 0 {48 requester = c.Request.Header.Get("X-Forwarded-For")49 }50-50 // if the requester is still empty, use the hard-coded address from the socket52- if requester == "" {51+ if len(requester) == 0 {52 requester = c.Request.RemoteAddr53 }54 55 var color string23 unmodified linesadded:mode.go+42 added
1+package gin2+3+import (4+ "os"5+)6+7+const GIN_MODE = "GIN_MODE"8+9+const (10+ DebugMode string = "debug"11+ ReleaseMode string = "release"12+ TestMode string = "test"13+)14+const (15+ debugCode = iota16+ releaseCode = iota17+ testCode = iota18+)19+20+var gin_mode int = debugCode21+22+func SetMode(value string) {23+ switch value {24+ case DebugMode:25+ gin_mode = debugCode26+ case ReleaseMode:27+ gin_mode = releaseCode28+ case TestMode:29+ gin_mode = testCode30+ default:31+ panic("gin mode unknown, the allowed modes are: " + DebugMode + " and " + ReleaseMode)32+ }33+}34+35+func init() {36+ value := os.Getenv(GIN_MODE)37+ if len(value) == 0 {38+ SetMode(DebugMode)39+ } else {40+ SetMode(value)41+ }42+}modified:README.md+48 added-15 removed
1 #Gin Web Framework2 3-[](https://godoc.org/github.com/gin-gonic/gin)3+[](https://godoc.org/github.com/gin-gonic/gin)4 [](https://travis-ci.org/gin-gonic/gin)5 6 Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster. If you need performance and good productivity, you will love Gin. 7 187 unmodified lines195 r.Run(":8080")196 }197 ```198 199+#### Model binding and validation200 200-#### JSON parsing and validation201+To bind a request body into a type, use model binding. We currently support binding of JSON, XML and standard form values (foo=bar&boo=baz).202 203+Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`.204+205+When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use BindWith. 206+207+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.208+209 ```go210+// Binding from JSON211 type LoginJSON struct {212 User string `json:"user" binding:"required"`213 Password string `json:"password" binding:"required"`214 }215 216+// Binding from form values217+type LoginForm struct {218+ User string `form:"user" binding:"required"`219+ Password string `form:"password" binding:"required"` 220+}221+222 func main() {223 r := gin.Default()224 225+ // Example for binding JSON ({"user": "manu", "password": "123"})226 r.POST("/login", func(c *gin.Context) {227 var json LoginJSON228 214- // If EnsureBody returns false, it will write automatically the error215- // in the HTTP stream and return a 400 error. If you want custom error216- // handling you should use: c.ParseBody(interface{}) error217- if c.EnsureBody(&json) {218- if json.User == "manu" && json.Password == "123" {219- c.JSON(200, gin.H{"status": "you are logged in"})220- } else {221- c.JSON(401, gin.H{"status": "unauthorized"})222- }229+ c.Bind(&json) // This will infer what binder to use depending on the content-type header.230+ if json.User == "manu" && json.Password == "123" {231+ c.JSON(200, gin.H{"status": "you are logged in"})232+ } else {233+ c.JSON(401, gin.H{"status": "unauthorized"})234+ }223- }235 })236 237+ // Example for binding a HTLM form (user=manu&password=123)238+ r.POST("/login", func(c *gin.Context) {239+ var form LoginForm240+241+ c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML.242+ if form.User == "manu" && form.Password == "123" {243+ c.JSON(200, gin.H{"status": "you are logged in"})244+ } else {245+ c.JSON(401, gin.H{"status": "unauthorized"})246+ }247+ })248+249 // Listen and server on 0.0.0.0:8080250 r.Run(":8080")251 }252 ```253 231-#### XML, and JSON rendering254+#### XML and JSON rendering255 256 ```go257 func main() {258 r := gin.Default()60 unmodified lines319 r.Run(":8080")320 }321 ```322 323+#### Redirects324 325+Issuing a HTTP redirect is easy:326+327+```r.GET("/test", func(c *gin.Context) {328+ c.Redirect(301, "http://www.google.com/")329+})330+331+Both internal and external locations are supported.332+```333+334 #### Custom Middlewares335 336 ```go337 func Logger() gin.HandlerFunc {86 unmodified lines424 // simulate a long task with time.Sleep(). 5 seconds425 time.Sleep(5 * time.Second)426 427 // note than you are using the copied context "c_cp", IMPORTANT395- log.Println("Done! in path " + c_cp.Req.URL.Path)428+ log.Println("Done! in path " + c_cp.Request.URL.Path)429 }()430 })431 432 1 unmodified line434 // simulate a long task with time.Sleep(). 5 seconds435 time.Sleep(5 * time.Second)436 437 // since we are NOT using a goroutine, we do not have to copy the context405- log.Println("Done! in path " + c.Req.URL.Path)438+ log.Println("Done! in path " + c.Request.URL.Path)439 })440 441 // Listen and server on 0.0.0.0:8080442 r.Run(":8080")29 unmodified linesadded:recovery_test.go+52 added
1+package gin2+3+import (4+ "bytes"5+ "log"6+ "os"7+ "testing"8+)9+10+// TestPanicInHandler assert that panic has been recovered.11+func TestPanicInHandler(t *testing.T) {12+ // SETUP13+ log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing14+ r := New()15+ r.Use(Recovery())16+ r.GET("/recovery", func(_ *Context) {17+ panic("Oupps, Houston, we have a problem")18+ })19+20+ // RUN21+ w := PerformRequest(r, "GET", "/recovery")22+23+ // restore logging24+ log.SetOutput(os.Stderr)25+26+ if w.Code != 500 {27+ t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)28+ }29+}30+31+// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.32+func TestPanicWithAbort(t *testing.T) {33+ // SETUP34+ log.SetOutput(bytes.NewBuffer(nil))35+ r := New()36+ r.Use(Recovery())37+ r.GET("/recovery", func(c *Context) {38+ c.Abort(400)39+ panic("Oupps, Houston, we have a problem")40+ })41+42+ // RUN43+ w := PerformRequest(r, "GET", "/recovery")44+45+ // restore logging46+ log.SetOutput(os.Stderr)47+48+ // TEST49+ if w.Code != 500 {50+ t.Errorf("Response code should be Bad request, was: %s", w.Code)51+ }52+}modified:response_writer.go+20 added-10 removed
1 package gin2 3 import (4+ "log"5 "net/http"6 )7 8 type (9 ResponseWriter interface {10 http.ResponseWriter11 Status() int12 Written() bool12-13- // private14- setStatus(int)13+ WriteHeaderNow()14 }15 16 responseWriter struct {17 http.ResponseWriter3 unmodified lines21 )22 23 func (w *responseWriter) reset(writer http.ResponseWriter) {24 w.ResponseWriter = writer26- w.status = 025+ w.status = 20026 w.written = false27 }28 30-func (w *responseWriter) setStatus(code int) {31- w.status = code29+func (w *responseWriter) WriteHeader(code int) {30+ if code != 0 {31+ w.status = code32+ if w.written {33+ log.Println("[GIN] WARNING. Headers were already written!")34+ }35+ }36 }37 34-func (w *responseWriter) WriteHeader(code int) {35- w.status = code36- w.written = true37- w.ResponseWriter.WriteHeader(code)38+func (w *responseWriter) WriteHeaderNow() {39+ if !w.written {40+ w.written = true41+ w.ResponseWriter.WriteHeader(w.status)42+ }43 }44 45+func (w *responseWriter) Write(data []byte) (n int, err error) {46+ w.WriteHeaderNow()47+ return w.ResponseWriter.Write(data)48+}49+50 func (w *responseWriter) Status() int {51 return w.status52 }53 3 unmodified linesmodified:utils.go+6 added
1 package gin2 3 import (4 "encoding/xml"5+ "reflect"6+ "runtime"7 )8 9 type H map[string]interface{}10 28 unmodified lines39 }40 }41 return content42 }43+44+func funcName(f interface{}) string {45+ return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()46+}