Skip to content
Myr

Merge branch 'develop'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Manu Mtz-Almeida · committed by Manu Mtz-Almeida · parents c3abaf9, a3a5753 · Browse files · 14 files+970 added−56 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+970 added−56 removed

  • other:+970 added−56 removed

14 files+970 added−56 removed

modified:render/render.go+37 added-14 removed
20 unmodified lines
2122 // Plain text23 plainRender struct{}2425 // Redirects26 redirectRender struct{}2728 // Redirects29 htmlDebugRender struct{}3031 // form binding32 HTMLRender struct {33 Template *template.Template34 }35)3637var (32 JSON = jsonRender{}33 XML = xmlRender{}34 Plain = plainRender{}38 JSON = jsonRender{}39 XML = xmlRender{}40 Plain = plainRender{}41 Redirect = redirectRender{}42 HTMLDebug = htmlDebugRender{}43)4445func writeHeader(w http.ResponseWriter, code int, contentType string) {38 if code >= 0 {39 w.Header().Set("Content-Type", contentType)40 w.WriteHeader(code)46 w.Header().Set("Content-Type", contentType)47 w.WriteHeader(code)41 }48}4950func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {51 writeHeader(w, code, "application/json")52 encoder := json.NewEncoder(w)53 return encoder.Encode(data[0])54}5556func (_ redirectRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {57 w.Header().Set("Location", data[0].(string))58 w.WriteHeader(code)59 return nil60}6162func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {63 writeHeader(w, code, "application/xml")64 encoder := xml.NewEncoder(w)65 return encoder.Encode(data[0])66}6756func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {57 writeHeader(w, code, "text/html")58 file := data[0].(string)59 obj := data[1]60 return html.Template.ExecuteTemplate(w, file, obj)61}6268func (_ plainRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {69 writeHeader(w, code, "text/plain")70 format := data[0].(string)71 args := data[1].([]interface{})
4 unmodified lines
76 _, err = w.Write([]byte(format))77 }78 return err79}8081func (_ htmlDebugRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {82 writeHeader(w, code, "text/html")83 file := data[0].(string)84 obj := data[1]85 t, err := template.ParseFiles(file)86 if err != nil {87 return err88 }89 return t.ExecuteTemplate(w, file, obj)90}9192func (html HTMLRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {93 writeHeader(w, code, "text/html")94 file := data[0].(string)95 obj := data[1]96 return html.Template.ExecuteTemplate(w, file, obj)97}
added:auth_test.go+57 added
1package gin23import (4 "encoding/base64"5 "net/http"6 "net/http/httptest"7 "testing"8)910func TestBasicAuthSucceed(t *testing.T) {11 req, _ := http.NewRequest("GET", "/login", nil)12 w := httptest.NewRecorder()1314 r := New()15 accounts := Accounts{"admin": "password"}16 r.Use(BasicAuth(accounts))1718 r.GET("/login", func(c *Context) {19 c.String(200, "autorized")20 })2122 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))23 r.ServeHTTP(w, req)2425 if w.Code != 200 {26 t.Errorf("Response code should be Ok, was: %s", w.Code)27 }28 bodyAsString := w.Body.String()2930 if bodyAsString != "autorized" {31 t.Errorf("Response body should be `autorized`, was %s", bodyAsString)32 }33}3435func TestBasicAuth401(t *testing.T) {36 req, _ := http.NewRequest("GET", "/login", nil)37 w := httptest.NewRecorder()3839 r := New()40 accounts := Accounts{"foo": "bar"}41 r.Use(BasicAuth(accounts))4243 r.GET("/login", func(c *Context) {44 c.String(200, "autorized")45 })4647 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))48 r.ServeHTTP(w, req)4950 if w.Code != 401 {51 t.Errorf("Response code should be Not autorized, was: %s", w.Code)52 }5354 if w.HeaderMap.Get("WWW-Authenticate") != "Basic realm=\"Authorization Required\"" {55 t.Errorf("WWW-Authenticate header is incorrect: %s", w.HeaderMap.Get("Content-Type"))56 }57}
modified:AUTHORS.md+16 added-6 removed
modified:CHANGELOG.md+8 added-2 removed
added:context_test.go+438 added
1package gin23import (4 "bytes"5 "errors"6 "html/template"7 "net/http"8 "net/http/httptest"9 "testing"10)1112// TestContextParamsGet tests that a parameter can be parsed from the URL.13func TestContextParamsByName(t *testing.T) {14 req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil)15 w := httptest.NewRecorder()16 name := ""1718 r := New()19 r.GET("/test/:name", func(c *Context) {20 name = c.Params.ByName("name")21 })2223 r.ServeHTTP(w, req)2425 if name != "alexandernyquist" {26 t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name)27 }28}2930// TestContextSetGet tests that a parameter is set correctly on the31// current context and can be retrieved using Get.32func TestContextSetGet(t *testing.T) {33 req, _ := http.NewRequest("GET", "/test", nil)34 w := httptest.NewRecorder()3536 r := New()37 r.GET("/test", func(c *Context) {38 // Key should be lazily created39 if c.Keys != nil {40 t.Error("Keys should be nil")41 }4243 // Set44 c.Set("foo", "bar")4546 v, err := c.Get("foo")47 if err != nil {48 t.Errorf("Error on exist key")49 }50 if v != "bar" {51 t.Errorf("Value should be bar, was %s", v)52 }53 })5455 r.ServeHTTP(w, req)56}5758// TestContextJSON tests that the response is serialized as JSON59// and Content-Type is set to application/json60func TestContextJSON(t *testing.T) {61 req, _ := http.NewRequest("GET", "/test", nil)62 w := httptest.NewRecorder()6364 r := New()65 r.GET("/test", func(c *Context) {66 c.JSON(200, H{"foo": "bar"})67 })6869 r.ServeHTTP(w, req)7071 if w.Body.String() != "{\"foo\":\"bar\"}\n" {72 t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String())73 }7475 if w.HeaderMap.Get("Content-Type") != "application/json" {76 t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))77 }78}7980// TestContextHTML tests that the response executes the templates81// and responds with Content-Type set to text/html82func TestContextHTML(t *testing.T) {83 req, _ := http.NewRequest("GET", "/test", nil)84 w := httptest.NewRecorder()8586 r := New()87 templ, _ := template.New("t").Parse(`Hello {{.Name}}`)88 r.SetHTMLTemplate(templ)8990 type TestData struct{ Name string }9192 r.GET("/test", func(c *Context) {93 c.HTML(200, "t", TestData{"alexandernyquist"})94 })9596 r.ServeHTTP(w, req)9798 if w.Body.String() != "Hello alexandernyquist" {99 t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String())100 }101102 if w.HeaderMap.Get("Content-Type") != "text/html" {103 t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type"))104 }105}106107// TestContextString tests that the response is returned108// with Content-Type set to text/plain109func TestContextString(t *testing.T) {110 req, _ := http.NewRequest("GET", "/test", nil)111 w := httptest.NewRecorder()112113 r := New()114 r.GET("/test", func(c *Context) {115 c.String(200, "test")116 })117118 r.ServeHTTP(w, req)119120 if w.Body.String() != "test" {121 t.Errorf("Response should be test, was: %s", w.Body.String())122 }123124 if w.HeaderMap.Get("Content-Type") != "text/plain" {125 t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))126 }127}128129// TestContextXML tests that the response is serialized as XML130// and Content-Type is set to application/xml131func TestContextXML(t *testing.T) {132 req, _ := http.NewRequest("GET", "/test", nil)133 w := httptest.NewRecorder()134135 r := New()136 r.GET("/test", func(c *Context) {137 c.XML(200, H{"foo": "bar"})138 })139140 r.ServeHTTP(w, req)141142 if w.Body.String() != "<map><foo>bar</foo></map>" {143 t.Errorf("Response should be <map><foo>bar</foo></map>, was: %s", w.Body.String())144 }145146 if w.HeaderMap.Get("Content-Type") != "application/xml" {147 t.Errorf("Content-Type should be application/xml, was %s", w.HeaderMap.Get("Content-Type"))148 }149}150151// TestContextData tests that the response can be written from `bytesting`152// with specified MIME type153func TestContextData(t *testing.T) {154 req, _ := http.NewRequest("GET", "/test/csv", nil)155 w := httptest.NewRecorder()156157 r := New()158 r.GET("/test/csv", func(c *Context) {159 c.Data(200, "text/csv", []byte(`foo,bar`))160 })161162 r.ServeHTTP(w, req)163164 if w.Body.String() != "foo,bar" {165 t.Errorf("Response should be foo&bar, was: %s", w.Body.String())166 }167168 if w.HeaderMap.Get("Content-Type") != "text/csv" {169 t.Errorf("Content-Type should be text/csv, was %s", w.HeaderMap.Get("Content-Type"))170 }171}172173func TestContextFile(t *testing.T) {174 req, _ := http.NewRequest("GET", "/test/file", nil)175 w := httptest.NewRecorder()176177 r := New()178 r.GET("/test/file", func(c *Context) {179 c.File("./gin.go")180 })181182 r.ServeHTTP(w, req)183184 bodyAsString := w.Body.String()185186 if len(bodyAsString) == 0 {187 t.Errorf("Got empty body instead of file data")188 }189190 if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {191 t.Errorf("Content-Type should be text/plain; charset=utf-8, was %s", w.HeaderMap.Get("Content-Type"))192 }193}194195// TestHandlerFunc - ensure that custom middleware works properly196func TestHandlerFunc(t *testing.T) {197198 req, _ := http.NewRequest("GET", "/", nil)199 w := httptest.NewRecorder()200201 r := New()202 var stepsPassed int = 0203204 r.Use(func(context *Context) {205 stepsPassed += 1206 context.Next()207 stepsPassed += 1208 })209210 r.ServeHTTP(w, req)211212 if w.Code != 404 {213 t.Errorf("Response code should be Not found, was: %s", w.Code)214 }215216 if stepsPassed != 2 {217 t.Errorf("Falied to switch context in handler function: %s", stepsPassed)218 }219}220221// TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers222func TestBadAbortHandlersChain(t *testing.T) {223 // SETUP224 var stepsPassed int = 0225 r := New()226 r.Use(func(c *Context) {227 stepsPassed += 1228 c.Next()229 stepsPassed += 1230 // after check and abort231 c.Abort(409)232 })233 r.Use(func(c *Context) {234 stepsPassed += 1235 c.Next()236 stepsPassed += 1237 c.Abort(403)238 })239240 // RUN241 w := PerformRequest(r, "GET", "/")242243 // TEST244 if w.Code != 409 {245 t.Errorf("Response code should be Forbiden, was: %d", w.Code)246 }247 if stepsPassed != 4 {248 t.Errorf("Falied to switch context in handler function: %d", stepsPassed)249 }250}251252// TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order253func TestAbortHandlersChain(t *testing.T) {254 // SETUP255 var stepsPassed int = 0256 r := New()257 r.Use(func(context *Context) {258 stepsPassed += 1259 context.Abort(409)260 })261 r.Use(func(context *Context) {262 stepsPassed += 1263 context.Next()264 stepsPassed += 1265 })266267 // RUN268 w := PerformRequest(r, "GET", "/")269270 // TEST271 if w.Code != 409 {272 t.Errorf("Response code should be Conflict, was: %d", w.Code)273 }274 if stepsPassed != 1 {275 t.Errorf("Falied to switch context in handler function: %d", stepsPassed)276 }277}278279// TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as280// as well as Abort281func TestFailHandlersChain(t *testing.T) {282 // SETUP283 var stepsPassed int = 0284 r := New()285 r.Use(func(context *Context) {286 stepsPassed += 1287 context.Fail(500, errors.New("foo"))288 })289 r.Use(func(context *Context) {290 stepsPassed += 1291 context.Next()292 stepsPassed += 1293 })294295 // RUN296 w := PerformRequest(r, "GET", "/")297298 // TEST299 if w.Code != 500 {300 t.Errorf("Response code should be Server error, was: %d", w.Code)301 }302 if stepsPassed != 1 {303 t.Errorf("Falied to switch context in handler function: %d", stepsPassed)304 }305}306307func TestBindingJSON(t *testing.T) {308309 body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))310311 r := New()312 r.POST("/binding/json", func(c *Context) {313 var body struct {314 Foo string `json:"foo"`315 }316 if c.Bind(&body) {317 c.JSON(200, H{"parsed": body.Foo})318 }319 })320321 req, _ := http.NewRequest("POST", "/binding/json", body)322 req.Header.Set("Content-Type", "application/json")323 w := httptest.NewRecorder()324325 r.ServeHTTP(w, req)326327 if w.Code != 200 {328 t.Errorf("Response code should be Ok, was: %s", w.Code)329 }330331 if w.Body.String() != "{\"parsed\":\"bar\"}\n" {332 t.Errorf("Response should be {\"parsed\":\"bar\"}, was: %s", w.Body.String())333 }334335 if w.HeaderMap.Get("Content-Type") != "application/json" {336 t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))337 }338}339340func TestBindingJSONEncoding(t *testing.T) {341342 body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}"))343344 r := New()345 r.POST("/binding/json", func(c *Context) {346 var body struct {347 Foo string `json:"foo"`348 }349 if c.Bind(&body) {350 c.JSON(200, H{"parsed": body.Foo})351 }352 })353354 req, _ := http.NewRequest("POST", "/binding/json", body)355 req.Header.Set("Content-Type", "application/json; charset=utf-8")356 w := httptest.NewRecorder()357358 r.ServeHTTP(w, req)359360 if w.Code != 200 {361 t.Errorf("Response code should be Ok, was: %s", w.Code)362 }363364 if w.Body.String() != "{\"parsed\":\"嘉\"}\n" {365 t.Errorf("Response should be {\"parsed\":\"嘉\"}, was: %s", w.Body.String())366 }367368 if w.HeaderMap.Get("Content-Type") != "application/json" {369 t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))370 }371}372373func TestBindingJSONNoContentType(t *testing.T) {374375 body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))376377 r := New()378 r.POST("/binding/json", func(c *Context) {379 var body struct {380 Foo string `json:"foo"`381 }382 if c.Bind(&body) {383 c.JSON(200, H{"parsed": body.Foo})384 }385386 })387388 req, _ := http.NewRequest("POST", "/binding/json", body)389 w := httptest.NewRecorder()390391 r.ServeHTTP(w, req)392393 if w.Code != 400 {394 t.Errorf("Response code should be Bad request, was: %s", w.Code)395 }396397 if w.Body.String() == "{\"parsed\":\"bar\"}\n" {398 t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())399 }400401 if w.HeaderMap.Get("Content-Type") == "application/json" {402 t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))403 }404}405406func TestBindingJSONMalformed(t *testing.T) {407408 body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n"))409410 r := New()411 r.POST("/binding/json", func(c *Context) {412 var body struct {413 Foo string `json:"foo"`414 }415 if c.Bind(&body) {416 c.JSON(200, H{"parsed": body.Foo})417 }418419 })420421 req, _ := http.NewRequest("POST", "/binding/json", body)422 req.Header.Set("Content-Type", "application/json")423424 w := httptest.NewRecorder()425426 r.ServeHTTP(w, req)427428 if w.Code != 400 {429 t.Errorf("Response code should be Bad request, was: %s", w.Code)430 }431 if w.Body.String() == "{\"parsed\":\"bar\"}\n" {432 t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())433 }434435 if w.HeaderMap.Get("Content-Type") == "application/json" {436 t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))437 }438}
modified:context.go+9 added
245 unmodified lines
246func (c *Context) String(code int, format string, values ...interface{}) {247 c.Render(code, render.Plain, format, values)248}249250// Returns a HTTP redirect to the specific location.251func (c *Context) Redirect(code int, location string) {252 if code >= 300 && code <= 308 {253 c.Render(code, render.Redirect, location)254 } else {255 panic(fmt.Sprintf("Cannot send a redirect with status code %d", code))256 }257}258259// Writes some data into the body stream and updates the HTTP code.260func (c *Context) Data(code int, contentType string, data []byte) {261 if len(contentType) > 0 {262 c.Writer.Header().Set("Content-Type", contentType)
11 unmodified lines
added:gin_test.go+203 added
1package gin23import (4 "io/ioutil"5 "net/http"6 "net/http/httptest"7 "os"8 "path"9 "strings"10 "testing"11)1213func init() {14 SetMode(TestMode)15}1617func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {18 req, _ := http.NewRequest(method, path, nil)19 w := httptest.NewRecorder()20 r.ServeHTTP(w, req)21 return w22}2324// TestSingleRouteOK tests that POST route is correctly invoked.25func testRouteOK(method string, t *testing.T) {26 // SETUP27 passed := false28 r := New()29 r.Handle(method, "/test", []HandlerFunc{func(c *Context) {30 passed = true31 }})3233 // RUN34 w := PerformRequest(r, method, "/test")3536 // TEST37 if passed == false {38 t.Errorf(method + " route handler was not invoked.")39 }40 if w.Code != http.StatusOK {41 t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)42 }43}44func TestRouterGroupRouteOK(t *testing.T) {45 testRouteOK("POST", t)46 testRouteOK("DELETE", t)47 testRouteOK("PATCH", t)48 testRouteOK("PUT", t)49 testRouteOK("OPTIONS", t)50 testRouteOK("HEAD", t)51}5253// TestSingleRouteOK tests that POST route is correctly invoked.54func testRouteNotOK(method string, t *testing.T) {55 // SETUP56 passed := false57 r := New()58 r.Handle(method, "/test_2", []HandlerFunc{func(c *Context) {59 passed = true60 }})6162 // RUN63 w := PerformRequest(r, method, "/test")6465 // TEST66 if passed == true {67 t.Errorf(method + " route handler was invoked, when it should not")68 }69 if w.Code != http.StatusNotFound {70 // If this fails, it's because httprouter needs to be updated to at least f78f58a0db71 t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))72 }73}7475// TestSingleRouteOK tests that POST route is correctly invoked.76func TestRouteNotOK(t *testing.T) {77 testRouteNotOK("POST", t)78 testRouteNotOK("DELETE", t)79 testRouteNotOK("PATCH", t)80 testRouteNotOK("PUT", t)81 testRouteNotOK("OPTIONS", t)82 testRouteNotOK("HEAD", t)83}8485// TestSingleRouteOK tests that POST route is correctly invoked.86func testRouteNotOK2(method string, t *testing.T) {87 // SETUP88 passed := false89 r := New()90 var methodRoute string91 if method == "POST" {92 methodRoute = "GET"93 } else {94 methodRoute = "POST"95 }96 r.Handle(methodRoute, "/test", []HandlerFunc{func(c *Context) {97 passed = true98 }})99100 // RUN101 w := PerformRequest(r, method, "/test")102103 // TEST104 if passed == true {105 t.Errorf(method + " route handler was invoked, when it should not")106 }107 if w.Code != http.StatusNotFound {108 // If this fails, it's because httprouter needs to be updated to at least f78f58a0db109 t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))110 }111}112113// TestSingleRouteOK tests that POST route is correctly invoked.114func TestRouteNotOK2(t *testing.T) {115 testRouteNotOK2("POST", t)116 testRouteNotOK2("DELETE", t)117 testRouteNotOK2("PATCH", t)118 testRouteNotOK2("PUT", t)119 testRouteNotOK2("OPTIONS", t)120 testRouteNotOK2("HEAD", t)121}122123// TestHandleStaticFile - ensure the static file handles properly124func TestHandleStaticFile(t *testing.T) {125 // SETUP file126 testRoot, _ := os.Getwd()127 f, err := ioutil.TempFile(testRoot, "")128 if err != nil {129 t.Error(err)130 }131 defer os.Remove(f.Name())132 filePath := path.Join("/", path.Base(f.Name()))133 f.WriteString("Gin Web Framework")134 f.Close()135136 // SETUP gin137 r := New()138 r.Static("./", testRoot)139140 // RUN141 w := PerformRequest(r, "GET", filePath)142143 // TEST144 if w.Code != 200 {145 t.Errorf("Response code should be Ok, was: %s", w.Code)146 }147 if w.Body.String() != "Gin Web Framework" {148 t.Errorf("Response should be test, was: %s", w.Body.String())149 }150 if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {151 t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))152 }153}154155// TestHandleStaticDir - ensure the root/sub dir handles properly156func TestHandleStaticDir(t *testing.T) {157 // SETUP158 r := New()159 r.Static("/", "./")160161 // RUN162 w := PerformRequest(r, "GET", "/")163164 // TEST165 bodyAsString := w.Body.String()166 if w.Code != 200 {167 t.Errorf("Response code should be Ok, was: %s", w.Code)168 }169 if len(bodyAsString) == 0 {170 t.Errorf("Got empty body instead of file tree")171 }172 if !strings.Contains(bodyAsString, "gin.go") {173 t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)174 }175 if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {176 t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))177 }178}179180// TestHandleHeadToDir - ensure the root/sub dir handles properly181func TestHandleHeadToDir(t *testing.T) {182 // SETUP183 r := New()184 r.Static("/", "./")185186 // RUN187 w := PerformRequest(r, "HEAD", "/")188189 // TEST190 bodyAsString := w.Body.String()191 if w.Code != 200 {192 t.Errorf("Response code should be Ok, was: %s", w.Code)193 }194 if len(bodyAsString) == 0 {195 t.Errorf("Got empty body instead of file tree")196 }197 if !strings.Contains(bodyAsString, "gin.go") {198 t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)199 }200 if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {201 t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))202 }203}
modified:gin.go+32 added-6 removed
1package gin23import (4 "fmt"5 "github.com/gin-gonic/gin/render"6 "github.com/julienschmidt/httprouter"7 "html/template"8 "math"
36 unmodified lines
45)4647func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {48 c := engine.createContext(w, req, nil, engine.finalNoRoute)49 // set 404 by default, useful for logging48 c.Writer.setStatus(404)50 c.Writer.WriteHeader(404)51 c.Next()52 if !c.Writer.Written() {53 if c.Writer.Status() == 404 {51 c.Data(404, MIMEPlain, []byte("404 page not found"))54 c.Data(-1, MIMEPlain, []byte("404 page not found"))55 } else {56 c.Writer.WriteHeaderNow()57 }58 }59 engine.cache.Put(c)60}61
19 unmodified lines
81 return engine82}8384func (engine *Engine) LoadHTMLGlob(pattern string) {85 if gin_mode == debugCode {86 engine.HTMLRender = render.HTMLDebug87 } else {79 templ := template.Must(template.ParseGlob(pattern))80 engine.SetHTMLTemplate(templ)88 templ := template.Must(template.ParseGlob(pattern))89 engine.SetHTMLTemplate(templ)90 }91}9293func (engine *Engine) LoadHTMLFiles(files ...string) {94 if gin_mode == debugCode {95 engine.HTMLRender = render.HTMLDebug96 } else {84 templ := template.Must(template.ParseFiles(files...))85 engine.SetHTMLTemplate(templ)97 templ := template.Must(template.ParseFiles(files...))98 engine.SetHTMLTemplate(templ)99 }100}101102func (engine *Engine) SetHTMLTemplate(templ *template.Template) {103 engine.HTMLRender = render.HTMLRender{
17 unmodified lines
121 engine.router.ServeHTTP(w, req)122}123124func (engine *Engine) Run(addr string) {125 if gin_mode == debugCode {126 fmt.Println("[GIN-debug] Listening and serving HTTP on " + addr)127 }128 if err := http.ListenAndServe(addr, engine); err != nil {129 panic(err)130 }131}132133func (engine *Engine) RunTLS(addr string, cert string, key string) {134 if gin_mode == debugCode {135 fmt.Println("[GIN-debug] Listening and serving HTTPS on " + addr)136 }137 if err := http.ListenAndServeTLS(addr, cert, key, engine); err != nil {138 panic(err)139 }140}
41 unmodified lines
182// communication with a proxy).183func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {184 p = group.pathFor(p)185 handlers = group.combineHandlers(handlers)186 if gin_mode == debugCode {187 nuHandlers := len(handlers)188 name := funcName(handlers[nuHandlers-1])189 fmt.Printf("[GIN-debug] %-5s %-25s --> %s (%d handlers)\n", method, p, name, nuHandlers)190 }191 group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {192 c := group.engine.createContext(w, req, params, handlers)193 c.Next()194 c.Writer.WriteHeaderNow()195 group.engine.cache.Put(c)196 })197}198
60 unmodified lines
modified:logger.go+2 added-3 removed
42 unmodified lines
4344 // save the IP of the requester45 requester := c.Request.Header.Get("X-Real-IP")46 // if the requester-header is empty, check the forwarded-header47 if requester == "" {47 if len(requester) == 0 {48 requester = c.Request.Header.Get("X-Forwarded-For")49 }5050 // if the requester is still empty, use the hard-coded address from the socket52 if requester == "" {51 if len(requester) == 0 {52 requester = c.Request.RemoteAddr53 }5455 var color string
23 unmodified lines
added:mode.go+42 added
1package gin23import (4 "os"5)67const GIN_MODE = "GIN_MODE"89const (10 DebugMode string = "debug"11 ReleaseMode string = "release"12 TestMode string = "test"13)14const (15 debugCode = iota16 releaseCode = iota17 testCode = iota18)1920var gin_mode int = debugCode2122func SetMode(value string) {23 switch value {24 case DebugMode:25 gin_mode = debugCode26 case ReleaseMode:27 gin_mode = releaseCode28 case TestMode:29 gin_mode = testCode30 default:31 panic("gin mode unknown, the allowed modes are: " + DebugMode + " and " + ReleaseMode)32 }33}3435func init() {36 value := os.Getenv(GIN_MODE)37 if len(value) == 0 {38 SetMode(DebugMode)39 } else {40 SetMode(value)41 }42}
modified:README.md+48 added-15 removed
1#Gin Web Framework23[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.png)](https://godoc.org/github.com/gin-gonic/gin)3[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin)4[![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin)56Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster. If you need performance and good productivity, you will love Gin. 7![Gin console logger](http://gin-gonic.github.io/gin/other/console.png)
187 unmodified lines
195 r.Run(":8080")196}197```198199#### Model binding and validation200200#### JSON parsing and validation201To 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).202203Note 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"`.204205When 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. 206207You 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.208209```go210// Binding from JSON211type LoginJSON struct {212 User string `json:"user" binding:"required"`213 Password string `json:"password" binding:"required"`214}215216// Binding from form values217type LoginForm struct {218 User string `form:"user" binding:"required"`219 Password string `form:"password" binding:"required"` 220}221222func main() {223 r := gin.Default()224225 // Example for binding JSON ({"user": "manu", "password": "123"})226 r.POST("/login", func(c *gin.Context) {227 var json LoginJSON228214 // If EnsureBody returns false, it will write automatically the error215 // in the HTTP stream and return a 400 error. If you want custom error216 // handling you should use: c.ParseBody(interface{}) error217 if c.EnsureBody(&json) {218 if json.User == "manu" && json.Password == "123" {219 c.JSON(200, gin.H{"status": "you are logged in"})220 } else {221 c.JSON(401, gin.H{"status": "unauthorized"})222 }229 c.Bind(&json) // This will infer what binder to use depending on the content-type header.230 if json.User == "manu" && json.Password == "123" {231 c.JSON(200, gin.H{"status": "you are logged in"})232 } else {233 c.JSON(401, gin.H{"status": "unauthorized"})234 }223 }235 })236237 // Example for binding a HTLM form (user=manu&password=123)238 r.POST("/login", func(c *gin.Context) {239 var form LoginForm240241 c.BindWith(&form, binding.Form) // You can also specify which binder to use. We support binding.Form, binding.JSON and binding.XML.242 if form.User == "manu" && form.Password == "123" {243 c.JSON(200, gin.H{"status": "you are logged in"})244 } else {245 c.JSON(401, gin.H{"status": "unauthorized"})246 }247 })248249 // Listen and server on 0.0.0.0:8080250 r.Run(":8080")251}252```253231#### XML, and JSON rendering254#### XML and JSON rendering255256```go257func main() {258 r := gin.Default()
60 unmodified lines
319 r.Run(":8080")320}321```322323#### Redirects324325Issuing a HTTP redirect is easy:326327```r.GET("/test", func(c *gin.Context) {328 c.Redirect(301, "http://www.google.com/")329})330331Both internal and external locations are supported.332```333334#### Custom Middlewares335336```go337func Logger() gin.HandlerFunc {
86 unmodified lines
424 // simulate a long task with time.Sleep(). 5 seconds425 time.Sleep(5 * time.Second)426427 // note than you are using the copied context "c_cp", IMPORTANT395 log.Println("Done! in path " + c_cp.Req.URL.Path)428 log.Println("Done! in path " + c_cp.Request.URL.Path)429 }()430 })431432
1 unmodified line
434 // simulate a long task with time.Sleep(). 5 seconds435 time.Sleep(5 * time.Second)436437 // since we are NOT using a goroutine, we do not have to copy the context405 log.Println("Done! in path " + c.Req.URL.Path)438 log.Println("Done! in path " + c.Request.URL.Path)439 })440441 // Listen and server on 0.0.0.0:8080442 r.Run(":8080")
29 unmodified lines
added:recovery_test.go+52 added
1package gin23import (4 "bytes"5 "log"6 "os"7 "testing"8)910// TestPanicInHandler assert that panic has been recovered.11func TestPanicInHandler(t *testing.T) {12 // SETUP13 log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing14 r := New()15 r.Use(Recovery())16 r.GET("/recovery", func(_ *Context) {17 panic("Oupps, Houston, we have a problem")18 })1920 // RUN21 w := PerformRequest(r, "GET", "/recovery")2223 // restore logging24 log.SetOutput(os.Stderr)2526 if w.Code != 500 {27 t.Errorf("Response code should be Internal Server Error, was: %s", w.Code)28 }29}3031// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.32func TestPanicWithAbort(t *testing.T) {33 // SETUP34 log.SetOutput(bytes.NewBuffer(nil))35 r := New()36 r.Use(Recovery())37 r.GET("/recovery", func(c *Context) {38 c.Abort(400)39 panic("Oupps, Houston, we have a problem")40 })4142 // RUN43 w := PerformRequest(r, "GET", "/recovery")4445 // restore logging46 log.SetOutput(os.Stderr)4748 // TEST49 if w.Code != 500 {50 t.Errorf("Response code should be Bad request, was: %s", w.Code)51 }52}
modified:response_writer.go+20 added-10 removed
1package gin23import (4 "log"5 "net/http"6)78type (9 ResponseWriter interface {10 http.ResponseWriter11 Status() int12 Written() bool1213 // private14 setStatus(int)13 WriteHeaderNow()14 }1516 responseWriter struct {17 http.ResponseWriter
3 unmodified lines
21)2223func (w *responseWriter) reset(writer http.ResponseWriter) {24 w.ResponseWriter = writer26 w.status = 025 w.status = 20026 w.written = false27}2830func (w *responseWriter) setStatus(code int) {31 w.status = code29func (w *responseWriter) WriteHeader(code int) {30 if code != 0 {31 w.status = code32 if w.written {33 log.Println("[GIN] WARNING. Headers were already written!")34 }35 }36}3734func (w *responseWriter) WriteHeader(code int) {35 w.status = code36 w.written = true37 w.ResponseWriter.WriteHeader(code)38func (w *responseWriter) WriteHeaderNow() {39 if !w.written {40 w.written = true41 w.ResponseWriter.WriteHeader(w.status)42 }43}4445func (w *responseWriter) Write(data []byte) (n int, err error) {46 w.WriteHeaderNow()47 return w.ResponseWriter.Write(data)48}4950func (w *responseWriter) Status() int {51 return w.status52}53
3 unmodified lines
modified:utils.go+6 added
1package gin23import (4 "encoding/xml"5 "reflect"6 "runtime"7)89type H map[string]interface{}10
28 unmodified lines
39 }40 }41 return content42}4344func funcName(f interface{}) string {45 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()46}