Skip to content
Myr

chore: use http.Status* instead of hard code (#1482)

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

authored by 田欧 · committed by Bo-Yi Wu · parent 8aef947 · Browse files · 20 files+209 added−192 removed
This commit

State

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

Diff stats

20 files+209 added−192 removed

  • other:+209 added−192 removed

20 files+209 added−192 removed

modified:examples/basic/main_test.go+1 added-1 removed
13 unmodified lines
14 w := httptest.NewRecorder()15 req, _ := http.NewRequest("GET", "/ping", nil)16 router.ServeHTTP(w, req)1718 assert.Equal(t, 200, w.Code)18 assert.Equal(t, http.StatusOK, w.Code)19 assert.Equal(t, "pong", w.Body.String())20}
modified:examples/basic/main.go+6 added-4 removed
1package main23import (4 "net/http"56 "github.com/gin-gonic/gin"7)89var DB = make(map[string]string)
4 unmodified lines
14 r := gin.Default()1516 // Ping test17 r.GET("/ping", func(c *gin.Context) {16 c.String(200, "pong")18 c.String(http.StatusOK, "pong")19 })2021 // Get user value22 r.GET("/user/:name", func(c *gin.Context) {23 user := c.Params.ByName("name")24 value, ok := DB[user]25 if ok {24 c.JSON(200, gin.H{"user": user, "value": value})26 c.JSON(http.StatusOK, gin.H{"user": user, "value": value})27 } else {26 c.JSON(200, gin.H{"user": user, "status": "no value"})28 c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})29 }30 })3132 // Authorized group (uses gin.BasicAuth() middleware)
17 unmodified lines
50 }5152 if c.Bind(&json) == nil {53 DB[user] = json.Value52 c.JSON(200, gin.H{"status": "ok"})54 c.JSON(http.StatusOK, gin.H{"status": "ok"})55 }56 })5758 return r
7 unmodified lines
modified:examples/favicon/main.go+3 added-1 removed
1package main23import (4 "net/http"56 "github.com/gin-gonic/gin"7 "github.com/thinkerou/favicon"8)910func main() {11 app := gin.Default()12 app.Use(favicon.New("./favicon.ico"))13 app.GET("/ping", func(c *gin.Context) {12 c.String(200, "Hello favicon.")14 c.String(http.StatusOK, "Hello favicon.")15 })16 app.Run(":8080")17}
modified:examples/http2/main.go+2 added-1 removed
1 unmodified line
23import (4 "html/template"5 "log"6 "net/http"7 "os"89 "github.com/gin-gonic/gin"10)
16 unmodified lines
27 r := gin.Default()28 r.SetHTMLTemplate(html)2930 r.GET("/welcome", func(c *gin.Context) {30 c.HTML(200, "https", gin.H{31 c.HTML(http.StatusOK, "https", gin.H{32 "status": "success",33 })34 })35
3 unmodified lines
modified:examples/realtime-advanced/routes.go+6 added-5 removed
2 unmodified lines
3import (4 "fmt"5 "html"6 "io"7 "net/http"8 "strings"9 "time"1011 "github.com/gin-gonic/gin"
9 unmodified lines
21 if value%200 == 0 {22 fmt.Println("ip blocked")23 }24 c.Abort()24 c.String(503, "you were automatically banned :)")25 c.String(http.StatusServiceUnavailable, "you were automatically banned :)")26 }27}2829func index(c *gin.Context) {29 c.Redirect(301, "/room/hn")30 c.Redirect(http.StatusMovedPermanently, "/room/hn")31}3233func roomGET(c *gin.Context) {34 roomid := c.Param("roomid")
3 unmodified lines
38 }39 if len(nick) > 13 {40 nick = nick[0:12] + "..."41 }41 c.HTML(200, "room_login.templ.html", gin.H{42 c.HTML(http.StatusOK, "room_login.templ.html", gin.H{43 "roomid": roomid,44 "nick": nick,45 "timestamp": time.Now().Unix(),46 })
8 unmodified lines
5556 validMessage := len(message) > 1 && len(message) < 20057 validNick := len(nick) > 1 && len(nick) < 1458 if !validMessage || !validNick {58 c.JSON(400, gin.H{59 c.JSON(http.StatusBadRequest, gin.H{60 "status": "failed",61 "error": "the message or nickname is too long",62 })63 return
4 unmodified lines
68 "message": html.EscapeString(message),69 }70 messages.Add("inbound", 1)71 room(roomid).Submit(post)71 c.JSON(200, post)72 c.JSON(http.StatusOK, post)73}7475func streamRoom(c *gin.Context) {76 roomid := c.Param("roomid")
20 unmodified lines
modified:examples/realtime-chat/main.go+3 added-2 removed
2 unmodified lines
3import (4 "fmt"5 "io"6 "math/rand"7 "net/http"89 "github.com/gin-gonic/gin"10)11
22 unmodified lines
3435func roomGET(c *gin.Context) {36 roomid := c.Param("roomid")37 userid := fmt.Sprint(rand.Int31())37 c.HTML(200, "chat_room", gin.H{38 c.HTML(http.StatusOK, "chat_room", gin.H{39 "roomid": roomid,40 "userid": userid,41 })42}
3 unmodified lines
46 userid := c.PostForm("user")47 message := c.PostForm("message")48 room(roomid).Submit(userid + ": " + message)4949 c.JSON(200, gin.H{50 c.JSON(http.StatusOK, gin.H{51 "status": "success",52 "message": message,53 })54}
5 unmodified lines
modified:render/redirect.go+2 added
14 unmodified lines
15 Location string16}1718func (r Redirect) Render(w http.ResponseWriter) error {19 // todo(thinkerou): go1.6 not support StatusPermanentRedirect(308)20 // when we upgrade go version we can use http.StatusPermanentRedirect21 if (r.Code < 300 || r.Code > 308) && r.Code != 201 {22 panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code))23 }24 http.Redirect(w, r.Request, r.Location, r.Code)
4 unmodified lines
modified:render/render_test.go+2 added-2 removed
284 unmodified lines
285 req, err := http.NewRequest("GET", "/test-redirect", nil)286 assert.NoError(t, err)287288 data1 := Redirect{289 Code: 301,289 Code: http.StatusMovedPermanently,290 Request: req,291 Location: "/new/location",292 }293
1 unmodified line
295 err = data1.Render(w)296 assert.NoError(t, err)297298 data2 := Redirect{299 Code: 200,299 Code: http.StatusOK,300 Request: req,301 Location: "/new/location",302 }303
150 unmodified lines
modified:auth_test.go+6 added-6 removed
91 unmodified lines
92 accounts := Accounts{"admin": "password"}93 router := New()94 router.Use(BasicAuth(accounts))95 router.GET("/login", func(c *Context) {96 c.String(200, c.MustGet(AuthUserKey).(string))96 c.String(http.StatusOK, c.MustGet(AuthUserKey).(string))97 })9899 w := httptest.NewRecorder()100 req, _ := http.NewRequest("GET", "/login", nil)101 req.Header.Set("Authorization", authorizationHeader("admin", "password"))102 router.ServeHTTP(w, req)103104 assert.Equal(t, 200, w.Code)104 assert.Equal(t, http.StatusOK, w.Code)105 assert.Equal(t, "admin", w.Body.String())106}107108func TestBasicAuth401(t *testing.T) {
2 unmodified lines
111 router := New()112 router.Use(BasicAuth(accounts))113 router.GET("/login", func(c *Context) {114 called = true115 c.String(200, c.MustGet(AuthUserKey).(string))115 c.String(http.StatusOK, c.MustGet(AuthUserKey).(string))116 })117118 w := httptest.NewRecorder()119 req, _ := http.NewRequest("GET", "/login", nil)120 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))121 router.ServeHTTP(w, req)122123 assert.False(t, called)124 assert.Equal(t, 401, w.Code)124 assert.Equal(t, http.StatusUnauthorized, w.Code)125 assert.Equal(t, "Basic realm=\"Authorization Required\"", w.HeaderMap.Get("WWW-Authenticate"))126}127128func TestBasicAuth401WithCustomRealm(t *testing.T) {
2 unmodified lines
131 router := New()132 router.Use(BasicAuthForRealm(accounts, "My Custom \"Realm\""))133 router.GET("/login", func(c *Context) {134 called = true135 c.String(200, c.MustGet(AuthUserKey).(string))135 c.String(http.StatusOK, c.MustGet(AuthUserKey).(string))136 })137138 w := httptest.NewRecorder()139 req, _ := http.NewRequest("GET", "/login", nil)140 req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password")))141 router.ServeHTTP(w, req)142143 assert.False(t, called)144 assert.Equal(t, 401, w.Code)144 assert.Equal(t, http.StatusUnauthorized, w.Code)145 assert.Equal(t, "Basic realm=\"My Custom \\\"Realm\\\"\"", w.HeaderMap.Get("WWW-Authenticate"))146}
modified:benchmarks_test.go+3 added-3 removed
52 unmodified lines
53 data := struct {54 Status string `json:"status"`55 }{"ok"}56 router.GET("/json", func(c *Context) {57 c.JSON(200, data)57 c.JSON(http.StatusOK, data)58 })59 runRequest(B, router, "GET", "/json")60}61
3 unmodified lines
65 <html><body><h1>{{.}}</h1></body></html>`))66 router.SetHTMLTemplate(t)6768 router.GET("/html", func(c *Context) {69 c.HTML(200, "index", "hola")69 c.HTML(http.StatusOK, "index", "hola")70 })71 runRequest(B, router, "GET", "/html")72}73
7 unmodified lines
8182func BenchmarkOneRouteString(B *testing.B) {83 router := New()84 router.GET("/text", func(c *Context) {85 c.String(200, "this is a plain text")85 c.String(http.StatusOK, "this is a plain text")86 })87 runRequest(B, router, "GET", "/text")88}89
71 unmodified lines
modified:context_test.go+78 added-75 removed
7 unmodified lines
8 "bytes"9 "errors"10 "fmt"11 "html/template"12 "io"13 "mime/multipart"14 "net/http"15 "net/http/httptest"16 "reflect"
4 unmodified lines
21 "github.com/gin-contrib/sse"22 "github.com/gin-gonic/gin/binding"23 "github.com/stretchr/testify/assert"24 "golang.org/x/net/context"24 "io"25)2627var _ context.Context = &Context{}28
555 unmodified lines
584 assert.Error(t, err)585}586587func TestContextBodyAllowedForStatus(t *testing.T) {588 // todo(thinkerou): go1.6 not support StatusProcessing589 assert.False(t, false, bodyAllowedForStatus(102))589 assert.False(t, false, bodyAllowedForStatus(204))590 assert.False(t, false, bodyAllowedForStatus(304))591 assert.True(t, true, bodyAllowedForStatus(500))590 assert.False(t, false, bodyAllowedForStatus(http.StatusNoContent))591 assert.False(t, false, bodyAllowedForStatus(http.StatusNotModified))592 assert.True(t, true, bodyAllowedForStatus(http.StatusInternalServerError))593}594595type TestPanicRender struct {596}
22 unmodified lines
619func TestContextRenderJSON(t *testing.T) {620 w := httptest.NewRecorder()621 c, _ := CreateTestContext(w)622622 c.JSON(201, H{"foo": "bar"})623 c.JSON(http.StatusCreated, H{"foo": "bar"})624624 assert.Equal(t, 201, w.Code)625 assert.Equal(t, http.StatusCreated, w.Code)626 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())627 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))628}629
3 unmodified lines
633 w := httptest.NewRecorder()634 c, _ := CreateTestContext(w)635 c.Request, _ = http.NewRequest("GET", "http://example.com/?callback=x", nil)636636 c.JSONP(201, H{"foo": "bar"})637 c.JSONP(http.StatusCreated, H{"foo": "bar"})638638 assert.Equal(t, 201, w.Code)639 assert.Equal(t, http.StatusCreated, w.Code)640 assert.Equal(t, "x({\"foo\":\"bar\"})", w.Body.String())641 assert.Equal(t, "application/javascript; charset=utf-8", w.HeaderMap.Get("Content-Type"))642}643
3 unmodified lines
647 w := httptest.NewRecorder()648 c, _ := CreateTestContext(w)649 c.Request, _ = http.NewRequest("GET", "http://example.com", nil)650650 c.JSONP(201, H{"foo": "bar"})651 c.JSONP(http.StatusCreated, H{"foo": "bar"})652652 assert.Equal(t, 201, w.Code)653 assert.Equal(t, http.StatusCreated, w.Code)654 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())655 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))656}657
1 unmodified line
659func TestContextRenderNoContentJSON(t *testing.T) {660 w := httptest.NewRecorder()661 c, _ := CreateTestContext(w)662662 c.JSON(204, H{"foo": "bar"})663 c.JSON(http.StatusNoContent, H{"foo": "bar"})664664 assert.Equal(t, 204, w.Code)665 assert.Equal(t, http.StatusNoContent, w.Code)666 assert.Empty(t, w.Body.String())667 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))668}669
3 unmodified lines
673 w := httptest.NewRecorder()674 c, _ := CreateTestContext(w)675676 c.Header("Content-Type", "application/vnd.api+json")676 c.JSON(201, H{"foo": "bar"})677 c.JSON(http.StatusCreated, H{"foo": "bar"})678678 assert.Equal(t, 201, w.Code)679 assert.Equal(t, http.StatusCreated, w.Code)680 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())681 assert.Equal(t, "application/vnd.api+json", w.HeaderMap.Get("Content-Type"))682}683
2 unmodified lines
686 w := httptest.NewRecorder()687 c, _ := CreateTestContext(w)688689 c.Header("Content-Type", "application/vnd.api+json")689 c.JSON(204, H{"foo": "bar"})690 c.JSON(http.StatusNoContent, H{"foo": "bar"})691691 assert.Equal(t, 204, w.Code)692 assert.Equal(t, http.StatusNoContent, w.Code)693 assert.Empty(t, w.Body.String())694 assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")695}696
2 unmodified lines
699func TestContextRenderIndentedJSON(t *testing.T) {700 w := httptest.NewRecorder()701 c, _ := CreateTestContext(w)702702 c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})703 c.IndentedJSON(http.StatusCreated, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})704704 assert.Equal(t, 201, w.Code)705 assert.Equal(t, http.StatusCreated, w.Code)706 assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}", w.Body.String())707 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))708}709
1 unmodified line
711func TestContextRenderNoContentIndentedJSON(t *testing.T) {712 w := httptest.NewRecorder()713 c, _ := CreateTestContext(w)714714 c.IndentedJSON(204, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})715 c.IndentedJSON(http.StatusNoContent, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})716716 assert.Equal(t, 204, w.Code)717 assert.Equal(t, http.StatusNoContent, w.Code)718 assert.Empty(t, w.Body.String())719 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))720}721
3 unmodified lines
725 w := httptest.NewRecorder()726 c, router := CreateTestContext(w)727728 router.SecureJsonPrefix("&&&START&&&")728 c.SecureJSON(201, []string{"foo", "bar"})729 c.SecureJSON(http.StatusCreated, []string{"foo", "bar"})730730 assert.Equal(t, 201, w.Code)731 assert.Equal(t, http.StatusCreated, w.Code)732 assert.Equal(t, "&&&START&&&[\"foo\",\"bar\"]", w.Body.String())733 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))734}735
1 unmodified line
737func TestContextRenderNoContentSecureJSON(t *testing.T) {738 w := httptest.NewRecorder()739 c, _ := CreateTestContext(w)740740 c.SecureJSON(204, []string{"foo", "bar"})741 c.SecureJSON(http.StatusNoContent, []string{"foo", "bar"})742742 assert.Equal(t, 204, w.Code)743 assert.Equal(t, http.StatusNoContent, w.Code)744 assert.Empty(t, w.Body.String())745 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))746}747
16 unmodified lines
764765 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))766 router.SetHTMLTemplate(templ)767767 c.HTML(201, "t", H{"name": "alexandernyquist"})768 c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})769769 assert.Equal(t, 201, w.Code)770 assert.Equal(t, http.StatusCreated, w.Code)771 assert.Equal(t, "Hello alexandernyquist", w.Body.String())772 assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))773}774
13 unmodified lines
788 router.SetHTMLTemplate(templ)789790 assert.Equal(t, "[GIN-debug] [WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called\nat initialization. ie. before any route is registered or the router is listening in a socket:\n\n\trouter := gin.Default()\n\trouter.SetHTMLTemplate(template) // << good place\n\n", b.String())791791 c.HTML(201, "t", H{"name": "alexandernyquist"})792 c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})793793 assert.Equal(t, 201, w.Code)794 assert.Equal(t, http.StatusCreated, w.Code)795 assert.Equal(t, "Hello alexandernyquist", w.Body.String())796 assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))797}798
3 unmodified lines
802 c, router := CreateTestContext(w)803 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))804 router.SetHTMLTemplate(templ)805805 c.HTML(204, "t", H{"name": "alexandernyquist"})806 c.HTML(http.StatusNoContent, "t", H{"name": "alexandernyquist"})807807 assert.Equal(t, 204, w.Code)808 assert.Equal(t, http.StatusNoContent, w.Code)809 assert.Empty(t, w.Body.String())810 assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))811}812
2 unmodified lines
815func TestContextRenderXML(t *testing.T) {816 w := httptest.NewRecorder()817 c, _ := CreateTestContext(w)818818 c.XML(201, H{"foo": "bar"})819 c.XML(http.StatusCreated, H{"foo": "bar"})820820 assert.Equal(t, 201, w.Code)821 assert.Equal(t, http.StatusCreated, w.Code)822 assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())823 assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))824}825
1 unmodified line
827func TestContextRenderNoContentXML(t *testing.T) {828 w := httptest.NewRecorder()829 c, _ := CreateTestContext(w)830830 c.XML(204, H{"foo": "bar"})831 c.XML(http.StatusNoContent, H{"foo": "bar"})832832 assert.Equal(t, 204, w.Code)833 assert.Equal(t, http.StatusNoContent, w.Code)834 assert.Empty(t, w.Body.String())835 assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))836}837
2 unmodified lines
840func TestContextRenderString(t *testing.T) {841 w := httptest.NewRecorder()842 c, _ := CreateTestContext(w)843843 c.String(201, "test %s %d", "string", 2)844 c.String(http.StatusCreated, "test %s %d", "string", 2)845845 assert.Equal(t, 201, w.Code)846 assert.Equal(t, http.StatusCreated, w.Code)847 assert.Equal(t, "test string 2", w.Body.String())848 assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))849}850
1 unmodified line
852func TestContextRenderNoContentString(t *testing.T) {853 w := httptest.NewRecorder()854 c, _ := CreateTestContext(w)855855 c.String(204, "test %s %d", "string", 2)856 c.String(http.StatusNoContent, "test %s %d", "string", 2)857857 assert.Equal(t, 204, w.Code)858 assert.Equal(t, http.StatusNoContent, w.Code)859 assert.Empty(t, w.Body.String())860 assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))861}862
3 unmodified lines
866 w := httptest.NewRecorder()867 c, _ := CreateTestContext(w)868869 c.Header("Content-Type", "text/html; charset=utf-8")869 c.String(201, "<html>%s %d</html>", "string", 3)870 c.String(http.StatusCreated, "<html>%s %d</html>", "string", 3)871871 assert.Equal(t, 201, w.Code)872 assert.Equal(t, http.StatusCreated, w.Code)873 assert.Equal(t, "<html>string 3</html>", w.Body.String())874 assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))875}876
2 unmodified lines
879 w := httptest.NewRecorder()880 c, _ := CreateTestContext(w)881882 c.Header("Content-Type", "text/html; charset=utf-8")882 c.String(204, "<html>%s %d</html>", "string", 3)883 c.String(http.StatusNoContent, "<html>%s %d</html>", "string", 3)884884 assert.Equal(t, 204, w.Code)885 assert.Equal(t, http.StatusNoContent, w.Code)886 assert.Empty(t, w.Body.String())887 assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))888}889
2 unmodified lines
892func TestContextRenderData(t *testing.T) {893 w := httptest.NewRecorder()894 c, _ := CreateTestContext(w)895895 c.Data(201, "text/csv", []byte(`foo,bar`))896 c.Data(http.StatusCreated, "text/csv", []byte(`foo,bar`))897897 assert.Equal(t, 201, w.Code)898 assert.Equal(t, http.StatusCreated, w.Code)899 assert.Equal(t, "foo,bar", w.Body.String())900 assert.Equal(t, "text/csv", w.HeaderMap.Get("Content-Type"))901}902
1 unmodified line
904func TestContextRenderNoContentData(t *testing.T) {905 w := httptest.NewRecorder()906 c, _ := CreateTestContext(w)907907 c.Data(204, "text/csv", []byte(`foo,bar`))908 c.Data(http.StatusNoContent, "text/csv", []byte(`foo,bar`))909909 assert.Equal(t, 204, w.Code)910 assert.Equal(t, http.StatusNoContent, w.Code)911 assert.Empty(t, w.Body.String())912 assert.Equal(t, "text/csv", w.HeaderMap.Get("Content-Type"))913}914
20 unmodified lines
935936 c.Request, _ = http.NewRequest("GET", "/", nil)937 c.File("./gin.go")938938 assert.Equal(t, 200, w.Code)939 assert.Equal(t, http.StatusOK, w.Code)940 assert.Contains(t, w.Body.String(), "func New() *Engine {")941 assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))942}943
2 unmodified lines
946func TestContextRenderYAML(t *testing.T) {947 w := httptest.NewRecorder()948 c, _ := CreateTestContext(w)949949 c.YAML(201, H{"foo": "bar"})950 c.YAML(http.StatusCreated, H{"foo": "bar"})951951 assert.Equal(t, 201, w.Code)952 assert.Equal(t, http.StatusCreated, w.Code)953 assert.Equal(t, "foo: bar\n", w.Body.String())954 assert.Equal(t, "application/x-yaml; charset=utf-8", w.HeaderMap.Get("Content-Type"))955}956
21 unmodified lines
978 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)979 assert.Panics(t, func() { c.Redirect(299, "/new_path") })980 assert.Panics(t, func() { c.Redirect(309, "/new_path") })981981 c.Redirect(301, "/path")982 c.Redirect(http.StatusMovedPermanently, "/path")983 c.Writer.WriteHeaderNow()983 assert.Equal(t, 301, w.Code)984 assert.Equal(t, http.StatusMovedPermanently, w.Code)985 assert.Equal(t, "/path", w.Header().Get("Location"))986}987988func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {989 w := httptest.NewRecorder()990 c, _ := CreateTestContext(w)991992 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)992 c.Redirect(302, "http://google.com")993 c.Redirect(http.StatusFound, "http://google.com")994 c.Writer.WriteHeaderNow()995995 assert.Equal(t, 302, w.Code)996 assert.Equal(t, http.StatusFound, w.Code)997 assert.Equal(t, "http://google.com", w.Header().Get("Location"))998}9991000func TestContextRenderRedirectWith201(t *testing.T) {1001 w := httptest.NewRecorder()1002 c, _ := CreateTestContext(w)10031004 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)1004 c.Redirect(201, "/resource")1005 c.Redirect(http.StatusCreated, "/resource")1006 c.Writer.WriteHeaderNow()10071007 assert.Equal(t, 201, w.Code)1008 assert.Equal(t, http.StatusCreated, w.Code)1009 assert.Equal(t, "/resource", w.Header().Get("Location"))1010}10111012func TestContextRenderRedirectAll(t *testing.T) {1013 c, _ := CreateTestContext(httptest.NewRecorder())1014 c.Request, _ = http.NewRequest("POST", "http://example.com", nil)1014 assert.Panics(t, func() { c.Redirect(200, "/resource") })1015 assert.Panics(t, func() { c.Redirect(202, "/resource") })1015 assert.Panics(t, func() { c.Redirect(http.StatusOK, "/resource") })1016 assert.Panics(t, func() { c.Redirect(http.StatusAccepted, "/resource") })1017 assert.Panics(t, func() { c.Redirect(299, "/resource") })1018 assert.Panics(t, func() { c.Redirect(309, "/resource") })1018 assert.NotPanics(t, func() { c.Redirect(300, "/resource") })1019 assert.NotPanics(t, func() { c.Redirect(http.StatusMultipleChoices, "/resource") })1020 // todo(thinkerou): go1.6 not support StatusPermanentRedirect(308)1021 // when we upgrade go version we can use http.StatusPermanentRedirect1022 assert.NotPanics(t, func() { c.Redirect(308, "/resource") })1023}10241025func TestContextNegotiationWithJSON(t *testing.T) {1026 w := httptest.NewRecorder()1027 c, _ := CreateTestContext(w)1028 c.Request, _ = http.NewRequest("POST", "", nil)10291027 c.Negotiate(200, Negotiate{1030 c.Negotiate(http.StatusOK, Negotiate{1031 Offered: []string{MIMEJSON, MIMEXML},1032 Data: H{"foo": "bar"},1033 })10341032 assert.Equal(t, 200, w.Code)1035 assert.Equal(t, http.StatusOK, w.Code)1036 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())1037 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))1038}1039
1 unmodified line
1041 w := httptest.NewRecorder()1042 c, _ := CreateTestContext(w)1043 c.Request, _ = http.NewRequest("POST", "", nil)10441042 c.Negotiate(200, Negotiate{1045 c.Negotiate(http.StatusOK, Negotiate{1046 Offered: []string{MIMEXML, MIMEJSON},1047 Data: H{"foo": "bar"},1048 })10491047 assert.Equal(t, 200, w.Code)1050 assert.Equal(t, http.StatusOK, w.Code)1051 assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())1052 assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))1053}1054
3 unmodified lines
1058 c.Request, _ = http.NewRequest("POST", "", nil)1059 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))1060 router.SetHTMLTemplate(templ)10611059 c.Negotiate(200, Negotiate{1062 c.Negotiate(http.StatusOK, Negotiate{1063 Offered: []string{MIMEHTML},1064 Data: H{"name": "gin"},1065 HTMLName: "t",1066 })10671065 assert.Equal(t, 200, w.Code)1068 assert.Equal(t, http.StatusOK, w.Code)1069 assert.Equal(t, "Hello gin", w.Body.String())1070 assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))1071}1072
1 unmodified line
1074 w := httptest.NewRecorder()1075 c, _ := CreateTestContext(w)1076 c.Request, _ = http.NewRequest("POST", "", nil)10771075 c.Negotiate(200, Negotiate{1078 c.Negotiate(http.StatusOK, Negotiate{1079 Offered: []string{MIMEPOSTForm},1080 })10811079 assert.Equal(t, 406, w.Code)1082 assert.Equal(t, http.StatusNotAcceptable, w.Code)1083 assert.Equal(t, c.index, abortIndex)1084 assert.True(t, c.IsAborted())1085}1086
49 unmodified lines
1136 w := httptest.NewRecorder()1137 c, _ := CreateTestContext(w)11381139 c.index = 41137 c.AbortWithStatus(401)1140 c.AbortWithStatus(http.StatusUnauthorized)11411142 assert.Equal(t, abortIndex, c.index)1140 assert.Equal(t, 401, c.Writer.Status())1141 assert.Equal(t, 401, w.Code)1143 assert.Equal(t, http.StatusUnauthorized, c.Writer.Status())1144 assert.Equal(t, http.StatusUnauthorized, w.Code)1145 assert.True(t, c.IsAborted())1146}11471148type testJSONAbortMsg struct {
9 unmodified lines
1158 in := new(testJSONAbortMsg)1159 in.Bar = "barValue"1160 in.Foo = "fooValue"11611159 c.AbortWithStatusJSON(415, in)1162 c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, in)11631164 assert.Equal(t, abortIndex, c.index)1162 assert.Equal(t, 415, c.Writer.Status())1163 assert.Equal(t, 415, w.Code)1165 assert.Equal(t, http.StatusUnsupportedMediaType, c.Writer.Status())1166 assert.Equal(t, http.StatusUnsupportedMediaType, w.Code)1167 assert.True(t, c.IsAborted())11681169 contentType := w.Header().Get("Content-Type")1170 assert.Equal(t, "application/json; charset=utf-8", contentType)
54 unmodified lines
1225func TestContextAbortWithError(t *testing.T) {1226 w := httptest.NewRecorder()1227 c, _ := CreateTestContext(w)12281226 c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")1229 c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input")12301228 assert.Equal(t, 401, w.Code)1231 assert.Equal(t, http.StatusUnauthorized, w.Code)1232 assert.Equal(t, abortIndex, c.index)1233 assert.True(t, c.IsAborted())1234}1235
99 unmodified lines
1335 c.Writer.WriteHeaderNow()13361337 assert.Empty(t, obj.Bar)1338 assert.Empty(t, obj.Foo)1336 assert.Equal(t, 400, w.Code)1339 assert.Equal(t, http.StatusBadRequest, w.Code)1340 assert.True(t, c.IsAborted())1341}13421343func TestContextAutoShouldBindJSON(t *testing.T) {
276 unmodified lines
modified:githubapi_test.go+1 added-1 removed
291 unmodified lines
292 output["status"] = "good"293 for _, param := range c.Params {294 output[param.Key] = param.Value295 }296 c.JSON(200, output)296 c.JSON(http.StatusOK, output)297 })298 }299}300
90 unmodified lines
modified:logger_test.go+9 added-8 removed
5 unmodified lines
67import (8 "bytes"9 "errors"10 "net/http"11 "testing"1213 "github.com/stretchr/testify/assert"14)
78 unmodified lines
93 assert.Equal(t, string([]byte{27, 91, 48, 109}), colorForMethod("TRACE"), "trace is not defined and should be the reset color")94}9596func TestColorForStatus(t *testing.T) {96 assert.Equal(t, string([]byte{27, 91, 57, 55, 59, 52, 50, 109}), colorForStatus(200), "2xx should be green")97 assert.Equal(t, string([]byte{27, 91, 57, 48, 59, 52, 55, 109}), colorForStatus(301), "3xx should be white")98 assert.Equal(t, string([]byte{27, 91, 57, 55, 59, 52, 51, 109}), colorForStatus(404), "4xx should be yellow")97 assert.Equal(t, string([]byte{27, 91, 57, 55, 59, 52, 50, 109}), colorForStatus(http.StatusOK), "2xx should be green")98 assert.Equal(t, string([]byte{27, 91, 57, 48, 59, 52, 55, 109}), colorForStatus(http.StatusMovedPermanently), "3xx should be white")99 assert.Equal(t, string([]byte{27, 91, 57, 55, 59, 52, 51, 109}), colorForStatus(http.StatusNotFound), "4xx should be yellow")100 assert.Equal(t, string([]byte{27, 91, 57, 55, 59, 52, 49, 109}), colorForStatus(2), "other things should be red")101}102103func TestErrorLogger(t *testing.T) {
2 unmodified lines
106 router.GET("/error", func(c *Context) {107 c.Error(errors.New("this is an error"))108 })109 router.GET("/abort", func(c *Context) {109 c.AbortWithError(401, errors.New("no authorized"))110 c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized"))111 })112 router.GET("/print", func(c *Context) {113 c.Error(errors.New("this is an error"))113 c.String(500, "hola!")114 c.String(http.StatusInternalServerError, "hola!")115 })116117 w := performRequest(router, "GET", "/error")117 assert.Equal(t, 200, w.Code)118 assert.Equal(t, http.StatusOK, w.Code)119 assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String())120121 w = performRequest(router, "GET", "/abort")121 assert.Equal(t, 401, w.Code)122 assert.Equal(t, http.StatusUnauthorized, w.Code)123 assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String())124125 w = performRequest(router, "GET", "/print")125 assert.Equal(t, 500, w.Code)126 assert.Equal(t, http.StatusInternalServerError, w.Code)127 assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String())128}129130func TestSkippingPaths(t *testing.T) {
20 unmodified lines
modified:logger.go+4 added-3 removed
5 unmodified lines
67import (8 "fmt"9 "io"10 "net/http"11 "os"12 "time"1314 "github.com/mattn/go-isatty"
103 unmodified lines
118}119120func colorForStatus(code int) string {121 switch {121 case code >= 200 && code < 300:122 case code >= http.StatusOK && code < http.StatusMultipleChoices:123 return green123 case code >= 300 && code < 400:124 case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:125 return white125 case code >= 400 && code < 500:126 case code >= http.StatusBadRequest && code < http.StatusInternalServerError:127 return yellow128 default:129 return red130 }
22 unmodified lines
modified:middleware_test.go+17 added-16 removed
4 unmodified lines
5package gin67import (8 "errors"9 "net/http"10 "strings"11 "testing"1213 "github.com/gin-contrib/sse"
23 unmodified lines
37 // RUN38 w := performRequest(router, "GET", "/")3940 // TEST40 assert.Equal(t, 200, w.Code)41 assert.Equal(t, http.StatusOK, w.Code)42 assert.Equal(t, "ACDB", signature)43}4445func TestMiddlewareNoRoute(t *testing.T) {
27 unmodified lines
73 // RUN74 w := performRequest(router, "GET", "/")7576 // TEST76 assert.Equal(t, 404, w.Code)77 assert.Equal(t, http.StatusNotFound, w.Code)78 assert.Equal(t, "ACEGHFDB", signature)79}8081func TestMiddlewareNoMethodEnabled(t *testing.T) {
28 unmodified lines
110 // RUN111 w := performRequest(router, "GET", "/")112113 // TEST113 assert.Equal(t, 405, w.Code)114 assert.Equal(t, http.StatusMethodNotAllowed, w.Code)115 assert.Equal(t, "ACEGHFDB", signature)116}117118func TestMiddlewareNoMethodDisabled(t *testing.T) {
28 unmodified lines
147 // RUN148 w := performRequest(router, "GET", "/")149150 // TEST150 assert.Equal(t, 404, w.Code)151 assert.Equal(t, http.StatusNotFound, w.Code)152 assert.Equal(t, "AC X DB", signature)153}154155func TestMiddlewareAbort(t *testing.T) {
3 unmodified lines
159 signature += "A"160 })161 router.Use(func(c *Context) {162 signature += "C"162 c.AbortWithStatus(401)163 c.AbortWithStatus(http.StatusUnauthorized)164 c.Next()165 signature += "D"166 })167 router.GET("/", func(c *Context) {
5 unmodified lines
173 // RUN174 w := performRequest(router, "GET", "/")175176 // TEST176 assert.Equal(t, 401, w.Code)177 assert.Equal(t, http.StatusUnauthorized, w.Code)178 assert.Equal(t, "ACD", signature)179}180181func TestMiddlewareAbortHandlersChainAndNext(t *testing.T) {
1 unmodified line
183 router := New()184 router.Use(func(c *Context) {185 signature += "A"186 c.Next()186 c.AbortWithStatus(410)187 c.AbortWithStatus(http.StatusGone)188 signature += "B"189190 })191 router.GET("/", func(c *Context) {
3 unmodified lines
195 // RUN196 w := performRequest(router, "GET", "/")197198 // TEST198 assert.Equal(t, 410, w.Code)199 assert.Equal(t, http.StatusGone, w.Code)200 assert.Equal(t, "ACB", signature)201}202203// TestFailHandlersChain - ensure that Fail interrupt used middleware in fifo order as
3 unmodified lines
207 signature := ""208 router := New()209 router.Use(func(context *Context) {210 signature += "A"210 context.AbortWithError(500, errors.New("foo"))211 context.AbortWithError(http.StatusInternalServerError, errors.New("foo"))212 })213 router.Use(func(context *Context) {214 signature += "B"215 context.Next()
2 unmodified lines
218 // RUN219 w := performRequest(router, "GET", "/")220221 // TEST221 assert.Equal(t, 500, w.Code)222 assert.Equal(t, http.StatusInternalServerError, w.Code)223 assert.Equal(t, "A", signature)224}225226func TestMiddlewareWrite(t *testing.T) {227 router := New()228 router.Use(func(c *Context) {228 c.String(400, "hola\n")229 c.String(http.StatusBadRequest, "hola\n")230 })231 router.Use(func(c *Context) {231 c.XML(400, H{"foo": "bar"})232 c.XML(http.StatusBadRequest, H{"foo": "bar"})233 })234 router.Use(func(c *Context) {234 c.JSON(400, H{"foo": "bar"})235 c.JSON(http.StatusBadRequest, H{"foo": "bar"})236 })237 router.GET("/", func(c *Context) {237 c.JSON(400, H{"foo": "bar"})238 c.JSON(http.StatusBadRequest, H{"foo": "bar"})239 }, func(c *Context) {239 c.Render(400, sse.Event{240 c.Render(http.StatusBadRequest, sse.Event{241 Event: "test",242 Data: "message",243 })244 })245246 w := performRequest(router, "GET", "/")247247 assert.Equal(t, 400, w.Code)248 assert.Equal(t, http.StatusBadRequest, w.Code)249 assert.Equal(t, strings.Replace("hola\n<map><foo>bar</foo></map>{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", "", -1), strings.Replace(w.Body.String(), " ", "", -1))250}
modified:recovery_test.go+4 added-3 removed
4 unmodified lines
5package gin67import (8 "bytes"9 "net/http"10 "testing"1112 "github.com/stretchr/testify/assert"13)
8 unmodified lines
22 })23 // RUN24 w := performRequest(router, "GET", "/recovery")25 // TEST25 assert.Equal(t, 500, w.Code)26 assert.Equal(t, http.StatusInternalServerError, w.Code)27 assert.Contains(t, buffer.String(), "GET /recovery")28 assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")29 assert.Contains(t, buffer.String(), "TestPanicInHandler")30}
2 unmodified lines
33func TestPanicWithAbort(t *testing.T) {34 router := New()35 router.Use(RecoveryWithWriter(nil))36 router.GET("/recovery", func(c *Context) {36 c.AbortWithStatus(400)37 c.AbortWithStatus(http.StatusBadRequest)38 panic("Oupps, Houston, we have a problem")39 })40 // RUN41 w := performRequest(router, "GET", "/recovery")42 // TEST42 assert.Equal(t, 400, w.Code)43 assert.Equal(t, http.StatusBadRequest, w.Code)44}4546func TestSource(t *testing.T) {47 bs := source(nil, 0)
17 unmodified lines
modified:response_writer_test.go+10 added-10 removed
33 unmodified lines
34 var w ResponseWriter = writer3536 writer.reset(testWritter)37 assert.Equal(t, -1, writer.size)38 assert.Equal(t, 200, writer.status)38 assert.Equal(t, http.StatusOK, writer.status)39 assert.Equal(t, testWritter, writer.ResponseWriter)40 assert.Equal(t, -1, w.Size())41 assert.Equal(t, 200, w.Status())41 assert.Equal(t, http.StatusOK, w.Status())42 assert.False(t, w.Written())43}4445func TestResponseWriterWriteHeader(t *testing.T) {
1 unmodified line
47 writer := &responseWriter{}48 writer.reset(testWritter)49 w := ResponseWriter(writer)5051 w.WriteHeader(300)51 w.WriteHeader(http.StatusMultipleChoices)52 assert.False(t, w.Written())53 assert.Equal(t, 300, w.Status())54 assert.NotEqual(t, 300, testWritter.Code)53 assert.Equal(t, http.StatusMultipleChoices, w.Status())54 assert.NotEqual(t, http.StatusMultipleChoices, testWritter.Code)5556 w.WriteHeader(-1)57 assert.Equal(t, 300, w.Status())57 assert.Equal(t, http.StatusMultipleChoices, w.Status())58}5960func TestResponseWriterWriteHeadersNow(t *testing.T) {61 testWritter := httptest.NewRecorder()62 writer := &responseWriter{}63 writer.reset(testWritter)64 w := ResponseWriter(writer)6566 w.WriteHeader(300)66 w.WriteHeader(http.StatusMultipleChoices)67 w.WriteHeaderNow()6869 assert.True(t, w.Written())70 assert.Equal(t, 0, w.Size())71 assert.Equal(t, 300, testWritter.Code)71 assert.Equal(t, http.StatusMultipleChoices, testWritter.Code)7273 writer.size = 1074 w.WriteHeaderNow()75 assert.Equal(t, 10, w.Size())
7 unmodified lines
8384 n, err := w.Write([]byte("hola"))85 assert.Equal(t, 4, n)86 assert.Equal(t, 4, w.Size())87 assert.Equal(t, 200, w.Status())88 assert.Equal(t, 200, testWritter.Code)87 assert.Equal(t, http.StatusOK, w.Status())88 assert.Equal(t, http.StatusOK, testWritter.Code)89 assert.Equal(t, "hola", testWritter.Body.String())90 assert.NoError(t, err)9192 n, err = w.Write([]byte(" adios"))
39 unmodified lines
modified:routergroup_test.go+4 added-3 removed
3 unmodified lines
45package gin67import (8 "net/http"9 "testing"1011 "github.com/stretchr/testify/assert"12)
37 unmodified lines
50 login := v1.Group("/login/", func(c *Context) {}, func(c *Context) {})51 assert.Equal(t, "/v1/login/", login.BasePath())5253 handler := func(c *Context) {53 c.String(400, "the method was %s and index %d", c.Request.Method, c.index)54 c.String(http.StatusBadRequest, "the method was %s and index %d", c.Request.Method, c.index)55 }5657 switch method {58 case "GET":
21 unmodified lines
80 panic("unknown method")81 }8283 w := performRequest(router, method, "/v1/login/test")83 assert.Equal(t, 400, w.Code)84 assert.Equal(t, http.StatusBadRequest, w.Code)85 assert.Equal(t, "the method was "+method+" and index 3", w.Body.String())8687 w = performRequest(router, method, "/v1/test")87 assert.Equal(t, 400, w.Code)88 assert.Equal(t, http.StatusBadRequest, w.Code)89 assert.Equal(t, "the method was "+method+" and index 1", w.Body.String())90}9192func TestRouterGroupInvalidStatic(t *testing.T) {
86 unmodified lines
modified:routes_test.go+44 added-44 removed
78 unmodified lines
7980func TestRouterMethod(t *testing.T) {81 router := New()82 router.PUT("/hey2", func(c *Context) {83 c.String(200, "sup2")83 c.String(http.StatusOK, "sup2")84 })8586 router.PUT("/hey", func(c *Context) {87 c.String(200, "called")87 c.String(http.StatusOK, "called")88 })8990 router.PUT("/hey3", func(c *Context) {91 c.String(200, "sup3")91 c.String(http.StatusOK, "sup3")92 })9394 w := performRequest(router, "PUT", "/hey")9596 assert.Equal(t, 200, w.Code)96 assert.Equal(t, http.StatusOK, w.Code)97 assert.Equal(t, "called", w.Body.String())98}99100func TestRouterGroupRouteOK(t *testing.T) {
42 unmodified lines
143 router.PUT("/path4/", func(c *Context) {})144145 w := performRequest(router, "GET", "/path/")146 assert.Equal(t, "/path", w.Header().Get("Location"))147 assert.Equal(t, 301, w.Code)147 assert.Equal(t, http.StatusMovedPermanently, w.Code)148149 w = performRequest(router, "GET", "/path2")150 assert.Equal(t, "/path2/", w.Header().Get("Location"))151 assert.Equal(t, 301, w.Code)151 assert.Equal(t, http.StatusMovedPermanently, w.Code)152153 w = performRequest(router, "POST", "/path3/")154 assert.Equal(t, "/path3", w.Header().Get("Location"))155 assert.Equal(t, 307, w.Code)155 assert.Equal(t, http.StatusTemporaryRedirect, w.Code)156157 w = performRequest(router, "PUT", "/path4")158 assert.Equal(t, "/path4/", w.Header().Get("Location"))159 assert.Equal(t, 307, w.Code)159 assert.Equal(t, http.StatusTemporaryRedirect, w.Code)160161 w = performRequest(router, "GET", "/path")162 assert.Equal(t, 200, w.Code)162 assert.Equal(t, http.StatusOK, w.Code)163164 w = performRequest(router, "GET", "/path2/")165 assert.Equal(t, 200, w.Code)165 assert.Equal(t, http.StatusOK, w.Code)166167 w = performRequest(router, "POST", "/path3")168 assert.Equal(t, 200, w.Code)168 assert.Equal(t, http.StatusOK, w.Code)169170 w = performRequest(router, "PUT", "/path4/")171 assert.Equal(t, 200, w.Code)171 assert.Equal(t, http.StatusOK, w.Code)172173 router.RedirectTrailingSlash = false174175 w = performRequest(router, "GET", "/path/")176 assert.Equal(t, 404, w.Code)176 assert.Equal(t, http.StatusNotFound, w.Code)177 w = performRequest(router, "GET", "/path2")178 assert.Equal(t, 404, w.Code)178 assert.Equal(t, http.StatusNotFound, w.Code)179 w = performRequest(router, "POST", "/path3/")180 assert.Equal(t, 404, w.Code)180 assert.Equal(t, http.StatusNotFound, w.Code)181 w = performRequest(router, "PUT", "/path4")182 assert.Equal(t, 404, w.Code)182 assert.Equal(t, http.StatusNotFound, w.Code)183}184185func TestRouteRedirectFixedPath(t *testing.T) {186 router := New()
6 unmodified lines
193 router.POST("/Path4/", func(c *Context) {})194195 w := performRequest(router, "GET", "/PATH")196 assert.Equal(t, "/path", w.Header().Get("Location"))197 assert.Equal(t, 301, w.Code)197 assert.Equal(t, http.StatusMovedPermanently, w.Code)198199 w = performRequest(router, "GET", "/path2")200 assert.Equal(t, "/Path2", w.Header().Get("Location"))201 assert.Equal(t, 301, w.Code)201 assert.Equal(t, http.StatusMovedPermanently, w.Code)202203 w = performRequest(router, "POST", "/path3")204 assert.Equal(t, "/PATH3", w.Header().Get("Location"))205 assert.Equal(t, 307, w.Code)205 assert.Equal(t, http.StatusTemporaryRedirect, w.Code)206207 w = performRequest(router, "POST", "/path4")208 assert.Equal(t, "/Path4/", w.Header().Get("Location"))209 assert.Equal(t, 307, w.Code)209 assert.Equal(t, http.StatusTemporaryRedirect, w.Code)210}211212// TestContextParamsGet tests that a parameter can be parsed from the URL.213func TestRouteParamsByName(t *testing.T) {
21 unmodified lines
235 })236237 w := performRequest(router, "GET", "/test/john/smith/is/super/great")238239 assert.Equal(t, 200, w.Code)239 assert.Equal(t, http.StatusOK, w.Code)240 assert.Equal(t, "john", name)241 assert.Equal(t, "smith", lastName)242 assert.Equal(t, "/is/super/great", wild)243}
20 unmodified lines
264 w := performRequest(router, "GET", "/using_static/"+filename)265 w2 := performRequest(router, "GET", "/result")266267 assert.Equal(t, w, w2)268 assert.Equal(t, 200, w.Code)268 assert.Equal(t, http.StatusOK, w.Code)269 assert.Equal(t, "Gin Web Framework", w.Body.String())270 assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))271272 w3 := performRequest(router, "HEAD", "/using_static/"+filename)273 w4 := performRequest(router, "HEAD", "/result")274275 assert.Equal(t, w3, w4)276 assert.Equal(t, 200, w3.Code)276 assert.Equal(t, http.StatusOK, w3.Code)277}278279// TestHandleStaticDir - ensure the root/sub dir handles properly280func TestRouteStaticListingDir(t *testing.T) {
1 unmodified line
282 router.StaticFS("/", Dir("./", true))283284 w := performRequest(router, "GET", "/")285286 assert.Equal(t, 200, w.Code)286 assert.Equal(t, http.StatusOK, w.Code)287 assert.Contains(t, w.Body.String(), "gin.go")288 assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))289}290
3 unmodified lines
294 router.Static("/", "./")295296 w := performRequest(router, "GET", "/")297298 assert.Equal(t, 404, w.Code)298 assert.Equal(t, http.StatusNotFound, w.Code)299 assert.NotContains(t, w.Body.String(), "gin.go")300}301302func TestRouterMiddlewareAndStatic(t *testing.T) {
6 unmodified lines
309 static.Static("/", "./")310311 w := performRequest(router, "GET", "/gin.go")312313 assert.Equal(t, 200, w.Code)313 assert.Equal(t, http.StatusOK, w.Code)314 assert.Contains(t, w.Body.String(), "package gin")315 assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))316 assert.NotEqual(t, w.HeaderMap.Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST")317 assert.Equal(t, "Mon, 02 Jan 2006 15:04:05 MST", w.HeaderMap.Get("Expires"))
29 unmodified lines
347 router := New()348 router.HandleMethodNotAllowed = false349 router.POST("/path", func(c *Context) {})350 w := performRequest(router, "GET", "/path")351 assert.Equal(t, 404, w.Code)351 assert.Equal(t, http.StatusNotFound, w.Code)352353 router.NoMethod(func(c *Context) {354 c.String(http.StatusTeapot, "responseText")355 })356 w = performRequest(router, "GET", "/path")357 assert.Equal(t, "404 page not found", w.Body.String())358 assert.Equal(t, 404, w.Code)358 assert.Equal(t, http.StatusNotFound, w.Code)359}360361func TestRouterNotFound(t *testing.T) {362 router := New()
6 unmodified lines
369 route string370 code int371 location string372 }{373 {"/path/", 301, "/path"}, // TSR -/374 {"/dir", 301, "/dir/"}, // TSR +/375 {"", 301, "/"}, // TSR +/376 {"/PATH", 301, "/path"}, // Fixed Case377 {"/DIR/", 301, "/dir/"}, // Fixed Case378 {"/PATH/", 301, "/path"}, // Fixed Case -/379 {"/DIR", 301, "/dir/"}, // Fixed Case +/380 {"/../path", 301, "/path"}, // CleanPath381 {"/nope", 404, ""}, // NotFound373 {"/path/", http.StatusMovedPermanently, "/path"}, // TSR -/374 {"/dir", http.StatusMovedPermanently, "/dir/"}, // TSR +/375 {"", http.StatusMovedPermanently, "/"}, // TSR +/376 {"/PATH", http.StatusMovedPermanently, "/path"}, // Fixed Case377 {"/DIR/", http.StatusMovedPermanently, "/dir/"}, // Fixed Case378 {"/PATH/", http.StatusMovedPermanently, "/path"}, // Fixed Case -/379 {"/DIR", http.StatusMovedPermanently, "/dir/"}, // Fixed Case +/380 {"/../path", http.StatusMovedPermanently, "/path"}, // CleanPath381 {"/nope", http.StatusNotFound, ""}, // NotFound382 }383 for _, tr := range testRoutes {384 w := performRequest(router, "GET", tr.route)385 assert.Equal(t, tr.code, w.Code)386 if w.Code != 404 {386 if w.Code != http.StatusNotFound {387 assert.Equal(t, tr.location, fmt.Sprint(w.Header().Get("Location")))388 }389 }390391 // Test custom not found handler392 var notFound bool393 router.NoRoute(func(c *Context) {394 c.AbortWithStatus(404)394 c.AbortWithStatus(http.StatusNotFound)395 notFound = true396 })397 w := performRequest(router, "GET", "/nope")398 assert.Equal(t, 404, w.Code)398 assert.Equal(t, http.StatusNotFound, w.Code)399 assert.True(t, notFound)400401 // Test other method than GET (want 307 instead of 301)402 router.PATCH("/path", func(c *Context) {})403 w = performRequest(router, "PATCH", "/path/")404 assert.Equal(t, 307, w.Code)404 assert.Equal(t, http.StatusTemporaryRedirect, w.Code)405 assert.Equal(t, "map[Location:[/path]]", fmt.Sprint(w.Header()))406407 // Test special case where no node for the prefix "/" exists408 router = New()409 router.GET("/a", func(c *Context) {})410 w = performRequest(router, "GET", "/")411 assert.Equal(t, 404, w.Code)411 assert.Equal(t, http.StatusNotFound, w.Code)412}413414func TestRouteRawPath(t *testing.T) {415 route := New()
10 unmodified lines
426 assert.Equal(t, "222", num)427 })428429 w := performRequest(route, "POST", "/project/Some%2FOther%2FProject/build/222")430 assert.Equal(t, 200, w.Code)430 assert.Equal(t, http.StatusOK, w.Code)431}432433func TestRouteRawPathNoUnescape(t *testing.T) {434 route := New()
11 unmodified lines
446 assert.Equal(t, "333", num)447 })448449 w := performRequest(route, "POST", "/project/Some%2FOther%2FProject/build/333")450 assert.Equal(t, 200, w.Code)450 assert.Equal(t, http.StatusOK, w.Code)451}452453func TestRouteServeErrorWithWriteHeader(t *testing.T) {454 route := New()
9 unmodified lines
modified:utils_test.go+4 added-4 removed
23 unmodified lines
2425func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {26 assert.Equal(t.T, "POST", req.Method)27 assert.Equal(t.T, "/path", req.URL.Path)28 w.WriteHeader(500)28 w.WriteHeader(http.StatusInternalServerError)29 fmt.Fprint(w, "hello")30}3132func TestWrap(t *testing.T) {
1 unmodified line
34 router.POST("/path", WrapH(&testStruct{t}))35 router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) {36 assert.Equal(t, "GET", req.Method)37 assert.Equal(t, "/path2", req.URL.Path)38 w.WriteHeader(400)38 w.WriteHeader(http.StatusBadRequest)39 fmt.Fprint(w, "hola!")40 }))4142 w := performRequest(router, "POST", "/path")43 assert.Equal(t, 500, w.Code)43 assert.Equal(t, http.StatusInternalServerError, w.Code)44 assert.Equal(t, "hello", w.Body.String())4546 w = performRequest(router, "GET", "/path2")47 assert.Equal(t, 400, w.Code)47 assert.Equal(t, http.StatusBadRequest, w.Code)48 assert.Equal(t, "hola!", w.Body.String())49}5051func TestLastChar(t *testing.T) {
88 unmodified lines