From a0ae5c296d8baf3290ffc4973cf96e526cb1efaa Mon Sep 17 00:00:00 2001
From: Alexander Nyquist <nyquist.alexander@gmail.com>
Date: Fri, 4 Jul 2014 10:12:28 +0200
Subject: [PATCH 01/32] Started writing unit tests

---
 gin_test.go | 290 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 290 insertions(+)
 create mode 100644 gin_test.go

diff --git a/gin_test.go b/gin_test.go
new file mode 100644
index 00000000..eb6ccce0
--- /dev/null
+++ b/gin_test.go
@@ -0,0 +1,290 @@
+package gin
+
+import(
+	"testing"
+	"html/template"
+	"net/http"
+	"net/http/httptest"
+)
+
+// TestRouterGroupGETRouteOK tests that GET route is correctly invoked.
+func TestRouterGroupGETRouteOK(t *testing.T) {
+	req, _ := http.NewRequest("GET", "/test", nil)
+	w := httptest.NewRecorder()
+	passed := false
+
+	r := Default()
+	r.GET("/test", func (c *Context) {
+		passed = true
+	})
+
+	r.ServeHTTP(w, req)
+
+	if passed == false {
+		t.Errorf("GET route handler was not invoked.")
+	}
+
+	if w.Code != http.StatusOK {
+		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
+	}
+}
+
+// TestRouterGroupPOSTRouteOK tests that POST route is correctly invoked.
+func TestRouterGroupPOSTRouteOK(t *testing.T) {
+	req, _ := http.NewRequest("POST", "/test", nil)
+	w := httptest.NewRecorder()
+	passed := false
+
+	r := Default()
+	r.POST("/test", func (c *Context) {
+		passed = true
+	})
+
+	r.ServeHTTP(w, req)
+
+	if passed == false {
+		t.Errorf("POST route handler was not invoked.")
+	}
+
+	if w.Code != http.StatusOK {
+		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
+	}
+}
+
+// TestRouterGroupDELETERouteOK tests that DELETE route is correctly invoked.
+func TestRouterGroupDELETERouteOK(t *testing.T) {
+	req, _ := http.NewRequest("DELETE", "/test", nil)
+	w := httptest.NewRecorder()
+	passed := false
+
+	r := Default()
+	r.DELETE("/test", func (c *Context) {
+		passed = true
+	})
+
+	r.ServeHTTP(w, req)
+
+	if passed == false {
+		t.Errorf("DELETE route handler was not invoked.")
+	}
+
+	if w.Code != http.StatusOK {
+		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
+	}
+}
+
+// TestRouterGroupPATCHRouteOK tests that PATCH route is correctly invoked.
+func TestRouterGroupPATCHRouteOK(t *testing.T) {
+	req, _ := http.NewRequest("PATCH", "/test", nil)
+	w := httptest.NewRecorder()
+	passed := false
+
+	r := Default()
+	r.PATCH("/test", func (c *Context) {
+		passed = true
+	})
+
+	r.ServeHTTP(w, req)
+
+	if passed == false {
+		t.Errorf("PATCH route handler was not invoked.")
+	}
+
+	if w.Code != http.StatusOK {
+		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
+	}
+}
+
+// TestRouterGroupPUTRouteOK tests that PUT route is correctly invoked.
+func TestRouterGroupPUTRouteOK(t *testing.T) {
+	req, _ := http.NewRequest("PUT", "/test", nil)
+	w := httptest.NewRecorder()
+	passed := false
+
+	r := Default()
+	r.PUT("/test", func (c *Context) {
+		passed = true
+	})
+
+	r.ServeHTTP(w, req)
+
+	if passed == false {
+		t.Errorf("PUT route handler was not invoked.")
+	}
+
+	if w.Code != http.StatusOK {
+		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
+	}
+}
+
+
+// TestRouterGroupOPTIONSRouteOK tests that OPTIONS route is correctly invoked.
+func TestRouterGroupOPTIONSRouteOK(t *testing.T) {
+	req, _ := http.NewRequest("OPTIONS", "/test", nil)
+	w := httptest.NewRecorder()
+	passed := false
+
+	r := Default()
+	r.OPTIONS("/test", func (c *Context) {
+		passed = true
+	})
+
+	r.ServeHTTP(w, req)
+
+	if passed == false {
+		t.Errorf("OPTIONS route handler was not invoked.")
+	}
+
+	if w.Code != http.StatusOK {
+		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
+	}
+}
+
+
+// TestRouterGroupHEADRouteOK tests that HEAD route is correctly invoked.
+func TestRouterGroupHEADRouteOK(t *testing.T) {
+	req, _ := http.NewRequest("HEAD", "/test", nil)
+	w := httptest.NewRecorder()
+	passed := false
+
+	r := Default()
+	r.HEAD("/test", func (c *Context) {
+		passed = true
+	})
+
+	r.ServeHTTP(w, req)
+
+	if passed == false {
+		t.Errorf("HEAD route handler was not invoked.")
+	}
+
+	if w.Code != http.StatusOK {
+		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
+	}
+}
+
+
+// TestRouterGroup404 tests that 404 is returned for a route that does not exist.
+func TestEngine404(t *testing.T) {
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+	
+	r := Default()
+	r.ServeHTTP(w, req)
+	
+	if w.Code != http.StatusNotFound {
+		t.Errorf("Response code should be %v, was %d", http.StatusNotFound, w.Code)
+	}
+}
+
+// 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 := Default()
+	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 := Default()
+	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")
+
+		if v := c.Get("foo"); 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 := Default()
+	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 := Default()
+	r.HTMLTemplates = template.Must(template.New("t").Parse(`Hello {{.Name}}`))
+
+	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 := Default()
+	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"))
+	}
+}
\ No newline at end of file

From 70593e8dfe8874034a07157eaab169c948b7dd6d Mon Sep 17 00:00:00 2001
From: Alexander Nyquist <nyquist.alexander@gmail.com>
Date: Fri, 4 Jul 2014 11:01:11 +0200
Subject: [PATCH 02/32] Added test for requests to / when no route for / is
 defined

---
 gin_test.go | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/gin_test.go b/gin_test.go
index eb6ccce0..e66c5e3d 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -29,6 +29,24 @@ func TestRouterGroupGETRouteOK(t *testing.T) {
 	}
 }
 
