diff --git a/AUTHORS.md b/AUTHORS.md index 67535a4..c09e263 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -5,7 +5,7 @@ List of all the awesome people working to make Gin the best Web Framework in Go! ##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. @@ -22,10 +22,13 @@ People and companies, who have contributed, in alphabetical order. - 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)** @@ -67,20 +70,23 @@ People and companies, who have contributed, in alphabetical order. **@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 @@ -95,4 +101,8 @@ People and companies, who have contributed, in alphabetical order. **@SkuliOskarsson (Skuli Oskarsson)** -- Fixes some texts in README II \ No newline at end of file +- Fixes some texts in README II + + +**@yuyabee** +- Fixed README \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c39907..5ec8c5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ -##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) diff --git a/README.md b/README.md index 6fa52d0..f150f43 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ #Gin Web Framework -[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.png)](https://godoc.org/github.com/gin-gonic/gin) +[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin) [![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin) 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. @@ -196,39 +196,62 @@ func main() { } ``` +#### Model binding and validation -#### JSON parsing and validation +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). + +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"`. + +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. + +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. ```go +// Binding from JSON type LoginJSON struct { User string `json:"user" binding:"required"` Password string `json:"password" binding:"required"` } +// Binding from form values +type LoginForm struct { + User string `form:"user" binding:"required"` + Password string `form:"password" binding:"required"` +} + func main() { r := gin.Default() + // Example for binding JSON ({"user": "manu", "password": "123"}) r.POST("/login", func(c *gin.Context) { var json LoginJSON - // If EnsureBody returns false, it will write automatically the error - // in the HTTP stream and return a 400 error. If you want custom error - // handling you should use: c.ParseBody(interface{}) error - if c.EnsureBody(&json) { - if json.User == "manu" && json.Password == "123" { - c.JSON(200, gin.H{"status": "you are logged in"}) - } else { - c.JSON(401, gin.H{"status": "unauthorized"}) - } - } + c.Bind(&json) // This will infer what binder to use depending on the content-type header. + if json.User == "manu" && json.Password == "123" { + c.JSON(200, gin.H{"status": "you are logged in"}) + } else { + c.JSON(401, gin.H{"status": "unauthorized"}) + } }) + // Example for binding a HTLM form (user=manu&password=123) + r.POST("/login", func(c *gin.Context) { + var form LoginForm + + c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML. + if form.User == "manu" && form.Password == "123" { + c.JSON(200, gin.H{"status": "you are logged in"}) + } else { + c.JSON(401, gin.H{"status": "unauthorized"}) + } + }) + // Listen and server on 0.0.0.0:8080 r.Run(":8080") } ``` -#### XML, and JSON rendering +#### XML and JSON rendering ```go func main() { @@ -297,6 +320,16 @@ func main() { } ``` +#### Redirects + +Issuing a HTTP redirect is easy: + +```r.GET("/test", func(c *gin.Context) { + c.Redirect(301, "http://www.google.com/") +}) + +Both internal and external locations are supported. +``` #### Custom Middlewares @@ -392,7 +425,7 @@ func main() { time.Sleep(5 * time.Second) // note than you are using the copied context "c_cp", IMPORTANT - log.Println("Done! in path " + c_cp.Req.URL.Path) + log.Println("Done! in path " + c_cp.Request.URL.Path) }() }) @@ -402,7 +435,7 @@ func main() { time.Sleep(5 * time.Second) // since we are NOT using a goroutine, we do not have to copy the context - log.Println("Done! in path " + c.Req.URL.Path) + log.Println("Done! in path " + c.Request.URL.Path) }) // Listen and server on 0.0.0.0:8080 diff --git a/auth_test.go b/auth_test.go new file mode 100644 index 0000000..cc70bc0 --- /dev/null +++ b/auth_test.go @@ -0,0 +1,57 @@ +package gin + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "testing" +) + +func TestBasicAuthSucceed(t *testing.T) { + req, _ := http.NewRequest("GET", "/login", nil) + w := httptest.NewRecorder() + + r := New() + accounts := Accounts{"admin": "password"} + r.Use(BasicAuth(accounts)) + + r.GET("/login", func(c *Context) { + c.String(200, "autorized") + }) + + req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + bodyAsString := w.Body.String() + + if bodyAsString != "autorized" { + t.Errorf("Response body should be `autorized`, was %s", bodyAsString) + } +} + +func TestBasicAuth401(t *testing.T) { + req, _ := http.NewRequest("GET", "/login", nil) + w := httptest.NewRecorder() + + r := New() + accounts := Accounts{"foo": "bar"} + r.Use(BasicAuth(accounts)) + + r.GET("/login", func(c *Context) { + c.String(200, "autorized") + }) + + req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) + r.ServeHTTP(w, req) + + if w.Code != 401 { + t.Errorf("Response code should be Not autorized, was: %s", w.Code) + } + + if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" { + t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type")) + } +} diff --git a/context.go b/context.go index 17ba45c..8fed41d 100644 --- a/context.go +++ b/context.go @@ -247,6 +247,15 @@ func (c *Context) String(code int, format string, values ...interface{}) { c.Render(code, render.Plain, format, values) } +// Returns a HTTP redirect to the specific location. +func (c *Context) Redirect(code int, location string) { + if code >= 300 && code <= 308 { + c.Render(code, render.Redirect, location) + } else { + panic(fmt.Sprintf("Cannot send a redirect with status code %d", code)) + } +} + // Writes some data into the body stream and updates the HTTP code. func (c *Context) Data(code int, contentType string, data []byte) { if len(contentType) > 0 { diff --git a/context_test.go b/context_test.go new file mode 100644 index 0000000..3b3302e --- /dev/null +++ b/context_test.go @@ -0,0 +1,438 @@ +package gin + +import ( + "bytes" + "errors" + "html/template" + "net/http" + "net/http/httptest" + "testing" +) + +// TestContextParamsGet tests that a parameter can be parsed from the URL. +func TestContextParamsByName(t *testing.T) { + req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil) + w := httptest.NewRecorder() + name := "" + + r := New() + r.GET("/test/:name", func(c *Context) { + name = c.Params.ByName("name") + }) + + r.ServeHTTP(w, req) + + if name != "alexandernyquist" { + t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name) + } +} + +// TestContextSetGet tests that a parameter is set correctly on the +// current context and can be retrieved using Get. +func TestContextSetGet(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := New() + r.GET("/test", func(c *Context) { + // Key should be lazily created + if c.Keys != nil { + t.Error("Keys should be nil") + } + + // Set + c.Set("foo", "bar") + + v, err := c.Get("foo") + if err != nil { + t.Errorf("Error on exist key") + } + if v != "bar" { + t.Errorf("Value should be bar, was %s", v) + } + }) + + r.ServeHTTP(w, req) +} + +// TestContextJSON tests that the response is serialized as JSON +// and Content-Type is set to application/json +func TestContextJSON(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := New() + r.GET("/test", func(c *Context) { + c.JSON(200, H{"foo": "bar"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "{\"foo\":\"bar\"}\n" { + t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextHTML tests that the response executes the templates +// and responds with Content-Type set to text/html +func TestContextHTML(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := New() + templ, _ := template.New("t").Parse(`Hello {{.Name}}`) + r.SetHTMLTemplate(templ) + + type TestData struct{ Name string } + + r.GET("/test", func(c *Context) { + c.HTML(200, "t", TestData{"alexandernyquist"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "Hello alexandernyquist" { + t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/html" { + t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextString tests that the response is returned +// with Content-Type set to text/plain +func TestContextString(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := New() + r.GET("/test", func(c *Context) { + c.String(200, "test") + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "test" { + t.Errorf("Response should be test, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/plain" { + t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextXML tests that the response is serialized as XML +// and Content-Type is set to application/xml +func TestContextXML(t *testing.T) { + req, _ := http.NewRequest("GET", "/test", nil) + w := httptest.NewRecorder() + + r := New() + r.GET("/test", func(c *Context) { + c.XML(200, H{"foo": "bar"}) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "bar" { + t.Errorf("Response should be bar, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/xml" { + t.Errorf("Content-Type should be application/xml, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestContextData tests that the response can be written from `bytesting` +// with specified MIME type +func TestContextData(t *testing.T) { + req, _ := http.NewRequest("GET", "/test/csv", nil) + w := httptest.NewRecorder() + + r := New() + r.GET("/test/csv", func(c *Context) { + c.Data(200, "text/csv", []byte(`foo,bar`)) + }) + + r.ServeHTTP(w, req) + + if w.Body.String() != "foo,bar" { + t.Errorf("Response should be foo&bar, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "text/csv" { + t.Errorf("Content-Type should be text/csv, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +func TestContextFile(t *testing.T) { + req, _ := http.NewRequest("GET", "/test/file", nil) + w := httptest.NewRecorder() + + r := New() + r.GET("/test/file", func(c *Context) { + c.File("./gin.go") + }) + + r.ServeHTTP(w, req) + + bodyAsString := w.Body.String() + + if len(bodyAsString) == 0 { + t.Errorf("Got empty body instead of file data") + } + + if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" { + t.Errorf("Content-Type should be text/plain; charset=utf-8, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestHandlerFunc - ensure that custom middleware works properly +func TestHandlerFunc(t *testing.T) { + + req, _ := http.NewRequest("GET", "/", nil) + w := httptest.NewRecorder() + + r := New() + var stepsPassed int = 0 + + r.Use(func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }) + + r.ServeHTTP(w, req) + + if w.Code != 404 { + t.Errorf("Response code should be Not found, was: %s", w.Code) + } + + if stepsPassed != 2 { + t.Errorf("Falied to switch context in handler function: %s", stepsPassed) + } +} + +// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers +func TestBadAbortHandlersChain(t *testing.T) { + // SETUP + var stepsPassed int = 0 + r := New() + r.Use(func(c *Context) { + stepsPassed += 1 + c.Next() + stepsPassed += 1 + // after check and abort + c.Abort(409) + }) + r.Use(func(c *Context) { + stepsPassed += 1 + c.Next() + stepsPassed += 1 + c.Abort(403) + }) + + // RUN + w := PerformRequest(r, "GET", "/") + + // TEST + if w.Code != 409 { + t.Errorf("Response code should be Forbiden, was: %d", w.Code) + } + if stepsPassed != 4 { + t.Errorf("Falied to switch context in handler function: %d", stepsPassed) + } +} + +// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order +func TestAbortHandlersChain(t *testing.T) { + // SETUP + var stepsPassed int = 0 + r := New() + r.Use(func(context *Context) { + stepsPassed += 1 + context.Abort(409) + }) + r.Use(func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }) + + // RUN + w := PerformRequest(r, "GET", "/") + + // TEST + if w.Code != 409 { + t.Errorf("Response code should be Conflict, was: %d", w.Code) + } + if stepsPassed != 1 { + t.Errorf("Falied to switch context in handler function: %d", stepsPassed) + } +} + +// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as +// as well as Abort +func TestFailHandlersChain(t *testing.T) { + // SETUP + var stepsPassed int = 0 + r := New() + r.Use(func(context *Context) { + stepsPassed += 1 + context.Fail(500, errors.New("foo")) + }) + r.Use(func(context *Context) { + stepsPassed += 1 + context.Next() + stepsPassed += 1 + }) + + // RUN + w := PerformRequest(r, "GET", "/") + + // TEST + if w.Code != 500 { + t.Errorf("Response code should be Server error, was: %d", w.Code) + } + if stepsPassed != 1 { + t.Errorf("Falied to switch context in handler function: %d", stepsPassed) + } +} + +func TestBindingJSON(t *testing.T) { + + body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}")) + + r := New() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + + if w.Body.String() != "{\"parsed\":\"bar\"}\n" { + t.Errorf("Response should be {\"parsed\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +func TestBindingJSONEncoding(t *testing.T) { + + body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}")) + + r := New() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + req.Header.Set("Content-Type", "application/json; charset=utf-8") + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + + if w.Body.String() != "{\"parsed\":\"嘉\"}\n" { + t.Errorf("Response should be {\"parsed\":\"嘉\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") != "application/json" { + t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +func TestBindingJSONNoContentType(t *testing.T) { + + body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}")) + + r := New() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 400 { + t.Errorf("Response code should be Bad request, was: %s", w.Code) + } + + if w.Body.String() == "{\"parsed\":\"bar\"}\n" { + t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") == "application/json" { + t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +func TestBindingJSONMalformed(t *testing.T) { + + body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n")) + + r := New() + r.POST("/binding/json", func(c *Context) { + var body struct { + Foo string `json:"foo"` + } + if c.Bind(&body) { + c.JSON(200, H{"parsed": body.Foo}) + } + + }) + + req, _ := http.NewRequest("POST", "/binding/json", body) + req.Header.Set("Content-Type", "application/json") + + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + if w.Code != 400 { + t.Errorf("Response code should be Bad request, was: %s", w.Code) + } + if w.Body.String() == "{\"parsed\":\"bar\"}\n" { + t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String()) + } + + if w.HeaderMap.Get("Content-Type") == "application/json" { + t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type")) + } +} diff --git a/gin.go b/gin.go index 106e1b9..0f4753e 100644 --- a/gin.go +++ b/gin.go @@ -1,6 +1,7 @@ package gin import ( + "fmt" "github.com/gin-gonic/gin/render" "github.com/julienschmidt/httprouter" "html/template" @@ -45,10 +46,15 @@ type ( func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) { c := engine.createContext(w, req, nil, engine.finalNoRoute) - c.Writer.setStatus(404) + // set 404 by default, useful for logging + c.Writer.WriteHeader(404) c.Next() if !c.Writer.Written() { - c.Data(404, MIMEPlain, []byte("404 page not found")) + if c.Writer.Status() == 404 { + c.Data(-1, MIMEPlain, []byte("404 page not found")) + } else { + c.Writer.WriteHeaderNow() + } } engine.cache.Put(c) } @@ -76,13 +82,21 @@ func Default() *Engine { } func (engine *Engine) LoadHTMLGlob(pattern string) { - templ := template.Must(template.ParseGlob(pattern)) - engine.SetHTMLTemplate(templ) + if gin_mode == debugCode { + engine.HTMLRender = render.HTMLDebug + } else { + templ := template.Must(template.ParseGlob(pattern)) + engine.SetHTMLTemplate(templ) + } } func (engine *Engine) LoadHTMLFiles(files ...string) { - templ := template.Must(template.ParseFiles(files...)) - engine.SetHTMLTemplate(templ) + if gin_mode == debugCode { + engine.HTMLRender = render.HTMLDebug + } else { + templ := template.Must(template.ParseFiles(files...)) + engine.SetHTMLTemplate(templ) + } } func (engine *Engine) SetHTMLTemplate(templ *template.Template) { @@ -108,12 +122,18 @@ func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { } func (engine *Engine) Run(addr string) { + if gin_mode == debugCode { + fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr) + } if err := http.ListenAndServe(addr, engine); err != nil { panic(err) } } func (engine *Engine) RunTLS(addr string, cert string, key string) { + if gin_mode == debugCode { + fmt.Println("[GIN-debug] Listening and serving HTTPS on " + addr) + } if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil { panic(err) } @@ -163,9 +183,15 @@ func (group *RouterGroup) pathFor(p string) string { func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) { p = group.pathFor(p) handlers = group.combineHandlers(handlers) + if gin_mode == debugCode { + nuHandlers := len(handlers) + name := funcName(handlers[nuHandlers-1]) + fmt.Printf("[GIN-debug] %-5s %-25s --> %s (%d handlers)\n", method, p, name, nuHandlers) + } group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) { c := group.engine.createContext(w, req, params, handlers) c.Next() + c.Writer.WriteHeaderNow() group.engine.cache.Put(c) }) } diff --git a/gin_test.go b/gin_test.go new file mode 100644 index 0000000..7425cc2 --- /dev/null +++ b/gin_test.go @@ -0,0 +1,203 @@ +package gin + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "path" + "strings" + "testing" +) + +func init() { + SetMode(TestMode) +} + +func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder { + req, _ := http.NewRequest(method, path, nil) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w +} + +// TestSingleRouteOK tests that POST route is correctly invoked. +func testRouteOK(method string, t *testing.T) { + // SETUP + passed := false + r := New() + r.Handle(method, "/test", []HandlerFunc{func(c *Context) { + passed = true + }}) + + // RUN + w := PerformRequest(r, method, "/test") + + // TEST + if passed == false { + t.Errorf(method + " route handler was not invoked.") + } + if w.Code != http.StatusOK { + t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code) + } +} +func TestRouterGroupRouteOK(t *testing.T) { + testRouteOK("POST", t) + testRouteOK("DELETE", t) + testRouteOK("PATCH", t) + testRouteOK("PUT", t) + testRouteOK("OPTIONS", t) + testRouteOK("HEAD", t) +} + +// TestSingleRouteOK tests that POST route is correctly invoked. +func testRouteNotOK(method string, t *testing.T) { + // SETUP + passed := false + r := New() + r.Handle(method, "/test_2", []HandlerFunc{func(c *Context) { + passed = true + }}) + + // RUN + w := PerformRequest(r, method, "/test") + + // TEST + if passed == true { + t.Errorf(method + " route handler was invoked, when it should not") + } + if w.Code != http.StatusNotFound { + // If this fails, it's because httprouter needs to be updated to at least f78f58a0db + t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location")) + } +} + +// TestSingleRouteOK tests that POST route is correctly invoked. +func TestRouteNotOK(t *testing.T) { + testRouteNotOK("POST", t) + testRouteNotOK("DELETE", t) + testRouteNotOK("PATCH", t) + testRouteNotOK("PUT", t) + testRouteNotOK("OPTIONS", t) + testRouteNotOK("HEAD", t) +} + +// TestSingleRouteOK tests that POST route is correctly invoked. +func testRouteNotOK2(method string, t *testing.T) { + // SETUP + passed := false + r := New() + var methodRoute string + if method == "POST" { + methodRoute = "GET" + } else { + methodRoute = "POST" + } + r.Handle(methodRoute, "/test", []HandlerFunc{func(c *Context) { + passed = true + }}) + + // RUN + w := PerformRequest(r, method, "/test") + + // TEST + if passed == true { + t.Errorf(method + " route handler was invoked, when it should not") + } + if w.Code != http.StatusNotFound { + // If this fails, it's because httprouter needs to be updated to at least f78f58a0db + t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location")) + } +} + +// TestSingleRouteOK tests that POST route is correctly invoked. +func TestRouteNotOK2(t *testing.T) { + testRouteNotOK2("POST", t) + testRouteNotOK2("DELETE", t) + testRouteNotOK2("PATCH", t) + testRouteNotOK2("PUT", t) + testRouteNotOK2("OPTIONS", t) + testRouteNotOK2("HEAD", t) +} + +// TestHandleStaticFile - ensure the static file handles properly +func TestHandleStaticFile(t *testing.T) { + // SETUP file + testRoot, _ := os.Getwd() + f, err := ioutil.TempFile(testRoot, "") + if err != nil { + t.Error(err) + } + defer os.Remove(f.Name()) + filePath := path.Join("/", path.Base(f.Name())) + f.WriteString("Gin Web Framework") + f.Close() + + // SETUP gin + r := New() + r.Static("./", testRoot) + + // RUN + w := PerformRequest(r, "GET", filePath) + + // TEST + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + if w.Body.String() != "Gin Web Framework" { + t.Errorf("Response should be test, was: %s", w.Body.String()) + } + if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" { + t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestHandleStaticDir - ensure the root/sub dir handles properly +func TestHandleStaticDir(t *testing.T) { + // SETUP + r := New() + r.Static("/", "./") + + // RUN + w := PerformRequest(r, "GET", "/") + + // TEST + bodyAsString := w.Body.String() + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + if len(bodyAsString) == 0 { + t.Errorf("Got empty body instead of file tree") + } + if !strings.Contains(bodyAsString, "gin.go") { + t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString) + } + if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" { + t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) + } +} + +// TestHandleHeadToDir - ensure the root/sub dir handles properly +func TestHandleHeadToDir(t *testing.T) { + // SETUP + r := New() + r.Static("/", "./") + + // RUN + w := PerformRequest(r, "HEAD", "/") + + // TEST + bodyAsString := w.Body.String() + if w.Code != 200 { + t.Errorf("Response code should be Ok, was: %s", w.Code) + } + if len(bodyAsString) == 0 { + t.Errorf("Got empty body instead of file tree") + } + if !strings.Contains(bodyAsString, "gin.go") { + t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString) + } + if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" { + t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type")) + } +} diff --git a/logger.go b/logger.go index 5a67f7c..8cbc24b 100644 --- a/logger.go +++ b/logger.go @@ -44,12 +44,11 @@ func Logger() HandlerFunc { // save the IP of the requester requester := c.Request.Header.Get("X-Real-IP") // if the requester-header is empty, check the forwarded-header - if requester == "" { + if len(requester) == 0 { requester = c.Request.Header.Get("X-Forwarded-For") } - // if the requester is still empty, use the hard-coded address from the socket - if requester == "" { + if len(requester) == 0 { requester = c.Request.RemoteAddr } diff --git a/mode.go b/mode.go new file mode 100644 index 0000000..85f133b --- /dev/null +++ b/mode.go @@ -0,0 +1,42 @@ +package gin + +import ( + "os" +) + +const GIN_MODE = "GIN_MODE" + +const ( + DebugMode string = "debug" + ReleaseMode string = "release" + TestMode string = "test" +) +const ( + debugCode = iota + releaseCode = iota + testCode = iota +) + +var gin_mode int = debugCode + +func SetMode(value string) { + switch value { + case DebugMode: + gin_mode = debugCode + case ReleaseMode: + gin_mode = releaseCode + case TestMode: + gin_mode = testCode + default: + panic("gin mode unknown, the allowed modes are: " + DebugMode + " and " + ReleaseMode) + } +} + +func init() { + value := os.Getenv(GIN_MODE) + if len(value) == 0 { + SetMode(DebugMode) + } else { + SetMode(value) + } +} diff --git a/recovery_test.go b/recovery_test.go new file mode 100644 index 0000000..9d3d088 --- /dev/null +++ b/recovery_test.go @@ -0,0 +1,52 @@ +package gin + +import ( + "bytes" + "log" + "os" + "testing" +) + +// TestPanicInHandler assert that panic has been recovered. +func TestPanicInHandler(t *testing.T) { + // SETUP + log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing + r := New() + r.Use(Recovery()) + r.GET("/recovery", func(_ *Context) { + panic("Oupps, Houston, we have a problem") + }) + + // RUN + w := PerformRequest(r, "GET", "/recovery") + + // restore logging + log.SetOutput(os.Stderr) + + if w.Code != 500 { + t.Errorf("Response code should be Internal Server Error, was: %s", w.Code) + } +} + +// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. +func TestPanicWithAbort(t *testing.T) { + // SETUP + log.SetOutput(bytes.NewBuffer(nil)) + r := New() + r.Use(Recovery()) + r.GET("/recovery", func(c *Context) { + c.Abort(400) + panic("Oupps, Houston, we have a problem") + }) + + // RUN + w := PerformRequest(r, "GET", "/recovery") + + // restore logging + log.SetOutput(os.Stderr) + + // TEST + if w.Code != 500 { + t.Errorf("Response code should be Bad request, was: %s", w.Code) + } +} diff --git a/render/render.go b/render/render.go index 2915ddc..bc982a3 100644 --- a/render/render.go +++ b/render/render.go @@ -22,6 +22,12 @@ type ( // Plain text plainRender struct{} + // Redirects + redirectRender struct{} + + // Redirects + htmlDebugRender struct{} + // form binding HTMLRender struct { Template *template.Template @@ -29,16 +35,16 @@ type ( ) var ( - JSON = jsonRender{} - XML = xmlRender{} - Plain = plainRender{} + JSON = jsonRender{} + XML = xmlRender{} + Plain = plainRender{} + Redirect = redirectRender{} + HTMLDebug = htmlDebugRender{} ) func writeHeader(w http.ResponseWriter, code int, contentType string) { - if code >= 0 { - w.Header().Set("Content-Type", contentType) - w.WriteHeader(code) - } + w.Header().Set("Content-Type", contentType) + w.WriteHeader(code) } func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { @@ -47,19 +53,18 @@ func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{}) return encoder.Encode(data[0]) } +func (_ redirectRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { + w.Header().Set("Location", data[0].(string)) + w.WriteHeader(code) + return nil +} + func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { writeHeader(w, code, "application/xml") encoder := xml.NewEncoder(w) return encoder.Encode(data[0]) } -func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { - writeHeader(w, code, "text/html") - file := data[0].(string) - obj := data[1] - return html.Template.ExecuteTemplate(w, file, obj) -} - func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { writeHeader(w, code, "text/plain") format := data[0].(string) @@ -72,3 +77,21 @@ func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{} } return err } + +func (_ htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { + writeHeader(w, code, "text/html") + file := data[0].(string) + obj := data[1] + t, err := template.ParseFiles(file) + if err != nil { + return err + } + return t.ExecuteTemplate(w, file, obj) +} + +func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { + writeHeader(w, code, "text/html") + file := data[0].(string) + obj := data[1] + return html.Template.ExecuteTemplate(w, file, obj) +} diff --git a/response_writer.go b/response_writer.go index cf02e90..2da8e33 100644 --- a/response_writer.go +++ b/response_writer.go @@ -1,6 +1,7 @@ package gin import ( + "log" "net/http" ) @@ -9,9 +10,7 @@ type ( http.ResponseWriter Status() int Written() bool - - // private - setStatus(int) + WriteHeaderNow() } responseWriter struct { @@ -23,18 +22,29 @@ type ( func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer - w.status = 0 + w.status = 200 w.written = false } -func (w *responseWriter) setStatus(code int) { - w.status = code +func (w *responseWriter) WriteHeader(code int) { + if code != 0 { + w.status = code + if w.written { + log.Println("[GIN] WARNING. Headers were already written!") + } + } } -func (w *responseWriter) WriteHeader(code int) { - w.status = code - w.written = true - w.ResponseWriter.WriteHeader(code) +func (w *responseWriter) WriteHeaderNow() { + if !w.written { + w.written = true + w.ResponseWriter.WriteHeader(w.status) + } +} + +func (w *responseWriter) Write(data []byte) (n int, err error) { + w.WriteHeaderNow() + return w.ResponseWriter.Write(data) } func (w *responseWriter) Status() int { diff --git a/utils.go b/utils.go index 90cca1b..6417efd 100644 --- a/utils.go +++ b/utils.go @@ -2,6 +2,8 @@ package gin import ( "encoding/xml" + "reflect" + "runtime" ) type H map[string]interface{} @@ -38,3 +40,7 @@ func filterFlags(content string) string { } return content } + +func funcName(f interface{}) string { + return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() +}