+// TestRouterGroupGETNoRootExistsRouteOK tests that a GET requse to root is correctly
+// handled (404) when no root route exists.
+func TestRouterGroupGETNoRootExistsRouteOK(t *testing.T) {
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+	
+	r := Default()
+	r.GET("/test", func (c *Context) {
+	})
+
+	r.ServeHTTP(w, req)
+
+	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"))
+	}
+}
+
 // TestRouterGroupPOSTRouteOK tests that POST route is correctly invoked.
 func TestRouterGroupPOSTRouteOK(t *testing.T) {
 	req, _ := http.NewRequest("POST", "/test", nil)

From f944cff1a8787874e6165d9ec9cfe119d9db7441 Mon Sep 17 00:00:00 2001
From: msoedov <msoedov@gmail.com>
Date: Sat, 5 Jul 2014 18:04:11 +0300
Subject: [PATCH 03/32] Added tests for ServeFiles #37

---
 gin_test.go | 116 +++++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 93 insertions(+), 23 deletions(-)

diff --git a/gin_test.go b/gin_test.go
index e66c5e3d..c853b0f4 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -1,10 +1,14 @@
 package gin
 
-import(
-	"testing"
+import (
 	"html/template"
+	"io/ioutil"
 	"net/http"
 	"net/http/httptest"
+	"os"
+	"path"
+	"strings"
+	"testing"
 )
 
 // TestRouterGroupGETRouteOK tests that GET route is correctly invoked.
@@ -14,7 +18,7 @@ func TestRouterGroupGETRouteOK(t *testing.T) {
 	passed := false
 
 	r := Default()
-	r.GET("/test", func (c *Context) {
+	r.GET("/test", func(c *Context) {
 		passed = true
 	})
 
@@ -34,9 +38,9 @@ func TestRouterGroupGETRouteOK(t *testing.T) {
 func TestRouterGroupGETNoRootExistsRouteOK(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/", nil)
 	w := httptest.NewRecorder()
-	
+
 	r := Default()
-	r.GET("/test", func (c *Context) {
+	r.GET("/test", func(c *Context) {
 	})
 
 	r.ServeHTTP(w, req)
@@ -54,7 +58,7 @@ func TestRouterGroupPOSTRouteOK(t *testing.T) {
 	passed := false
 
 	r := Default()
-	r.POST("/test", func (c *Context) {
+	r.POST("/test", func(c *Context) {
 		passed = true
 	})
 
@@ -76,7 +80,7 @@ func TestRouterGroupDELETERouteOK(t *testing.T) {
 	passed := false
 
 	r := Default()
-	r.DELETE("/test", func (c *Context) {
+	r.DELETE("/test", func(c *Context) {
 		passed = true
 	})
 
@@ -98,7 +102,7 @@ func TestRouterGroupPATCHRouteOK(t *testing.T) {
 	passed := false
 
 	r := Default()
-	r.PATCH("/test", func (c *Context) {
+	r.PATCH("/test", func(c *Context) {
 		passed = true
 	})
 
@@ -120,7 +124,7 @@ func TestRouterGroupPUTRouteOK(t *testing.T) {
 	passed := false
 
 	r := Default()
-	r.PUT("/test", func (c *Context) {
+	r.PUT("/test", func(c *Context) {
 		passed = true
 	})
 
@@ -135,7 +139,6 @@ func TestRouterGroupPUTRouteOK(t *testing.T) {
 	}
 }
 
-
 // TestRouterGroupOPTIONSRouteOK tests that OPTIONS route is correctly invoked.
 func TestRouterGroupOPTIONSRouteOK(t *testing.T) {
 	req, _ := http.NewRequest("OPTIONS", "/test", nil)
@@ -143,7 +146,7 @@ func TestRouterGroupOPTIONSRouteOK(t *testing.T) {
 	passed := false
 
 	r := Default()
-	r.OPTIONS("/test", func (c *Context) {
+	r.OPTIONS("/test", func(c *Context) {
 		passed = true
 	})
 
@@ -158,7 +161,6 @@ func TestRouterGroupOPTIONSRouteOK(t *testing.T) {
 	}
 }
 
-
 // TestRouterGroupHEADRouteOK tests that HEAD route is correctly invoked.
 func TestRouterGroupHEADRouteOK(t *testing.T) {
 	req, _ := http.NewRequest("HEAD", "/test", nil)
@@ -166,7 +168,7 @@ func TestRouterGroupHEADRouteOK(t *testing.T) {
 	passed := false
 
 	r := Default()
-	r.HEAD("/test", func (c *Context) {
+	r.HEAD("/test", func(c *Context) {
 		passed = true
 	})
 
@@ -181,15 +183,14 @@ func TestRouterGroupHEADRouteOK(t *testing.T) {
 	}
 }
 
-
 // TestRouterGroup404 tests that 404 is returned for a route that does not exist.
 func TestEngine404(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/", nil)
 	w := httptest.NewRecorder()
-	
+
 	r := Default()
 	r.ServeHTTP(w, req)
-	
+
 	if w.Code != http.StatusNotFound {
 		t.Errorf("Response code should be %v, was %d", http.StatusNotFound, w.Code)
 	}
@@ -202,7 +203,7 @@ func TestContextParamsByName(t *testing.T) {
 	name := ""
 
 	r := Default()
-	r.GET("/test/:name", func (c *Context) {
+	r.GET("/test/:name", func(c *Context) {
 		name = c.Params.ByName("name")
 	})
 
@@ -220,7 +221,7 @@ func TestContextSetGet(t *testing.T) {
 	w := httptest.NewRecorder()
 
 	r := Default()
-	r.GET("/test", func (c *Context) {
+	r.GET("/test", func(c *Context) {
 		// Key should be lazily created
 		if c.Keys != nil {
 			t.Error("Keys should be nil")
@@ -244,7 +245,7 @@ func TestContextJSON(t *testing.T) {
 	w := httptest.NewRecorder()
 
 	r := Default()
-	r.GET("/test", func (c *Context) {
+	r.GET("/test", func(c *Context) {
 		c.JSON(200, H{"foo": "bar"})
 	})
 
@@ -268,9 +269,9 @@ func TestContextHTML(t *testing.T) {
 	r := Default()
 	r.HTMLTemplates = template.Must(template.New("t").Parse(`Hello {{.Name}}`))
 
-	type TestData struct { Name string }
+	type TestData struct{ Name string }
 
-	r.GET("/test", func (c *Context) {
+	r.GET("/test", func(c *Context) {
 		c.HTML(200, "t", TestData{"alexandernyquist"})
 	})
 
@@ -292,7 +293,7 @@ func TestContextString(t *testing.T) {
 	w := httptest.NewRecorder()
 
 	r := Default()
-	r.GET("/test", func (c *Context) {
+	r.GET("/test", func(c *Context) {
 		c.String(200, "test")
 	})
 
@@ -305,4 +306,73 @@ func TestContextString(t *testing.T) {
 	if w.HeaderMap.Get("Content-Type") != "text/plain" {
 		t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
 	}
-}
\ No newline at end of file
+}
+
+// TestHandleStaticFile - ensure the static file handles properly
+func TestHandleStaticFile(t *testing.T) {
+
+	testRoot, _ := os.Getwd()
+
+	f, err := ioutil.TempFile(testRoot, "")
+	defer os.Remove(f.Name())
+
+	if err != nil {
+		t.Error(err)
+	}
+
+	filePath := path.Join("/", path.Base(f.Name()))
+	req, _ := http.NewRequest("GET", filePath, nil)
+
+	f.WriteString("Gin Web Framework")
+	f.Close()
+
+	w := httptest.NewRecorder()
+
+	r := Default()
+	r.ServeFiles("/*filepath", http.Dir("./"))
+
+	r.ServeHTTP(w, req)
+
+	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) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+
+	w := httptest.NewRecorder()
+
+	r := Default()
+	r.ServeFiles("/*filepath", http.Dir("./"))
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 200 {
+		t.Errorf("Response code should be Ok, was: %s", w.Code)
+	}
+
+	bodyAsString := w.Body.String()
+
+	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"))
+	}
+}

From 893387458242d5c76707d5e0d8ffdb8504d04839 Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Fri, 18 Jul 2014 17:42:38 +0300
Subject: [PATCH 04/32] Fixed tests up to master branch

---
 gin_test.go | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/gin_test.go b/gin_test.go
index c853b0f4..5bf737c7 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -230,7 +230,11 @@ func TestContextSetGet(t *testing.T) {
 		// Set
 		c.Set("foo", "bar")
 
-		if v := c.Get("foo"); v != "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)
 		}
 	})
@@ -267,7 +271,8 @@ func TestContextHTML(t *testing.T) {
 	w := httptest.NewRecorder()
 
 	r := Default()
-	r.HTMLTemplates = template.Must(template.New("t").Parse(`Hello {{.Name}}`))
+	templ, _ := template.New("t").Parse(`Hello {{.Name}}`)
+	r.SetHTMLTemplate(templ)
 
 	type TestData struct{ Name string }
 

From 89b4c6e0d1b65514c04f1a05a13b55a1d269bde5 Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Thu, 24 Jul 2014 16:51:11 +0300
Subject: [PATCH 05/32] Replaced deprecated ServeFiles

---
 gin_test.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/gin_test.go b/gin_test.go
index 5bf737c7..730794ef 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -334,7 +334,7 @@ func TestHandleStaticFile(t *testing.T) {
 	w := httptest.NewRecorder()
 
 	r := Default()
-	r.ServeFiles("/*filepath", http.Dir("./"))
+	r.Static("./", testRoot)
 
 	r.ServeHTTP(w, req)
 
@@ -359,7 +359,7 @@ func TestHandleStaticDir(t *testing.T) {
 	w := httptest.NewRecorder()
 
 	r := Default()
-	r.ServeFiles("/*filepath", http.Dir("./"))
+	r.Static("/", "./")
 
 	r.ServeHTTP(w, req)
 

From 51cbd7c75eb523f75116e73c5058c40940f495d9 Mon Sep 17 00:00:00 2001
From: Keiji Yoshida <yoshida.keiji.84@gmail.com>
Date: Sat, 26 Jul 2014 01:57:24 +0900
Subject: [PATCH 06/32] Update README.md

---
 README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 6fa52d0b..b0d5f4b1 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.  

From 74ca5f3bd9c4a076b76adb545638480f27e15779 Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Mon, 28 Jul 2014 13:05:23 +0300
Subject: [PATCH 07/32] Added dummy tests for middleware

---
 gin_test.go | 157 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 157 insertions(+)

diff --git a/gin_test.go b/gin_test.go
index 730794ef..60fa148f 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -1,6 +1,7 @@
 package gin
 
 import (
+	"errors"
 	"html/template"
 	"io/ioutil"
 	"net/http"
@@ -381,3 +382,159 @@ func TestHandleStaticDir(t *testing.T) {
 		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) {
+
+	req, _ := http.NewRequest("HEAD", "/", nil)
+
+	w := httptest.NewRecorder()
+
+	r := Default()
+	r.Static("/", "./")
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 200 {
+		t.Errorf("Response code should be Ok, was: %s", w.Code)
+	}
+
+	bodyAsString := w.Body.String()
+
+	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"))
+	}
+}
+
+// TestHandlerFunc - ensure that custom middleware works properly
+func TestHandlerFunc(t *testing.T) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	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) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	var stepsPassed int = 0
+
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+		context.Next()
+		stepsPassed += 1
+		// after check and abort
+		context.Abort(409)
+	},
+		func(context *Context) {
+			stepsPassed += 1
+			context.Next()
+			stepsPassed += 1
+			context.Abort(403)
+		},
+	)
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 403 {
+		t.Errorf("Response code should be Forbiden, was: %s", w.Code)
+	}
+
+	if stepsPassed != 4 {
+		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+	}
+}
+
+// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order
+func TestAbortHandlersChain(t *testing.T) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	var stepsPassed int = 0
+
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+		context.Abort(409)
+	},
+		func(context *Context) {
+			stepsPassed += 1
+			context.Next()
+			stepsPassed += 1
+		},
+	)
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 409 {
+		t.Errorf("Response code should be Conflict, was: %s", w.Code)
+	}
+
+	if stepsPassed != 1 {
+		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+	}
+}
+
+// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as
+// as well as Abort
+func TestFailHandlersChain(t *testing.T) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	var stepsPassed int = 0
+
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+
+		context.Fail(500, errors.New("foo"))
+	},
+		func(context *Context) {
+			stepsPassed += 1
+			context.Next()
+			stepsPassed += 1
+		},
+	)
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 500 {
+		t.Errorf("Response code should be Server error, was: %s", w.Code)
+	}
+
+	if stepsPassed != 1 {
+		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+	}
+
+}

From 593de4e91369b0d001bb0327274b20a73895389f Mon Sep 17 00:00:00 2001
From: Alexander Nyquist <nyquist.alexander@gmail.com>
Date: Tue, 29 Jul 2014 00:48:02 +0200
Subject: [PATCH 08/32] Added support for redirects

---
 README.md        | 12 +++++++++++-
 context.go       |  5 +++++
 render/render.go | 16 +++++++++++++---
 3 files changed, 29 insertions(+), 4 deletions(-)

diff --git a/README.md b/README.md
index 6fa52d0b..15868de3 100644
--- a/README.md
+++ b/README.md
@@ -228,7 +228,7 @@ func main() {
 }
 ```
 
-#### XML, and JSON rendering
+#### XML and JSON rendering
 
 ```go
 func main() {
@@ -297,6 +297,16 @@ func main() {
 }
 ```
 
+#### Redirects
+
+Issuing a HTTP redirect is easy:
+
+```r.GET("/test", func(c *gin.Context) {
+	c.Redirect("http://www.google.com/", 302)
+})
+
+Both internal and external locations are supported.
+```
 
 #### Custom Middlewares
 
diff --git a/context.go b/context.go
index 17ba45c2..65a3c5cc 100644
--- a/context.go
+++ b/context.go
@@ -247,6 +247,11 @@ func (c *Context) String(code int, format string, values ...interface{}) {
 	c.Render(code, render.Plain, format, values)
 }
 
+// Returns a 302 redirect to the specific location.
+func (c *Context) Redirect(location string, code int) {
+	c.Render(302, render.Redirect, location, 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/render/render.go b/render/render.go
index 2915ddc8..b034daeb 100644
--- a/render/render.go
+++ b/render/render.go
@@ -22,6 +22,9 @@ type (
 	// Plain text
 	plainRender struct{}
 
+	// Redirects
+	redirectRender struct{}
+
 	// form binding
 	HTMLRender struct {
 		Template *template.Template
@@ -29,9 +32,10 @@ type (
 )
 
 var (
-	JSON  = jsonRender{}
-	XML   = xmlRender{}
-	Plain = plainRender{}
+	JSON     = jsonRender{}
+	XML      = xmlRender{}
+	Plain    = plainRender{}
+	Redirect = redirectRender{}
 )
 
 func writeHeader(w http.ResponseWriter, code int, contentType string) {
@@ -47,6 +51,12 @@ 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(data[1].(int))
+	return nil
+}
+
 func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
 	writeHeader(w, code, "application/xml")
 	encoder := xml.NewEncoder(w)

From 2c4460d7cc42f8e6f915f36ff80f5cb6937c57a7 Mon Sep 17 00:00:00 2001
From: Alexander Nyquist <nyquist.alexander@gmail.com>
Date: Tue, 29 Jul 2014 00:51:34 +0200
Subject: [PATCH 09/32] Fixed status code when redirecting

---
 context.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/context.go b/context.go
index 65a3c5cc..ccad913e 100644
--- a/context.go
+++ b/context.go
@@ -247,9 +247,9 @@ func (c *Context) String(code int, format string, values ...interface{}) {
 	c.Render(code, render.Plain, format, values)
 }
 
-// Returns a 302 redirect to the specific location.
+// Returns a HTTP redirect to the specific location.
 func (c *Context) Redirect(location string, code int) {
-	c.Render(302, render.Redirect, location, code)
+	c.Render(code, render.Redirect, location, code)
 }
 
 // Writes some data into the body stream and updates the HTTP code.

From e350ae7c7ea10e92a5c51a886ccd957b1a12afb6 Mon Sep 17 00:00:00 2001
From: Alexander Nyquist <nyquist.alexander@gmail.com>
Date: Tue, 29 Jul 2014 00:53:56 +0200
Subject: [PATCH 10/32] Removed redundancy when redirecting

---
 context.go       | 2 +-
 render/render.go | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/context.go b/context.go
index ccad913e..069f1265 100644
--- a/context.go
+++ b/context.go
@@ -249,7 +249,7 @@ func (c *Context) String(code int, format string, values ...interface{}) {
 
 // Returns a HTTP redirect to the specific location.
 func (c *Context) Redirect(location string, code int) {
-	c.Render(code, render.Redirect, location, code)
+	c.Render(code, render.Redirect, location)
 }
 
 // Writes some data into the body stream and updates the HTTP code.
diff --git a/render/render.go b/render/render.go
index b034daeb..293bbf99 100644
--- a/render/render.go
+++ b/render/render.go
@@ -53,7 +53,7 @@ func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{})
 
 func (_ redirectRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
 	w.Header().Set("Location", data[0].(string))
-	w.WriteHeader(data[1].(int))
+	w.WriteHeader(code)
 	return nil
 }
 

From 64fb835e6f157d4b103084d7b6bb4d13440aac06 Mon Sep 17 00:00:00 2001
From: Alexander Nyquist <nyquist.alexander@gmail.com>
Date: Sat, 2 Aug 2014 17:06:09 +0200
Subject: [PATCH 11/32] Only accepting 3xx status codes when redirecting.
 Swapped location and code arguments for Redirect signature

---
 README.md  | 2 +-
 context.go | 8 ++++++--
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/README.md b/README.md
index 15868de3..7b9196d3 100644
--- a/README.md
+++ b/README.md
@@ -302,7 +302,7 @@ func main() {
 Issuing a HTTP redirect is easy:
 
 ```r.GET("/test", func(c *gin.Context) {
-	c.Redirect("http://www.google.com/", 302)
+	c.Redirect(301, "http://www.google.com/")
 })
 
 Both internal and external locations are supported.
diff --git a/context.go b/context.go
index 069f1265..8fed41de 100644
--- a/context.go
+++ b/context.go
@@ -248,8 +248,12 @@ func (c *Context) String(code int, format string, values ...interface{}) {
 }
 
 // Returns a HTTP redirect to the specific location.
-func (c *Context) Redirect(location string, code int) {
-	c.Render(code, render.Redirect, 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.

From 38dcdcc985f38ff812c221d970a272f7057cb9ac Mon Sep 17 00:00:00 2001
From: Alexander Nyquist <nyquist.alexander@gmail.com>
Date: Sun, 3 Aug 2014 01:31:48 +0200
Subject: [PATCH 12/32] Started on improved documentation for model binding

---
 README.md | 45 ++++++++++++++++++++++++++++++++++-----------
 1 file changed, 34 insertions(+), 11 deletions(-)

diff --git a/README.md b/README.md
index 6fa52d0b..a9fe8d3c 100644
--- a/README.md
+++ b/README.md
@@ -196,33 +196,56 @@ 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")
 }

From 6abe841c1fc6306f7d9f1ee6aed527dd195deb9e Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Fri, 8 Aug 2014 14:48:15 +0300
Subject: [PATCH 13/32] Splited tests into separate files

---
 context_test.go | 252 ++++++++++++++++++++++++++++++++++++++++++++++++
 gin_test.go     | 245 ----------------------------------------------
 2 files changed, 252 insertions(+), 245 deletions(-)
 create mode 100644 context_test.go

diff --git a/context_test.go b/context_test.go
new file mode 100644
index 00000000..84801273
--- /dev/null
+++ b/context_test.go
@@ -0,0 +1,252 @@
+package gin
+
+import (
+	"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 := Default()
+	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 := Default()
+	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 := Default()
+	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 := Default()
+	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 := Default()
+	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"))
+	}
+}
+
+// TestHandlerFunc - ensure that custom middleware works properly
+func TestHandlerFunc(t *testing.T) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	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) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	var stepsPassed int = 0
+
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+		context.Next()
+		stepsPassed += 1
+		// after check and abort
+		context.Abort(409)
+	},
+		func(context *Context) {
+			stepsPassed += 1
+			context.Next()
+			stepsPassed += 1
+			context.Abort(403)
+		},
+	)
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 403 {
+		t.Errorf("Response code should be Forbiden, was: %s", w.Code)
+	}
+
+	if stepsPassed != 4 {
+		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+	}
+}
+
+// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order
+func TestAbortHandlersChain(t *testing.T) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	var stepsPassed int = 0
+
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+		context.Abort(409)
+	},
+		func(context *Context) {
+			stepsPassed += 1
+			context.Next()
+			stepsPassed += 1
+		},
+	)
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 409 {
+		t.Errorf("Response code should be Conflict, was: %s", w.Code)
+	}
+
+	if stepsPassed != 1 {
+		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+	}
+}
+
+// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as
+// as well as Abort
+func TestFailHandlersChain(t *testing.T) {
+
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	r := Default()
+	var stepsPassed int = 0
+
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+
+		context.Fail(500, errors.New("foo"))
+	},
+		func(context *Context) {
+			stepsPassed += 1
+			context.Next()
+			stepsPassed += 1
+		},
+	)
+
+	r.ServeHTTP(w, req)
+
+	if w.Code != 500 {
+		t.Errorf("Response code should be Server error, was: %s", w.Code)
+	}
+
+	if stepsPassed != 1 {
+		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+	}
+
+}
diff --git a/gin_test.go b/gin_test.go
index 60fa148f..61b3c351 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -1,8 +1,6 @@
 package gin
 
 import (
-	"errors"
-	"html/template"
 	"io/ioutil"
 	"net/http"
 	"net/http/httptest"
@@ -197,123 +195,6 @@ func TestEngine404(t *testing.T) {
 	}
 }
 
-// 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 := Default()
-	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 := Default()
-	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 := Default()
-	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 := Default()
-	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 := Default()
-	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"))
-	}
-}
-
 // TestHandleStaticFile - ensure the static file handles properly
 func TestHandleStaticFile(t *testing.T) {
 
@@ -412,129 +293,3 @@ func TestHandleHeadToDir(t *testing.T) {
 		t.Errorf("Content-Type should be text/plain, 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 := Default()
-	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) {
-
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
-
-	r := Default()
-	var stepsPassed int = 0
-
-	r.Use(func(context *Context) {
-		stepsPassed += 1
-		context.Next()
-		stepsPassed += 1
-		// after check and abort
-		context.Abort(409)
-	},
-		func(context *Context) {
-			stepsPassed += 1
-			context.Next()
-			stepsPassed += 1
-			context.Abort(403)
-		},
-	)
-
-	r.ServeHTTP(w, req)
-
-	if w.Code != 403 {
-		t.Errorf("Response code should be Forbiden, was: %s", w.Code)
-	}
-
-	if stepsPassed != 4 {
-		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
-	}
-}
-
-// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order
-func TestAbortHandlersChain(t *testing.T) {
-
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
-
-	r := Default()
-	var stepsPassed int = 0
-
-	r.Use(func(context *Context) {
-		stepsPassed += 1
-		context.Abort(409)
-	},
-		func(context *Context) {
-			stepsPassed += 1
-			context.Next()
-			stepsPassed += 1
-		},
-	)
-
-	r.ServeHTTP(w, req)
-
-	if w.Code != 409 {
-		t.Errorf("Response code should be Conflict, was: %s", w.Code)
-	}
-
-	if stepsPassed != 1 {
-		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
-	}
-}
-
-// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as
-// as well as Abort
-func TestFailHandlersChain(t *testing.T) {
-
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
-
-	r := Default()
-	var stepsPassed int = 0
-
-	r.Use(func(context *Context) {
-		stepsPassed += 1
-
-		context.Fail(500, errors.New("foo"))
-	},
-		func(context *Context) {
-			stepsPassed += 1
-			context.Next()
-			stepsPassed += 1
-		},
-	)
-
-	r.ServeHTTP(w, req)
-
-	if w.Code != 500 {
-		t.Errorf("Response code should be Server error, was: %s", w.Code)
-	}
-
-	if stepsPassed != 1 {
-		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
-	}
-
-}

From fcd997e08362409aca1d83c6fbd54c33b8857b40 Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Fri, 8 Aug 2014 15:50:52 +0300
Subject: [PATCH 14/32] Added test for recovery

---
 recovery_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)
 create mode 100644 recovery_test.go

diff --git a/recovery_test.go b/recovery_test.go
new file mode 100644
index 00000000..097700ce
--- /dev/null
+++ b/recovery_test.go
@@ -0,0 +1,44 @@
+package gin
+
+import (
+	"bytes"
+	"log"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"testing"
+)
+
+// TestPanicInHandler assert that panic has been recovered.
+func TestPanicInHandler(t *testing.T) {
+	req, _ := http.NewRequest("GET", "/", nil)
+	w := httptest.NewRecorder()
+
+	// Disable panic logs for testing
+	log.SetOutput(bytes.NewBuffer(nil))
+
+	r := Default()
+	r.GET("/", func(_ *Context) {
+		panic("Oupps, Houston, we have a problem")
+	})
+
+	r.ServeHTTP(w, req)
+
+	// restore logging
+	log.SetOutput(os.Stderr)
+
+	if w.Code != 500 {
+		t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)
+	}
+	bodyAsString := w.Body.String()
+
+	//	fixme:
+	if bodyAsString != "" {
+		t.Errorf("Response body should be empty, was  %s", bodyAsString)
+	}
+	//fixme:
+	if len(w.HeaderMap) != 0 {
+		t.Errorf("No headers should be provided, was %s", w.HeaderMap)
+	}
+
+}

From 80cf66cde6e4831dfb3d2ebd75e1c6aa70f670d2 Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Fri, 8 Aug 2014 16:31:01 +0300
Subject: [PATCH 15/32] Added test cases for context file, data, XML response
 writers.

---
 context_test.go | 67 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)

diff --git a/context_test.go b/context_test.go
index 84801273..9662bf52 100644
--- a/context_test.go
+++ b/context_test.go
@@ -125,6 +125,73 @@ func TestContextString(t *testing.T) {
 	}
 }
 
+// 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 := Default()
+	r.GET("/test", func(c *Context) {
+		c.XML(200, H{"foo": "bar"})
+	})
+
+	r.ServeHTTP(w, req)
+
+	if w.Body.String() != "<map><foo>bar</foo></map>" {
+		t.Errorf("Response should be <map><foo>bar</foo></map>, 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 := Default()
+	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 := Default()
+	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) {
 

From 685d2c99cf473e152b9a6d3a02016f7f31997436 Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Mon, 11 Aug 2014 13:25:52 +0300
Subject: [PATCH 16/32] Added tests for JSON binding.

---
 context_test.go | 135 +++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 134 insertions(+), 1 deletion(-)

diff --git a/context_test.go b/context_test.go
index 9662bf52..9a2394a2 100644
--- a/context_test.go
+++ b/context_test.go
@@ -1,6 +1,7 @@
 package gin
 
 import (
+	"bytes"
 	"errors"
 	"html/template"
 	"net/http"
@@ -169,7 +170,6 @@ func TestContextData(t *testing.T) {
 	}
 }
 
-
 func TestContextFile(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test/file", nil)
 	w := httptest.NewRecorder()
@@ -317,3 +317,136 @@ func TestFailHandlersChain(t *testing.T) {
 	}
 
 }
+
+func TestBindingJSON(t *testing.T) {
+
+	body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
+
+	r := Default()
+	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 := Default()
+	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 := Default()
+	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 := Default()
+	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"))
+	}
+}

From f2176c3100d032cff4e093503ca0aba95954308c Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Mon, 11 Aug 2014 13:37:35 +0300
Subject: [PATCH 17/32] Adjusted tests for recovery.

---
 recovery_test.go | 42 +++++++++++++++++++++++++++++++++++++++---
 1 file changed, 39 insertions(+), 3 deletions(-)

diff --git a/recovery_test.go b/recovery_test.go
index 097700ce..7383a1df 100644
--- a/recovery_test.go
+++ b/recovery_test.go
@@ -11,14 +11,14 @@ import (
 
 // TestPanicInHandler assert that panic has been recovered.
 func TestPanicInHandler(t *testing.T) {
-	req, _ := http.NewRequest("GET", "/", nil)
+	req, _ := http.NewRequest("GET", "/recovery", nil)
 	w := httptest.NewRecorder()
 
 	// Disable panic logs for testing
 	log.SetOutput(bytes.NewBuffer(nil))
 
 	r := Default()
-	r.GET("/", func(_ *Context) {
+	r.GET("/recovery", func(_ *Context) {
 		panic("Oupps, Houston, we have a problem")
 	})
 
@@ -32,7 +32,43 @@ func TestPanicInHandler(t *testing.T) {
 	}
 	bodyAsString := w.Body.String()
 
-	//	fixme:
+	//fixme: no message provided?
+	if bodyAsString != "" {
+		t.Errorf("Response body should be empty, was  %s", bodyAsString)
+	}
+	//fixme:
+	if len(w.HeaderMap) != 0 {
+		t.Errorf("No headers should be provided, was %s", w.HeaderMap)
+	}
+
+}
+
+// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
+func TestPanicWithAbort(t *testing.T) {
+	req, _ := http.NewRequest("GET", "/recovery", nil)
+	w := httptest.NewRecorder()
+
+	// Disable panic logs for testing
+	log.SetOutput(bytes.NewBuffer(nil))
+
+	r := Default()
+	r.GET("/recovery", func(c *Context) {
+		c.Abort(400)
+		panic("Oupps, Houston, we have a problem")
+	})
+
+	r.ServeHTTP(w, req)
+
+	// restore logging
+	log.SetOutput(os.Stderr)
+
+	// fixme: why not 500?
+	if w.Code != 400 {
+		t.Errorf("Response code should be Bad request, was: %s", w.Code)
+	}
+	bodyAsString := w.Body.String()
+
+	//fixme: no message provided?
 	if bodyAsString != "" {
 		t.Errorf("Response body should be empty, was  %s", bodyAsString)
 	}

From 4c57a35441e1bf01807b6bc3b8a0d78c22fa6de6 Mon Sep 17 00:00:00 2001
From: Sasha Myasoedov <msoedov@gmail.com>
Date: Tue, 12 Aug 2014 12:32:06 +0300
Subject: [PATCH 18/32] Added tests for basic auth.

---
 auth_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
 create mode 100644 auth_test.go

diff --git a/auth_test.go b/auth_test.go
new file mode 100644
index 00000000..d9b4f4d4
--- /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 := Default()
+	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 := Default()
+	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"))
+	}
+}

From 78c7101ff6d416d3c26742832beb089d3f006b9a Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Mon, 18 Aug 2014 04:52:01 +0200
Subject: [PATCH 19/32] Check existence of X-Forwarded-For by comparing the
 length

---
 logger.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/logger.go b/logger.go
index 5a67f7c2..2667d131 100644
--- a/logger.go
+++ b/logger.go
@@ -44,12 +44,12 @@ 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
 		}
 

From dcafad3ced1d87333a7abdaecafc984813df5392 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Mon, 18 Aug 2014 05:24:48 +0200
Subject: [PATCH 20/32] Deferring WriteHeader. Part 1

---
 gin.go             | 10 ++++++++--
 logger.go          |  1 -
 render/render.go   |  6 ++----
 response_writer.go | 33 ++++++++++++++++++++++++---------
 4 files changed, 34 insertions(+), 16 deletions(-)

diff --git a/gin.go b/gin.go
index 106e1b9c..99c5cbce 100644
--- a/gin.go
+++ b/gin.go
@@ -45,10 +45,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)
 }
@@ -166,6 +171,7 @@ func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
 	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/logger.go b/logger.go
index 2667d131..8cbc24be 100644
--- a/logger.go
+++ b/logger.go
@@ -47,7 +47,6 @@ func Logger() HandlerFunc {
 		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 len(requester) == 0 {
 			requester = c.Request.RemoteAddr
diff --git a/render/render.go b/render/render.go
index 2915ddc8..9080acea 100644
--- a/render/render.go
+++ b/render/render.go
@@ -35,10 +35,8 @@ var (
 )
 
 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 {
diff --git a/response_writer.go b/response_writer.go
index cf02e90c..3d9de82d 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 {
@@ -27,14 +26,30 @@ func (w *responseWriter) reset(writer http.ResponseWriter) {
 	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) {
+	if !w.written {
+		if w.status != 0 {
+			w.ResponseWriter.WriteHeader(w.status)
+		}
+		w.written = true
+	}
+	return w.ResponseWriter.Write(data)
 }
 
 func (w *responseWriter) Status() int {

From e11ff5bacb3988242152f22cb635a5752bf59949 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Mon, 18 Aug 2014 19:48:01 +0200
Subject: [PATCH 21/32] response_writes uses 200 as default status code.

---
 response_writer.go | 9 ++-------
 1 file changed, 2 insertions(+), 7 deletions(-)

diff --git a/response_writer.go b/response_writer.go
index 3d9de82d..2da8e336 100644
--- a/response_writer.go
+++ b/response_writer.go
@@ -22,7 +22,7 @@ type (
 
 func (w *responseWriter) reset(writer http.ResponseWriter) {
 	w.ResponseWriter = writer
-	w.status = 0
+	w.status = 200
 	w.written = false
 }
 
@@ -43,12 +43,7 @@ func (w *responseWriter) WriteHeaderNow() {
 }
 
 func (w *responseWriter) Write(data []byte) (n int, err error) {
-	if !w.written {
-		if w.status != 0 {
-			w.ResponseWriter.WriteHeader(w.status)
-		}
-		w.written = true
-	}
+	w.WriteHeaderNow()
 	return w.ResponseWriter.Write(data)
 }
 

From d85245b5aabc0b09a5d5f46c8893279443dddc1d Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Mon, 18 Aug 2014 19:48:48 +0200
Subject: [PATCH 22/32] Improves unit tests

- Reusing much more code
- More coverage
- Cleanup
- Fixes some cases
---
 auth_test.go     |   4 +-
 context_test.go  | 128 ++++++++++-----------
 gin_test.go      | 288 ++++++++++++++++-------------------------------
 recovery_test.go |  54 +++------
 4 files changed, 168 insertions(+), 306 deletions(-)

diff --git a/auth_test.go b/auth_test.go
index d9b4f4d4..cc70bc08 100644
--- a/auth_test.go
+++ b/auth_test.go
@@ -11,7 +11,7 @@ func TestBasicAuthSucceed(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/login", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	accounts := Accounts{"admin": "password"}
 	r.Use(BasicAuth(accounts))
 
@@ -36,7 +36,7 @@ func TestBasicAuth401(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/login", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	accounts := Accounts{"foo": "bar"}
 	r.Use(BasicAuth(accounts))
 
diff --git a/context_test.go b/context_test.go
index 9a2394a2..3b3302e8 100644
--- a/context_test.go
+++ b/context_test.go
@@ -15,7 +15,7 @@ func TestContextParamsByName(t *testing.T) {
 	w := httptest.NewRecorder()
 	name := ""
 
-	r := Default()
+	r := New()
 	r.GET("/test/:name", func(c *Context) {
 		name = c.Params.ByName("name")
 	})
@@ -33,7 +33,7 @@ func TestContextSetGet(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	r.GET("/test", func(c *Context) {
 		// Key should be lazily created
 		if c.Keys != nil {
@@ -61,7 +61,7 @@ func TestContextJSON(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	r.GET("/test", func(c *Context) {
 		c.JSON(200, H{"foo": "bar"})
 	})
@@ -83,7 +83,7 @@ func TestContextHTML(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	templ, _ := template.New("t").Parse(`Hello {{.Name}}`)
 	r.SetHTMLTemplate(templ)
 
@@ -110,7 +110,7 @@ func TestContextString(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	r.GET("/test", func(c *Context) {
 		c.String(200, "test")
 	})
@@ -132,7 +132,7 @@ func TestContextXML(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	r.GET("/test", func(c *Context) {
 		c.XML(200, H{"foo": "bar"})
 	})
@@ -154,7 +154,7 @@ func TestContextData(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test/csv", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	r.GET("/test/csv", func(c *Context) {
 		c.Data(200, "text/csv", []byte(`foo,bar`))
 	})
@@ -174,7 +174,7 @@ func TestContextFile(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/test/file", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	r.GET("/test/file", func(c *Context) {
 		c.File("./gin.go")
 	})
@@ -198,7 +198,7 @@ func TestHandlerFunc(t *testing.T) {
 	req, _ := http.NewRequest("GET", "/", nil)
 	w := httptest.NewRecorder()
 
-	r := Default()
+	r := New()
 	var stepsPassed int = 0
 
 	r.Use(func(context *Context) {
@@ -220,109 +220,95 @@ func TestHandlerFunc(t *testing.T) {
 
 // TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers
 func TestBadAbortHandlersChain(t *testing.T) {
-
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
-
-	r := Default()
+	// SETUP
 	var stepsPassed int = 0
-
-	r.Use(func(context *Context) {
+	r := New()
+	r.Use(func(c *Context) {
 		stepsPassed += 1
-		context.Next()
+		c.Next()
 		stepsPassed += 1
 		// after check and abort
-		context.Abort(409)
-	},
-		func(context *Context) {
-			stepsPassed += 1
-			context.Next()
-			stepsPassed += 1
-			context.Abort(403)
-		},
-	)
+		c.Abort(409)
+	})
+	r.Use(func(c *Context) {
+		stepsPassed += 1
+		c.Next()
+		stepsPassed += 1
+		c.Abort(403)
+	})
 
-	r.ServeHTTP(w, req)
+	// RUN
+	w := PerformRequest(r, "GET", "/")
 
-	if w.Code != 403 {
-		t.Errorf("Response code should be Forbiden, was: %s", w.Code)
+	// 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: %s", stepsPassed)
+		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) {
-
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
-
-	r := Default()
+	// SETUP
 	var stepsPassed int = 0
-
+	r := New()
 	r.Use(func(context *Context) {
 		stepsPassed += 1
 		context.Abort(409)
-	},
-		func(context *Context) {
-			stepsPassed += 1
-			context.Next()
-			stepsPassed += 1
-		},
-	)
+	})
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+		context.Next()
+		stepsPassed += 1
+	})
 
-	r.ServeHTTP(w, req)
+	// RUN
+	w := PerformRequest(r, "GET", "/")
 
+	// TEST
 	if w.Code != 409 {
-		t.Errorf("Response code should be Conflict, was: %s", w.Code)
+		t.Errorf("Response code should be Conflict, was: %d", w.Code)
 	}
-
 	if stepsPassed != 1 {
-		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+		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) {
-
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
-
-	r := Default()
+	// SETUP
 	var stepsPassed int = 0
-
+	r := New()
 	r.Use(func(context *Context) {
 		stepsPassed += 1
-
 		context.Fail(500, errors.New("foo"))
-	},
-		func(context *Context) {
-			stepsPassed += 1
-			context.Next()
-			stepsPassed += 1
-		},
-	)
+	})
+	r.Use(func(context *Context) {
+		stepsPassed += 1
+		context.Next()
+		stepsPassed += 1
+	})
 
-	r.ServeHTTP(w, req)
+	// RUN
+	w := PerformRequest(r, "GET", "/")
 
+	// TEST
 	if w.Code != 500 {
-		t.Errorf("Response code should be Server error, was: %s", w.Code)
+		t.Errorf("Response code should be Server error, was: %d", w.Code)
 	}
-
 	if stepsPassed != 1 {
-		t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
+		t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
 	}
-
 }
 
 func TestBindingJSON(t *testing.T) {
 
 	body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
 
-	r := Default()
+	r := New()
 	r.POST("/binding/json", func(c *Context) {
 		var body struct {
 			Foo string `json:"foo"`
@@ -355,7 +341,7 @@ func TestBindingJSONEncoding(t *testing.T) {
 
 	body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}"))
 
-	r := Default()
+	r := New()
 	r.POST("/binding/json", func(c *Context) {
 		var body struct {
 			Foo string `json:"foo"`
@@ -388,7 +374,7 @@ func TestBindingJSONNoContentType(t *testing.T) {
 
 	body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
 
-	r := Default()
+	r := New()
 	r.POST("/binding/json", func(c *Context) {
 		var body struct {
 			Foo string `json:"foo"`
@@ -421,7 +407,7 @@ func TestBindingJSONMalformed(t *testing.T) {
 
 	body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n"))
 
-	r := Default()
+	r := New()
 	r.POST("/binding/json", func(c *Context) {
 		var body struct {
 			Foo string `json:"foo"`
diff --git a/gin_test.go b/gin_test.go
index 61b3c351..0cd5bf1b 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -10,224 +10,139 @@ import (
 	"testing"
 )
 
-// TestRouterGroupGETRouteOK tests that GET route is correctly invoked.
-func TestRouterGroupGETRouteOK(t *testing.T) {
-	req, _ := http.NewRequest("GET", "/test", nil)
+func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
+	req, _ := http.NewRequest(method, path, nil)
 	w := httptest.NewRecorder()
-	passed := false
-
-	r := Default()
-	r.GET("/test", func(c *Context) {
-		passed = true
-	})
-
 	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("GET route handler was not invoked.")
+		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)
+}
 
-// TestRouterGroupGETNoRootExistsRouteOK tests that a GET requse to root is correctly
-// handled (404) when no root route exists.
-func TestRouterGroupGETNoRootExistsRouteOK(t *testing.T) {
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
+// 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
+	}})
 
-	r := Default()
-	r.GET("/test", func(c *Context) {
-	})
-
-	r.ServeHTTP(w, req)
+	// 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"))
 	}
 }
 
-// TestRouterGroupPOSTRouteOK tests that POST route is correctly invoked.
-func TestRouterGroupPOSTRouteOK(t *testing.T) {
-	req, _ := http.NewRequest("POST", "/test", nil)
-	w := httptest.NewRecorder()
-	passed := false
-
-	r := Default()
-	r.POST("/test", func(c *Context) {
-		passed = true
-	})
-
-	r.ServeHTTP(w, req)
-
-	if passed == false {
-		t.Errorf("POST route handler was not invoked.")
-	}
-
-	if w.Code != http.StatusOK {
-		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
-	}
+// 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)
 }
 
-// TestRouterGroupDELETERouteOK tests that DELETE route is correctly invoked.
-func TestRouterGroupDELETERouteOK(t *testing.T) {
-	req, _ := http.NewRequest("DELETE", "/test", nil)
-	w := httptest.NewRecorder()
+// TestSingleRouteOK tests that POST route is correctly invoked.
+func testRouteNotOK2(method string, t *testing.T) {
+	// SETUP
 	passed := false
-
-	r := Default()
-	r.DELETE("/test", func(c *Context) {
+	r := New()
+	var methodRoute string
+	if method == "POST" {
+		methodRoute = "GET"
+	} else {
+		methodRoute = "POST"
+	}
+	r.Handle(methodRoute, "/test", []HandlerFunc{func(c *Context) {
 		passed = true
-	})
+	}})
 
-	r.ServeHTTP(w, req)
+	// RUN
+	w := PerformRequest(r, method, "/test")
 
-	if passed == false {
-		t.Errorf("DELETE route handler was not invoked.")
+	// TEST
+	if passed == true {
+		t.Errorf(method + " route handler was invoked, when it should not")
 	}
-
-	if w.Code != http.StatusOK {
-		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
-	}
-}
-
-// TestRouterGroupPATCHRouteOK tests that PATCH route is correctly invoked.
-func TestRouterGroupPATCHRouteOK(t *testing.T) {
-	req, _ := http.NewRequest("PATCH", "/test", nil)
-	w := httptest.NewRecorder()
-	passed := false
-
-	r := Default()
-	r.PATCH("/test", func(c *Context) {
-		passed = true
-	})
-
-	r.ServeHTTP(w, req)
-
-	if passed == false {
-		t.Errorf("PATCH route handler was not invoked.")
-	}
-
-	if w.Code != http.StatusOK {
-		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
-	}
-}
-
-// TestRouterGroupPUTRouteOK tests that PUT route is correctly invoked.
-func TestRouterGroupPUTRouteOK(t *testing.T) {
-	req, _ := http.NewRequest("PUT", "/test", nil)
-	w := httptest.NewRecorder()
-	passed := false
-
-	r := Default()
-	r.PUT("/test", func(c *Context) {
-		passed = true
-	})
-
-	r.ServeHTTP(w, req)
-
-	if passed == false {
-		t.Errorf("PUT route handler was not invoked.")
-	}
-
-	if w.Code != http.StatusOK {
-		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
-	}
-}
-
-// TestRouterGroupOPTIONSRouteOK tests that OPTIONS route is correctly invoked.
-func TestRouterGroupOPTIONSRouteOK(t *testing.T) {
-	req, _ := http.NewRequest("OPTIONS", "/test", nil)
-	w := httptest.NewRecorder()
-	passed := false
-
-	r := Default()
-	r.OPTIONS("/test", func(c *Context) {
-		passed = true
-	})
-
-	r.ServeHTTP(w, req)
-
-	if passed == false {
-		t.Errorf("OPTIONS route handler was not invoked.")
-	}
-
-	if w.Code != http.StatusOK {
-		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
-	}
-}
-
-// TestRouterGroupHEADRouteOK tests that HEAD route is correctly invoked.
-func TestRouterGroupHEADRouteOK(t *testing.T) {
-	req, _ := http.NewRequest("HEAD", "/test", nil)
-	w := httptest.NewRecorder()
-	passed := false
-
-	r := Default()
-	r.HEAD("/test", func(c *Context) {
-		passed = true
-	})
-
-	r.ServeHTTP(w, req)
-
-	if passed == false {
-		t.Errorf("HEAD route handler was not invoked.")
-	}
-
-	if w.Code != http.StatusOK {
-		t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
-	}
-}
-
-// TestRouterGroup404 tests that 404 is returned for a route that does not exist.
-func TestEngine404(t *testing.T) {
-	req, _ := http.NewRequest("GET", "/", nil)
-	w := httptest.NewRecorder()
-
-	r := Default()
-	r.ServeHTTP(w, req)
-
 	if w.Code != http.StatusNotFound {
-		t.Errorf("Response code should be %v, was %d", http.StatusNotFound, w.Code)
+		// 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, "")
-	defer os.Remove(f.Name())
-
 	if err != nil {
 		t.Error(err)
 	}
-
+	defer os.Remove(f.Name())
 	filePath := path.Join("/", path.Base(f.Name()))
-	req, _ := http.NewRequest("GET", filePath, nil)
-
 	f.WriteString("Gin Web Framework")
 	f.Close()
 
-	w := httptest.NewRecorder()
-
-	r := Default()
+	// SETUP gin
+	r := New()
 	r.Static("./", testRoot)
 
-	r.ServeHTTP(w, req)
+	// 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"))
 	}
@@ -235,30 +150,24 @@ func TestHandleStaticFile(t *testing.T) {
 
 // TestHandleStaticDir - ensure the root/sub dir handles properly
 func TestHandleStaticDir(t *testing.T) {
-
-	req, _ := http.NewRequest("GET", "/", nil)
-
-	w := httptest.NewRecorder()
-
-	r := Default()
+	// SETUP
+	r := New()
 	r.Static("/", "./")
 
-	r.ServeHTTP(w, req)
+	// 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)
 	}
-
-	bodyAsString := w.Body.String()
-
 	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"))
 	}
@@ -266,29 +175,24 @@ func TestHandleStaticDir(t *testing.T) {
 
 // TestHandleHeadToDir - ensure the root/sub dir handles properly
 func TestHandleHeadToDir(t *testing.T) {
-
-	req, _ := http.NewRequest("HEAD", "/", nil)
-
-	w := httptest.NewRecorder()
-
-	r := Default()
+	// SETUP
+	r := New()
 	r.Static("/", "./")
 
-	r.ServeHTTP(w, req)
+	// 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)
 	}
-
-	bodyAsString := w.Body.String()
-
 	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/recovery_test.go b/recovery_test.go
index 7383a1df..9d3d0880 100644
--- a/recovery_test.go
+++ b/recovery_test.go
@@ -3,26 +3,22 @@ package gin
 import (
 	"bytes"
 	"log"
-	"net/http"
-	"net/http/httptest"
 	"os"
 	"testing"
 )
 
 // TestPanicInHandler assert that panic has been recovered.
 func TestPanicInHandler(t *testing.T) {
-	req, _ := http.NewRequest("GET", "/recovery", nil)
-	w := httptest.NewRecorder()
-
-	// Disable panic logs for testing
-	log.SetOutput(bytes.NewBuffer(nil))
-
-	r := Default()
+	// 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")
 	})
 
-	r.ServeHTTP(w, req)
+	// RUN
+	w := PerformRequest(r, "GET", "/recovery")
 
 	// restore logging
 	log.SetOutput(os.Stderr)
@@ -30,51 +26,27 @@ func TestPanicInHandler(t *testing.T) {
 	if w.Code != 500 {
 		t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)
 	}
-	bodyAsString := w.Body.String()
-
-	//fixme: no message provided?
-	if bodyAsString != "" {
-		t.Errorf("Response body should be empty, was  %s", bodyAsString)
-	}
-	//fixme:
-	if len(w.HeaderMap) != 0 {
-		t.Errorf("No headers should be provided, was %s", w.HeaderMap)
-	}
-
 }
 
 // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
 func TestPanicWithAbort(t *testing.T) {
-	req, _ := http.NewRequest("GET", "/recovery", nil)
-	w := httptest.NewRecorder()
-
-	// Disable panic logs for testing
+	// SETUP
 	log.SetOutput(bytes.NewBuffer(nil))
-
-	r := Default()
+	r := New()
+	r.Use(Recovery())
 	r.GET("/recovery", func(c *Context) {
 		c.Abort(400)
 		panic("Oupps, Houston, we have a problem")
 	})
 
-	r.ServeHTTP(w, req)
+	// RUN
+	w := PerformRequest(r, "GET", "/recovery")
 
 	// restore logging
 	log.SetOutput(os.Stderr)
 
-	// fixme: why not 500?
-	if w.Code != 400 {
+	// TEST
+	if w.Code != 500 {
 		t.Errorf("Response code should be Bad request, was: %s", w.Code)
 	}
-	bodyAsString := w.Body.String()
-
-	//fixme: no message provided?
-	if bodyAsString != "" {
-		t.Errorf("Response body should be empty, was  %s", bodyAsString)
-	}
-	//fixme:
-	if len(w.HeaderMap) != 0 {
-		t.Errorf("No headers should be provided, was %s", w.HeaderMap)
-	}
-
 }

From 2b486327db838703e7b2eddec24ee6d09c84b4a4 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Mon, 18 Aug 2014 20:55:33 +0200
Subject: [PATCH 23/32] Updates CHANGELOG

---
 CHANGELOG.md | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c399078..437b01bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,11 @@
 
 ###Gin 0.4 (??)
 
+- [NEW] Unit tests
+- [NEW] Add Content.Redirect()
+- [FIX] Deferring WriteHeader()
+- [FIX] Improved documentation for model binding
+
 
 ###Gin 0.3 (Jul 18, 2014)
 

From 312e03296096d861900ca456551f3e74d380c23a Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Mon, 18 Aug 2014 21:01:54 +0200
Subject: [PATCH 24/32] Updates AUTHORS.md

---
 AUTHORS.md | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/AUTHORS.md b/AUTHORS.md
index 67535a41..4a844091 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -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

From 809eee8a72ac1bd65a4d5ca20c89ee0adb9101e6 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Tue, 19 Aug 2014 03:40:52 +0200
Subject: [PATCH 25/32] Adds debug mode (part 1)

- Adds API to switch the gin's mode
- Log listening port
- Log routes
---
 gin.go   | 12 ++++++++++++
 mode.go  | 38 ++++++++++++++++++++++++++++++++++++++
 utils.go |  6 ++++++
 3 files changed, 56 insertions(+)
 create mode 100644 mode.go

diff --git a/gin.go b/gin.go
index 99c5cbce..c1adbb49 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"
@@ -113,12 +114,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)
 	}
@@ -168,6 +175,11 @@ 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()
diff --git a/mode.go b/mode.go
new file mode 100644
index 00000000..803a2ec4
--- /dev/null
+++ b/mode.go
@@ -0,0 +1,38 @@
+package gin
+
+import (
+	"os"
+)
+
+const GIN_MODE = "GIN_MODE"
+
+const (
+	DebugMode   string = "debug"
+	ReleaseMode string = "release"
+)
+const (
+	debugCode   = iota
+	releaseCode = iota
+)
+
+var gin_mode int = debugCode
+
+func SetMode(value string) {
+	switch value {
+	case DebugMode:
+		gin_mode = debugCode
+	case ReleaseMode:
+		gin_mode = releaseCode
+	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/utils.go b/utils.go
index 90cca1be..6417efd9 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()
+}

From a0437ff9f2589629d2d8afbff68d4be6ffce6ab4 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Tue, 19 Aug 2014 03:41:05 +0200
Subject: [PATCH 26/32] Typo in AUTHORS

---
 AUTHORS.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/AUTHORS.md b/AUTHORS.md
index 4a844091..2a7c347f 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.

From f39b692fc522849b3fc5a63213043b46193d1914 Mon Sep 17 00:00:00 2001
From: yuyabe <yuyabee@gmail.com>
Date: Tue, 19 Aug 2014 01:38:03 -0700
Subject: [PATCH 27/32] Update README.md

---
 README.md | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/README.md b/README.md
index 6fa52d0b..af6b3a54 100644
--- a/README.md
+++ b/README.md
@@ -392,7 +392,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 +402,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

From 378610b3b215bc8d07c4c4b6dc42c59a8fe20b1a Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Wed, 20 Aug 2014 18:14:10 +0200
Subject: [PATCH 28/32] HTML template debug mode.

- theHTML templates are reloaded each time
---
 gin.go           |  8 ++++++--
 render/render.go | 33 ++++++++++++++++++++++-----------
 2 files changed, 28 insertions(+), 13 deletions(-)

diff --git a/gin.go b/gin.go
index c1adbb49..8b6d17d5 100644
--- a/gin.go
+++ b/gin.go
@@ -92,8 +92,12 @@ func (engine *Engine) LoadHTMLFiles(files ...string) {
 }
 
 func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
-	engine.HTMLRender = render.HTMLRender{
-		Template: templ,
+	if gin_mode == debugCode {
+		engine.HTMLRender = render.HTMLDebug
+	} else {
+		engine.HTMLRender = render.HTMLRender{
+			Template: templ,
+		}
 	}
 }
 
diff --git a/render/render.go b/render/render.go
index 207e7a52..57a59fe1 100644
--- a/render/render.go
+++ b/render/render.go
@@ -25,6 +25,9 @@ type (
 	// Redirects
 	redirectRender struct{}
 
+	// Redirects
+	htmlDebugRender struct{}
+
 	// form binding
 	HTMLRender struct {
 		Template *template.Template
@@ -32,10 +35,11 @@ type (
 )
 
 var (
-	JSON     = jsonRender{}
-	XML      = xmlRender{}
-	Plain    = plainRender{}
-	Redirect = redirectRender{}
+	JSON      = jsonRender{}
+	XML       = xmlRender{}
+	Plain     = plainRender{}
+	Redirect  = redirectRender{}
+	HTMLDebug = htmlDebugRender{}
 )
 
 func writeHeader(w http.ResponseWriter, code int, contentType string) {
@@ -61,13 +65,6 @@ func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{})
 	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)
@@ -80,3 +77,17 @@ 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]
+	return template.New(file).Execute(w, 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)
+}

From 0ed259ca34d5af4e91a9820dd1923b89f6bb58d5 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Thu, 21 Aug 2014 01:01:05 +0200
Subject: [PATCH 29/32] Adds TestMode

---
 mode.go | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/mode.go b/mode.go
index 803a2ec4..85f133b9 100644
--- a/mode.go
+++ b/mode.go
@@ -9,10 +9,12 @@ 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
@@ -23,6 +25,8 @@ func SetMode(value string) {
 		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)
 	}

From 94f2f3f7eba02686e60f788d2766ee5003ab17a2 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Thu, 21 Aug 2014 01:01:42 +0200
Subject: [PATCH 30/32] Using test mode

---
 gin_test.go | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/gin_test.go b/gin_test.go
index 0cd5bf1b..7425cc21 100644
--- a/gin_test.go
+++ b/gin_test.go
@@ -10,6 +10,10 @@ import (
 	"testing"
 )
 
+func init() {
+	SetMode(TestMode)
+}
+
 func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
 	req, _ := http.NewRequest(method, path, nil)
 	w := httptest.NewRecorder()

From 46225ea53a2c5f82ad2d02bff2e08d756eab9fc1 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Thu, 21 Aug 2014 01:04:35 +0200
Subject: [PATCH 31/32] Fixes html debug mode

---
 gin.go           | 30 +++++++++++++++++-------------
 render/render.go |  6 +++++-
 2 files changed, 22 insertions(+), 14 deletions(-)

diff --git a/gin.go b/gin.go
index 8b6d17d5..0f4753e2 100644
--- a/gin.go
+++ b/gin.go
@@ -82,22 +82,26 @@ func Default() *Engine {
 }
 
 func (engine *Engine) LoadHTMLGlob(pattern string) {
-	templ := template.Must(template.ParseGlob(pattern))
-	engine.SetHTMLTemplate(templ)
-}
-
-func (engine *Engine) LoadHTMLFiles(files ...string) {
-	templ := template.Must(template.ParseFiles(files...))
-	engine.SetHTMLTemplate(templ)
-}
-
-func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
 	if gin_mode == debugCode {
 		engine.HTMLRender = render.HTMLDebug
 	} else {
-		engine.HTMLRender = render.HTMLRender{
-			Template: templ,
-		}
+		templ := template.Must(template.ParseGlob(pattern))
+		engine.SetHTMLTemplate(templ)
+	}
+}
+
+func (engine *Engine) LoadHTMLFiles(files ...string) {
+	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) {
+	engine.HTMLRender = render.HTMLRender{
+		Template: templ,
 	}
 }
 
diff --git a/render/render.go b/render/render.go
index 57a59fe1..bc982a30 100644
--- a/render/render.go
+++ b/render/render.go
@@ -82,7 +82,11 @@ func (_ htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interfa
 	writeHeader(w, code, "text/html")
 	file := data[0].(string)
 	obj := data[1]
-	return template.New(file).Execute(w, obj)
+	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 {

From 2ec71baf2574058bbcd0c4414b4100965711f151 Mon Sep 17 00:00:00 2001
From: Manu Mtz-Almeida <manu.valladolid@gmail.com>
Date: Thu, 21 Aug 2014 01:13:37 +0200
Subject: [PATCH 32/32] Updates CHANGELOG and AUTHORS

---
 AUTHORS.md   | 6 +++++-
 CHANGELOG.md | 5 +++--
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/AUTHORS.md b/AUTHORS.md
index 2a7c347f..c09e263f 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -101,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 437b01bf..5ec8c5ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,7 +1,8 @@
-##Changelog
+#Changelog
 
-###Gin 0.4 (??)
+###Gin 0.4 (Aug 21, 2014)
 
+- [NEW] Development mode
 - [NEW] Unit tests
 - [NEW] Add Content.Redirect()
 - [FIX] Deferring WriteHeader()