repo_name
stringclasses
2 values
pr_number
int64
2.62k
123k
pr_title
stringlengths
8
193
pr_description
stringlengths
0
27.9k
author
stringlengths
3
23
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
21
28k
filepath
stringlengths
7
174
before_content
stringlengths
0
554M
after_content
stringlengths
0
554M
label
int64
-1
1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./logger_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestLogger(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer)) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithConfig(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithConfig(LoggerConfig{Output: buffer})) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithFormatter(t *testing.T) { buffer := new(bytes.Buffer) d := DefaultWriter DefaultWriter = buffer defer func() { DefaultWriter = d }() router := New() router.Use(LoggerWithFormatter(func(param LogFormatterParams) string { return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) })) router.GET("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") } func TestLoggerWithConfigFormatting(t *testing.T) { var gotParam LogFormatterParams var gotKeys map[string]any buffer := new(bytes.Buffer) router := New() router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, Formatter: func(param LogFormatterParams) string { // for assert test gotParam = param return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) }, })) router.GET("/example", func(c *Context) { // set dummy ClientIP c.Request.Header.Set("X-Forwarded-For", "20.20.20.20") gotKeys = c.Keys time.Sleep(time.Millisecond) }) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // LogFormatterParams test assert.NotNil(t, gotParam.Request) assert.NotEmpty(t, gotParam.TimeStamp) assert.Equal(t, 200, gotParam.StatusCode) assert.NotEmpty(t, gotParam.Latency) assert.Equal(t, "20.20.20.20", gotParam.ClientIP) assert.Equal(t, "GET", gotParam.Method) assert.Equal(t, "/example?a=100", gotParam.Path) assert.Empty(t, gotParam.ErrorMessage) assert.Equal(t, gotKeys, gotParam.Keys) } func TestDefaultLogFormatter(t *testing.T) { timeStamp := time.Unix(1544173902, 0).UTC() termFalseParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } termTrueParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termTrueLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termFalseLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 5s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 2743h29m3s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseLongDurationParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 5s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 2743h29m3s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueLongDurationParam)) } func TestColorForMethod(t *testing.T) { colorForMethod := func(method string) string { p := LogFormatterParams{ Method: method, } return p.MethodColor() } assert.Equal(t, blue, colorForMethod("GET"), "get should be blue") assert.Equal(t, cyan, colorForMethod("POST"), "post should be cyan") assert.Equal(t, yellow, colorForMethod("PUT"), "put should be yellow") assert.Equal(t, red, colorForMethod("DELETE"), "delete should be red") assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green") assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta") assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white") assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color") } func TestColorForStatus(t *testing.T) { colorForStatus := func(code int) string { p := LogFormatterParams{ StatusCode: code, } return p.StatusCodeColor() } assert.Equal(t, green, colorForStatus(http.StatusOK), "2xx should be green") assert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), "3xx should be white") assert.Equal(t, yellow, colorForStatus(http.StatusNotFound), "4xx should be yellow") assert.Equal(t, red, colorForStatus(2), "other things should be red") } func TestResetColor(t *testing.T) { p := LogFormatterParams{} assert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor()) } func TestIsOutputColor(t *testing.T) { // test with isTerm flag true. p := LogFormatterParams{ isTerm: true, } consoleColorMode = autoColor assert.Equal(t, true, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // test with isTerm flag false. p = LogFormatterParams{ isTerm: false, } consoleColorMode = autoColor assert.Equal(t, false, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // reset console color mode. consoleColorMode = autoColor } func TestErrorLogger(t *testing.T) { router := New() router.Use(ErrorLogger()) router.GET("/error", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck }) router.GET("/abort", func(c *Context) { c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) //nolint: errcheck }) router.GET("/print", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck c.String(http.StatusInternalServerError, "hola!") }) w := PerformRequest(router, "GET", "/error") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String()) w = PerformRequest(router, "GET", "/abort") assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String()) w = PerformRequest(router, "GET", "/print") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String()) } func TestLoggerWithWriterSkippingPaths(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer, "/skipped")) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestLoggerWithConfigSkippingPaths(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, SkipPaths: []string{"/skipped"}, })) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestDisableConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) DisableConsoleColor() assert.Equal(t, disableColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor } func TestForceConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) ForceConsoleColor() assert.Equal(t, forceColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestLogger(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer)) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithConfig(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithConfig(LoggerConfig{Output: buffer})) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithFormatter(t *testing.T) { buffer := new(bytes.Buffer) d := DefaultWriter DefaultWriter = buffer defer func() { DefaultWriter = d }() router := New() router.Use(LoggerWithFormatter(func(param LogFormatterParams) string { return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) })) router.GET("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") } func TestLoggerWithConfigFormatting(t *testing.T) { var gotParam LogFormatterParams var gotKeys map[string]any buffer := new(bytes.Buffer) router := New() router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, Formatter: func(param LogFormatterParams) string { // for assert test gotParam = param return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) }, })) router.GET("/example", func(c *Context) { // set dummy ClientIP c.Request.Header.Set("X-Forwarded-For", "20.20.20.20") gotKeys = c.Keys time.Sleep(time.Millisecond) }) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // LogFormatterParams test assert.NotNil(t, gotParam.Request) assert.NotEmpty(t, gotParam.TimeStamp) assert.Equal(t, 200, gotParam.StatusCode) assert.NotEmpty(t, gotParam.Latency) assert.Equal(t, "20.20.20.20", gotParam.ClientIP) assert.Equal(t, "GET", gotParam.Method) assert.Equal(t, "/example?a=100", gotParam.Path) assert.Empty(t, gotParam.ErrorMessage) assert.Equal(t, gotKeys, gotParam.Keys) } func TestDefaultLogFormatter(t *testing.T) { timeStamp := time.Unix(1544173902, 0).UTC() termFalseParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } termTrueParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termTrueLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termFalseLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 5s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 2743h29m3s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseLongDurationParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 5s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 2743h29m3s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueLongDurationParam)) } func TestColorForMethod(t *testing.T) { colorForMethod := func(method string) string { p := LogFormatterParams{ Method: method, } return p.MethodColor() } assert.Equal(t, blue, colorForMethod("GET"), "get should be blue") assert.Equal(t, cyan, colorForMethod("POST"), "post should be cyan") assert.Equal(t, yellow, colorForMethod("PUT"), "put should be yellow") assert.Equal(t, red, colorForMethod("DELETE"), "delete should be red") assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green") assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta") assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white") assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color") } func TestColorForStatus(t *testing.T) { colorForStatus := func(code int) string { p := LogFormatterParams{ StatusCode: code, } return p.StatusCodeColor() } assert.Equal(t, green, colorForStatus(http.StatusOK), "2xx should be green") assert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), "3xx should be white") assert.Equal(t, yellow, colorForStatus(http.StatusNotFound), "4xx should be yellow") assert.Equal(t, red, colorForStatus(2), "other things should be red") } func TestResetColor(t *testing.T) { p := LogFormatterParams{} assert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor()) } func TestIsOutputColor(t *testing.T) { // test with isTerm flag true. p := LogFormatterParams{ isTerm: true, } consoleColorMode = autoColor assert.Equal(t, true, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // test with isTerm flag false. p = LogFormatterParams{ isTerm: false, } consoleColorMode = autoColor assert.Equal(t, false, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // reset console color mode. consoleColorMode = autoColor } func TestErrorLogger(t *testing.T) { router := New() router.Use(ErrorLogger()) router.GET("/error", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck }) router.GET("/abort", func(c *Context) { c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) //nolint: errcheck }) router.GET("/print", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck c.String(http.StatusInternalServerError, "hola!") }) w := PerformRequest(router, "GET", "/error") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String()) w = PerformRequest(router, "GET", "/abort") assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String()) w = PerformRequest(router, "GET", "/print") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String()) } func TestLoggerWithWriterSkippingPaths(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer, "/skipped")) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestLoggerWithConfigSkippingPaths(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, SkipPaths: []string{"/skipped"}, })) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestDisableConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) DisableConsoleColor() assert.Equal(t, disableColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor } func TestForceConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) ForceConsoleColor() assert.Equal(t, forceColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/default_validator_benchmark_test.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "strconv" "testing" ) func BenchmarkSliceValidationError(b *testing.B) { const size int = 100 for i := 0; i < b.N; i++ { e := make(SliceValidationError, size) for j := 0; j < size; j++ { e[j] = errors.New(strconv.Itoa(j)) } if len(e.Error()) == 0 { b.Errorf("error") } } }
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "strconv" "testing" ) func BenchmarkSliceValidationError(b *testing.B) { const size int = 100 for i := 0; i < b.N; i++ { e := make(SliceValidationError, size) for j := 0; j < size; j++ { e[j] = errors.New(strconv.Itoa(j)) } if len(e.Error()) == 0 { b.Errorf("error") } } }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./render/protobuf.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "google.golang.org/protobuf/proto" ) // ProtoBuf contains the given interface object. type ProtoBuf struct { Data any } var protobufContentType = []string{"application/x-protobuf"} // Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType. func (r ProtoBuf) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := proto.Marshal(r.Data.(proto.Message)) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (ProtoBuf) writes ProtoBuf ContentType. func (r ProtoBuf) WriteContentType(w http.ResponseWriter) { writeContentType(w, protobufContentType) }
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "google.golang.org/protobuf/proto" ) // ProtoBuf contains the given interface object. type ProtoBuf struct { Data any } var protobufContentType = []string{"application/x-protobuf"} // Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType. func (r ProtoBuf) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := proto.Marshal(r.Data.(proto.Message)) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (ProtoBuf) writes ProtoBuf ContentType. func (r ProtoBuf) WriteContentType(w http.ResponseWriter) { writeContentType(w, protobufContentType) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./render/data.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" // Data contains ContentType and bytes data. type Data struct { ContentType string Data []byte } // Render (Data) writes data with custom ContentType. func (r Data) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) _, err = w.Write(r.Data) return } // WriteContentType (Data) writes custom ContentType. func (r Data) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" // Data contains ContentType and bytes data. type Data struct { ContentType string Data []byte } // Render (Data) writes data with custom ContentType. func (r Data) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) _, err = w.Write(r.Data) return } // WriteContentType (Data) writes custom ContentType. func (r Data) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./path_test.go
// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The Go Authors. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "strings" "testing" "github.com/stretchr/testify/assert" ) type cleanPathTest struct { path, result string } var cleanTests = []cleanPathTest{ // Already clean {"/", "/"}, {"/abc", "/abc"}, {"/a/b/c", "/a/b/c"}, {"/abc/", "/abc/"}, {"/a/b/c/", "/a/b/c/"}, // missing root {"", "/"}, {"a/", "/a/"}, {"abc", "/abc"}, {"abc/def", "/abc/def"}, {"a/b/c", "/a/b/c"}, // Remove doubled slash {"//", "/"}, {"/abc//", "/abc/"}, {"/abc/def//", "/abc/def/"}, {"/a/b/c//", "/a/b/c/"}, {"/abc//def//ghi", "/abc/def/ghi"}, {"//abc", "/abc"}, {"///abc", "/abc"}, {"//abc//", "/abc/"}, // Remove . elements {".", "/"}, {"./", "/"}, {"/abc/./def", "/abc/def"}, {"/./abc/def", "/abc/def"}, {"/abc/.", "/abc/"}, // Remove .. elements {"..", "/"}, {"../", "/"}, {"../../", "/"}, {"../..", "/"}, {"../../abc", "/abc"}, {"/abc/def/ghi/../jkl", "/abc/def/jkl"}, {"/abc/def/../ghi/../jkl", "/abc/jkl"}, {"/abc/def/..", "/abc"}, {"/abc/def/../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"}, // Combinations {"abc/./../def", "/def"}, {"abc//./../def", "/def"}, {"abc/../../././../def", "/def"}, } func TestPathClean(t *testing.T) { for _, test := range cleanTests { assert.Equal(t, test.result, cleanPath(test.path)) assert.Equal(t, test.result, cleanPath(test.result)) } } func TestPathCleanMallocs(t *testing.T) { if testing.Short() { t.Skip("skipping malloc count in short mode") } for _, test := range cleanTests { allocs := testing.AllocsPerRun(100, func() { cleanPath(test.result) }) assert.EqualValues(t, allocs, 0) } } func BenchmarkPathClean(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { for _, test := range cleanTests { cleanPath(test.path) } } } func genLongPaths() (testPaths []cleanPathTest) { for i := 1; i <= 1234; i++ { ss := strings.Repeat("a", i) correctPath := "/" + ss testPaths = append(testPaths, cleanPathTest{ path: correctPath, result: correctPath, }, cleanPathTest{ path: ss, result: correctPath, }, cleanPathTest{ path: "//" + ss, result: correctPath, }, cleanPathTest{ path: "/" + ss + "/b/..", result: correctPath, }) } return } func TestPathCleanLong(t *testing.T) { cleanTests := genLongPaths() for _, test := range cleanTests { assert.Equal(t, test.result, cleanPath(test.path)) assert.Equal(t, test.result, cleanPath(test.result)) } } func BenchmarkPathCleanLong(b *testing.B) { cleanTests := genLongPaths() b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { for _, test := range cleanTests { cleanPath(test.path) } } }
// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The Go Authors. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "strings" "testing" "github.com/stretchr/testify/assert" ) type cleanPathTest struct { path, result string } var cleanTests = []cleanPathTest{ // Already clean {"/", "/"}, {"/abc", "/abc"}, {"/a/b/c", "/a/b/c"}, {"/abc/", "/abc/"}, {"/a/b/c/", "/a/b/c/"}, // missing root {"", "/"}, {"a/", "/a/"}, {"abc", "/abc"}, {"abc/def", "/abc/def"}, {"a/b/c", "/a/b/c"}, // Remove doubled slash {"//", "/"}, {"/abc//", "/abc/"}, {"/abc/def//", "/abc/def/"}, {"/a/b/c//", "/a/b/c/"}, {"/abc//def//ghi", "/abc/def/ghi"}, {"//abc", "/abc"}, {"///abc", "/abc"}, {"//abc//", "/abc/"}, // Remove . elements {".", "/"}, {"./", "/"}, {"/abc/./def", "/abc/def"}, {"/./abc/def", "/abc/def"}, {"/abc/.", "/abc/"}, // Remove .. elements {"..", "/"}, {"../", "/"}, {"../../", "/"}, {"../..", "/"}, {"../../abc", "/abc"}, {"/abc/def/ghi/../jkl", "/abc/def/jkl"}, {"/abc/def/../ghi/../jkl", "/abc/jkl"}, {"/abc/def/..", "/abc"}, {"/abc/def/../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"}, // Combinations {"abc/./../def", "/def"}, {"abc//./../def", "/def"}, {"abc/../../././../def", "/def"}, } func TestPathClean(t *testing.T) { for _, test := range cleanTests { assert.Equal(t, test.result, cleanPath(test.path)) assert.Equal(t, test.result, cleanPath(test.result)) } } func TestPathCleanMallocs(t *testing.T) { if testing.Short() { t.Skip("skipping malloc count in short mode") } for _, test := range cleanTests { allocs := testing.AllocsPerRun(100, func() { cleanPath(test.result) }) assert.EqualValues(t, allocs, 0) } } func BenchmarkPathClean(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { for _, test := range cleanTests { cleanPath(test.path) } } } func genLongPaths() (testPaths []cleanPathTest) { for i := 1; i <= 1234; i++ { ss := strings.Repeat("a", i) correctPath := "/" + ss testPaths = append(testPaths, cleanPathTest{ path: correctPath, result: correctPath, }, cleanPathTest{ path: ss, result: correctPath, }, cleanPathTest{ path: "//" + ss, result: correctPath, }, cleanPathTest{ path: "/" + ss + "/b/..", result: correctPath, }) } return } func TestPathCleanLong(t *testing.T) { cleanTests := genLongPaths() for _, test := range cleanTests { assert.Equal(t, test.result, cleanPath(test.path)) assert.Equal(t, test.result, cleanPath(test.result)) } } func BenchmarkPathCleanLong(b *testing.B) { cleanTests := genLongPaths() b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { for _, test := range cleanTests { cleanPath(test.path) } } }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./ginS/gins.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package ginS import ( "html/template" "net/http" "sync" "github.com/gin-gonic/gin" ) var once sync.Once var internalEngine *gin.Engine func engine() *gin.Engine { once.Do(func() { internalEngine = gin.Default() }) return internalEngine } // LoadHTMLGlob is a wrapper for Engine.LoadHTMLGlob. func LoadHTMLGlob(pattern string) { engine().LoadHTMLGlob(pattern) } // LoadHTMLFiles is a wrapper for Engine.LoadHTMLFiles. func LoadHTMLFiles(files ...string) { engine().LoadHTMLFiles(files...) } // SetHTMLTemplate is a wrapper for Engine.SetHTMLTemplate. func SetHTMLTemplate(templ *template.Template) { engine().SetHTMLTemplate(templ) } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func NoRoute(handlers ...gin.HandlerFunc) { engine().NoRoute(handlers...) } // NoMethod is a wrapper for Engine.NoMethod. func NoMethod(handlers ...gin.HandlerFunc) { engine().NoMethod(handlers...) } // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func Group(relativePath string, handlers ...gin.HandlerFunc) *gin.RouterGroup { return engine().Group(relativePath, handlers...) } // Handle is a wrapper for Engine.Handle. func Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Handle(httpMethod, relativePath, handlers...) } // POST is a shortcut for router.Handle("POST", path, handle) func POST(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().POST(relativePath, handlers...) } // GET is a shortcut for router.Handle("GET", path, handle) func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().GET(relativePath, handlers...) } // DELETE is a shortcut for router.Handle("DELETE", path, handle) func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().DELETE(relativePath, handlers...) } // PATCH is a shortcut for router.Handle("PATCH", path, handle) func PATCH(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PATCH(relativePath, handlers...) } // PUT is a shortcut for router.Handle("PUT", path, handle) func PUT(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PUT(relativePath, handlers...) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) func OPTIONS(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().OPTIONS(relativePath, handlers...) } // HEAD is a shortcut for router.Handle("HEAD", path, handle) func HEAD(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().HEAD(relativePath, handlers...) } // Any is a wrapper for Engine.Any. func Any(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Any(relativePath, handlers...) } // StaticFile is a wrapper for Engine.StaticFile. func StaticFile(relativePath, filepath string) gin.IRoutes { return engine().StaticFile(relativePath, filepath) } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // // router.Static("/static", "/var/www") func Static(relativePath, root string) gin.IRoutes { return engine().Static(relativePath, root) } // StaticFS is a wrapper for Engine.StaticFS. func StaticFS(relativePath string, fs http.FileSystem) gin.IRoutes { return engine().StaticFS(relativePath, fs) } // Use attaches a global middleware to the router. i.e. the middlewares attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func Use(middlewares ...gin.HandlerFunc) gin.IRoutes { return engine().Use(middlewares...) } // Routes returns a slice of registered routes. func Routes() gin.RoutesInfo { return engine().Routes() } // Run attaches to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func Run(addr ...string) (err error) { return engine().Run(addr...) } // RunTLS attaches to a http.Server and starts listening and serving HTTPS requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func RunTLS(addr, certFile, keyFile string) (err error) { return engine().RunTLS(addr, certFile, keyFile) } // RunUnix attaches to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file) // Note: this method will block the calling goroutine indefinitely unless an error happens. func RunUnix(file string) (err error) { return engine().RunUnix(file) } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: the method will block the calling goroutine indefinitely unless on error happens. func RunFd(fd int) (err error) { return engine().RunFd(fd) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package ginS import ( "html/template" "net/http" "sync" "github.com/gin-gonic/gin" ) var once sync.Once var internalEngine *gin.Engine func engine() *gin.Engine { once.Do(func() { internalEngine = gin.Default() }) return internalEngine } // LoadHTMLGlob is a wrapper for Engine.LoadHTMLGlob. func LoadHTMLGlob(pattern string) { engine().LoadHTMLGlob(pattern) } // LoadHTMLFiles is a wrapper for Engine.LoadHTMLFiles. func LoadHTMLFiles(files ...string) { engine().LoadHTMLFiles(files...) } // SetHTMLTemplate is a wrapper for Engine.SetHTMLTemplate. func SetHTMLTemplate(templ *template.Template) { engine().SetHTMLTemplate(templ) } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func NoRoute(handlers ...gin.HandlerFunc) { engine().NoRoute(handlers...) } // NoMethod is a wrapper for Engine.NoMethod. func NoMethod(handlers ...gin.HandlerFunc) { engine().NoMethod(handlers...) } // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func Group(relativePath string, handlers ...gin.HandlerFunc) *gin.RouterGroup { return engine().Group(relativePath, handlers...) } // Handle is a wrapper for Engine.Handle. func Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Handle(httpMethod, relativePath, handlers...) } // POST is a shortcut for router.Handle("POST", path, handle) func POST(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().POST(relativePath, handlers...) } // GET is a shortcut for router.Handle("GET", path, handle) func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().GET(relativePath, handlers...) } // DELETE is a shortcut for router.Handle("DELETE", path, handle) func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().DELETE(relativePath, handlers...) } // PATCH is a shortcut for router.Handle("PATCH", path, handle) func PATCH(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PATCH(relativePath, handlers...) } // PUT is a shortcut for router.Handle("PUT", path, handle) func PUT(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PUT(relativePath, handlers...) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) func OPTIONS(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().OPTIONS(relativePath, handlers...) } // HEAD is a shortcut for router.Handle("HEAD", path, handle) func HEAD(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().HEAD(relativePath, handlers...) } // Any is a wrapper for Engine.Any. func Any(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Any(relativePath, handlers...) } // StaticFile is a wrapper for Engine.StaticFile. func StaticFile(relativePath, filepath string) gin.IRoutes { return engine().StaticFile(relativePath, filepath) } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // // router.Static("/static", "/var/www") func Static(relativePath, root string) gin.IRoutes { return engine().Static(relativePath, root) } // StaticFS is a wrapper for Engine.StaticFS. func StaticFS(relativePath string, fs http.FileSystem) gin.IRoutes { return engine().StaticFS(relativePath, fs) } // Use attaches a global middleware to the router. i.e. the middlewares attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func Use(middlewares ...gin.HandlerFunc) gin.IRoutes { return engine().Use(middlewares...) } // Routes returns a slice of registered routes. func Routes() gin.RoutesInfo { return engine().Routes() } // Run attaches to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func Run(addr ...string) (err error) { return engine().Run(addr...) } // RunTLS attaches to a http.Server and starts listening and serving HTTPS requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func RunTLS(addr, certFile, keyFile string) (err error) { return engine().RunTLS(addr, certFile, keyFile) } // RunUnix attaches to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file) // Note: this method will block the calling goroutine indefinitely unless an error happens. func RunUnix(file string) (err error) { return engine().RunUnix(file) } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: the method will block the calling goroutine indefinitely unless on error happens. func RunFd(fd int) (err error) { return engine().RunFd(fd) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./auth.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "crypto/subtle" "encoding/base64" "net/http" "strconv" "github.com/gin-gonic/gin/internal/bytesconv" ) // AuthUserKey is the cookie name for user credential in basic auth. const AuthUserKey = "user" // Accounts defines a key/value for user/pass list of authorized logins. type Accounts map[string]string type authPair struct { value string user string } type authPairs []authPair func (a authPairs) searchCredential(authValue string) (string, bool) { if authValue == "" { return "", false } for _, pair := range a { if subtle.ConstantTimeCompare(bytesconv.StringToBytes(pair.value), bytesconv.StringToBytes(authValue)) == 1 { return pair.user, true } } return "", false } // BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where // the key is the user name and the value is the password, as well as the name of the Realm. // If the realm is empty, "Authorization Required" will be used by default. // (see http://tools.ietf.org/html/rfc2617#section-1.2) func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { if realm == "" { realm = "Authorization Required" } realm = "Basic realm=" + strconv.Quote(realm) pairs := processAccounts(accounts) return func(c *Context) { // Search user in the slice of allowed credentials user, found := pairs.searchCredential(c.requestHeader("Authorization")) if !found { // Credentials doesn't match, we return 401 and abort handlers chain. c.Header("WWW-Authenticate", realm) c.AbortWithStatus(http.StatusUnauthorized) return } // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using // c.MustGet(gin.AuthUserKey). c.Set(AuthUserKey, user) } } // BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where // the key is the user name and the value is the password. func BasicAuth(accounts Accounts) HandlerFunc { return BasicAuthForRealm(accounts, "") } func processAccounts(accounts Accounts) authPairs { length := len(accounts) assert1(length > 0, "Empty list of authorized credentials") pairs := make(authPairs, 0, length) for user, password := range accounts { assert1(user != "", "User can not be empty") value := authorizationHeader(user, password) pairs = append(pairs, authPair{ value: value, user: user, }) } return pairs } func authorizationHeader(user, password string) string { base := user + ":" + password return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base)) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "crypto/subtle" "encoding/base64" "net/http" "strconv" "github.com/gin-gonic/gin/internal/bytesconv" ) // AuthUserKey is the cookie name for user credential in basic auth. const AuthUserKey = "user" // Accounts defines a key/value for user/pass list of authorized logins. type Accounts map[string]string type authPair struct { value string user string } type authPairs []authPair func (a authPairs) searchCredential(authValue string) (string, bool) { if authValue == "" { return "", false } for _, pair := range a { if subtle.ConstantTimeCompare(bytesconv.StringToBytes(pair.value), bytesconv.StringToBytes(authValue)) == 1 { return pair.user, true } } return "", false } // BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where // the key is the user name and the value is the password, as well as the name of the Realm. // If the realm is empty, "Authorization Required" will be used by default. // (see http://tools.ietf.org/html/rfc2617#section-1.2) func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { if realm == "" { realm = "Authorization Required" } realm = "Basic realm=" + strconv.Quote(realm) pairs := processAccounts(accounts) return func(c *Context) { // Search user in the slice of allowed credentials user, found := pairs.searchCredential(c.requestHeader("Authorization")) if !found { // Credentials doesn't match, we return 401 and abort handlers chain. c.Header("WWW-Authenticate", realm) c.AbortWithStatus(http.StatusUnauthorized) return } // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using // c.MustGet(gin.AuthUserKey). c.Set(AuthUserKey, user) } } // BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where // the key is the user name and the value is the password. func BasicAuth(accounts Accounts) HandlerFunc { return BasicAuthForRealm(accounts, "") } func processAccounts(accounts Accounts) authPairs { length := len(accounts) assert1(length > 0, "Empty list of authorized credentials") pairs := make(authPairs, 0, length) for user, password := range accounts { assert1(user != "", "User can not be empty") value := authorizationHeader(user, password) pairs = append(pairs, authPair{ value: value, user: user, }) } return pairs } func authorizationHeader(user, password string) string { base := user + ":" + password return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base)) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./render/html.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "html/template" "net/http" ) // Delims represents a set of Left and Right delimiters for HTML template rendering. type Delims struct { // Left delimiter, defaults to {{. Left string // Right delimiter, defaults to }}. Right string } // HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. type HTMLRender interface { // Instance returns an HTML instance. Instance(string, any) Render } // HTMLProduction contains template reference and its delims. type HTMLProduction struct { Template *template.Template Delims Delims } // HTMLDebug contains template delims and pattern and function with file list. type HTMLDebug struct { Files []string Glob string Delims Delims FuncMap template.FuncMap } // HTML contains template reference and its name with given interface object. type HTML struct { Template *template.Template Name string Data any } var htmlContentType = []string{"text/html; charset=utf-8"} // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ Template: r.Template, Name: name, Data: data, } } // Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. func (r HTMLDebug) Instance(name string, data any) Render { return HTML{ Template: r.loadTemplate(), Name: name, Data: data, } } func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} } if len(r.Files) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) } if r.Glob != "" { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) } panic("the HTML debug render was created without files or glob pattern") } // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) if r.Name == "" { return r.Template.Execute(w, r.Data) } return r.Template.ExecuteTemplate(w, r.Name, r.Data) } // WriteContentType (HTML) writes HTML ContentType. func (r HTML) WriteContentType(w http.ResponseWriter) { writeContentType(w, htmlContentType) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "html/template" "net/http" ) // Delims represents a set of Left and Right delimiters for HTML template rendering. type Delims struct { // Left delimiter, defaults to {{. Left string // Right delimiter, defaults to }}. Right string } // HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. type HTMLRender interface { // Instance returns an HTML instance. Instance(string, any) Render } // HTMLProduction contains template reference and its delims. type HTMLProduction struct { Template *template.Template Delims Delims } // HTMLDebug contains template delims and pattern and function with file list. type HTMLDebug struct { Files []string Glob string Delims Delims FuncMap template.FuncMap } // HTML contains template reference and its name with given interface object. type HTML struct { Template *template.Template Name string Data any } var htmlContentType = []string{"text/html; charset=utf-8"} // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ Template: r.Template, Name: name, Data: data, } } // Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. func (r HTMLDebug) Instance(name string, data any) Render { return HTML{ Template: r.loadTemplate(), Name: name, Data: data, } } func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} } if len(r.Files) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) } if r.Glob != "" { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) } panic("the HTML debug render was created without files or glob pattern") } // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) if r.Name == "" { return r.Template.Execute(w, r.Data) } return r.Template.ExecuteTemplate(w, r.Name, r.Data) } // WriteContentType (HTML) writes HTML ContentType. func (r HTML) WriteContentType(w http.ResponseWriter) { writeContentType(w, htmlContentType) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./testdata/protoexample/test.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.15.8 // source: test.proto package protoexample import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type FOO int32 const ( FOO_X FOO = 17 ) // Enum value maps for FOO. var ( FOO_name = map[int32]string{ 17: "X", } FOO_value = map[string]int32{ "X": 17, } ) func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FOO) Descriptor() protoreflect.EnumDescriptor { return file_test_proto_enumTypes[0].Descriptor() } func (FOO) Type() protoreflect.EnumType { return &file_test_proto_enumTypes[0] } func (x FOO) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FOO) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FOO(num) return nil } // Deprecated: Use FOO.Descriptor instead. func (FOO) EnumDescriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0} } type Test struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"` } // Default values for Test fields. const ( Default_Test_Type = int32(77) ) func (x *Test) Reset() { *x = Test{} if protoimpl.UnsafeEnabled { mi := &file_test_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Test) String() string { return protoimpl.X.MessageStringOf(x) } func (*Test) ProtoMessage() {} func (x *Test) ProtoReflect() protoreflect.Message { mi := &file_test_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Test.ProtoReflect.Descriptor instead. func (*Test) Descriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0} } func (x *Test) GetLabel() string { if x != nil && x.Label != nil { return *x.Label } return "" } func (x *Test) GetType() int32 { if x != nil && x.Type != nil { return *x.Type } return Default_Test_Type } func (x *Test) GetReps() []int64 { if x != nil { return x.Reps } return nil } func (x *Test) GetOptionalgroup() *Test_OptionalGroup { if x != nil { return x.Optionalgroup } return nil } type Test_OptionalGroup struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RequiredField *string `protobuf:"bytes,5,req,name=RequiredField" json:"RequiredField,omitempty"` } func (x *Test_OptionalGroup) Reset() { *x = Test_OptionalGroup{} if protoimpl.UnsafeEnabled { mi := &file_test_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Test_OptionalGroup) String() string { return protoimpl.X.MessageStringOf(x) } func (*Test_OptionalGroup) ProtoMessage() {} func (x *Test_OptionalGroup) ProtoReflect() protoreflect.Message { mi := &file_test_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Test_OptionalGroup.ProtoReflect.Descriptor instead. func (*Test_OptionalGroup) Descriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0, 0} } func (x *Test_OptionalGroup) GetRequiredField() string { if x != nil && x.RequiredField != nil { return *x.RequiredField } return "" } var File_test_proto protoreflect.FileDescriptor var file_test_proto_rawDesc = []byte{ 0x0a, 0x0a, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x22, 0xc7, 0x01, 0x0a, 0x04, 0x54, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x02, 0x28, 0x09, 0x52, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x16, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x3a, 0x02, 0x37, 0x37, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x65, 0x70, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x03, 0x52, 0x04, 0x72, 0x65, 0x70, 0x73, 0x12, 0x46, 0x0a, 0x0d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0a, 0x32, 0x20, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x2e, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x0d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x1a, 0x35, 0x0a, 0x0d, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x24, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x05, 0x20, 0x02, 0x28, 0x09, 0x52, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x2a, 0x0c, 0x0a, 0x03, 0x46, 0x4f, 0x4f, 0x12, 0x05, 0x0a, 0x01, 0x58, 0x10, 0x11, } var ( file_test_proto_rawDescOnce sync.Once file_test_proto_rawDescData = file_test_proto_rawDesc ) func file_test_proto_rawDescGZIP() []byte { file_test_proto_rawDescOnce.Do(func() { file_test_proto_rawDescData = protoimpl.X.CompressGZIP(file_test_proto_rawDescData) }) return file_test_proto_rawDescData } var file_test_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_test_proto_goTypes = []any{ (FOO)(0), // 0: protoexample.FOO (*Test)(nil), // 1: protoexample.Test (*Test_OptionalGroup)(nil), // 2: protoexample.Test.OptionalGroup } var file_test_proto_depIdxs = []int32{ 2, // 0: protoexample.Test.optionalgroup:type_name -> protoexample.Test.OptionalGroup 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_test_proto_init() } func file_test_proto_init() { if File_test_proto != nil { return } if !protoimpl.UnsafeEnabled { file_test_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*Test); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_test_proto_msgTypes[1].Exporter = func(v any, i int) any { switch v := v.(*Test_OptionalGroup); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_test_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_test_proto_goTypes, DependencyIndexes: file_test_proto_depIdxs, EnumInfos: file_test_proto_enumTypes, MessageInfos: file_test_proto_msgTypes, }.Build() File_test_proto = out.File file_test_proto_rawDesc = nil file_test_proto_goTypes = nil file_test_proto_depIdxs = nil }
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.15.8 // source: test.proto package protoexample import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type FOO int32 const ( FOO_X FOO = 17 ) // Enum value maps for FOO. var ( FOO_name = map[int32]string{ 17: "X", } FOO_value = map[string]int32{ "X": 17, } ) func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FOO) Descriptor() protoreflect.EnumDescriptor { return file_test_proto_enumTypes[0].Descriptor() } func (FOO) Type() protoreflect.EnumType { return &file_test_proto_enumTypes[0] } func (x FOO) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FOO) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FOO(num) return nil } // Deprecated: Use FOO.Descriptor instead. func (FOO) EnumDescriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0} } type Test struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"` } // Default values for Test fields. const ( Default_Test_Type = int32(77) ) func (x *Test) Reset() { *x = Test{} if protoimpl.UnsafeEnabled { mi := &file_test_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Test) String() string { return protoimpl.X.MessageStringOf(x) } func (*Test) ProtoMessage() {} func (x *Test) ProtoReflect() protoreflect.Message { mi := &file_test_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Test.ProtoReflect.Descriptor instead. func (*Test) Descriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0} } func (x *Test) GetLabel() string { if x != nil && x.Label != nil { return *x.Label } return "" } func (x *Test) GetType() int32 { if x != nil && x.Type != nil { return *x.Type } return Default_Test_Type } func (x *Test) GetReps() []int64 { if x != nil { return x.Reps } return nil } func (x *Test) GetOptionalgroup() *Test_OptionalGroup { if x != nil { return x.Optionalgroup } return nil } type Test_OptionalGroup struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RequiredField *string `protobuf:"bytes,5,req,name=RequiredField" json:"RequiredField,omitempty"` } func (x *Test_OptionalGroup) Reset() { *x = Test_OptionalGroup{} if protoimpl.UnsafeEnabled { mi := &file_test_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Test_OptionalGroup) String() string { return protoimpl.X.MessageStringOf(x) } func (*Test_OptionalGroup) ProtoMessage() {} func (x *Test_OptionalGroup) ProtoReflect() protoreflect.Message { mi := &file_test_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Test_OptionalGroup.ProtoReflect.Descriptor instead. func (*Test_OptionalGroup) Descriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0, 0} } func (x *Test_OptionalGroup) GetRequiredField() string { if x != nil && x.RequiredField != nil { return *x.RequiredField } return "" } var File_test_proto protoreflect.FileDescriptor var file_test_proto_rawDesc = []byte{ 0x0a, 0x0a, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x22, 0xc7, 0x01, 0x0a, 0x04, 0x54, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x02, 0x28, 0x09, 0x52, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x16, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x3a, 0x02, 0x37, 0x37, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x65, 0x70, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x03, 0x52, 0x04, 0x72, 0x65, 0x70, 0x73, 0x12, 0x46, 0x0a, 0x0d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0a, 0x32, 0x20, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x2e, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x0d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x1a, 0x35, 0x0a, 0x0d, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x24, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x05, 0x20, 0x02, 0x28, 0x09, 0x52, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x2a, 0x0c, 0x0a, 0x03, 0x46, 0x4f, 0x4f, 0x12, 0x05, 0x0a, 0x01, 0x58, 0x10, 0x11, } var ( file_test_proto_rawDescOnce sync.Once file_test_proto_rawDescData = file_test_proto_rawDesc ) func file_test_proto_rawDescGZIP() []byte { file_test_proto_rawDescOnce.Do(func() { file_test_proto_rawDescData = protoimpl.X.CompressGZIP(file_test_proto_rawDescData) }) return file_test_proto_rawDescData } var file_test_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_test_proto_goTypes = []any{ (FOO)(0), // 0: protoexample.FOO (*Test)(nil), // 1: protoexample.Test (*Test_OptionalGroup)(nil), // 2: protoexample.Test.OptionalGroup } var file_test_proto_depIdxs = []int32{ 2, // 0: protoexample.Test.optionalgroup:type_name -> protoexample.Test.OptionalGroup 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_test_proto_init() } func file_test_proto_init() { if File_test_proto != nil { return } if !protoimpl.UnsafeEnabled { file_test_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*Test); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_test_proto_msgTypes[1].Exporter = func(v any, i int) any { switch v := v.(*Test_OptionalGroup); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_test_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_test_proto_goTypes, DependencyIndexes: file_test_proto_depIdxs, EnumInfos: file_test_proto_enumTypes, MessageInfos: file_test_proto_msgTypes, }.Build() File_test_proto = out.File file_test_proto_rawDesc = nil file_test_proto_goTypes = nil file_test_proto_depIdxs = nil }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./internal/bytesconv/bytesconv.go
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package bytesconv import ( "unsafe" ) // StringToBytes converts string to byte slice without a memory allocation. func StringToBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer( &struct { string Cap int }{s, len(s)}, )) } // BytesToString converts byte slice to string without a memory allocation. func BytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) }
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package bytesconv import ( "unsafe" ) // StringToBytes converts string to byte slice without a memory allocation. func StringToBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer( &struct { string Cap int }{s, len(s)}, )) } // BytesToString converts byte slice to string without a memory allocation. func BytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./debug.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "runtime" "strconv" "strings" ) const ginSupportMinGoVer = 16 // IsDebugging returns true if the framework is running in debug mode. // Use SetMode(gin.ReleaseMode) to disable debug mode. func IsDebugging() bool { return ginMode == debugCode } // DebugPrintRouteFunc indicates debug log output format. var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int) func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) handlerName := nameOfFunction(handlers.Last()) if DebugPrintRouteFunc == nil { debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } else { DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) } } } func debugPrintLoadTemplate(tmpl *template.Template) { if IsDebugging() { var buf strings.Builder for _, tmpl := range tmpl.Templates() { buf.WriteString("\t- ") buf.WriteString(tmpl.Name()) buf.WriteString("\n") } debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) } } func debugPrint(format string, values ...any) { if IsDebugging() { if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) } } func getMinVer(v string) (uint64, error) { first := strings.IndexByte(v, '.') last := strings.LastIndexByte(v, '.') if first == last { return strconv.ParseUint(v[first+1:], 10, 64) } return strconv.ParseUint(v[first+1:last], 10, 64) } func debugPrintWARNINGDefault() { if v, e := getMinVer(runtime.Version()); e == nil && v < ginSupportMinGoVer { debugPrint(`[WARNING] Now Gin requires Go 1.16+. `) } debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. `) } func debugPrintWARNINGNew() { debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) `) } func debugPrintWARNINGSetHTMLTemplate() { debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization. ie. before any route is registered or the router is listening in a socket: router := gin.Default() router.SetHTMLTemplate(template) // << good place `) } func debugPrintError(err error) { if err != nil && IsDebugging() { fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) } }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "runtime" "strconv" "strings" ) const ginSupportMinGoVer = 16 // IsDebugging returns true if the framework is running in debug mode. // Use SetMode(gin.ReleaseMode) to disable debug mode. func IsDebugging() bool { return ginMode == debugCode } // DebugPrintRouteFunc indicates debug log output format. var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int) func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) handlerName := nameOfFunction(handlers.Last()) if DebugPrintRouteFunc == nil { debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } else { DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) } } } func debugPrintLoadTemplate(tmpl *template.Template) { if IsDebugging() { var buf strings.Builder for _, tmpl := range tmpl.Templates() { buf.WriteString("\t- ") buf.WriteString(tmpl.Name()) buf.WriteString("\n") } debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) } } func debugPrint(format string, values ...any) { if IsDebugging() { if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) } } func getMinVer(v string) (uint64, error) { first := strings.IndexByte(v, '.') last := strings.LastIndexByte(v, '.') if first == last { return strconv.ParseUint(v[first+1:], 10, 64) } return strconv.ParseUint(v[first+1:last], 10, 64) } func debugPrintWARNINGDefault() { if v, e := getMinVer(runtime.Version()); e == nil && v < ginSupportMinGoVer { debugPrint(`[WARNING] Now Gin requires Go 1.16+. `) } debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. `) } func debugPrintWARNINGNew() { debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) `) } func debugPrintWARNINGSetHTMLTemplate() { debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization. ie. before any route is registered or the router is listening in a socket: router := gin.Default() router.SetHTMLTemplate(template) // << good place `) } func debugPrintError(err error) { if err != nil && IsDebugging() { fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) } }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./recovery_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "net" "net/http" "os" "strings" "syscall" "testing" "github.com/stretchr/testify/assert" ) func TestPanicClean(t *testing.T) { buffer := new(bytes.Buffer) router := New() password := "my-super-secret-password" router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery", header{ Key: "Host", Value: "www.google.com", }, header{ Key: "Authorization", Value: fmt.Sprintf("Bearer %s", password), }, header{ Key: "Content-Type", Value: "application/json", }, ) // TEST assert.Equal(t, http.StatusBadRequest, w.Code) // Check the buffer does not have the secret key assert.NotContains(t, buffer.String(), password) } // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") SetMode(TestMode) } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) } func TestSource(t *testing.T) { bs := source(nil, 0) assert.Equal(t, dunno, bs) in := [][]byte{ []byte("Hello world."), []byte("Hi, gin.."), } bs = source(in, 10) assert.Equal(t, dunno, bs) bs = source(in, 1) assert.Equal(t, []byte("Hello world."), bs) } func TestFunction(t *testing.T) { bs := function(1) assert.Equal(t, dunno, bs) } // TestPanicWithBrokenPipe asserts that recovery specifically handles // writing responses to broken pipes func TestPanicWithBrokenPipe(t *testing.T) { const expectCode = 204 expectMsgs := map[syscall.Errno]string{ syscall.EPIPE: "broken pipe", syscall.ECONNRESET: "connection reset by peer", } for errno, expectMsg := range expectMsgs { t.Run(expectMsg, func(t *testing.T) { var buf bytes.Buffer router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Oops. Client connection closed e := &net.OpError{Err: &os.SyscallError{Err: errno}} panic(e) }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, expectCode, w.Code) assert.Contains(t, strings.ToLower(buf.String()), expectMsg) }) } } func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "net" "net/http" "os" "strings" "syscall" "testing" "github.com/stretchr/testify/assert" ) func TestPanicClean(t *testing.T) { buffer := new(bytes.Buffer) router := New() password := "my-super-secret-password" router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery", header{ Key: "Host", Value: "www.google.com", }, header{ Key: "Authorization", Value: fmt.Sprintf("Bearer %s", password), }, header{ Key: "Content-Type", Value: "application/json", }, ) // TEST assert.Equal(t, http.StatusBadRequest, w.Code) // Check the buffer does not have the secret key assert.NotContains(t, buffer.String(), password) } // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") SetMode(TestMode) } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) } func TestSource(t *testing.T) { bs := source(nil, 0) assert.Equal(t, dunno, bs) in := [][]byte{ []byte("Hello world."), []byte("Hi, gin.."), } bs = source(in, 10) assert.Equal(t, dunno, bs) bs = source(in, 1) assert.Equal(t, []byte("Hello world."), bs) } func TestFunction(t *testing.T) { bs := function(1) assert.Equal(t, dunno, bs) } // TestPanicWithBrokenPipe asserts that recovery specifically handles // writing responses to broken pipes func TestPanicWithBrokenPipe(t *testing.T) { const expectCode = 204 expectMsgs := map[syscall.Errno]string{ syscall.EPIPE: "broken pipe", syscall.ECONNRESET: "connection reset by peer", } for errno, expectMsg := range expectMsgs { t.Run(expectMsg, func(t *testing.T) { var buf bytes.Buffer router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Oops. Client connection closed e := &net.OpError{Err: &os.SyscallError{Err: errno}} panic(e) }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, expectCode, w.Code) assert.Contains(t, strings.ToLower(buf.String()), expectMsg) }) } } func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/form.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "net/http" ) const defaultMemory = 32 << 20 type formBinding struct{} type formPostBinding struct{} type formMultipartBinding struct{} func (formBinding) Name() string { return "form" } func (formBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) { return err } if err := mapForm(obj, req.Form); err != nil { return err } return validate(obj) } func (formPostBinding) Name() string { return "form-urlencoded" } func (formPostBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := mapForm(obj, req.PostForm); err != nil { return err } return validate(obj) } func (formMultipartBinding) Name() string { return "multipart/form-data" } func (formMultipartBinding) Bind(req *http.Request, obj any) error { if err := req.ParseMultipartForm(defaultMemory); err != nil { return err } if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { return err } return validate(obj) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "net/http" ) const defaultMemory = 32 << 20 type formBinding struct{} type formPostBinding struct{} type formMultipartBinding struct{} func (formBinding) Name() string { return "form" } func (formBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) { return err } if err := mapForm(obj, req.Form); err != nil { return err } return validate(obj) } func (formPostBinding) Name() string { return "form-urlencoded" } func (formPostBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := mapForm(obj, req.PostForm); err != nil { return err } return validate(obj) } func (formMultipartBinding) Name() string { return "multipart/form-data" } func (formMultipartBinding) Bind(req *http.Request, obj any) error { if err := req.ParseMultipartForm(defaultMemory); err != nil { return err } if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { return err } return validate(obj) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./internal/json/sonic.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build sonic && avx && (linux || windows || darwin) && amd64 // +build sonic // +build avx // +build linux windows darwin // +build amd64 package json import "github.com/bytedance/sonic" var ( json = sonic.ConfigStd // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build sonic && avx && (linux || windows || darwin) && amd64 // +build sonic // +build avx // +build linux windows darwin // +build amd64 package json import "github.com/bytedance/sonic" var ( json = sonic.ConfigStd // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/header.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "net/http" "net/textproto" "reflect" ) type headerBinding struct{} func (headerBinding) Name() string { return "header" } func (headerBinding) Bind(req *http.Request, obj any) error { if err := mapHeader(obj, req.Header); err != nil { return err } return validate(obj) } func mapHeader(ptr any, h map[string][]string) error { return mappingByPtr(ptr, headerSource(h), "header") } type headerSource map[string][]string var _ setter = headerSource(nil) func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (bool, error) { return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt) }
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "net/http" "net/textproto" "reflect" ) type headerBinding struct{} func (headerBinding) Name() string { return "header" } func (headerBinding) Bind(req *http.Request, obj any) error { if err := mapHeader(obj, req.Header); err != nil { return err } return validate(obj) } func mapHeader(ptr any, h map[string][]string) error { return mappingByPtr(ptr, headerSource(h), "header") } type headerSource map[string][]string var _ setter = headerSource(nil) func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (bool, error) { return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./test_helpers.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import "net/http" // CreateTestContext returns a fresh engine and context for testing purposes func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { r = New() c = r.allocateContext(0) c.reset() c.writermem.reset(w) return } // CreateTestContextOnly returns a fresh context base on the engine for testing purposes func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) { c = r.allocateContext(r.maxParams) c.reset() c.writermem.reset(w) return }
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import "net/http" // CreateTestContext returns a fresh engine and context for testing purposes func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { r = New() c = r.allocateContext(0) c.reset() c.writermem.reset(w) return } // CreateTestContextOnly returns a fresh context base on the engine for testing purposes func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) { c = r.allocateContext(r.maxParams) c.reset() c.writermem.reset(w) return }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./mode_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "flag" "os" "testing" "github.com/gin-gonic/gin/binding" "github.com/stretchr/testify/assert" ) func init() { os.Setenv(EnvGinMode, TestMode) } func TestSetMode(t *testing.T) { assert.Equal(t, testCode, ginMode) assert.Equal(t, TestMode, Mode()) os.Unsetenv(EnvGinMode) SetMode("") assert.Equal(t, testCode, ginMode) assert.Equal(t, TestMode, Mode()) tmp := flag.CommandLine flag.CommandLine = flag.NewFlagSet("", flag.ContinueOnError) SetMode("") assert.Equal(t, debugCode, ginMode) assert.Equal(t, DebugMode, Mode()) flag.CommandLine = tmp SetMode(DebugMode) assert.Equal(t, debugCode, ginMode) assert.Equal(t, DebugMode, Mode()) SetMode(ReleaseMode) assert.Equal(t, releaseCode, ginMode) assert.Equal(t, ReleaseMode, Mode()) SetMode(TestMode) assert.Equal(t, testCode, ginMode) assert.Equal(t, TestMode, Mode()) assert.Panics(t, func() { SetMode("unknown") }) } func TestDisableBindValidation(t *testing.T) { v := binding.Validator assert.NotNil(t, binding.Validator) DisableBindValidation() assert.Nil(t, binding.Validator) binding.Validator = v } func TestEnableJsonDecoderUseNumber(t *testing.T) { assert.False(t, binding.EnableDecoderUseNumber) EnableJsonDecoderUseNumber() assert.True(t, binding.EnableDecoderUseNumber) } func TestEnableJsonDecoderDisallowUnknownFields(t *testing.T) { assert.False(t, binding.EnableDecoderDisallowUnknownFields) EnableJsonDecoderDisallowUnknownFields() assert.True(t, binding.EnableDecoderDisallowUnknownFields) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "flag" "os" "testing" "github.com/gin-gonic/gin/binding" "github.com/stretchr/testify/assert" ) func init() { os.Setenv(EnvGinMode, TestMode) } func TestSetMode(t *testing.T) { assert.Equal(t, testCode, ginMode) assert.Equal(t, TestMode, Mode()) os.Unsetenv(EnvGinMode) SetMode("") assert.Equal(t, testCode, ginMode) assert.Equal(t, TestMode, Mode()) tmp := flag.CommandLine flag.CommandLine = flag.NewFlagSet("", flag.ContinueOnError) SetMode("") assert.Equal(t, debugCode, ginMode) assert.Equal(t, DebugMode, Mode()) flag.CommandLine = tmp SetMode(DebugMode) assert.Equal(t, debugCode, ginMode) assert.Equal(t, DebugMode, Mode()) SetMode(ReleaseMode) assert.Equal(t, releaseCode, ginMode) assert.Equal(t, ReleaseMode, Mode()) SetMode(TestMode) assert.Equal(t, testCode, ginMode) assert.Equal(t, TestMode, Mode()) assert.Panics(t, func() { SetMode("unknown") }) } func TestDisableBindValidation(t *testing.T) { v := binding.Validator assert.NotNil(t, binding.Validator) DisableBindValidation() assert.Nil(t, binding.Validator) binding.Validator = v } func TestEnableJsonDecoderUseNumber(t *testing.T) { assert.False(t, binding.EnableDecoderUseNumber) EnableJsonDecoderUseNumber() assert.True(t, binding.EnableDecoderUseNumber) } func TestEnableJsonDecoderDisallowUnknownFields(t *testing.T) { assert.False(t, binding.EnableDecoderDisallowUnknownFields) EnableJsonDecoderDisallowUnknownFields() assert.True(t, binding.EnableDecoderDisallowUnknownFields) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./errors.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "reflect" "strings" "github.com/gin-gonic/gin/internal/json" ) // ErrorType is an unsigned 64-bit error code as defined in the gin spec. type ErrorType uint64 const ( // ErrorTypeBind is used when Context.Bind() fails. ErrorTypeBind ErrorType = 1 << 63 // ErrorTypeRender is used when Context.Render() fails. ErrorTypeRender ErrorType = 1 << 62 // ErrorTypePrivate indicates a private error. ErrorTypePrivate ErrorType = 1 << 0 // ErrorTypePublic indicates a public error. ErrorTypePublic ErrorType = 1 << 1 // ErrorTypeAny indicates any other error. ErrorTypeAny ErrorType = 1<<64 - 1 // ErrorTypeNu indicates any other error. ErrorTypeNu = 2 ) // Error represents a error's specification. type Error struct { Err error Type ErrorType Meta any } type errorMsgs []*Error var _ error = (*Error)(nil) // SetType sets the error's type. func (msg *Error) SetType(flags ErrorType) *Error { msg.Type = flags return msg } // SetMeta sets the error's meta data. func (msg *Error) SetMeta(data any) *Error { msg.Meta = data return msg } // JSON creates a properly formatted JSON func (msg *Error) JSON() any { jsonData := H{} if msg.Meta != nil { value := reflect.ValueOf(msg.Meta) switch value.Kind() { case reflect.Struct: return msg.Meta case reflect.Map: for _, key := range value.MapKeys() { jsonData[key.String()] = value.MapIndex(key).Interface() } default: jsonData["meta"] = msg.Meta } } if _, ok := jsonData["error"]; !ok { jsonData["error"] = msg.Error() } return jsonData } // MarshalJSON implements the json.Marshaller interface. func (msg *Error) MarshalJSON() ([]byte, error) { return json.Marshal(msg.JSON()) } // Error implements the error interface. func (msg Error) Error() string { return msg.Err.Error() } // IsType judges one error. func (msg *Error) IsType(flags ErrorType) bool { return (msg.Type & flags) > 0 } // Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap() func (msg *Error) Unwrap() error { return msg.Err } // ByType returns a readonly copy filtered the byte. // ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic. func (a errorMsgs) ByType(typ ErrorType) errorMsgs { if len(a) == 0 { return nil } if typ == ErrorTypeAny { return a } var result errorMsgs for _, msg := range a { if msg.IsType(typ) { result = append(result, msg) } } return result } // Last returns the last error in the slice. It returns nil if the array is empty. // Shortcut for errors[len(errors)-1]. func (a errorMsgs) Last() *Error { if length := len(a); length > 0 { return a[length-1] } return nil } // Errors returns an array with all the error messages. // Example: // // c.Error(errors.New("first")) // c.Error(errors.New("second")) // c.Error(errors.New("third")) // c.Errors.Errors() // == []string{"first", "second", "third"} func (a errorMsgs) Errors() []string { if len(a) == 0 { return nil } errorStrings := make([]string, len(a)) for i, err := range a { errorStrings[i] = err.Error() } return errorStrings } func (a errorMsgs) JSON() any { switch length := len(a); length { case 0: return nil case 1: return a.Last().JSON() default: jsonData := make([]any, length) for i, err := range a { jsonData[i] = err.JSON() } return jsonData } } // MarshalJSON implements the json.Marshaller interface. func (a errorMsgs) MarshalJSON() ([]byte, error) { return json.Marshal(a.JSON()) } func (a errorMsgs) String() string { if len(a) == 0 { return "" } var buffer strings.Builder for i, msg := range a { fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err) if msg.Meta != nil { fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) } } return buffer.String() }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "reflect" "strings" "github.com/gin-gonic/gin/internal/json" ) // ErrorType is an unsigned 64-bit error code as defined in the gin spec. type ErrorType uint64 const ( // ErrorTypeBind is used when Context.Bind() fails. ErrorTypeBind ErrorType = 1 << 63 // ErrorTypeRender is used when Context.Render() fails. ErrorTypeRender ErrorType = 1 << 62 // ErrorTypePrivate indicates a private error. ErrorTypePrivate ErrorType = 1 << 0 // ErrorTypePublic indicates a public error. ErrorTypePublic ErrorType = 1 << 1 // ErrorTypeAny indicates any other error. ErrorTypeAny ErrorType = 1<<64 - 1 // ErrorTypeNu indicates any other error. ErrorTypeNu = 2 ) // Error represents a error's specification. type Error struct { Err error Type ErrorType Meta any } type errorMsgs []*Error var _ error = (*Error)(nil) // SetType sets the error's type. func (msg *Error) SetType(flags ErrorType) *Error { msg.Type = flags return msg } // SetMeta sets the error's meta data. func (msg *Error) SetMeta(data any) *Error { msg.Meta = data return msg } // JSON creates a properly formatted JSON func (msg *Error) JSON() any { jsonData := H{} if msg.Meta != nil { value := reflect.ValueOf(msg.Meta) switch value.Kind() { case reflect.Struct: return msg.Meta case reflect.Map: for _, key := range value.MapKeys() { jsonData[key.String()] = value.MapIndex(key).Interface() } default: jsonData["meta"] = msg.Meta } } if _, ok := jsonData["error"]; !ok { jsonData["error"] = msg.Error() } return jsonData } // MarshalJSON implements the json.Marshaller interface. func (msg *Error) MarshalJSON() ([]byte, error) { return json.Marshal(msg.JSON()) } // Error implements the error interface. func (msg Error) Error() string { return msg.Err.Error() } // IsType judges one error. func (msg *Error) IsType(flags ErrorType) bool { return (msg.Type & flags) > 0 } // Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap() func (msg *Error) Unwrap() error { return msg.Err } // ByType returns a readonly copy filtered the byte. // ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic. func (a errorMsgs) ByType(typ ErrorType) errorMsgs { if len(a) == 0 { return nil } if typ == ErrorTypeAny { return a } var result errorMsgs for _, msg := range a { if msg.IsType(typ) { result = append(result, msg) } } return result } // Last returns the last error in the slice. It returns nil if the array is empty. // Shortcut for errors[len(errors)-1]. func (a errorMsgs) Last() *Error { if length := len(a); length > 0 { return a[length-1] } return nil } // Errors returns an array with all the error messages. // Example: // // c.Error(errors.New("first")) // c.Error(errors.New("second")) // c.Error(errors.New("third")) // c.Errors.Errors() // == []string{"first", "second", "third"} func (a errorMsgs) Errors() []string { if len(a) == 0 { return nil } errorStrings := make([]string, len(a)) for i, err := range a { errorStrings[i] = err.Error() } return errorStrings } func (a errorMsgs) JSON() any { switch length := len(a); length { case 0: return nil case 1: return a.Last().JSON() default: jsonData := make([]any, length) for i, err := range a { jsonData[i] = err.JSON() } return jsonData } } // MarshalJSON implements the json.Marshaller interface. func (a errorMsgs) MarshalJSON() ([]byte, error) { return json.Marshal(a.JSON()) } func (a errorMsgs) String() string { if len(a) == 0 { return "" } var buffer strings.Builder for i, msg := range a { fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err) if msg.Meta != nil { fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) } } return buffer.String() }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/xml_test.go
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestXMLBindingBindBody(t *testing.T) { var s struct { Foo string `xml:"foo"` } xmlBody := `<?xml version="1.0" encoding="UTF-8"?> <root> <foo>FOO</foo> </root>` err := xmlBinding{}.BindBody([]byte(xmlBody), &s) require.NoError(t, err) assert.Equal(t, "FOO", s.Foo) }
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestXMLBindingBindBody(t *testing.T) { var s struct { Foo string `xml:"foo"` } xmlBody := `<?xml version="1.0" encoding="UTF-8"?> <root> <foo>FOO</foo> </root>` err := xmlBinding{}.BindBody([]byte(xmlBody), &s) require.NoError(t, err) assert.Equal(t, "FOO", s.Foo) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./response_writer.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bufio" "io" "net" "net/http" ) const ( noWritten = -1 defaultStatus = http.StatusOK ) // ResponseWriter ... type ResponseWriter interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // Status returns the HTTP response status code of the current request. Status() int // Size returns the number of bytes already written into the response http body. // See Written() Size() int // WriteString writes the string into the response body. WriteString(string) (int, error) // Written returns true if the response body was already written. Written() bool // WriteHeaderNow forces to write the http header (status code + headers). WriteHeaderNow() // Pusher get the http.Pusher for server push Pusher() http.Pusher } type responseWriter struct { http.ResponseWriter size int status int } var _ ResponseWriter = (*responseWriter)(nil) func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer w.size = noWritten w.status = defaultStatus } func (w *responseWriter) WriteHeader(code int) { if code > 0 && w.status != code { if w.Written() { debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) } w.status = code } } func (w *responseWriter) WriteHeaderNow() { if !w.Written() { w.size = 0 w.ResponseWriter.WriteHeader(w.status) } } func (w *responseWriter) Write(data []byte) (n int, err error) { w.WriteHeaderNow() n, err = w.ResponseWriter.Write(data) w.size += n return } func (w *responseWriter) WriteString(s string) (n int, err error) { w.WriteHeaderNow() n, err = io.WriteString(w.ResponseWriter, s) w.size += n return } func (w *responseWriter) Status() int { return w.status } func (w *responseWriter) Size() int { return w.size } func (w *responseWriter) Written() bool { return w.size != noWritten } // Hijack implements the http.Hijacker interface. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() } // CloseNotify implements the http.CloseNotifier interface. func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Flush implements the http.Flusher interface. func (w *responseWriter) Flush() { w.WriteHeaderNow() w.ResponseWriter.(http.Flusher).Flush() } func (w *responseWriter) Pusher() (pusher http.Pusher) { if pusher, ok := w.ResponseWriter.(http.Pusher); ok { return pusher } return nil }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bufio" "io" "net" "net/http" ) const ( noWritten = -1 defaultStatus = http.StatusOK ) // ResponseWriter ... type ResponseWriter interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // Status returns the HTTP response status code of the current request. Status() int // Size returns the number of bytes already written into the response http body. // See Written() Size() int // WriteString writes the string into the response body. WriteString(string) (int, error) // Written returns true if the response body was already written. Written() bool // WriteHeaderNow forces to write the http header (status code + headers). WriteHeaderNow() // Pusher get the http.Pusher for server push Pusher() http.Pusher } type responseWriter struct { http.ResponseWriter size int status int } var _ ResponseWriter = (*responseWriter)(nil) func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer w.size = noWritten w.status = defaultStatus } func (w *responseWriter) WriteHeader(code int) { if code > 0 && w.status != code { if w.Written() { debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) } w.status = code } } func (w *responseWriter) WriteHeaderNow() { if !w.Written() { w.size = 0 w.ResponseWriter.WriteHeader(w.status) } } func (w *responseWriter) Write(data []byte) (n int, err error) { w.WriteHeaderNow() n, err = w.ResponseWriter.Write(data) w.size += n return } func (w *responseWriter) WriteString(s string) (n int, err error) { w.WriteHeaderNow() n, err = io.WriteString(w.ResponseWriter, s) w.size += n return } func (w *responseWriter) Status() int { return w.status } func (w *responseWriter) Size() int { return w.size } func (w *responseWriter) Written() bool { return w.size != noWritten } // Hijack implements the http.Hijacker interface. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() } // CloseNotify implements the http.CloseNotifier interface. func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Flush implements the http.Flusher interface. func (w *responseWriter) Flush() { w.WriteHeaderNow() w.ResponseWriter.(http.Flusher).Flush() } func (w *responseWriter) Pusher() (pusher http.Pusher) { if pusher, ok := w.ResponseWriter.(http.Pusher); ok { return pusher } return nil }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/uri.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding type uriBinding struct{} func (uriBinding) Name() string { return "uri" } func (uriBinding) BindUri(m map[string][]string, obj any) error { if err := mapURI(obj, m); err != nil { return err } return validate(obj) }
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding type uriBinding struct{} func (uriBinding) Name() string { return "uri" } func (uriBinding) BindUri(m map[string][]string, obj any) error { if err := mapURI(obj, m); err != nil { return err } return validate(obj) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./internal/bytesconv/bytesconv_test.go
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package bytesconv import ( "bytes" "math/rand" "strings" "testing" "time" ) var testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere." var testBytes = []byte(testString) func rawBytesToStr(b []byte) string { return string(b) } func rawStrToBytes(s string) []byte { return []byte(s) } // go test -v func TestBytesToString(t *testing.T) { data := make([]byte, 1024) for i := 0; i < 100; i++ { rand.Read(data) if rawBytesToStr(data) != BytesToString(data) { t.Fatal("don't match") } } } const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const ( letterIdxBits = 6 // 6 bits to represent a letter index letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits ) var src = rand.NewSource(time.Now().UnixNano()) func RandStringBytesMaskImprSrcSB(n int) string { sb := strings.Builder{} sb.Grow(n) // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { if remain == 0 { cache, remain = src.Int63(), letterIdxMax } if idx := int(cache & letterIdxMask); idx < len(letterBytes) { sb.WriteByte(letterBytes[idx]) i-- } cache >>= letterIdxBits remain-- } return sb.String() } func TestStringToBytes(t *testing.T) { for i := 0; i < 100; i++ { s := RandStringBytesMaskImprSrcSB(64) if !bytes.Equal(rawStrToBytes(s), StringToBytes(s)) { t.Fatal("don't match") } } } // go test -v -run=none -bench=^BenchmarkBytesConv -benchmem=true func BenchmarkBytesConvBytesToStrRaw(b *testing.B) { for i := 0; i < b.N; i++ { rawBytesToStr(testBytes) } } func BenchmarkBytesConvBytesToStr(b *testing.B) { for i := 0; i < b.N; i++ { BytesToString(testBytes) } } func BenchmarkBytesConvStrToBytesRaw(b *testing.B) { for i := 0; i < b.N; i++ { rawStrToBytes(testString) } } func BenchmarkBytesConvStrToBytes(b *testing.B) { for i := 0; i < b.N; i++ { StringToBytes(testString) } }
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package bytesconv import ( "bytes" "math/rand" "strings" "testing" "time" ) var testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere." var testBytes = []byte(testString) func rawBytesToStr(b []byte) string { return string(b) } func rawStrToBytes(s string) []byte { return []byte(s) } // go test -v func TestBytesToString(t *testing.T) { data := make([]byte, 1024) for i := 0; i < 100; i++ { rand.Read(data) if rawBytesToStr(data) != BytesToString(data) { t.Fatal("don't match") } } } const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const ( letterIdxBits = 6 // 6 bits to represent a letter index letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits ) var src = rand.NewSource(time.Now().UnixNano()) func RandStringBytesMaskImprSrcSB(n int) string { sb := strings.Builder{} sb.Grow(n) // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { if remain == 0 { cache, remain = src.Int63(), letterIdxMax } if idx := int(cache & letterIdxMask); idx < len(letterBytes) { sb.WriteByte(letterBytes[idx]) i-- } cache >>= letterIdxBits remain-- } return sb.String() } func TestStringToBytes(t *testing.T) { for i := 0; i < 100; i++ { s := RandStringBytesMaskImprSrcSB(64) if !bytes.Equal(rawStrToBytes(s), StringToBytes(s)) { t.Fatal("don't match") } } } // go test -v -run=none -bench=^BenchmarkBytesConv -benchmem=true func BenchmarkBytesConvBytesToStrRaw(b *testing.B) { for i := 0; i < b.N; i++ { rawBytesToStr(testBytes) } } func BenchmarkBytesConvBytesToStr(b *testing.B) { for i := 0; i < b.N; i++ { BytesToString(testBytes) } } func BenchmarkBytesConvStrToBytesRaw(b *testing.B) { for i := 0; i < b.N; i++ { rawStrToBytes(testString) } } func BenchmarkBytesConvStrToBytes(b *testing.B) { for i := 0; i < b.N; i++ { StringToBytes(testString) } }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./mode.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "flag" "io" "os" "github.com/gin-gonic/gin/binding" ) // EnvGinMode indicates environment name for gin mode. const EnvGinMode = "GIN_MODE" const ( // DebugMode indicates gin mode is debug. DebugMode = "debug" // ReleaseMode indicates gin mode is release. ReleaseMode = "release" // TestMode indicates gin mode is test. TestMode = "test" ) const ( debugCode = iota releaseCode testCode ) // DefaultWriter is the default io.Writer used by Gin for debug output and // middleware output like Logger() or Recovery(). // Note that both Logger and Recovery provides custom ways to configure their // output io.Writer. // To support coloring in Windows use: // // import "github.com/mattn/go-colorable" // gin.DefaultWriter = colorable.NewColorableStdout() var DefaultWriter io.Writer = os.Stdout // DefaultErrorWriter is the default io.Writer used by Gin to debug errors var DefaultErrorWriter io.Writer = os.Stderr var ( ginMode = debugCode modeName = DebugMode ) func init() { mode := os.Getenv(EnvGinMode) SetMode(mode) } // SetMode sets gin mode according to input string. func SetMode(value string) { if value == "" { if flag.Lookup("test.v") != nil { value = TestMode } else { value = DebugMode } } switch value { case DebugMode: ginMode = debugCode case ReleaseMode: ginMode = releaseCode case TestMode: ginMode = testCode default: panic("gin mode unknown: " + value + " (available mode: debug release test)") } modeName = value } // DisableBindValidation closes the default validator. func DisableBindValidation() { binding.Validator = nil } // EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to // call the UseNumber method on the JSON Decoder instance. func EnableJsonDecoderUseNumber() { binding.EnableDecoderUseNumber = true } // EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to // call the DisallowUnknownFields method on the JSON Decoder instance. func EnableJsonDecoderDisallowUnknownFields() { binding.EnableDecoderDisallowUnknownFields = true } // Mode returns current gin mode. func Mode() string { return modeName }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "flag" "io" "os" "github.com/gin-gonic/gin/binding" ) // EnvGinMode indicates environment name for gin mode. const EnvGinMode = "GIN_MODE" const ( // DebugMode indicates gin mode is debug. DebugMode = "debug" // ReleaseMode indicates gin mode is release. ReleaseMode = "release" // TestMode indicates gin mode is test. TestMode = "test" ) const ( debugCode = iota releaseCode testCode ) // DefaultWriter is the default io.Writer used by Gin for debug output and // middleware output like Logger() or Recovery(). // Note that both Logger and Recovery provides custom ways to configure their // output io.Writer. // To support coloring in Windows use: // // import "github.com/mattn/go-colorable" // gin.DefaultWriter = colorable.NewColorableStdout() var DefaultWriter io.Writer = os.Stdout // DefaultErrorWriter is the default io.Writer used by Gin to debug errors var DefaultErrorWriter io.Writer = os.Stderr var ( ginMode = debugCode modeName = DebugMode ) func init() { mode := os.Getenv(EnvGinMode) SetMode(mode) } // SetMode sets gin mode according to input string. func SetMode(value string) { if value == "" { if flag.Lookup("test.v") != nil { value = TestMode } else { value = DebugMode } } switch value { case DebugMode: ginMode = debugCode case ReleaseMode: ginMode = releaseCode case TestMode: ginMode = testCode default: panic("gin mode unknown: " + value + " (available mode: debug release test)") } modeName = value } // DisableBindValidation closes the default validator. func DisableBindValidation() { binding.Validator = nil } // EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to // call the UseNumber method on the JSON Decoder instance. func EnableJsonDecoderUseNumber() { binding.EnableDecoderUseNumber = true } // EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to // call the DisallowUnknownFields method on the JSON Decoder instance. func EnableJsonDecoderDisallowUnknownFields() { binding.EnableDecoderDisallowUnknownFields = true } // Mode returns current gin mode. func Mode() string { return modeName }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./debug_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "html/template" "io" "log" "os" "runtime" "sync" "testing" "github.com/stretchr/testify/assert" ) // TODO // func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) { // func debugPrint(format string, values ...interface{}) { func TestIsDebugging(t *testing.T) { SetMode(DebugMode) assert.True(t, IsDebugging()) SetMode(ReleaseMode) assert.False(t, IsDebugging()) SetMode(TestMode) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) debugPrint("DEBUG this!") SetMode(DebugMode) debugPrint("these are %d %s", 2, "error messages") SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] these are 2 error messages\n", re) } func TestDebugPrintError(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintError(nil) debugPrintError(errors.New("this is an error")) SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [ERROR] this is an error\n", re) } func TestDebugPrintRoutes(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintRouteFunc(t *testing.T) { DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintLoadTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl")) debugPrintLoadTemplate(templ) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] Loaded HTML Templates \(2\): \n(\t- \n|\t- hello\.tmpl\n){2}\n`, re) } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGSetHTMLTemplate() SetMode(TestMode) }) 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", re) } func TestDebugPrintWARNINGDefault(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) m, e := getMinVer(runtime.Version()) if e == nil && m < ginSupportMinGoVer { assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.16+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } else { assert.Equal(t, "[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } } func TestDebugPrintWARNINGNew(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGNew() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n", re) } func captureOutput(t *testing.T, f func()) string { reader, writer, err := os.Pipe() if err != nil { panic(err) } defaultWriter := DefaultWriter defaultErrorWriter := DefaultErrorWriter defer func() { DefaultWriter = defaultWriter DefaultErrorWriter = defaultErrorWriter log.SetOutput(os.Stderr) }() DefaultWriter = writer DefaultErrorWriter = writer log.SetOutput(writer) out := make(chan string) wg := new(sync.WaitGroup) wg.Add(1) go func() { var buf bytes.Buffer wg.Done() _, err := io.Copy(&buf, reader) assert.NoError(t, err) out <- buf.String() }() wg.Wait() f() writer.Close() return <-out } func TestGetMinVer(t *testing.T) { var m uint64 var e error _, e = getMinVer("go1") assert.NotNil(t, e) m, e = getMinVer("go1.1") assert.Equal(t, uint64(1), m) assert.Nil(t, e) m, e = getMinVer("go1.1.1") assert.Nil(t, e) assert.Equal(t, uint64(1), m) _, e = getMinVer("go1.1.1.1") assert.NotNil(t, e) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "html/template" "io" "log" "os" "runtime" "sync" "testing" "github.com/stretchr/testify/assert" ) // TODO // func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) { // func debugPrint(format string, values ...interface{}) { func TestIsDebugging(t *testing.T) { SetMode(DebugMode) assert.True(t, IsDebugging()) SetMode(ReleaseMode) assert.False(t, IsDebugging()) SetMode(TestMode) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) debugPrint("DEBUG this!") SetMode(DebugMode) debugPrint("these are %d %s", 2, "error messages") SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] these are 2 error messages\n", re) } func TestDebugPrintError(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintError(nil) debugPrintError(errors.New("this is an error")) SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [ERROR] this is an error\n", re) } func TestDebugPrintRoutes(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintRouteFunc(t *testing.T) { DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintLoadTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl")) debugPrintLoadTemplate(templ) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] Loaded HTML Templates \(2\): \n(\t- \n|\t- hello\.tmpl\n){2}\n`, re) } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGSetHTMLTemplate() SetMode(TestMode) }) 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", re) } func TestDebugPrintWARNINGDefault(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) m, e := getMinVer(runtime.Version()) if e == nil && m < ginSupportMinGoVer { assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.16+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } else { assert.Equal(t, "[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } } func TestDebugPrintWARNINGNew(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGNew() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n", re) } func captureOutput(t *testing.T, f func()) string { reader, writer, err := os.Pipe() if err != nil { panic(err) } defaultWriter := DefaultWriter defaultErrorWriter := DefaultErrorWriter defer func() { DefaultWriter = defaultWriter DefaultErrorWriter = defaultErrorWriter log.SetOutput(os.Stderr) }() DefaultWriter = writer DefaultErrorWriter = writer log.SetOutput(writer) out := make(chan string) wg := new(sync.WaitGroup) wg.Add(1) go func() { var buf bytes.Buffer wg.Done() _, err := io.Copy(&buf, reader) assert.NoError(t, err) out <- buf.String() }() wg.Wait() f() writer.Close() return <-out } func TestGetMinVer(t *testing.T) { var m uint64 var e error _, e = getMinVer("go1") assert.NotNil(t, e) m, e = getMinVer("go1.1") assert.Equal(t, uint64(1), m) assert.Nil(t, e) m, e = getMinVer("go1.1.1") assert.Nil(t, e) assert.Equal(t, uint64(1), m) _, e = getMinVer("go1.1.1.1") assert.NotNil(t, e) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.git/objects/pack/pack-6fe8e468585f639e05261af0171719bb51d0471c.idx
tOc =^y1Ry#5Jq3H`z6Ndv=Xz 9Po;]y(Ch  8 S t  < Z o  3 N j   = Y s  D h %He6To!DUn/Lg2Jg}1M`7Qh4H^w#>Th!=Xs:Tx$;\ *GZ>Rj%@d'iC"IjZ d,\PC6Sj D)e%7#}<wf97P5}_x<tA02Q-$-gDt`:Q##|VkɇQK, 0;;8kN۶\(Mi>OLkZiyMhnwoG=gf' nilkOtJ^Iy(/*hd8({JQ0Ӟ}uQO؄yP];)UU'yKIE4Whм0fkYk(wuR`JqW=UN:z-]75ޫbCx9V~[aPT֣@PJEQK798E#XG& 각:+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% )hh /L?VߗՀ09No+ J'hJ!  W [Qs(-J (/l 5 uk+O~O2 /j%`V  @aF 1z2 R"9x]Q""!2n%J+^.Q}tvG.d M UŅ ,4 a"-t0/ "* (|^F 8%Sgi*!}X// IZ%#!!@J".A].t H Y."%S> =|Z+zww0jsk) //-2;+dF ?T >-tb'04YQI#* p( q0z+ IaF^'" n"Y0c Lf0+Mp0 y#?_"s/X m+h,>+*!0aCyOOn&~7!: *e} He#% #@q0c+v- ij,n#(P\ ~-09;#*7)7+9<CPL ,\"'~ ?J#4+!0yQ!O&W Ü q?P' 'KK(צ!P)vY$%%,$gk.-H!%O.]N. @ѝ_Sl! OM')ݜ"N(UQ* "~0$4K;rN&0mA"%#f- ~ q' +v+0 ( (w!yxW lH'M O7' /E Dߢ&i5,>9 ~: (?R I!fS$s n+ .t/~(]ZkXB  ] ~!ۈ" %e%K&|C"qF+]/E90"L]|'Ks܊+!&a %&0Zک"}L]-D N%/lccM0(pHk%g% &OiQ"o05"l *w8b7מA})!!;6/x.x  KCn!U@<#++Q0YR/F0 hNW"ol"/( pcylwkx"-}-/ Jh d_xMmvN,+ 9/4,j}TohX_c&QG_&>2 ϔ<@A
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./CONTRIBUTING.md
## Contributing - With issues: - Use the search tool before opening a new issue. - Please provide source code and commit sha if you found a bug. - Review existing issues and provide feedback or react to them. - With pull requests: - Open your pull request against `master` - Your pull request should have no more than two commits, if not you should squash them. - It should pass all tests in the available continuous integration systems such as GitHub Actions. - You should add/modify tests to cover your proposed code changes. - If your pull request contains a new feature, please document it on the README.
## Contributing - With issues: - Use the search tool before opening a new issue. - Please provide source code and commit sha if you found a bug. - Review existing issues and provide feedback or react to them. - With pull requests: - Open your pull request against `master` - Your pull request should have no more than two commits, if not you should squash them. - It should pass all tests in the available continuous integration systems such as GitHub Actions. - You should add/modify tests to cover your proposed code changes. - If your pull request contains a new feature, please document it on the README.
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./any.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package gin type any = interface{}
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package gin type any = interface{}
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/msgpack.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package binding import ( "bytes" "io" "net/http" "github.com/ugorji/go/codec" ) type msgpackBinding struct{} func (msgpackBinding) Name() string { return "msgpack" } func (msgpackBinding) Bind(req *http.Request, obj any) error { return decodeMsgPack(req.Body, obj) } func (msgpackBinding) BindBody(body []byte, obj any) error { return decodeMsgPack(bytes.NewReader(body), obj) } func decodeMsgPack(r io.Reader, obj any) error { cdc := new(codec.MsgpackHandle) if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil { return err } return validate(obj) }
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package binding import ( "bytes" "io" "net/http" "github.com/ugorji/go/codec" ) type msgpackBinding struct{} func (msgpackBinding) Name() string { return "msgpack" } func (msgpackBinding) Bind(req *http.Request, obj any) error { return decodeMsgPack(req.Body, obj) } func (msgpackBinding) BindBody(body []byte, obj any) error { return decodeMsgPack(bytes.NewReader(body), obj) } func decodeMsgPack(r io.Reader, obj any) error { cdc := new(codec.MsgpackHandle) if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil { return err } return validate(obj) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./testdata/certificate/key.pem
-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAqbKP9hmkPn0GnLjDep/pXMzD25QGxan4g/iSXvPlyYYdhQef 9iilMse9HbcYAHXanoqblBbMIG4kXiPrU8lcd+Df+uNKFnvslxDeTPG7LWIoMj4M 0o3sqXOt2Mnj1APSVzNkd4G+8IvsmwkUoWMbLraudK25bwtogR22NdP4ZRlPEmHo bvI9h8MxLUix0xAY51sbA1r6qiAy5A+HRPMfD4LvebIquNjqlESKOScwL+ucgzP1 0s+3oqXFfLhuvjjd2ljp1gYiEO4qFE5P69nTkcpqy65BQWFju/8qhSkRkwH2t9RL ONDl9qR4NQAyeJdFx34ObC9ugbZMjqLGa48r4QIDAQABAoIBAD5mhd+GMEo2KU9J 9b/Ku8I/HapJtW/L/7Fvn0tBPncrVQGM+zpGWfDhV95sbGwG6lwwNeNvuqIWPlNL vAY0XkdKrrIQEDdSXH50WnpKzXxzwrou7QIj5Cmvevbjzl4xBZDBOilj0XWczmV4 IljyG5XC4UXQeAaoWEZaSZ1jk8yAt2Zq1Hgg7HqhHsK/arWXBgax+4K5nV/s9gZx yjKU9mXTIs7k/aNnZqwQKqcZF+l3mvbZttOaFwsP14H0I8OFW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b9qq4XGFBGYMLaMg+XbUVxNKEuvUdnwa4R7aZ9EfN34MwekkfA w5Cu9/GGG1ajVEfGA6PwBQKBgA3o71jGs8KFXOx7e90sivOTU5Z5fc6LTHNB0Rf7 NcJ5GmCPWRY/KZfb25AoE4B8GKDRMNt+X69zxZeZJ1KrU0rqxA02rlhyHB54gnoE G/4xMkn6/JkOC0w70PMhMBtohC7YzFOQwQEoNPT0nkno3Pl33xSLS6lPlwBo1JVj nPtZAoGACXNLXYkR5vexE+w6FGl59r4RQhu1XU8Mr5DIHeB7kXPN3RKbS201M+Tb SB5jbu0iDV477XkzSNmhaksFf2wM9MT6CaE+8n3UU5tMa+MmBGgwYTp/i9HkqVh5 jjpJifn1VWBINd4cpNzwCg9LXoo0tbtUPWwGzqVeyo/YE5GIHGo= -----END RSA PRIVATE KEY-----
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.github/ISSUE_TEMPLATE.md
- With issues: - Use the search tool before opening a new issue. - Please provide source code and commit sha if you found a bug. - Review existing issues and provide feedback or react to them. ## Description <!-- Description of a problem --> ## How to reproduce <!-- The smallest possible code example to show the problem that can be compiled, like --> ``` package main import ( "github.com/gin-gonic/gin" ) func main() { g := gin.Default() g.GET("/hello/:name", func(c *gin.Context) { c.String(200, "Hello %s", c.Param("name")) }) g.Run(":9000") } ``` ## Expectations <!-- Your expectation result of 'curl' command, like --> ``` $ curl http://localhost:8201/hello/world Hello world ``` ## Actual result <!-- Actual result showing the problem --> ``` $ curl -i http://localhost:8201/hello/world <YOUR RESULT> ``` ## Environment - go version: - gin version (or commit ref): - operating system:
- With issues: - Use the search tool before opening a new issue. - Please provide source code and commit sha if you found a bug. - Review existing issues and provide feedback or react to them. ## Description <!-- Description of a problem --> ## How to reproduce <!-- The smallest possible code example to show the problem that can be compiled, like --> ``` package main import ( "github.com/gin-gonic/gin" ) func main() { g := gin.Default() g.GET("/hello/:name", func(c *gin.Context) { c.String(200, "Hello %s", c.Param("name")) }) g.Run(":9000") } ``` ## Expectations <!-- Your expectation result of 'curl' command, like --> ``` $ curl http://localhost:8201/hello/world Hello world ``` ## Actual result <!-- Actual result showing the problem --> ``` $ curl -i http://localhost:8201/hello/world <YOUR RESULT> ``` ## Environment - go version: - gin version (or commit ref): - operating system:
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./testdata/certificate/cert.pem
-----BEGIN CERTIFICATE----- MIIC9DCCAdygAwIBAgIQUNSK+OxWHYYFxHVJV0IlpDANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMB4XDTE3MTExNjEyMDA0N1oXDTE4MTExNjEyMDA0 N1owEjEQMA4GA1UEChMHQWNtZSBDbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBAKmyj/YZpD59Bpy4w3qf6VzMw9uUBsWp+IP4kl7z5cmGHYUHn/YopTLH vR23GAB12p6Km5QWzCBuJF4j61PJXHfg3/rjShZ77JcQ3kzxuy1iKDI+DNKN7Klz rdjJ49QD0lczZHeBvvCL7JsJFKFjGy62rnStuW8LaIEdtjXT+GUZTxJh6G7yPYfD MS1IsdMQGOdbGwNa+qogMuQPh0TzHw+C73myKrjY6pREijknMC/rnIMz9dLPt6Kl xXy4br443dpY6dYGIhDuKhROT+vZ05HKasuuQUFhY7v/KoUpEZMB9rfUSzjQ5fak eDUAMniXRcd+DmwvboG2TI6ixmuPK+ECAwEAAaNGMEQwDgYDVR0PAQH/BAQDAgWg MBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwG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wAAATANBgkqhkiG9w0BAQsFAAOCAQEAMXOLvj7BFsxdbcfRPBd0OFrH/8lI7vPV LRcJ6r5iv0cnNvZXXbIOQLbg4clJAWjoE08nRm1KvNXhKdns0ELEV86YN2S6jThq rIGrBqKtaJLB3M9BtDSiQ6SGPLYrWvmhj3Avi8PbSGy51bpGbqopd16j6LYU7Cp2 TefMRlOAFtHojpCVon1CMpqcNxS0WNlQ3lUBSrw3HB0o12x++roja2ibF54tSHXB KUuadoEzN+mMBwenEBychmAGzdiG4GQHRmhigh85+mtW6UMGiqyCZHs0EgE9FCLL sRrsTI/VOzLz6lluygXkOsXrP+PP0SvmE3eylWjj9e2nj/u/Cy2YKg== -----END CERTIFICATE-----
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./render/reader.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "io" "net/http" "strconv" ) // Reader contains the IO reader and its length, and custom ContentType and other headers. type Reader struct { ContentType string ContentLength int64 Reader io.Reader Headers map[string]string } // Render (Reader) writes data with custom ContentType and headers. func (r Reader) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) if r.ContentLength >= 0 { if r.Headers == nil { r.Headers = map[string]string{} } r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10) } r.writeHeaders(w, r.Headers) _, err = io.Copy(w, r.Reader) return } // WriteContentType (Reader) writes custom ContentType. func (r Reader) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) } // writeHeaders writes custom Header. func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) { header := w.Header() for k, v := range headers { if header.Get(k) == "" { header.Set(k, v) } } }
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "io" "net/http" "strconv" ) // Reader contains the IO reader and its length, and custom ContentType and other headers. type Reader struct { ContentType string ContentLength int64 Reader io.Reader Headers map[string]string } // Render (Reader) writes data with custom ContentType and headers. func (r Reader) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) if r.ContentLength >= 0 { if r.Headers == nil { r.Headers = map[string]string{} } r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10) } r.writeHeaders(w, r.Headers) _, err = io.Copy(w, r.Reader) return } // WriteContentType (Reader) writes custom ContentType. func (r Reader) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) } // writeHeaders writes custom Header. func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) { header := w.Header() for k, v := range headers { if header.Get(k) == "" { header.Set(k, v) } } }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./internal/json/jsoniter.go
// Copyright 2017 Bo-Yi Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build jsoniter // +build jsoniter package json import jsoniter "github.com/json-iterator/go" var ( json = jsoniter.ConfigCompatibleWithStandardLibrary // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
// Copyright 2017 Bo-Yi Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build jsoniter // +build jsoniter package json import jsoniter "github.com/json-iterator/go" var ( json = jsoniter.ConfigCompatibleWithStandardLibrary // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./testdata/protoexample/test.proto
package protoexample; enum FOO {X=17;}; message Test { required string label = 1; optional int32 type = 2[default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4{ required string RequiredField = 5; } }
package protoexample; enum FOO {X=17;}; message Test { required string label = 1; optional int32 type = 2[default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4{ required string RequiredField = 5; } }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./Makefile
GO ?= go GOFMT ?= gofmt "-s" GO_VERSION=$(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2) PACKAGES ?= $(shell $(GO) list ./...) VETPACKAGES ?= $(shell $(GO) list ./... | grep -v /examples/) GOFILES := $(shell find . -name "*.go") TESTFOLDER := $(shell $(GO) list ./... | grep -E 'gin$$|binding$$|render$$' | grep -v examples) TESTTAGS ?= "" .PHONY: test test: echo "mode: count" > coverage.out for d in $(TESTFOLDER); do \ $(GO) test $(TESTTAGS) -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \ cat tmp.out; \ if grep -q "^--- FAIL" tmp.out; then \ rm tmp.out; \ exit 1; \ elif grep -q "build failed" tmp.out; then \ rm tmp.out; \ exit 1; \ elif grep -q "setup failed" tmp.out; then \ rm tmp.out; \ exit 1; \ fi; \ if [ -f profile.out ]; then \ cat profile.out | grep -v "mode:" >> coverage.out; \ rm profile.out; \ fi; \ done .PHONY: fmt fmt: $(GOFMT) -w $(GOFILES) .PHONY: fmt-check fmt-check: @diff=$$($(GOFMT) -d $(GOFILES)); \ if [ -n "$$diff" ]; then \ echo "Please run 'make fmt' and commit the result:"; \ echo "$${diff}"; \ exit 1; \ fi; vet: $(GO) vet $(VETPACKAGES) .PHONY: lint lint: @hash golint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ $(GO) get -u golang.org/x/lint/golint; \ fi for PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done; .PHONY: misspell-check misspell-check: @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/client9/misspell/cmd/misspell; \ fi misspell -error $(GOFILES) .PHONY: misspell misspell: @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/client9/misspell/cmd/misspell; \ fi misspell -w $(GOFILES) .PHONY: tools tools: @if [ $(GO_VERSION) -gt 15 ]; then \ $(GO) install golang.org/x/lint/golint@latest; \ $(GO) install github.com/client9/misspell/cmd/misspell@latest; \ elif [ $(GO_VERSION) -lt 16 ]; then \ $(GO) install golang.org/x/lint/golint; \ $(GO) install github.com/client9/misspell/cmd/misspell; \ fi
GO ?= go GOFMT ?= gofmt "-s" GO_VERSION=$(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2) PACKAGES ?= $(shell $(GO) list ./...) VETPACKAGES ?= $(shell $(GO) list ./... | grep -v /examples/) GOFILES := $(shell find . -name "*.go") TESTFOLDER := $(shell $(GO) list ./... | grep -E 'gin$$|binding$$|render$$' | grep -v examples) TESTTAGS ?= "" .PHONY: test test: echo "mode: count" > coverage.out for d in $(TESTFOLDER); do \ $(GO) test $(TESTTAGS) -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \ cat tmp.out; \ if grep -q "^--- FAIL" tmp.out; then \ rm tmp.out; \ exit 1; \ elif grep -q "build failed" tmp.out; then \ rm tmp.out; \ exit 1; \ elif grep -q "setup failed" tmp.out; then \ rm tmp.out; \ exit 1; \ fi; \ if [ -f profile.out ]; then \ cat profile.out | grep -v "mode:" >> coverage.out; \ rm profile.out; \ fi; \ done .PHONY: fmt fmt: $(GOFMT) -w $(GOFILES) .PHONY: fmt-check fmt-check: @diff=$$($(GOFMT) -d $(GOFILES)); \ if [ -n "$$diff" ]; then \ echo "Please run 'make fmt' and commit the result:"; \ echo "$${diff}"; \ exit 1; \ fi; vet: $(GO) vet $(VETPACKAGES) .PHONY: lint lint: @hash golint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ $(GO) get -u golang.org/x/lint/golint; \ fi for PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done; .PHONY: misspell-check misspell-check: @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/client9/misspell/cmd/misspell; \ fi misspell -error $(GOFILES) .PHONY: misspell misspell: @hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/client9/misspell/cmd/misspell; \ fi misspell -w $(GOFILES) .PHONY: tools tools: @if [ $(GO_VERSION) -gt 15 ]; then \ $(GO) install golang.org/x/lint/golint@latest; \ $(GO) install github.com/client9/misspell/cmd/misspell@latest; \ elif [ $(GO_VERSION) -lt 16 ]; then \ $(GO) install golang.org/x/lint/golint; \ $(GO) install github.com/client9/misspell/cmd/misspell; \ fi
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.git/logs/refs/remotes/origin/HEAD
0000000000000000000000000000000000000000 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031630 +0000 clone: from https://github.com/gin-gonic/gin.git
0000000000000000000000000000000000000000 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031630 +0000 clone: from https://github.com/gin-gonic/gin.git
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/yaml.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "io" "net/http" "gopkg.in/yaml.v2" ) type yamlBinding struct{} func (yamlBinding) Name() string { return "yaml" } func (yamlBinding) Bind(req *http.Request, obj any) error { return decodeYAML(req.Body, obj) } func (yamlBinding) BindBody(body []byte, obj any) error { return decodeYAML(bytes.NewReader(body), obj) } func decodeYAML(r io.Reader, obj any) error { decoder := yaml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "io" "net/http" "gopkg.in/yaml.v2" ) type yamlBinding struct{} func (yamlBinding) Name() string { return "yaml" } func (yamlBinding) Bind(req *http.Request, obj any) error { return decodeYAML(req.Body, obj) } func (yamlBinding) BindBody(body []byte, obj any) error { return decodeYAML(bytes.NewReader(body), obj) } func decodeYAML(r io.Reader, obj any) error { decoder := yaml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./response_writer_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) // TODO // func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { // func (w *responseWriter) CloseNotify() <-chan bool { // func (w *responseWriter) Flush() { var ( _ ResponseWriter = &responseWriter{} _ http.ResponseWriter = &responseWriter{} _ http.ResponseWriter = ResponseWriter(&responseWriter{}) _ http.Hijacker = ResponseWriter(&responseWriter{}) _ http.Flusher = ResponseWriter(&responseWriter{}) _ http.CloseNotifier = ResponseWriter(&responseWriter{}) ) func init() { SetMode(TestMode) } func TestResponseWriterReset(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} var w ResponseWriter = writer writer.reset(testWriter) assert.Equal(t, -1, writer.size) assert.Equal(t, http.StatusOK, writer.status) assert.Equal(t, testWriter, writer.ResponseWriter) assert.Equal(t, -1, w.Size()) assert.Equal(t, http.StatusOK, w.Status()) assert.False(t, w.Written()) } func TestResponseWriterWriteHeader(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) w.WriteHeader(http.StatusMultipleChoices) assert.False(t, w.Written()) assert.Equal(t, http.StatusMultipleChoices, w.Status()) assert.NotEqual(t, http.StatusMultipleChoices, testWriter.Code) w.WriteHeader(-1) assert.Equal(t, http.StatusMultipleChoices, w.Status()) } func TestResponseWriterWriteHeadersNow(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) w.WriteHeader(http.StatusMultipleChoices) w.WriteHeaderNow() assert.True(t, w.Written()) assert.Equal(t, 0, w.Size()) assert.Equal(t, http.StatusMultipleChoices, testWriter.Code) writer.size = 10 w.WriteHeaderNow() assert.Equal(t, 10, w.Size()) } func TestResponseWriterWrite(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) n, err := w.Write([]byte("hola")) assert.Equal(t, 4, n) assert.Equal(t, 4, w.Size()) assert.Equal(t, http.StatusOK, w.Status()) assert.Equal(t, http.StatusOK, testWriter.Code) assert.Equal(t, "hola", testWriter.Body.String()) assert.NoError(t, err) n, err = w.Write([]byte(" adios")) assert.Equal(t, 6, n) assert.Equal(t, 10, w.Size()) assert.Equal(t, "hola adios", testWriter.Body.String()) assert.NoError(t, err) } func TestResponseWriterHijack(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) assert.Panics(t, func() { _, _, err := w.Hijack() assert.NoError(t, err) }) assert.True(t, w.Written()) assert.Panics(t, func() { w.CloseNotify() }) w.Flush() } func TestResponseWriterFlush(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { writer := &responseWriter{} writer.reset(w) writer.WriteHeader(http.StatusInternalServerError) writer.Flush() })) defer testServer.Close() // should return 500 resp, err := http.Get(testServer.URL) assert.NoError(t, err) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) // TODO // func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { // func (w *responseWriter) CloseNotify() <-chan bool { // func (w *responseWriter) Flush() { var ( _ ResponseWriter = &responseWriter{} _ http.ResponseWriter = &responseWriter{} _ http.ResponseWriter = ResponseWriter(&responseWriter{}) _ http.Hijacker = ResponseWriter(&responseWriter{}) _ http.Flusher = ResponseWriter(&responseWriter{}) _ http.CloseNotifier = ResponseWriter(&responseWriter{}) ) func init() { SetMode(TestMode) } func TestResponseWriterReset(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} var w ResponseWriter = writer writer.reset(testWriter) assert.Equal(t, -1, writer.size) assert.Equal(t, http.StatusOK, writer.status) assert.Equal(t, testWriter, writer.ResponseWriter) assert.Equal(t, -1, w.Size()) assert.Equal(t, http.StatusOK, w.Status()) assert.False(t, w.Written()) } func TestResponseWriterWriteHeader(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) w.WriteHeader(http.StatusMultipleChoices) assert.False(t, w.Written()) assert.Equal(t, http.StatusMultipleChoices, w.Status()) assert.NotEqual(t, http.StatusMultipleChoices, testWriter.Code) w.WriteHeader(-1) assert.Equal(t, http.StatusMultipleChoices, w.Status()) } func TestResponseWriterWriteHeadersNow(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) w.WriteHeader(http.StatusMultipleChoices) w.WriteHeaderNow() assert.True(t, w.Written()) assert.Equal(t, 0, w.Size()) assert.Equal(t, http.StatusMultipleChoices, testWriter.Code) writer.size = 10 w.WriteHeaderNow() assert.Equal(t, 10, w.Size()) } func TestResponseWriterWrite(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) n, err := w.Write([]byte("hola")) assert.Equal(t, 4, n) assert.Equal(t, 4, w.Size()) assert.Equal(t, http.StatusOK, w.Status()) assert.Equal(t, http.StatusOK, testWriter.Code) assert.Equal(t, "hola", testWriter.Body.String()) assert.NoError(t, err) n, err = w.Write([]byte(" adios")) assert.Equal(t, 6, n) assert.Equal(t, 10, w.Size()) assert.Equal(t, "hola adios", testWriter.Body.String()) assert.NoError(t, err) } func TestResponseWriterHijack(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) assert.Panics(t, func() { _, _, err := w.Hijack() assert.NoError(t, err) }) assert.True(t, w.Written()) assert.Panics(t, func() { w.CloseNotify() }) w.Flush() } func TestResponseWriterFlush(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { writer := &responseWriter{} writer.reset(w) writer.WriteHeader(http.StatusInternalServerError) writer.Flush() })) defer testServer.Close() // should return 500 resp, err := http.Get(testServer.URL) assert.NoError(t, err) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.github/PULL_REQUEST_TEMPLATE.md
- With pull requests: - Open your pull request against `master` - Your pull request should have no more than two commits, if not you should squash them. - It should pass all tests in the available continuous integration systems such as GitHub Actions. - You should add/modify tests to cover your proposed code changes. - If your pull request contains a new feature, please document it on the README.
- With pull requests: - Open your pull request against `master` - Your pull request should have no more than two commits, if not you should squash them. - It should pass all tests in the available continuous integration systems such as GitHub Actions. - You should add/modify tests to cover your proposed code changes. - If your pull request contains a new feature, please document it on the README.
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.golangci.yml
run: timeout: 5m linters: enable: - asciicheck - depguard - dogsled - durationcheck - errcheck - errorlint - exportloopref - gci - gofmt - goimports - gosec - misspell - nakedret - nilerr - nolintlint - revive - wastedassign issues: exclude-rules: - linters: - structcheck - unused text: "`data` is unused" - linters: - staticcheck text: "SA1019:" - linters: - revive text: "var-naming:" - linters: - revive text: "exported:" - path: _test\.go linters: - gosec # security is not make sense in tests
run: timeout: 5m linters: enable: - asciicheck - depguard - dogsled - durationcheck - errcheck - errorlint - exportloopref - gci - gofmt - goimports - gosec - misspell - nakedret - nilerr - nolintlint - revive - wastedassign issues: exclude-rules: - linters: - structcheck - unused text: "`data` is unused" - linters: - staticcheck text: "SA1019:" - linters: - revive text: "var-naming:" - linters: - revive text: "exported:" - path: _test\.go linters: - gosec # security is not make sense in tests
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.git/hooks/pre-receive.sample
#!/bin/sh # # An example hook script to make use of push options. # The example simply echoes all push options that start with 'echoback=' # and rejects all pushes when the "reject" push option is used. # # To enable this hook, rename this file to "pre-receive". if test -n "$GIT_PUSH_OPTION_COUNT" then i=0 while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" do eval "value=\$GIT_PUSH_OPTION_$i" case "$value" in echoback=*) echo "echo from the pre-receive-hook: ${value#*=}" >&2 ;; reject) exit 1 esac i=$((i + 1)) done fi
#!/bin/sh # # An example hook script to make use of push options. # The example simply echoes all push options that start with 'echoback=' # and rejects all pushes when the "reject" push option is used. # # To enable this hook, rename this file to "pre-receive". if test -n "$GIT_PUSH_OPTION_COUNT" then i=0 while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" do eval "value=\$GIT_PUSH_OPTION_$i" case "$value" in echoback=*) echo "echo from the pre-receive-hook: ${value#*=}" >&2 ;; reject) exit 1 esac i=$((i + 1)) done fi
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.git/config
[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] url = https://github.com/gin-gonic/gin.git fetch = +refs/heads/*:refs/remotes/origin/* gh-resolved = base [branch "master"] remote = origin merge = refs/heads/master
[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] url = https://github.com/gin-gonic/gin.git fetch = +refs/heads/*:refs/remotes/origin/* gh-resolved = base [branch "master"] remote = origin merge = refs/heads/master
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.git/hooks/pre-push.sample
#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local sha1> <remote ref> <remote sha1> # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0
#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local sha1> <remote ref> <remote sha1> # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./middleware_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "net/http" "strings" "testing" "github.com/gin-contrib/sse" "github.com/stretchr/testify/assert" ) func TestMiddlewareGeneralCase(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" }) router.GET("/", func(c *Context) { signature += "D" }) router.NoRoute(func(c *Context) { signature += " X " }) router.NoMethod(func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "ACDB", signature) } func TestMiddlewareNoRoute(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() c.Next() c.Next() c.Next() signature += "D" }) router.NoRoute(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoMethod(func(c *Context) { signature += " X " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusNotFound, w.Code) assert.Equal(t, "ACEGHFDB", signature) } func TestMiddlewareNoMethodEnabled(t *testing.T) { signature := "" router := New() router.HandleMethodNotAllowed = true router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusMethodNotAllowed, w.Code) assert.Equal(t, "ACEGHFDB", signature) } func TestMiddlewareNoMethodDisabled(t *testing.T) { signature := "" router := New() // NoMethod disabled router.HandleMethodNotAllowed = false router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusNotFound, w.Code) assert.Equal(t, "AC X DB", signature) } func TestMiddlewareAbort(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" }) router.Use(func(c *Context) { signature += "C" c.AbortWithStatus(http.StatusUnauthorized) c.Next() signature += "D" }) router.GET("/", func(c *Context) { signature += " X " c.Next() signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "ACD", signature) } func TestMiddlewareAbortHandlersChainAndNext(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() c.AbortWithStatus(http.StatusGone) signature += "B" }) router.GET("/", func(c *Context) { signature += "C" c.Next() }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusGone, w.Code) assert.Equal(t, "ACB", signature) } // TestFailHandlersChain - ensure that Fail interrupt used middleware in fifo order as // as well as Abort func TestMiddlewareFailHandlersChain(t *testing.T) { // SETUP signature := "" router := New() router.Use(func(context *Context) { signature += "A" context.AbortWithError(http.StatusInternalServerError, errors.New("foo")) //nolint: errcheck }) router.Use(func(context *Context) { signature += "B" context.Next() signature += "C" }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "A", signature) } func TestMiddlewareWrite(t *testing.T) { router := New() router.Use(func(c *Context) { c.String(http.StatusBadRequest, "hola\n") }) router.Use(func(c *Context) { c.XML(http.StatusBadRequest, H{"foo": "bar"}) }) router.Use(func(c *Context) { c.JSON(http.StatusBadRequest, H{"foo": "bar"}) }) router.GET("/", func(c *Context) { c.JSON(http.StatusBadRequest, H{"foo": "bar"}) }, func(c *Context) { c.Render(http.StatusBadRequest, sse.Event{ Event: "test", Data: "message", }) }) w := PerformRequest(router, "GET", "/") assert.Equal(t, http.StatusBadRequest, w.Code) 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)) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "net/http" "strings" "testing" "github.com/gin-contrib/sse" "github.com/stretchr/testify/assert" ) func TestMiddlewareGeneralCase(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" }) router.GET("/", func(c *Context) { signature += "D" }) router.NoRoute(func(c *Context) { signature += " X " }) router.NoMethod(func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "ACDB", signature) } func TestMiddlewareNoRoute(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() c.Next() c.Next() c.Next() signature += "D" }) router.NoRoute(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoMethod(func(c *Context) { signature += " X " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusNotFound, w.Code) assert.Equal(t, "ACEGHFDB", signature) } func TestMiddlewareNoMethodEnabled(t *testing.T) { signature := "" router := New() router.HandleMethodNotAllowed = true router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusMethodNotAllowed, w.Code) assert.Equal(t, "ACEGHFDB", signature) } func TestMiddlewareNoMethodDisabled(t *testing.T) { signature := "" router := New() // NoMethod disabled router.HandleMethodNotAllowed = false router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusNotFound, w.Code) assert.Equal(t, "AC X DB", signature) } func TestMiddlewareAbort(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" }) router.Use(func(c *Context) { signature += "C" c.AbortWithStatus(http.StatusUnauthorized) c.Next() signature += "D" }) router.GET("/", func(c *Context) { signature += " X " c.Next() signature += " XX " }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "ACD", signature) } func TestMiddlewareAbortHandlersChainAndNext(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() c.AbortWithStatus(http.StatusGone) signature += "B" }) router.GET("/", func(c *Context) { signature += "C" c.Next() }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusGone, w.Code) assert.Equal(t, "ACB", signature) } // TestFailHandlersChain - ensure that Fail interrupt used middleware in fifo order as // as well as Abort func TestMiddlewareFailHandlersChain(t *testing.T) { // SETUP signature := "" router := New() router.Use(func(context *Context) { signature += "A" context.AbortWithError(http.StatusInternalServerError, errors.New("foo")) //nolint: errcheck }) router.Use(func(context *Context) { signature += "B" context.Next() signature += "C" }) // RUN w := PerformRequest(router, "GET", "/") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "A", signature) } func TestMiddlewareWrite(t *testing.T) { router := New() router.Use(func(c *Context) { c.String(http.StatusBadRequest, "hola\n") }) router.Use(func(c *Context) { c.XML(http.StatusBadRequest, H{"foo": "bar"}) }) router.Use(func(c *Context) { c.JSON(http.StatusBadRequest, H{"foo": "bar"}) }) router.GET("/", func(c *Context) { c.JSON(http.StatusBadRequest, H{"foo": "bar"}) }, func(c *Context) { c.Render(http.StatusBadRequest, sse.Event{ Event: "test", Data: "message", }) }) w := PerformRequest(router, "GET", "/") assert.Equal(t, http.StatusBadRequest, w.Code) 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)) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.git/ORIG_HEAD
c9b27249fbb6092bcc7f749811d73ef1d50eee73
c9b27249fbb6092bcc7f749811d73ef1d50eee73
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./CHANGELOG.md
# Gin ChangeLog ## Gin v1.8.1 ### ENHANCEMENTS * feat(context): add ContextWithFallback feature flag [#3172](https://github.com/gin-gonic/gin/pull/3172) ## Gin v1.8.0 ## Break Changes * TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967). Please replace `RemoteIP() (net.IP, bool)` with `RemoteIP() net.IP` * gin.Context with fallback value from gin.Context.Request.Context() [#2751](https://github.com/gin-gonic/gin/pull/2751) ### BUGFIXES * Fixed SetOutput() panics on go 1.17 [#2861](https://github.com/gin-gonic/gin/pull/2861) * Fix: wrong when wildcard follows named param [#2983](https://github.com/gin-gonic/gin/pull/2983) * Fix: missing sameSite when do context.reset() [#3123](https://github.com/gin-gonic/gin/pull/3123) ### ENHANCEMENTS * Use Header() instead of deprecated HeaderMap [#2694](https://github.com/gin-gonic/gin/pull/2694) * RouterGroup.Handle regular match optimization of http method [#2685](https://github.com/gin-gonic/gin/pull/2685) * Add support go-json, another drop-in json replacement [#2680](https://github.com/gin-gonic/gin/pull/2680) * Use errors.New to replace fmt.Errorf will much better [#2707](https://github.com/gin-gonic/gin/pull/2707) * Use Duration.Truncate for truncating precision [#2711](https://github.com/gin-gonic/gin/pull/2711) * Get client IP when using Cloudflare [#2723](https://github.com/gin-gonic/gin/pull/2723) * Optimize code adjust [#2700](https://github.com/gin-gonic/gin/pull/2700/files) * Optimize code and reduce code cyclomatic complexity [#2737](https://github.com/gin-gonic/gin/pull/2737) * Improve sliceValidateError.Error performance [#2765](https://github.com/gin-gonic/gin/pull/2765) * Support custom struct tag [#2720](https://github.com/gin-gonic/gin/pull/2720) * Improve router group tests [#2787](https://github.com/gin-gonic/gin/pull/2787) * Fallback Context.Deadline() Context.Done() Context.Err() to Context.Request.Context() [#2769](https://github.com/gin-gonic/gin/pull/2769) * Some codes optimize [#2830](https://github.com/gin-gonic/gin/pull/2830) [#2834](https://github.com/gin-gonic/gin/pull/2834) [#2838](https://github.com/gin-gonic/gin/pull/2838) [#2837](https://github.com/gin-gonic/gin/pull/2837) [#2788](https://github.com/gin-gonic/gin/pull/2788) [#2848](https://github.com/gin-gonic/gin/pull/2848) [#2851](https://github.com/gin-gonic/gin/pull/2851) [#2701](https://github.com/gin-gonic/gin/pull/2701) * TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967) * Test(route): expose performRequest func [#3012](https://github.com/gin-gonic/gin/pull/3012) * Support h2c with prior knowledge [#1398](https://github.com/gin-gonic/gin/pull/1398) * Feat attachment filename support utf8 [#3071](https://github.com/gin-gonic/gin/pull/3071) * Feat: add StaticFileFS [#2749](https://github.com/gin-gonic/gin/pull/2749) * Feat(context): return GIN Context from Value method [#2825](https://github.com/gin-gonic/gin/pull/2825) * Feat: automatically SetMode to TestMode when run go test [#3139](https://github.com/gin-gonic/gin/pull/3139) * Add TOML bining for gin [#3081](https://github.com/gin-gonic/gin/pull/3081) * IPv6 add default trusted proxies [#3033](https://github.com/gin-gonic/gin/pull/3033) ### DOCS * Add note about nomsgpack tag to the readme [#2703](https://github.com/gin-gonic/gin/pull/2703) ## Gin v1.7.7 ### BUGFIXES * Fixed X-Forwarded-For unsafe handling of CVE-2020-28483 [#2844](https://github.com/gin-gonic/gin/pull/2844), closed issue [#2862](https://github.com/gin-gonic/gin/issues/2862). * Tree: updated the code logic for `latestNode` [#2897](https://github.com/gin-gonic/gin/pull/2897), closed issue [#2894](https://github.com/gin-gonic/gin/issues/2894) [#2878](https://github.com/gin-gonic/gin/issues/2878). * Tree: fixed the misplacement of adding slashes [#2847](https://github.com/gin-gonic/gin/pull/2847), closed issue [#2843](https://github.com/gin-gonic/gin/issues/2843). * Tree: fixed tsr with mixed static and wildcard paths [#2924](https://github.com/gin-gonic/gin/pull/2924), closed issue [#2918](https://github.com/gin-gonic/gin/issues/2918). ### ENHANCEMENTS * TrustedProxies: make it backward-compatible [#2887](https://github.com/gin-gonic/gin/pull/2887), closed issue [#2819](https://github.com/gin-gonic/gin/issues/2819). * TrustedPlatform: provide custom options for another CDN services [#2906](https://github.com/gin-gonic/gin/pull/2906). ### DOCS * NoMethod: added usage annotation ([#2832](https://github.com/gin-gonic/gin/pull/2832#issuecomment-929954463)). ## Gin v1.7.6 ### BUGFIXES * bump new release to fix v1.7.5 release error by using v1.7.4 codes. ## Gin v1.7.4 ### BUGFIXES * bump new release to fix checksum mismatch ## Gin v1.7.3 ### BUGFIXES * fix level 1 router match [#2767](https://github.com/gin-gonic/gin/issues/2767), [#2796](https://github.com/gin-gonic/gin/issues/2796) ## Gin v1.7.2 ### BUGFIXES * Fix conflict between param and exact path [#2706](https://github.com/gin-gonic/gin/issues/2706). Close issue [#2682](https://github.com/gin-gonic/gin/issues/2682) [#2696](https://github.com/gin-gonic/gin/issues/2696). ## Gin v1.7.1 ### BUGFIXES * fix: data race with trustedCIDRs from [#2674](https://github.com/gin-gonic/gin/issues/2674)([#2675](https://github.com/gin-gonic/gin/pull/2675)) ## Gin v1.7.0 ### BUGFIXES * fix compile error from [#2572](https://github.com/gin-gonic/gin/pull/2572) ([#2600](https://github.com/gin-gonic/gin/pull/2600)) * fix: print headers without Authorization header on broken pipe ([#2528](https://github.com/gin-gonic/gin/pull/2528)) * fix(tree): reassign fullpath when register new node ([#2366](https://github.com/gin-gonic/gin/pull/2366)) ### ENHANCEMENTS * Support params and exact routes without creating conflicts ([#2663](https://github.com/gin-gonic/gin/pull/2663)) * chore: improve render string performance ([#2365](https://github.com/gin-gonic/gin/pull/2365)) * Sync route tree to httprouter latest code ([#2368](https://github.com/gin-gonic/gin/pull/2368)) * chore: rename getQueryCache/getFormCache to initQueryCache/initFormCa ([#2375](https://github.com/gin-gonic/gin/pull/2375)) * chore(performance): improve countParams ([#2378](https://github.com/gin-gonic/gin/pull/2378)) * Remove some functions that have the same effect as the bytes package ([#2387](https://github.com/gin-gonic/gin/pull/2387)) * update:SetMode function ([#2321](https://github.com/gin-gonic/gin/pull/2321)) * remove an unused type SecureJSONPrefix ([#2391](https://github.com/gin-gonic/gin/pull/2391)) * Add a redirect sample for POST method ([#2389](https://github.com/gin-gonic/gin/pull/2389)) * Add CustomRecovery builtin middleware ([#2322](https://github.com/gin-gonic/gin/pull/2322)) * binding: avoid 2038 problem on 32-bit architectures ([#2450](https://github.com/gin-gonic/gin/pull/2450)) * Prevent panic in Context.GetQuery() when there is no Request ([#2412](https://github.com/gin-gonic/gin/pull/2412)) * Add GetUint and GetUint64 method on gin.context ([#2487](https://github.com/gin-gonic/gin/pull/2487)) * update content-disposition header to MIME-style ([#2512](https://github.com/gin-gonic/gin/pull/2512)) * reduce allocs and improve the render `WriteString` ([#2508](https://github.com/gin-gonic/gin/pull/2508)) * implement ".Unwrap() error" on Error type ([#2525](https://github.com/gin-gonic/gin/pull/2525)) ([#2526](https://github.com/gin-gonic/gin/pull/2526)) * Allow bind with a map[string]string ([#2484](https://github.com/gin-gonic/gin/pull/2484)) * chore: update tree ([#2371](https://github.com/gin-gonic/gin/pull/2371)) * Support binding for slice/array obj [Rewrite] ([#2302](https://github.com/gin-gonic/gin/pull/2302)) * basic auth: fix timing oracle ([#2609](https://github.com/gin-gonic/gin/pull/2609)) * Add mixed param and non-param paths (port of httprouter[#329](https://github.com/gin-gonic/gin/pull/329)) ([#2663](https://github.com/gin-gonic/gin/pull/2663)) * feat(engine): add trustedproxies and remoteIP ([#2632](https://github.com/gin-gonic/gin/pull/2632)) ## Gin v1.6.3 ### ENHANCEMENTS * Improve performance: Change `*sync.RWMutex` to `sync.RWMutex` in context. [#2351](https://github.com/gin-gonic/gin/pull/2351) ## Gin v1.6.2 ### BUGFIXES * fix missing initial sync.RWMutex [#2305](https://github.com/gin-gonic/gin/pull/2305) ### ENHANCEMENTS * Add set samesite in cookie. [#2306](https://github.com/gin-gonic/gin/pull/2306) ## Gin v1.6.1 ### BUGFIXES * Revert "fix accept incoming network connections" [#2294](https://github.com/gin-gonic/gin/pull/2294) ## Gin v1.6.0 ### BREAKING * chore(performance): Improve performance for adding RemoveExtraSlash flag [#2159](https://github.com/gin-gonic/gin/pull/2159) * drop support govendor [#2148](https://github.com/gin-gonic/gin/pull/2148) * Added support for SameSite cookie flag [#1615](https://github.com/gin-gonic/gin/pull/1615) ### FEATURES * add yaml negotiation [#2220](https://github.com/gin-gonic/gin/pull/2220) * FileFromFS [#2112](https://github.com/gin-gonic/gin/pull/2112) ### BUGFIXES * Unix Socket Handling [#2280](https://github.com/gin-gonic/gin/pull/2280) * Use json marshall in context json to fix breaking new line issue. Fixes #2209 [#2228](https://github.com/gin-gonic/gin/pull/2228) * fix accept incoming network connections [#2216](https://github.com/gin-gonic/gin/pull/2216) * Fixed a bug in the calculation of the maximum number of parameters [#2166](https://github.com/gin-gonic/gin/pull/2166) * [FIX] allow empty headers on DataFromReader [#2121](https://github.com/gin-gonic/gin/pull/2121) * Add mutex for protect Context.Keys map [#1391](https://github.com/gin-gonic/gin/pull/1391) ### ENHANCEMENTS * Add mitigation for log injection [#2277](https://github.com/gin-gonic/gin/pull/2277) * tree: range over nodes values [#2229](https://github.com/gin-gonic/gin/pull/2229) * tree: remove duplicate assignment [#2222](https://github.com/gin-gonic/gin/pull/2222) * chore: upgrade go-isatty and json-iterator/go [#2215](https://github.com/gin-gonic/gin/pull/2215) * path: sync code with httprouter [#2212](https://github.com/gin-gonic/gin/pull/2212) * Use zero-copy approach to convert types between string and byte slice [#2206](https://github.com/gin-gonic/gin/pull/2206) * Reuse bytes when cleaning the URL paths [#2179](https://github.com/gin-gonic/gin/pull/2179) * tree: remove one else statement [#2177](https://github.com/gin-gonic/gin/pull/2177) * tree: sync httprouter update (#2173) (#2172) [#2171](https://github.com/gin-gonic/gin/pull/2171) * tree: sync part httprouter codes and reduce if/else [#2163](https://github.com/gin-gonic/gin/pull/2163) * use http method constant [#2155](https://github.com/gin-gonic/gin/pull/2155) * upgrade go-validator to v10 [#2149](https://github.com/gin-gonic/gin/pull/2149) * Refactor redirect request in gin.go [#1970](https://github.com/gin-gonic/gin/pull/1970) * Add build tag nomsgpack [#1852](https://github.com/gin-gonic/gin/pull/1852) ### DOCS * docs(path): improve comments [#2223](https://github.com/gin-gonic/gin/pull/2223) * Renew README to fit the modification of SetCookie method [#2217](https://github.com/gin-gonic/gin/pull/2217) * Fix spelling [#2202](https://github.com/gin-gonic/gin/pull/2202) * Remove broken link from README. [#2198](https://github.com/gin-gonic/gin/pull/2198) * Update docs on Context.Done(), Context.Deadline() and Context.Err() [#2196](https://github.com/gin-gonic/gin/pull/2196) * Update validator to v10 [#2190](https://github.com/gin-gonic/gin/pull/2190) * upgrade go-validator to v10 for README [#2189](https://github.com/gin-gonic/gin/pull/2189) * Update to currently output [#2188](https://github.com/gin-gonic/gin/pull/2188) * Fix "Custom Validators" example [#2186](https://github.com/gin-gonic/gin/pull/2186) * Add project to README [#2165](https://github.com/gin-gonic/gin/pull/2165) * docs(benchmarks): for gin v1.5 [#2153](https://github.com/gin-gonic/gin/pull/2153) * Changed wording for clarity in README.md [#2122](https://github.com/gin-gonic/gin/pull/2122) ### MISC * ci support go1.14 [#2262](https://github.com/gin-gonic/gin/pull/2262) * chore: upgrade depend version [#2231](https://github.com/gin-gonic/gin/pull/2231) * Drop support go1.10 [#2147](https://github.com/gin-gonic/gin/pull/2147) * fix comment in `mode.go` [#2129](https://github.com/gin-gonic/gin/pull/2129) ## Gin v1.5.0 - [FIX] Use DefaultWriter and DefaultErrorWriter for debug messages [#1891](https://github.com/gin-gonic/gin/pull/1891) - [NEW] Now you can parse the inline lowercase start structure [#1893](https://github.com/gin-gonic/gin/pull/1893) - [FIX] Some code improvements [#1909](https://github.com/gin-gonic/gin/pull/1909) - [FIX] Use encode replace json marshal increase json encoder speed [#1546](https://github.com/gin-gonic/gin/pull/1546) - [NEW] Hold matched route full path in the Context [#1826](https://github.com/gin-gonic/gin/pull/1826) - [FIX] Fix context.Params race condition on Copy() [#1841](https://github.com/gin-gonic/gin/pull/1841) - [NEW] Add context param query cache [#1450](https://github.com/gin-gonic/gin/pull/1450) - [FIX] Improve GetQueryMap performance [#1918](https://github.com/gin-gonic/gin/pull/1918) - [FIX] Improve get post data [#1920](https://github.com/gin-gonic/gin/pull/1920) - [FIX] Use context instead of x/net/context [#1922](https://github.com/gin-gonic/gin/pull/1922) - [FIX] Attempt to fix PostForm cache bug [#1931](https://github.com/gin-gonic/gin/pull/1931) - [NEW] Add support of multipart multi files [#1949](https://github.com/gin-gonic/gin/pull/1949) - [NEW] Support bind http header param [#1957](https://github.com/gin-gonic/gin/pull/1957) - [FIX] Drop support for go1.8 and go1.9 [#1933](https://github.com/gin-gonic/gin/pull/1933) - [FIX] Bugfix for the FullPath feature [#1919](https://github.com/gin-gonic/gin/pull/1919) - [FIX] Gin1.5 bytes.Buffer to strings.Builder [#1939](https://github.com/gin-gonic/gin/pull/1939) - [FIX] Upgrade github.com/ugorji/go/codec [#1969](https://github.com/gin-gonic/gin/pull/1969) - [NEW] Support bind unix time [#1980](https://github.com/gin-gonic/gin/pull/1980) - [FIX] Simplify code [#2004](https://github.com/gin-gonic/gin/pull/2004) - [NEW] Support negative Content-Length in DataFromReader [#1981](https://github.com/gin-gonic/gin/pull/1981) - [FIX] Identify terminal on a RISC-V architecture for auto-colored logs [#2019](https://github.com/gin-gonic/gin/pull/2019) - [BREAKING] `Context.JSONP()` now expects a semicolon (`;`) at the end [#2007](https://github.com/gin-gonic/gin/pull/2007) - [BREAKING] Upgrade default `binding.Validator` to v9 (see [its changelog](https://github.com/go-playground/validator/releases/tag/v9.0.0)) [#1015](https://github.com/gin-gonic/gin/pull/1015) - [NEW] Add `DisallowUnknownFields()` in `Context.BindJSON()` [#2028](https://github.com/gin-gonic/gin/pull/2028) - [NEW] Use specific `net.Listener` with `Engine.RunListener()` [#2023](https://github.com/gin-gonic/gin/pull/2023) - [FIX] Fix some typo [#2079](https://github.com/gin-gonic/gin/pull/2079) [#2080](https://github.com/gin-gonic/gin/pull/2080) - [FIX] Relocate binding body tests [#2086](https://github.com/gin-gonic/gin/pull/2086) - [FIX] Use Writer in Context.Status [#1606](https://github.com/gin-gonic/gin/pull/1606) - [FIX] `Engine.RunUnix()` now returns the error if it can't change the file mode [#2093](https://github.com/gin-gonic/gin/pull/2093) - [FIX] `RouterGroup.StaticFS()` leaked files. Now it closes them. [#2118](https://github.com/gin-gonic/gin/pull/2118) - [FIX] `Context.Request.FormFile` leaked file. Now it closes it. [#2114](https://github.com/gin-gonic/gin/pull/2114) - [FIX] Ignore walking on `form:"-"` mapping [#1943](https://github.com/gin-gonic/gin/pull/1943) ### Gin v1.4.0 - [NEW] Support for [Go Modules](https://github.com/golang/go/wiki/Modules) [#1569](https://github.com/gin-gonic/gin/pull/1569) - [NEW] Refactor of form mapping multipart request [#1829](https://github.com/gin-gonic/gin/pull/1829) - [FIX] Truncate Latency precision in long running request [#1830](https://github.com/gin-gonic/gin/pull/1830) - [FIX] IsTerm flag should not be affected by DisableConsoleColor method. [#1802](https://github.com/gin-gonic/gin/pull/1802) - [NEW] Supporting file binding [#1264](https://github.com/gin-gonic/gin/pull/1264) - [NEW] Add support for mapping arrays [#1797](https://github.com/gin-gonic/gin/pull/1797) - [FIX] Readme updates [#1793](https://github.com/gin-gonic/gin/pull/1793) [#1788](https://github.com/gin-gonic/gin/pull/1788) [1789](https://github.com/gin-gonic/gin/pull/1789) - [FIX] StaticFS: Fixed Logging two log lines on 404. [#1805](https://github.com/gin-gonic/gin/pull/1805), [#1804](https://github.com/gin-gonic/gin/pull/1804) - [NEW] Make context.Keys available as LogFormatterParams [#1779](https://github.com/gin-gonic/gin/pull/1779) - [NEW] Use internal/json for Marshal/Unmarshal [#1791](https://github.com/gin-gonic/gin/pull/1791) - [NEW] Support mapping time.Duration [#1794](https://github.com/gin-gonic/gin/pull/1794) - [NEW] Refactor form mappings [#1749](https://github.com/gin-gonic/gin/pull/1749) - [NEW] Added flag to context.Stream indicates if client disconnected in middle of stream [#1252](https://github.com/gin-gonic/gin/pull/1252) - [FIX] Moved [examples](https://github.com/gin-gonic/examples) to stand alone Repo [#1775](https://github.com/gin-gonic/gin/pull/1775) - [NEW] Extend context.File to allow for the content-disposition attachments via a new method context.Attachment [#1260](https://github.com/gin-gonic/gin/pull/1260) - [FIX] Support HTTP content negotiation wildcards [#1112](https://github.com/gin-gonic/gin/pull/1112) - [NEW] Add prefix from X-Forwarded-Prefix in redirectTrailingSlash [#1238](https://github.com/gin-gonic/gin/pull/1238) - [FIX] context.Copy() race condition [#1020](https://github.com/gin-gonic/gin/pull/1020) - [NEW] Add context.HandlerNames() [#1729](https://github.com/gin-gonic/gin/pull/1729) - [FIX] Change color methods to public in the defaultLogger. [#1771](https://github.com/gin-gonic/gin/pull/1771) - [FIX] Update writeHeaders method to use http.Header.Set [#1722](https://github.com/gin-gonic/gin/pull/1722) - [NEW] Add response size to LogFormatterParams [#1752](https://github.com/gin-gonic/gin/pull/1752) - [NEW] Allow ignoring field on form mapping [#1733](https://github.com/gin-gonic/gin/pull/1733) - [NEW] Add a function to force color in console output. [#1724](https://github.com/gin-gonic/gin/pull/1724) - [FIX] Context.Next() - recheck len of handlers on every iteration. [#1745](https://github.com/gin-gonic/gin/pull/1745) - [FIX] Fix all errcheck warnings [#1739](https://github.com/gin-gonic/gin/pull/1739) [#1653](https://github.com/gin-gonic/gin/pull/1653) - [NEW] context: inherits context cancellation and deadline from http.Request context for Go>=1.7 [#1690](https://github.com/gin-gonic/gin/pull/1690) - [NEW] Binding for URL Params [#1694](https://github.com/gin-gonic/gin/pull/1694) - [NEW] Add LoggerWithFormatter method [#1677](https://github.com/gin-gonic/gin/pull/1677) - [FIX] CI testing updates [#1671](https://github.com/gin-gonic/gin/pull/1671) [#1670](https://github.com/gin-gonic/gin/pull/1670) [#1682](https://github.com/gin-gonic/gin/pull/1682) [#1669](https://github.com/gin-gonic/gin/pull/1669) - [FIX] StaticFS(): Send 404 when path does not exist [#1663](https://github.com/gin-gonic/gin/pull/1663) - [FIX] Handle nil body for JSON binding [#1638](https://github.com/gin-gonic/gin/pull/1638) - [FIX] Support bind uri param [#1612](https://github.com/gin-gonic/gin/pull/1612) - [FIX] recovery: fix issue with syscall import on google app engine [#1640](https://github.com/gin-gonic/gin/pull/1640) - [FIX] Make sure the debug log contains line breaks [#1650](https://github.com/gin-gonic/gin/pull/1650) - [FIX] Panic stack trace being printed during recovery of broken pipe [#1089](https://github.com/gin-gonic/gin/pull/1089) [#1259](https://github.com/gin-gonic/gin/pull/1259) - [NEW] RunFd method to run http.Server through a file descriptor [#1609](https://github.com/gin-gonic/gin/pull/1609) - [NEW] Yaml binding support [#1618](https://github.com/gin-gonic/gin/pull/1618) - [FIX] Pass MaxMultipartMemory when FormFile is called [#1600](https://github.com/gin-gonic/gin/pull/1600) - [FIX] LoadHTML* tests [#1559](https://github.com/gin-gonic/gin/pull/1559) - [FIX] Removed use of sync.pool from HandleContext [#1565](https://github.com/gin-gonic/gin/pull/1565) - [FIX] Format output log to os.Stderr [#1571](https://github.com/gin-gonic/gin/pull/1571) - [FIX] Make logger use a yellow background and a darkgray text for legibility [#1570](https://github.com/gin-gonic/gin/pull/1570) - [FIX] Remove sensitive request information from panic log. [#1370](https://github.com/gin-gonic/gin/pull/1370) - [FIX] log.Println() does not print timestamp [#829](https://github.com/gin-gonic/gin/pull/829) [#1560](https://github.com/gin-gonic/gin/pull/1560) - [NEW] Add PureJSON renderer [#694](https://github.com/gin-gonic/gin/pull/694) - [FIX] Add missing copyright and update if/else [#1497](https://github.com/gin-gonic/gin/pull/1497) - [FIX] Update msgpack usage [#1498](https://github.com/gin-gonic/gin/pull/1498) - [FIX] Use protobuf on render [#1496](https://github.com/gin-gonic/gin/pull/1496) - [FIX] Add support for Protobuf format response [#1479](https://github.com/gin-gonic/gin/pull/1479) - [NEW] Set default time format in form binding [#1487](https://github.com/gin-gonic/gin/pull/1487) - [FIX] Add BindXML and ShouldBindXML [#1485](https://github.com/gin-gonic/gin/pull/1485) - [NEW] Upgrade dependency libraries [#1491](https://github.com/gin-gonic/gin/pull/1491) ## Gin v1.3.0 - [NEW] Add [`func (*Context) QueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.QueryMap), [`func (*Context) GetQueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetQueryMap), [`func (*Context) PostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.PostFormMap) and [`func (*Context) GetPostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetPostFormMap) to support `type map[string]string` as query string or form parameters, see [#1383](https://github.com/gin-gonic/gin/pull/1383) - [NEW] Add [`func (*Context) AsciiJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.AsciiJSON), see [#1358](https://github.com/gin-gonic/gin/pull/1358) - [NEW] Add `Pusher()` in [`type ResponseWriter`](https://godoc.org/github.com/gin-gonic/gin#ResponseWriter) for supporting http2 push, see [#1273](https://github.com/gin-gonic/gin/pull/1273) - [NEW] Add [`func (*Context) DataFromReader`](https://godoc.org/github.com/gin-gonic/gin#Context.DataFromReader) for serving dynamic data, see [#1304](https://github.com/gin-gonic/gin/pull/1304) - [NEW] Add [`func (*Context) ShouldBindBodyWith`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindBodyWith) allowing to call binding multiple times, see [#1341](https://github.com/gin-gonic/gin/pull/1341) - [NEW] Support pointers in form binding, see [#1336](https://github.com/gin-gonic/gin/pull/1336) - [NEW] Add [`func (*Context) JSONP`](https://godoc.org/github.com/gin-gonic/gin#Context.JSONP), see [#1333](https://github.com/gin-gonic/gin/pull/1333) - [NEW] Support default value in form binding, see [#1138](https://github.com/gin-gonic/gin/pull/1138) - [NEW] Expose validator engine in [`type StructValidator`](https://godoc.org/github.com/gin-gonic/gin/binding#StructValidator), see [#1277](https://github.com/gin-gonic/gin/pull/1277) - [NEW] Add [`func (*Context) ShouldBind`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBind), [`func (*Context) ShouldBindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindQuery) and [`func (*Context) ShouldBindJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindJSON), see [#1047](https://github.com/gin-gonic/gin/pull/1047) - [NEW] Add support for `time.Time` location in form binding, see [#1117](https://github.com/gin-gonic/gin/pull/1117) - [NEW] Add [`func (*Context) BindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.BindQuery), see [#1029](https://github.com/gin-gonic/gin/pull/1029) - [NEW] Make [jsonite](https://github.com/json-iterator/go) optional with build tags, see [#1026](https://github.com/gin-gonic/gin/pull/1026) - [NEW] Show query string in logger, see [#999](https://github.com/gin-gonic/gin/pull/999) - [NEW] Add [`func (*Context) SecureJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.SecureJSON), see [#987](https://github.com/gin-gonic/gin/pull/987) and [#993](https://github.com/gin-gonic/gin/pull/993) - [DEPRECATE] `func (*Context) GetCookie` for [`func (*Context) Cookie`](https://godoc.org/github.com/gin-gonic/gin#Context.Cookie) - [FIX] Don't display color tags if [`func DisableConsoleColor`](https://godoc.org/github.com/gin-gonic/gin#DisableConsoleColor) called, see [#1072](https://github.com/gin-gonic/gin/pull/1072) - [FIX] Gin Mode `""` when calling [`func Mode`](https://godoc.org/github.com/gin-gonic/gin#Mode) now returns `const DebugMode`, see [#1250](https://github.com/gin-gonic/gin/pull/1250) - [FIX] `Flush()` now doesn't overwrite `responseWriter` status code, see [#1460](https://github.com/gin-gonic/gin/pull/1460) ## Gin 1.2.0 - [NEW] Switch from godeps to govendor - [NEW] Add support for Let's Encrypt via gin-gonic/autotls - [NEW] Improve README examples and add extra at examples folder - [NEW] Improved support with App Engine - [NEW] Add custom template delimiters, see #860 - [NEW] Add Template Func Maps, see #962 - [NEW] Add \*context.Handler(), see #928 - [NEW] Add \*context.GetRawData() - [NEW] Add \*context.GetHeader() (request) - [NEW] Add \*context.AbortWithStatusJSON() (JSON content type) - [NEW] Add \*context.Keys type cast helpers - [NEW] Add \*context.ShouldBindWith() - [NEW] Add \*context.MustBindWith() - [NEW] Add \*engine.SetFuncMap() - [DEPRECATE] On next release: \*context.BindWith(), see #855 - [FIX] Refactor render - [FIX] Reworked tests - [FIX] logger now supports cygwin - [FIX] Use X-Forwarded-For before X-Real-Ip - [FIX] time.Time binding (#904) ## Gin 1.1.4 - [NEW] Support google appengine for IsTerminal func ## Gin 1.1.3 - [FIX] Reverted Logger: skip ANSI color commands ## Gin 1.1 - [NEW] Implement QueryArray and PostArray methods - [NEW] Refactor GetQuery and GetPostForm - [NEW] Add contribution guide - [FIX] Corrected typos in README - [FIX] Removed additional Iota - [FIX] Changed imports to gopkg instead of github in README (#733) - [FIX] Logger: skip ANSI color commands if output is not a tty ## Gin 1.0rc2 (...) - [PERFORMANCE] Fast path for writing Content-Type. - [PERFORMANCE] Much faster 404 routing - [PERFORMANCE] Allocation optimizations - [PERFORMANCE] Faster root tree lookup - [PERFORMANCE] Zero overhead, String() and JSON() rendering. - [PERFORMANCE] Faster ClientIP parsing - [PERFORMANCE] Much faster SSE implementation - [NEW] Benchmarks suite - [NEW] Bind validation can be disabled and replaced with custom validators. - [NEW] More flexible HTML render - [NEW] Multipart and PostForm bindings - [NEW] Adds method to return all the registered routes - [NEW] Context.HandlerName() returns the main handler's name - [NEW] Adds Error.IsType() helper - [FIX] Binding multipart form - [FIX] Integration tests - [FIX] Crash when binding non struct object in Context. - [FIX] RunTLS() implementation - [FIX] Logger() unit tests - [FIX] Adds SetHTMLTemplate() warning - [FIX] Context.IsAborted() - [FIX] More unit tests - [FIX] JSON, XML, HTML renders accept custom content-types - [FIX] gin.AbortIndex is unexported - [FIX] Better approach to avoid directory listing in StaticFS() - [FIX] Context.ClientIP() always returns the IP with trimmed spaces. - [FIX] Better warning when running in debug mode. - [FIX] Google App Engine integration. debugPrint does not use os.Stdout - [FIX] Fixes integer overflow in error type - [FIX] Error implements the json.Marshaller interface - [FIX] MIT license in every file ## Gin 1.0rc1 (May 22, 2015) - [PERFORMANCE] Zero allocation router - [PERFORMANCE] Faster JSON, XML and text rendering - [PERFORMANCE] Custom hand optimized HttpRouter for Gin - [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations - [NEW] Built-in support for golang.org/x/net/context - [NEW] Any(path, handler). Create a route that matches any path - [NEW] Refactored rendering pipeline (faster and static typed) - [NEW] Refactored errors API - [NEW] IndentedJSON() prints pretty JSON - [NEW] Added gin.DefaultWriter - [NEW] UNIX socket support - [NEW] RouterGroup.BasePath is exposed - [NEW] JSON validation using go-validate-yourself (very powerful options) - [NEW] Completed suite of unit tests - [NEW] HTTP streaming with c.Stream() - [NEW] StaticFile() creates a router for serving just one file. - [NEW] StaticFS() has an option to disable directory listing. - [NEW] StaticFS() for serving static files through virtual filesystems - [NEW] Server-Sent Events native support - [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler - [NEW] Added LoggerWithWriter() middleware - [NEW] Added RecoveryWithWriter() middleware - [NEW] Added DefaultPostFormValue() - [NEW] Added DefaultFormValue() - [NEW] Added DefaultParamValue() - [FIX] BasicAuth() when using custom realm - [FIX] Bug when serving static files in nested routing group - [FIX] Redirect using built-in http.Redirect() - [FIX] Logger when printing the requested path - [FIX] Documentation typos - [FIX] Context.Engine renamed to Context.engine - [FIX] Better debugging messages - [FIX] ErrorLogger - [FIX] Debug HTTP render - [FIX] Refactored binding and render modules - [FIX] Refactored Context initialization - [FIX] Refactored BasicAuth() - [FIX] NoMethod/NoRoute handlers - [FIX] Hijacking http - [FIX] Better support for Google App Engine (using log instead of fmt) ## Gin 0.6 (Mar 9, 2015) - [NEW] Support multipart/form-data - [NEW] NoMethod handler - [NEW] Validate sub structures - [NEW] Support for HTTP Realm Auth - [FIX] Unsigned integers in binding - [FIX] Improve color logger ## Gin 0.5 (Feb 7, 2015) - [NEW] Content Negotiation - [FIX] Solved security bug that allow a client to spoof ip - [FIX] Fix unexported/ignored fields in binding ## Gin 0.4 (Aug 21, 2014) - [NEW] Development mode - [NEW] Unit tests - [NEW] Add Content.Redirect() - [FIX] Deferring WriteHeader() - [FIX] Improved documentation for model binding ## Gin 0.3 (Jul 18, 2014) - [PERFORMANCE] Normal log and error log are printed in the same call. - [PERFORMANCE] Improve performance of NoRouter() - [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults. - [NEW] Flexible rendering API - [NEW] Add Context.File() - [NEW] Add shortcut RunTLS() for http.ListenAndServeTLS - [FIX] Rename NotFound404() to NoRoute() - [FIX] Errors in context are purged - [FIX] Adds HEAD method in Static file serving - [FIX] Refactors Static() file serving - [FIX] Using keyed initialization to fix app-engine integration - [FIX] Can't unmarshal JSON array, #63 - [FIX] Renaming Context.Req to Context.Request - [FIX] Check application/x-www-form-urlencoded when parsing form ## Gin 0.2b (Jul 08, 2014) - [PERFORMANCE] Using sync.Pool to allocatio/gc overhead - [NEW] Travis CI integration - [NEW] Completely new logger - [NEW] New API for serving static files. gin.Static() - [NEW] gin.H() can be serialized into XML - [NEW] Typed errors. Errors can be typed. Internet/external/custom. - [NEW] Support for Godeps - [NEW] Travis/Godocs badges in README - [NEW] New Bind() and BindWith() methods for parsing request body. - [NEW] Add Content.Copy() - [NEW] Add context.LastError() - [NEW] Add shortcut for OPTIONS HTTP method - [FIX] Tons of README fixes - [FIX] Header is written before body - [FIX] BasicAuth() and changes API a little bit - [FIX] Recovery() middleware only prints panics - [FIX] Context.Get() does not panic anymore. Use MustGet() instead. - [FIX] Multiple http.WriteHeader() in NotFound handlers - [FIX] Engine.Run() panics if http server can't be set up - [FIX] Crash when route path doesn't start with '/' - [FIX] Do not update header when status code is negative - [FIX] Setting response headers before calling WriteHeader in context.String() - [FIX] Add MIT license - [FIX] Changes behaviour of ErrorLogger() and Logger()
# Gin ChangeLog ## Gin v1.8.1 ### ENHANCEMENTS * feat(context): add ContextWithFallback feature flag [#3172](https://github.com/gin-gonic/gin/pull/3172) ## Gin v1.8.0 ## Break Changes * TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967). Please replace `RemoteIP() (net.IP, bool)` with `RemoteIP() net.IP` * gin.Context with fallback value from gin.Context.Request.Context() [#2751](https://github.com/gin-gonic/gin/pull/2751) ### BUGFIXES * Fixed SetOutput() panics on go 1.17 [#2861](https://github.com/gin-gonic/gin/pull/2861) * Fix: wrong when wildcard follows named param [#2983](https://github.com/gin-gonic/gin/pull/2983) * Fix: missing sameSite when do context.reset() [#3123](https://github.com/gin-gonic/gin/pull/3123) ### ENHANCEMENTS * Use Header() instead of deprecated HeaderMap [#2694](https://github.com/gin-gonic/gin/pull/2694) * RouterGroup.Handle regular match optimization of http method [#2685](https://github.com/gin-gonic/gin/pull/2685) * Add support go-json, another drop-in json replacement [#2680](https://github.com/gin-gonic/gin/pull/2680) * Use errors.New to replace fmt.Errorf will much better [#2707](https://github.com/gin-gonic/gin/pull/2707) * Use Duration.Truncate for truncating precision [#2711](https://github.com/gin-gonic/gin/pull/2711) * Get client IP when using Cloudflare [#2723](https://github.com/gin-gonic/gin/pull/2723) * Optimize code adjust [#2700](https://github.com/gin-gonic/gin/pull/2700/files) * Optimize code and reduce code cyclomatic complexity [#2737](https://github.com/gin-gonic/gin/pull/2737) * Improve sliceValidateError.Error performance [#2765](https://github.com/gin-gonic/gin/pull/2765) * Support custom struct tag [#2720](https://github.com/gin-gonic/gin/pull/2720) * Improve router group tests [#2787](https://github.com/gin-gonic/gin/pull/2787) * Fallback Context.Deadline() Context.Done() Context.Err() to Context.Request.Context() [#2769](https://github.com/gin-gonic/gin/pull/2769) * Some codes optimize [#2830](https://github.com/gin-gonic/gin/pull/2830) [#2834](https://github.com/gin-gonic/gin/pull/2834) [#2838](https://github.com/gin-gonic/gin/pull/2838) [#2837](https://github.com/gin-gonic/gin/pull/2837) [#2788](https://github.com/gin-gonic/gin/pull/2788) [#2848](https://github.com/gin-gonic/gin/pull/2848) [#2851](https://github.com/gin-gonic/gin/pull/2851) [#2701](https://github.com/gin-gonic/gin/pull/2701) * TrustedProxies: Add default IPv6 support and refactor [#2967](https://github.com/gin-gonic/gin/pull/2967) * Test(route): expose performRequest func [#3012](https://github.com/gin-gonic/gin/pull/3012) * Support h2c with prior knowledge [#1398](https://github.com/gin-gonic/gin/pull/1398) * Feat attachment filename support utf8 [#3071](https://github.com/gin-gonic/gin/pull/3071) * Feat: add StaticFileFS [#2749](https://github.com/gin-gonic/gin/pull/2749) * Feat(context): return GIN Context from Value method [#2825](https://github.com/gin-gonic/gin/pull/2825) * Feat: automatically SetMode to TestMode when run go test [#3139](https://github.com/gin-gonic/gin/pull/3139) * Add TOML bining for gin [#3081](https://github.com/gin-gonic/gin/pull/3081) * IPv6 add default trusted proxies [#3033](https://github.com/gin-gonic/gin/pull/3033) ### DOCS * Add note about nomsgpack tag to the readme [#2703](https://github.com/gin-gonic/gin/pull/2703) ## Gin v1.7.7 ### BUGFIXES * Fixed X-Forwarded-For unsafe handling of CVE-2020-28483 [#2844](https://github.com/gin-gonic/gin/pull/2844), closed issue [#2862](https://github.com/gin-gonic/gin/issues/2862). * Tree: updated the code logic for `latestNode` [#2897](https://github.com/gin-gonic/gin/pull/2897), closed issue [#2894](https://github.com/gin-gonic/gin/issues/2894) [#2878](https://github.com/gin-gonic/gin/issues/2878). * Tree: fixed the misplacement of adding slashes [#2847](https://github.com/gin-gonic/gin/pull/2847), closed issue [#2843](https://github.com/gin-gonic/gin/issues/2843). * Tree: fixed tsr with mixed static and wildcard paths [#2924](https://github.com/gin-gonic/gin/pull/2924), closed issue [#2918](https://github.com/gin-gonic/gin/issues/2918). ### ENHANCEMENTS * TrustedProxies: make it backward-compatible [#2887](https://github.com/gin-gonic/gin/pull/2887), closed issue [#2819](https://github.com/gin-gonic/gin/issues/2819). * TrustedPlatform: provide custom options for another CDN services [#2906](https://github.com/gin-gonic/gin/pull/2906). ### DOCS * NoMethod: added usage annotation ([#2832](https://github.com/gin-gonic/gin/pull/2832#issuecomment-929954463)). ## Gin v1.7.6 ### BUGFIXES * bump new release to fix v1.7.5 release error by using v1.7.4 codes. ## Gin v1.7.4 ### BUGFIXES * bump new release to fix checksum mismatch ## Gin v1.7.3 ### BUGFIXES * fix level 1 router match [#2767](https://github.com/gin-gonic/gin/issues/2767), [#2796](https://github.com/gin-gonic/gin/issues/2796) ## Gin v1.7.2 ### BUGFIXES * Fix conflict between param and exact path [#2706](https://github.com/gin-gonic/gin/issues/2706). Close issue [#2682](https://github.com/gin-gonic/gin/issues/2682) [#2696](https://github.com/gin-gonic/gin/issues/2696). ## Gin v1.7.1 ### BUGFIXES * fix: data race with trustedCIDRs from [#2674](https://github.com/gin-gonic/gin/issues/2674)([#2675](https://github.com/gin-gonic/gin/pull/2675)) ## Gin v1.7.0 ### BUGFIXES * fix compile error from [#2572](https://github.com/gin-gonic/gin/pull/2572) ([#2600](https://github.com/gin-gonic/gin/pull/2600)) * fix: print headers without Authorization header on broken pipe ([#2528](https://github.com/gin-gonic/gin/pull/2528)) * fix(tree): reassign fullpath when register new node ([#2366](https://github.com/gin-gonic/gin/pull/2366)) ### ENHANCEMENTS * Support params and exact routes without creating conflicts ([#2663](https://github.com/gin-gonic/gin/pull/2663)) * chore: improve render string performance ([#2365](https://github.com/gin-gonic/gin/pull/2365)) * Sync route tree to httprouter latest code ([#2368](https://github.com/gin-gonic/gin/pull/2368)) * chore: rename getQueryCache/getFormCache to initQueryCache/initFormCa ([#2375](https://github.com/gin-gonic/gin/pull/2375)) * chore(performance): improve countParams ([#2378](https://github.com/gin-gonic/gin/pull/2378)) * Remove some functions that have the same effect as the bytes package ([#2387](https://github.com/gin-gonic/gin/pull/2387)) * update:SetMode function ([#2321](https://github.com/gin-gonic/gin/pull/2321)) * remove an unused type SecureJSONPrefix ([#2391](https://github.com/gin-gonic/gin/pull/2391)) * Add a redirect sample for POST method ([#2389](https://github.com/gin-gonic/gin/pull/2389)) * Add CustomRecovery builtin middleware ([#2322](https://github.com/gin-gonic/gin/pull/2322)) * binding: avoid 2038 problem on 32-bit architectures ([#2450](https://github.com/gin-gonic/gin/pull/2450)) * Prevent panic in Context.GetQuery() when there is no Request ([#2412](https://github.com/gin-gonic/gin/pull/2412)) * Add GetUint and GetUint64 method on gin.context ([#2487](https://github.com/gin-gonic/gin/pull/2487)) * update content-disposition header to MIME-style ([#2512](https://github.com/gin-gonic/gin/pull/2512)) * reduce allocs and improve the render `WriteString` ([#2508](https://github.com/gin-gonic/gin/pull/2508)) * implement ".Unwrap() error" on Error type ([#2525](https://github.com/gin-gonic/gin/pull/2525)) ([#2526](https://github.com/gin-gonic/gin/pull/2526)) * Allow bind with a map[string]string ([#2484](https://github.com/gin-gonic/gin/pull/2484)) * chore: update tree ([#2371](https://github.com/gin-gonic/gin/pull/2371)) * Support binding for slice/array obj [Rewrite] ([#2302](https://github.com/gin-gonic/gin/pull/2302)) * basic auth: fix timing oracle ([#2609](https://github.com/gin-gonic/gin/pull/2609)) * Add mixed param and non-param paths (port of httprouter[#329](https://github.com/gin-gonic/gin/pull/329)) ([#2663](https://github.com/gin-gonic/gin/pull/2663)) * feat(engine): add trustedproxies and remoteIP ([#2632](https://github.com/gin-gonic/gin/pull/2632)) ## Gin v1.6.3 ### ENHANCEMENTS * Improve performance: Change `*sync.RWMutex` to `sync.RWMutex` in context. [#2351](https://github.com/gin-gonic/gin/pull/2351) ## Gin v1.6.2 ### BUGFIXES * fix missing initial sync.RWMutex [#2305](https://github.com/gin-gonic/gin/pull/2305) ### ENHANCEMENTS * Add set samesite in cookie. [#2306](https://github.com/gin-gonic/gin/pull/2306) ## Gin v1.6.1 ### BUGFIXES * Revert "fix accept incoming network connections" [#2294](https://github.com/gin-gonic/gin/pull/2294) ## Gin v1.6.0 ### BREAKING * chore(performance): Improve performance for adding RemoveExtraSlash flag [#2159](https://github.com/gin-gonic/gin/pull/2159) * drop support govendor [#2148](https://github.com/gin-gonic/gin/pull/2148) * Added support for SameSite cookie flag [#1615](https://github.com/gin-gonic/gin/pull/1615) ### FEATURES * add yaml negotiation [#2220](https://github.com/gin-gonic/gin/pull/2220) * FileFromFS [#2112](https://github.com/gin-gonic/gin/pull/2112) ### BUGFIXES * Unix Socket Handling [#2280](https://github.com/gin-gonic/gin/pull/2280) * Use json marshall in context json to fix breaking new line issue. Fixes #2209 [#2228](https://github.com/gin-gonic/gin/pull/2228) * fix accept incoming network connections [#2216](https://github.com/gin-gonic/gin/pull/2216) * Fixed a bug in the calculation of the maximum number of parameters [#2166](https://github.com/gin-gonic/gin/pull/2166) * [FIX] allow empty headers on DataFromReader [#2121](https://github.com/gin-gonic/gin/pull/2121) * Add mutex for protect Context.Keys map [#1391](https://github.com/gin-gonic/gin/pull/1391) ### ENHANCEMENTS * Add mitigation for log injection [#2277](https://github.com/gin-gonic/gin/pull/2277) * tree: range over nodes values [#2229](https://github.com/gin-gonic/gin/pull/2229) * tree: remove duplicate assignment [#2222](https://github.com/gin-gonic/gin/pull/2222) * chore: upgrade go-isatty and json-iterator/go [#2215](https://github.com/gin-gonic/gin/pull/2215) * path: sync code with httprouter [#2212](https://github.com/gin-gonic/gin/pull/2212) * Use zero-copy approach to convert types between string and byte slice [#2206](https://github.com/gin-gonic/gin/pull/2206) * Reuse bytes when cleaning the URL paths [#2179](https://github.com/gin-gonic/gin/pull/2179) * tree: remove one else statement [#2177](https://github.com/gin-gonic/gin/pull/2177) * tree: sync httprouter update (#2173) (#2172) [#2171](https://github.com/gin-gonic/gin/pull/2171) * tree: sync part httprouter codes and reduce if/else [#2163](https://github.com/gin-gonic/gin/pull/2163) * use http method constant [#2155](https://github.com/gin-gonic/gin/pull/2155) * upgrade go-validator to v10 [#2149](https://github.com/gin-gonic/gin/pull/2149) * Refactor redirect request in gin.go [#1970](https://github.com/gin-gonic/gin/pull/1970) * Add build tag nomsgpack [#1852](https://github.com/gin-gonic/gin/pull/1852) ### DOCS * docs(path): improve comments [#2223](https://github.com/gin-gonic/gin/pull/2223) * Renew README to fit the modification of SetCookie method [#2217](https://github.com/gin-gonic/gin/pull/2217) * Fix spelling [#2202](https://github.com/gin-gonic/gin/pull/2202) * Remove broken link from README. [#2198](https://github.com/gin-gonic/gin/pull/2198) * Update docs on Context.Done(), Context.Deadline() and Context.Err() [#2196](https://github.com/gin-gonic/gin/pull/2196) * Update validator to v10 [#2190](https://github.com/gin-gonic/gin/pull/2190) * upgrade go-validator to v10 for README [#2189](https://github.com/gin-gonic/gin/pull/2189) * Update to currently output [#2188](https://github.com/gin-gonic/gin/pull/2188) * Fix "Custom Validators" example [#2186](https://github.com/gin-gonic/gin/pull/2186) * Add project to README [#2165](https://github.com/gin-gonic/gin/pull/2165) * docs(benchmarks): for gin v1.5 [#2153](https://github.com/gin-gonic/gin/pull/2153) * Changed wording for clarity in README.md [#2122](https://github.com/gin-gonic/gin/pull/2122) ### MISC * ci support go1.14 [#2262](https://github.com/gin-gonic/gin/pull/2262) * chore: upgrade depend version [#2231](https://github.com/gin-gonic/gin/pull/2231) * Drop support go1.10 [#2147](https://github.com/gin-gonic/gin/pull/2147) * fix comment in `mode.go` [#2129](https://github.com/gin-gonic/gin/pull/2129) ## Gin v1.5.0 - [FIX] Use DefaultWriter and DefaultErrorWriter for debug messages [#1891](https://github.com/gin-gonic/gin/pull/1891) - [NEW] Now you can parse the inline lowercase start structure [#1893](https://github.com/gin-gonic/gin/pull/1893) - [FIX] Some code improvements [#1909](https://github.com/gin-gonic/gin/pull/1909) - [FIX] Use encode replace json marshal increase json encoder speed [#1546](https://github.com/gin-gonic/gin/pull/1546) - [NEW] Hold matched route full path in the Context [#1826](https://github.com/gin-gonic/gin/pull/1826) - [FIX] Fix context.Params race condition on Copy() [#1841](https://github.com/gin-gonic/gin/pull/1841) - [NEW] Add context param query cache [#1450](https://github.com/gin-gonic/gin/pull/1450) - [FIX] Improve GetQueryMap performance [#1918](https://github.com/gin-gonic/gin/pull/1918) - [FIX] Improve get post data [#1920](https://github.com/gin-gonic/gin/pull/1920) - [FIX] Use context instead of x/net/context [#1922](https://github.com/gin-gonic/gin/pull/1922) - [FIX] Attempt to fix PostForm cache bug [#1931](https://github.com/gin-gonic/gin/pull/1931) - [NEW] Add support of multipart multi files [#1949](https://github.com/gin-gonic/gin/pull/1949) - [NEW] Support bind http header param [#1957](https://github.com/gin-gonic/gin/pull/1957) - [FIX] Drop support for go1.8 and go1.9 [#1933](https://github.com/gin-gonic/gin/pull/1933) - [FIX] Bugfix for the FullPath feature [#1919](https://github.com/gin-gonic/gin/pull/1919) - [FIX] Gin1.5 bytes.Buffer to strings.Builder [#1939](https://github.com/gin-gonic/gin/pull/1939) - [FIX] Upgrade github.com/ugorji/go/codec [#1969](https://github.com/gin-gonic/gin/pull/1969) - [NEW] Support bind unix time [#1980](https://github.com/gin-gonic/gin/pull/1980) - [FIX] Simplify code [#2004](https://github.com/gin-gonic/gin/pull/2004) - [NEW] Support negative Content-Length in DataFromReader [#1981](https://github.com/gin-gonic/gin/pull/1981) - [FIX] Identify terminal on a RISC-V architecture for auto-colored logs [#2019](https://github.com/gin-gonic/gin/pull/2019) - [BREAKING] `Context.JSONP()` now expects a semicolon (`;`) at the end [#2007](https://github.com/gin-gonic/gin/pull/2007) - [BREAKING] Upgrade default `binding.Validator` to v9 (see [its changelog](https://github.com/go-playground/validator/releases/tag/v9.0.0)) [#1015](https://github.com/gin-gonic/gin/pull/1015) - [NEW] Add `DisallowUnknownFields()` in `Context.BindJSON()` [#2028](https://github.com/gin-gonic/gin/pull/2028) - [NEW] Use specific `net.Listener` with `Engine.RunListener()` [#2023](https://github.com/gin-gonic/gin/pull/2023) - [FIX] Fix some typo [#2079](https://github.com/gin-gonic/gin/pull/2079) [#2080](https://github.com/gin-gonic/gin/pull/2080) - [FIX] Relocate binding body tests [#2086](https://github.com/gin-gonic/gin/pull/2086) - [FIX] Use Writer in Context.Status [#1606](https://github.com/gin-gonic/gin/pull/1606) - [FIX] `Engine.RunUnix()` now returns the error if it can't change the file mode [#2093](https://github.com/gin-gonic/gin/pull/2093) - [FIX] `RouterGroup.StaticFS()` leaked files. Now it closes them. [#2118](https://github.com/gin-gonic/gin/pull/2118) - [FIX] `Context.Request.FormFile` leaked file. Now it closes it. [#2114](https://github.com/gin-gonic/gin/pull/2114) - [FIX] Ignore walking on `form:"-"` mapping [#1943](https://github.com/gin-gonic/gin/pull/1943) ### Gin v1.4.0 - [NEW] Support for [Go Modules](https://github.com/golang/go/wiki/Modules) [#1569](https://github.com/gin-gonic/gin/pull/1569) - [NEW] Refactor of form mapping multipart request [#1829](https://github.com/gin-gonic/gin/pull/1829) - [FIX] Truncate Latency precision in long running request [#1830](https://github.com/gin-gonic/gin/pull/1830) - [FIX] IsTerm flag should not be affected by DisableConsoleColor method. [#1802](https://github.com/gin-gonic/gin/pull/1802) - [NEW] Supporting file binding [#1264](https://github.com/gin-gonic/gin/pull/1264) - [NEW] Add support for mapping arrays [#1797](https://github.com/gin-gonic/gin/pull/1797) - [FIX] Readme updates [#1793](https://github.com/gin-gonic/gin/pull/1793) [#1788](https://github.com/gin-gonic/gin/pull/1788) [1789](https://github.com/gin-gonic/gin/pull/1789) - [FIX] StaticFS: Fixed Logging two log lines on 404. [#1805](https://github.com/gin-gonic/gin/pull/1805), [#1804](https://github.com/gin-gonic/gin/pull/1804) - [NEW] Make context.Keys available as LogFormatterParams [#1779](https://github.com/gin-gonic/gin/pull/1779) - [NEW] Use internal/json for Marshal/Unmarshal [#1791](https://github.com/gin-gonic/gin/pull/1791) - [NEW] Support mapping time.Duration [#1794](https://github.com/gin-gonic/gin/pull/1794) - [NEW] Refactor form mappings [#1749](https://github.com/gin-gonic/gin/pull/1749) - [NEW] Added flag to context.Stream indicates if client disconnected in middle of stream [#1252](https://github.com/gin-gonic/gin/pull/1252) - [FIX] Moved [examples](https://github.com/gin-gonic/examples) to stand alone Repo [#1775](https://github.com/gin-gonic/gin/pull/1775) - [NEW] Extend context.File to allow for the content-disposition attachments via a new method context.Attachment [#1260](https://github.com/gin-gonic/gin/pull/1260) - [FIX] Support HTTP content negotiation wildcards [#1112](https://github.com/gin-gonic/gin/pull/1112) - [NEW] Add prefix from X-Forwarded-Prefix in redirectTrailingSlash [#1238](https://github.com/gin-gonic/gin/pull/1238) - [FIX] context.Copy() race condition [#1020](https://github.com/gin-gonic/gin/pull/1020) - [NEW] Add context.HandlerNames() [#1729](https://github.com/gin-gonic/gin/pull/1729) - [FIX] Change color methods to public in the defaultLogger. [#1771](https://github.com/gin-gonic/gin/pull/1771) - [FIX] Update writeHeaders method to use http.Header.Set [#1722](https://github.com/gin-gonic/gin/pull/1722) - [NEW] Add response size to LogFormatterParams [#1752](https://github.com/gin-gonic/gin/pull/1752) - [NEW] Allow ignoring field on form mapping [#1733](https://github.com/gin-gonic/gin/pull/1733) - [NEW] Add a function to force color in console output. [#1724](https://github.com/gin-gonic/gin/pull/1724) - [FIX] Context.Next() - recheck len of handlers on every iteration. [#1745](https://github.com/gin-gonic/gin/pull/1745) - [FIX] Fix all errcheck warnings [#1739](https://github.com/gin-gonic/gin/pull/1739) [#1653](https://github.com/gin-gonic/gin/pull/1653) - [NEW] context: inherits context cancellation and deadline from http.Request context for Go>=1.7 [#1690](https://github.com/gin-gonic/gin/pull/1690) - [NEW] Binding for URL Params [#1694](https://github.com/gin-gonic/gin/pull/1694) - [NEW] Add LoggerWithFormatter method [#1677](https://github.com/gin-gonic/gin/pull/1677) - [FIX] CI testing updates [#1671](https://github.com/gin-gonic/gin/pull/1671) [#1670](https://github.com/gin-gonic/gin/pull/1670) [#1682](https://github.com/gin-gonic/gin/pull/1682) [#1669](https://github.com/gin-gonic/gin/pull/1669) - [FIX] StaticFS(): Send 404 when path does not exist [#1663](https://github.com/gin-gonic/gin/pull/1663) - [FIX] Handle nil body for JSON binding [#1638](https://github.com/gin-gonic/gin/pull/1638) - [FIX] Support bind uri param [#1612](https://github.com/gin-gonic/gin/pull/1612) - [FIX] recovery: fix issue with syscall import on google app engine [#1640](https://github.com/gin-gonic/gin/pull/1640) - [FIX] Make sure the debug log contains line breaks [#1650](https://github.com/gin-gonic/gin/pull/1650) - [FIX] Panic stack trace being printed during recovery of broken pipe [#1089](https://github.com/gin-gonic/gin/pull/1089) [#1259](https://github.com/gin-gonic/gin/pull/1259) - [NEW] RunFd method to run http.Server through a file descriptor [#1609](https://github.com/gin-gonic/gin/pull/1609) - [NEW] Yaml binding support [#1618](https://github.com/gin-gonic/gin/pull/1618) - [FIX] Pass MaxMultipartMemory when FormFile is called [#1600](https://github.com/gin-gonic/gin/pull/1600) - [FIX] LoadHTML* tests [#1559](https://github.com/gin-gonic/gin/pull/1559) - [FIX] Removed use of sync.pool from HandleContext [#1565](https://github.com/gin-gonic/gin/pull/1565) - [FIX] Format output log to os.Stderr [#1571](https://github.com/gin-gonic/gin/pull/1571) - [FIX] Make logger use a yellow background and a darkgray text for legibility [#1570](https://github.com/gin-gonic/gin/pull/1570) - [FIX] Remove sensitive request information from panic log. [#1370](https://github.com/gin-gonic/gin/pull/1370) - [FIX] log.Println() does not print timestamp [#829](https://github.com/gin-gonic/gin/pull/829) [#1560](https://github.com/gin-gonic/gin/pull/1560) - [NEW] Add PureJSON renderer [#694](https://github.com/gin-gonic/gin/pull/694) - [FIX] Add missing copyright and update if/else [#1497](https://github.com/gin-gonic/gin/pull/1497) - [FIX] Update msgpack usage [#1498](https://github.com/gin-gonic/gin/pull/1498) - [FIX] Use protobuf on render [#1496](https://github.com/gin-gonic/gin/pull/1496) - [FIX] Add support for Protobuf format response [#1479](https://github.com/gin-gonic/gin/pull/1479) - [NEW] Set default time format in form binding [#1487](https://github.com/gin-gonic/gin/pull/1487) - [FIX] Add BindXML and ShouldBindXML [#1485](https://github.com/gin-gonic/gin/pull/1485) - [NEW] Upgrade dependency libraries [#1491](https://github.com/gin-gonic/gin/pull/1491) ## Gin v1.3.0 - [NEW] Add [`func (*Context) QueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.QueryMap), [`func (*Context) GetQueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetQueryMap), [`func (*Context) PostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.PostFormMap) and [`func (*Context) GetPostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetPostFormMap) to support `type map[string]string` as query string or form parameters, see [#1383](https://github.com/gin-gonic/gin/pull/1383) - [NEW] Add [`func (*Context) AsciiJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.AsciiJSON), see [#1358](https://github.com/gin-gonic/gin/pull/1358) - [NEW] Add `Pusher()` in [`type ResponseWriter`](https://godoc.org/github.com/gin-gonic/gin#ResponseWriter) for supporting http2 push, see [#1273](https://github.com/gin-gonic/gin/pull/1273) - [NEW] Add [`func (*Context) DataFromReader`](https://godoc.org/github.com/gin-gonic/gin#Context.DataFromReader) for serving dynamic data, see [#1304](https://github.com/gin-gonic/gin/pull/1304) - [NEW] Add [`func (*Context) ShouldBindBodyWith`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindBodyWith) allowing to call binding multiple times, see [#1341](https://github.com/gin-gonic/gin/pull/1341) - [NEW] Support pointers in form binding, see [#1336](https://github.com/gin-gonic/gin/pull/1336) - [NEW] Add [`func (*Context) JSONP`](https://godoc.org/github.com/gin-gonic/gin#Context.JSONP), see [#1333](https://github.com/gin-gonic/gin/pull/1333) - [NEW] Support default value in form binding, see [#1138](https://github.com/gin-gonic/gin/pull/1138) - [NEW] Expose validator engine in [`type StructValidator`](https://godoc.org/github.com/gin-gonic/gin/binding#StructValidator), see [#1277](https://github.com/gin-gonic/gin/pull/1277) - [NEW] Add [`func (*Context) ShouldBind`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBind), [`func (*Context) ShouldBindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindQuery) and [`func (*Context) ShouldBindJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindJSON), see [#1047](https://github.com/gin-gonic/gin/pull/1047) - [NEW] Add support for `time.Time` location in form binding, see [#1117](https://github.com/gin-gonic/gin/pull/1117) - [NEW] Add [`func (*Context) BindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.BindQuery), see [#1029](https://github.com/gin-gonic/gin/pull/1029) - [NEW] Make [jsonite](https://github.com/json-iterator/go) optional with build tags, see [#1026](https://github.com/gin-gonic/gin/pull/1026) - [NEW] Show query string in logger, see [#999](https://github.com/gin-gonic/gin/pull/999) - [NEW] Add [`func (*Context) SecureJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.SecureJSON), see [#987](https://github.com/gin-gonic/gin/pull/987) and [#993](https://github.com/gin-gonic/gin/pull/993) - [DEPRECATE] `func (*Context) GetCookie` for [`func (*Context) Cookie`](https://godoc.org/github.com/gin-gonic/gin#Context.Cookie) - [FIX] Don't display color tags if [`func DisableConsoleColor`](https://godoc.org/github.com/gin-gonic/gin#DisableConsoleColor) called, see [#1072](https://github.com/gin-gonic/gin/pull/1072) - [FIX] Gin Mode `""` when calling [`func Mode`](https://godoc.org/github.com/gin-gonic/gin#Mode) now returns `const DebugMode`, see [#1250](https://github.com/gin-gonic/gin/pull/1250) - [FIX] `Flush()` now doesn't overwrite `responseWriter` status code, see [#1460](https://github.com/gin-gonic/gin/pull/1460) ## Gin 1.2.0 - [NEW] Switch from godeps to govendor - [NEW] Add support for Let's Encrypt via gin-gonic/autotls - [NEW] Improve README examples and add extra at examples folder - [NEW] Improved support with App Engine - [NEW] Add custom template delimiters, see #860 - [NEW] Add Template Func Maps, see #962 - [NEW] Add \*context.Handler(), see #928 - [NEW] Add \*context.GetRawData() - [NEW] Add \*context.GetHeader() (request) - [NEW] Add \*context.AbortWithStatusJSON() (JSON content type) - [NEW] Add \*context.Keys type cast helpers - [NEW] Add \*context.ShouldBindWith() - [NEW] Add \*context.MustBindWith() - [NEW] Add \*engine.SetFuncMap() - [DEPRECATE] On next release: \*context.BindWith(), see #855 - [FIX] Refactor render - [FIX] Reworked tests - [FIX] logger now supports cygwin - [FIX] Use X-Forwarded-For before X-Real-Ip - [FIX] time.Time binding (#904) ## Gin 1.1.4 - [NEW] Support google appengine for IsTerminal func ## Gin 1.1.3 - [FIX] Reverted Logger: skip ANSI color commands ## Gin 1.1 - [NEW] Implement QueryArray and PostArray methods - [NEW] Refactor GetQuery and GetPostForm - [NEW] Add contribution guide - [FIX] Corrected typos in README - [FIX] Removed additional Iota - [FIX] Changed imports to gopkg instead of github in README (#733) - [FIX] Logger: skip ANSI color commands if output is not a tty ## Gin 1.0rc2 (...) - [PERFORMANCE] Fast path for writing Content-Type. - [PERFORMANCE] Much faster 404 routing - [PERFORMANCE] Allocation optimizations - [PERFORMANCE] Faster root tree lookup - [PERFORMANCE] Zero overhead, String() and JSON() rendering. - [PERFORMANCE] Faster ClientIP parsing - [PERFORMANCE] Much faster SSE implementation - [NEW] Benchmarks suite - [NEW] Bind validation can be disabled and replaced with custom validators. - [NEW] More flexible HTML render - [NEW] Multipart and PostForm bindings - [NEW] Adds method to return all the registered routes - [NEW] Context.HandlerName() returns the main handler's name - [NEW] Adds Error.IsType() helper - [FIX] Binding multipart form - [FIX] Integration tests - [FIX] Crash when binding non struct object in Context. - [FIX] RunTLS() implementation - [FIX] Logger() unit tests - [FIX] Adds SetHTMLTemplate() warning - [FIX] Context.IsAborted() - [FIX] More unit tests - [FIX] JSON, XML, HTML renders accept custom content-types - [FIX] gin.AbortIndex is unexported - [FIX] Better approach to avoid directory listing in StaticFS() - [FIX] Context.ClientIP() always returns the IP with trimmed spaces. - [FIX] Better warning when running in debug mode. - [FIX] Google App Engine integration. debugPrint does not use os.Stdout - [FIX] Fixes integer overflow in error type - [FIX] Error implements the json.Marshaller interface - [FIX] MIT license in every file ## Gin 1.0rc1 (May 22, 2015) - [PERFORMANCE] Zero allocation router - [PERFORMANCE] Faster JSON, XML and text rendering - [PERFORMANCE] Custom hand optimized HttpRouter for Gin - [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations - [NEW] Built-in support for golang.org/x/net/context - [NEW] Any(path, handler). Create a route that matches any path - [NEW] Refactored rendering pipeline (faster and static typed) - [NEW] Refactored errors API - [NEW] IndentedJSON() prints pretty JSON - [NEW] Added gin.DefaultWriter - [NEW] UNIX socket support - [NEW] RouterGroup.BasePath is exposed - [NEW] JSON validation using go-validate-yourself (very powerful options) - [NEW] Completed suite of unit tests - [NEW] HTTP streaming with c.Stream() - [NEW] StaticFile() creates a router for serving just one file. - [NEW] StaticFS() has an option to disable directory listing. - [NEW] StaticFS() for serving static files through virtual filesystems - [NEW] Server-Sent Events native support - [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler - [NEW] Added LoggerWithWriter() middleware - [NEW] Added RecoveryWithWriter() middleware - [NEW] Added DefaultPostFormValue() - [NEW] Added DefaultFormValue() - [NEW] Added DefaultParamValue() - [FIX] BasicAuth() when using custom realm - [FIX] Bug when serving static files in nested routing group - [FIX] Redirect using built-in http.Redirect() - [FIX] Logger when printing the requested path - [FIX] Documentation typos - [FIX] Context.Engine renamed to Context.engine - [FIX] Better debugging messages - [FIX] ErrorLogger - [FIX] Debug HTTP render - [FIX] Refactored binding and render modules - [FIX] Refactored Context initialization - [FIX] Refactored BasicAuth() - [FIX] NoMethod/NoRoute handlers - [FIX] Hijacking http - [FIX] Better support for Google App Engine (using log instead of fmt) ## Gin 0.6 (Mar 9, 2015) - [NEW] Support multipart/form-data - [NEW] NoMethod handler - [NEW] Validate sub structures - [NEW] Support for HTTP Realm Auth - [FIX] Unsigned integers in binding - [FIX] Improve color logger ## Gin 0.5 (Feb 7, 2015) - [NEW] Content Negotiation - [FIX] Solved security bug that allow a client to spoof ip - [FIX] Fix unexported/ignored fields in binding ## Gin 0.4 (Aug 21, 2014) - [NEW] Development mode - [NEW] Unit tests - [NEW] Add Content.Redirect() - [FIX] Deferring WriteHeader() - [FIX] Improved documentation for model binding ## Gin 0.3 (Jul 18, 2014) - [PERFORMANCE] Normal log and error log are printed in the same call. - [PERFORMANCE] Improve performance of NoRouter() - [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults. - [NEW] Flexible rendering API - [NEW] Add Context.File() - [NEW] Add shortcut RunTLS() for http.ListenAndServeTLS - [FIX] Rename NotFound404() to NoRoute() - [FIX] Errors in context are purged - [FIX] Adds HEAD method in Static file serving - [FIX] Refactors Static() file serving - [FIX] Using keyed initialization to fix app-engine integration - [FIX] Can't unmarshal JSON array, #63 - [FIX] Renaming Context.Req to Context.Request - [FIX] Check application/x-www-form-urlencoded when parsing form ## Gin 0.2b (Jul 08, 2014) - [PERFORMANCE] Using sync.Pool to allocatio/gc overhead - [NEW] Travis CI integration - [NEW] Completely new logger - [NEW] New API for serving static files. gin.Static() - [NEW] gin.H() can be serialized into XML - [NEW] Typed errors. Errors can be typed. Internet/external/custom. - [NEW] Support for Godeps - [NEW] Travis/Godocs badges in README - [NEW] New Bind() and BindWith() methods for parsing request body. - [NEW] Add Content.Copy() - [NEW] Add context.LastError() - [NEW] Add shortcut for OPTIONS HTTP method - [FIX] Tons of README fixes - [FIX] Header is written before body - [FIX] BasicAuth() and changes API a little bit - [FIX] Recovery() middleware only prints panics - [FIX] Context.Get() does not panic anymore. Use MustGet() instead. - [FIX] Multiple http.WriteHeader() in NotFound handlers - [FIX] Engine.Run() panics if http server can't be set up - [FIX] Crash when route path doesn't start with '/' - [FIX] Do not update header when status code is negative - [FIX] Setting response headers before calling WriteHeader in context.String() - [FIX] Add MIT license - [FIX] Changes behaviour of ErrorLogger() and Logger()
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.git/logs/HEAD
0000000000000000000000000000000000000000 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031630 +0000 clone: from https://github.com/gin-gonic/gin.git 53fbf4dbfbf465b552057e6f8d199a275151b7a1 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031654 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 dc9cff732e27ce4ac21b25772a83c462a28b8b80 jupyter <[email protected]> 1705031654 +0000 checkout: moving from master to dc9cff732e27ce4ac21b25772a83c462a28b8b80 dc9cff732e27ce4ac21b25772a83c462a28b8b80 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031654 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 c2ba8f19ec19914b73290c53a32de479cd463555 jupyter <[email protected]> 1705031654 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to c2ba8f19ec19914b73290c53a32de479cd463555 c2ba8f19ec19914b73290c53a32de479cd463555 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031669 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 bb1fc2e0fe97c63dab1527baab88d01183853b8f jupyter <[email protected]> 1705031669 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to bb1fc2e0fe97c63dab1527baab88d01183853b8f bb1fc2e0fe97c63dab1527baab88d01183853b8f 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031669 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 4ea0e648e38a63d6caff14100f5eab5c50912bcd jupyter <[email protected]> 1705031669 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 4ea0e648e38a63d6caff14100f5eab5c50912bcd 4ea0e648e38a63d6caff14100f5eab5c50912bcd 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031681 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 fe989b6a6f8091b2708b39a60b1dd2a2bd3b2812 jupyter <[email protected]> 1705031681 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to fe989b6a6f8091b2708b39a60b1dd2a2bd3b2812 fe989b6a6f8091b2708b39a60b1dd2a2bd3b2812 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031681 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 757a638b7bbdd998375432fb22f693e82d7a7840 jupyter <[email protected]> 1705031681 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 757a638b7bbdd998375432fb22f693e82d7a7840 757a638b7bbdd998375432fb22f693e82d7a7840 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031707 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 44d0dd70924dd154e3b98bc340accc53484efa9c jupyter <[email protected]> 1705031707 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 44d0dd70924dd154e3b98bc340accc53484efa9c 44d0dd70924dd154e3b98bc340accc53484efa9c 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031707 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 386d244068db3693f938db4ead6d1f5f85942e3f jupyter <[email protected]> 1705031707 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 386d244068db3693f938db4ead6d1f5f85942e3f 386d244068db3693f938db4ead6d1f5f85942e3f 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031716 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 0c96a20209ca035964be126a745c167196fb6db3 jupyter <[email protected]> 1705031716 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 0c96a20209ca035964be126a745c167196fb6db3 0c96a20209ca035964be126a745c167196fb6db3 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031716 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 bd82c9e351be91e9e8267e5ce011627dd6c55d51 jupyter <[email protected]> 1705031716 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to bd82c9e351be91e9e8267e5ce011627dd6c55d51 bd82c9e351be91e9e8267e5ce011627dd6c55d51 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031722 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 4cee78f5382d5245c3652e6c15fee715eec505c3 jupyter <[email protected]> 1705031722 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 4cee78f5382d5245c3652e6c15fee715eec505c3 4cee78f5382d5245c3652e6c15fee715eec505c3 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031722 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 ea03e10384502e1baf6f560a2b0ea32c342ede5b jupyter <[email protected]> 1705031722 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to ea03e10384502e1baf6f560a2b0ea32c342ede5b ea03e10384502e1baf6f560a2b0ea32c342ede5b 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031738 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 7d8fc1563b4e1b4229e61c2fe4c9e31ce13ace7d jupyter <[email protected]> 1705031738 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 7d8fc1563b4e1b4229e61c2fe4c9e31ce13ace7d 7d8fc1563b4e1b4229e61c2fe4c9e31ce13ace7d 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031738 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 c9b27249fbb6092bcc7f749811d73ef1d50eee73 jupyter <[email protected]> 1705031738 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to c9b27249fbb6092bcc7f749811d73ef1d50eee73 c9b27249fbb6092bcc7f749811d73ef1d50eee73 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031773 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 234a1d33f7b329a6d701a7b249167f72de57c901 jupyter <[email protected]> 1705031773 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 234a1d33f7b329a6d701a7b249167f72de57c901
0000000000000000000000000000000000000000 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031630 +0000 clone: from https://github.com/gin-gonic/gin.git 53fbf4dbfbf465b552057e6f8d199a275151b7a1 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031654 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 dc9cff732e27ce4ac21b25772a83c462a28b8b80 jupyter <[email protected]> 1705031654 +0000 checkout: moving from master to dc9cff732e27ce4ac21b25772a83c462a28b8b80 dc9cff732e27ce4ac21b25772a83c462a28b8b80 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031654 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 c2ba8f19ec19914b73290c53a32de479cd463555 jupyter <[email protected]> 1705031654 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to c2ba8f19ec19914b73290c53a32de479cd463555 c2ba8f19ec19914b73290c53a32de479cd463555 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031669 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 bb1fc2e0fe97c63dab1527baab88d01183853b8f jupyter <[email protected]> 1705031669 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to bb1fc2e0fe97c63dab1527baab88d01183853b8f bb1fc2e0fe97c63dab1527baab88d01183853b8f 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031669 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 4ea0e648e38a63d6caff14100f5eab5c50912bcd jupyter <[email protected]> 1705031669 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 4ea0e648e38a63d6caff14100f5eab5c50912bcd 4ea0e648e38a63d6caff14100f5eab5c50912bcd 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031681 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 fe989b6a6f8091b2708b39a60b1dd2a2bd3b2812 jupyter <[email protected]> 1705031681 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to fe989b6a6f8091b2708b39a60b1dd2a2bd3b2812 fe989b6a6f8091b2708b39a60b1dd2a2bd3b2812 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031681 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 757a638b7bbdd998375432fb22f693e82d7a7840 jupyter <[email protected]> 1705031681 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 757a638b7bbdd998375432fb22f693e82d7a7840 757a638b7bbdd998375432fb22f693e82d7a7840 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031707 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 44d0dd70924dd154e3b98bc340accc53484efa9c jupyter <[email protected]> 1705031707 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 44d0dd70924dd154e3b98bc340accc53484efa9c 44d0dd70924dd154e3b98bc340accc53484efa9c 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031707 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 386d244068db3693f938db4ead6d1f5f85942e3f jupyter <[email protected]> 1705031707 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 386d244068db3693f938db4ead6d1f5f85942e3f 386d244068db3693f938db4ead6d1f5f85942e3f 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031716 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 0c96a20209ca035964be126a745c167196fb6db3 jupyter <[email protected]> 1705031716 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 0c96a20209ca035964be126a745c167196fb6db3 0c96a20209ca035964be126a745c167196fb6db3 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031716 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 bd82c9e351be91e9e8267e5ce011627dd6c55d51 jupyter <[email protected]> 1705031716 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to bd82c9e351be91e9e8267e5ce011627dd6c55d51 bd82c9e351be91e9e8267e5ce011627dd6c55d51 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031722 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 4cee78f5382d5245c3652e6c15fee715eec505c3 jupyter <[email protected]> 1705031722 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 4cee78f5382d5245c3652e6c15fee715eec505c3 4cee78f5382d5245c3652e6c15fee715eec505c3 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031722 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 ea03e10384502e1baf6f560a2b0ea32c342ede5b jupyter <[email protected]> 1705031722 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to ea03e10384502e1baf6f560a2b0ea32c342ede5b ea03e10384502e1baf6f560a2b0ea32c342ede5b 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031738 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 7d8fc1563b4e1b4229e61c2fe4c9e31ce13ace7d jupyter <[email protected]> 1705031738 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 7d8fc1563b4e1b4229e61c2fe4c9e31ce13ace7d 7d8fc1563b4e1b4229e61c2fe4c9e31ce13ace7d 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031738 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 c9b27249fbb6092bcc7f749811d73ef1d50eee73 jupyter <[email protected]> 1705031738 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to c9b27249fbb6092bcc7f749811d73ef1d50eee73 c9b27249fbb6092bcc7f749811d73ef1d50eee73 53fbf4dbfbf465b552057e6f8d199a275151b7a1 jupyter <[email protected]> 1705031773 +0000 reset: moving to origin/master 53fbf4dbfbf465b552057e6f8d199a275151b7a1 234a1d33f7b329a6d701a7b249167f72de57c901 jupyter <[email protected]> 1705031773 +0000 checkout: moving from 53fbf4dbfbf465b552057e6f8d199a275151b7a1 to 234a1d33f7b329a6d701a7b249167f72de57c901
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./render/redirect.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "fmt" "net/http" ) // Redirect contains the http request reference and redirects status code and location. type Redirect struct { Code int Request *http.Request Location string } // Render (Redirect) redirects the http request to new location and writes redirect response. func (r Redirect) Render(w http.ResponseWriter) error { if (r.Code < http.StatusMultipleChoices || r.Code > http.StatusPermanentRedirect) && r.Code != http.StatusCreated { panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code)) } http.Redirect(w, r.Request, r.Location, r.Code) return nil } // WriteContentType (Redirect) don't write any ContentType. func (r Redirect) WriteContentType(http.ResponseWriter) {}
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "fmt" "net/http" ) // Redirect contains the http request reference and redirects status code and location. type Redirect struct { Code int Request *http.Request Location string } // Render (Redirect) redirects the http request to new location and writes redirect response. func (r Redirect) Render(w http.ResponseWriter) error { if (r.Code < http.StatusMultipleChoices || r.Code > http.StatusPermanentRedirect) && r.Code != http.StatusCreated { panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code)) } http.Redirect(w, r.Request, r.Location, r.Code) return nil } // WriteContentType (Redirect) don't write any ContentType. func (r Redirect) WriteContentType(http.ResponseWriter) {}
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.github/workflows/goreleaser.yml
name: Goreleaser on: push: tags: - '*' permissions: contents: write jobs: goreleaser: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Go uses: actions/setup-go@v3 with: go-version: 1.17 - name: Run GoReleaser uses: goreleaser/goreleaser-action@v3 with: # either 'goreleaser' (default) or 'goreleaser-pro' distribution: goreleaser version: latest args: release --rm-dist env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
name: Goreleaser on: push: tags: - '*' permissions: contents: write jobs: goreleaser: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Go uses: actions/setup-go@v3 with: go-version: 1.17 - name: Run GoReleaser uses: goreleaser/goreleaser-action@v3 with: # either 'goreleaser' (default) or 'goreleaser-pro' distribution: goreleaser version: latest args: release --rm-dist env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./.github/workflows/codeql.yml
# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. name: "CodeQL" on: push: branches: [ master ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] schedule: - cron: '0 17 * * 5' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: # required for all workflows security-events: write strategy: fail-fast: false matrix: # Override automatic language detection by changing the below list # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] # TODO: Enable for javascript later language: [ 'go'] steps: - name: Checkout repository uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2
# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. name: "CodeQL" on: push: branches: [ master ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] schedule: - cron: '0 17 * * 5' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: # required for all workflows security-events: write strategy: fail-fast: false matrix: # Override automatic language detection by changing the below list # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] # TODO: Enable for javascript later language: [ 'go'] steps: - name: Checkout repository uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./benchmarks_test.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "html/template" "net/http" "os" "testing" ) func BenchmarkOneRoute(B *testing.B) { router := New() router.GET("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func BenchmarkRecoveryMiddleware(B *testing.B) { router := New() router.Use(Recovery()) router.GET("/", func(c *Context) {}) runRequest(B, router, "GET", "/") } func BenchmarkLoggerMiddleware(B *testing.B) { router := New() router.Use(LoggerWithWriter(newMockWriter())) router.GET("/", func(c *Context) {}) runRequest(B, router, "GET", "/") } func BenchmarkManyHandlers(B *testing.B) { router := New() router.Use(Recovery(), LoggerWithWriter(newMockWriter())) router.Use(func(c *Context) {}) router.Use(func(c *Context) {}) router.GET("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func Benchmark5Params(B *testing.B) { DefaultWriter = os.Stdout router := New() router.Use(func(c *Context) {}) router.GET("/param/:param1/:params2/:param3/:param4/:param5", func(c *Context) {}) runRequest(B, router, "GET", "/param/path/to/parameter/john/12345") } func BenchmarkOneRouteJSON(B *testing.B) { router := New() data := struct { Status string `json:"status"` }{"ok"} router.GET("/json", func(c *Context) { c.JSON(http.StatusOK, data) }) runRequest(B, router, "GET", "/json") } func BenchmarkOneRouteHTML(B *testing.B) { router := New() t := template.Must(template.New("index").Parse(` <html><body><h1>{{.}}</h1></body></html>`)) router.SetHTMLTemplate(t) router.GET("/html", func(c *Context) { c.HTML(http.StatusOK, "index", "hola") }) runRequest(B, router, "GET", "/html") } func BenchmarkOneRouteSet(B *testing.B) { router := New() router.GET("/ping", func(c *Context) { c.Set("key", "value") }) runRequest(B, router, "GET", "/ping") } func BenchmarkOneRouteString(B *testing.B) { router := New() router.GET("/text", func(c *Context) { c.String(http.StatusOK, "this is a plain text") }) runRequest(B, router, "GET", "/text") } func BenchmarkManyRoutesFist(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func BenchmarkManyRoutesLast(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, "OPTIONS", "/ping") } func Benchmark404(B *testing.B) { router := New() router.Any("/something", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func Benchmark404Many(B *testing.B) { router := New() router.GET("/", func(c *Context) {}) router.GET("/path/to/something", func(c *Context) {}) router.GET("/post/:id", func(c *Context) {}) router.GET("/view/:id", func(c *Context) {}) router.GET("/favicon.ico", func(c *Context) {}) router.GET("/robots.txt", func(c *Context) {}) router.GET("/delete/:id", func(c *Context) {}) router.GET("/user/:id/:mode", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, "GET", "/viewfake") } type mockWriter struct { headers http.Header } func newMockWriter() *mockWriter { return &mockWriter{ http.Header{}, } } func (m *mockWriter) Header() (h http.Header) { return m.headers } func (m *mockWriter) Write(p []byte) (n int, err error) { return len(p), nil } func (m *mockWriter) WriteString(s string) (n int, err error) { return len(s), nil } func (m *mockWriter) WriteHeader(int) {} func runRequest(B *testing.B, r *Engine, method, path string) { // create fake request req, err := http.NewRequest(method, path, nil) if err != nil { panic(err) } w := newMockWriter() B.ReportAllocs() B.ResetTimer() for i := 0; i < B.N; i++ { r.ServeHTTP(w, req) } }
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "html/template" "net/http" "os" "testing" ) func BenchmarkOneRoute(B *testing.B) { router := New() router.GET("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func BenchmarkRecoveryMiddleware(B *testing.B) { router := New() router.Use(Recovery()) router.GET("/", func(c *Context) {}) runRequest(B, router, "GET", "/") } func BenchmarkLoggerMiddleware(B *testing.B) { router := New() router.Use(LoggerWithWriter(newMockWriter())) router.GET("/", func(c *Context) {}) runRequest(B, router, "GET", "/") } func BenchmarkManyHandlers(B *testing.B) { router := New() router.Use(Recovery(), LoggerWithWriter(newMockWriter())) router.Use(func(c *Context) {}) router.Use(func(c *Context) {}) router.GET("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func Benchmark5Params(B *testing.B) { DefaultWriter = os.Stdout router := New() router.Use(func(c *Context) {}) router.GET("/param/:param1/:params2/:param3/:param4/:param5", func(c *Context) {}) runRequest(B, router, "GET", "/param/path/to/parameter/john/12345") } func BenchmarkOneRouteJSON(B *testing.B) { router := New() data := struct { Status string `json:"status"` }{"ok"} router.GET("/json", func(c *Context) { c.JSON(http.StatusOK, data) }) runRequest(B, router, "GET", "/json") } func BenchmarkOneRouteHTML(B *testing.B) { router := New() t := template.Must(template.New("index").Parse(` <html><body><h1>{{.}}</h1></body></html>`)) router.SetHTMLTemplate(t) router.GET("/html", func(c *Context) { c.HTML(http.StatusOK, "index", "hola") }) runRequest(B, router, "GET", "/html") } func BenchmarkOneRouteSet(B *testing.B) { router := New() router.GET("/ping", func(c *Context) { c.Set("key", "value") }) runRequest(B, router, "GET", "/ping") } func BenchmarkOneRouteString(B *testing.B) { router := New() router.GET("/text", func(c *Context) { c.String(http.StatusOK, "this is a plain text") }) runRequest(B, router, "GET", "/text") } func BenchmarkManyRoutesFist(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func BenchmarkManyRoutesLast(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, "OPTIONS", "/ping") } func Benchmark404(B *testing.B) { router := New() router.Any("/something", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, "GET", "/ping") } func Benchmark404Many(B *testing.B) { router := New() router.GET("/", func(c *Context) {}) router.GET("/path/to/something", func(c *Context) {}) router.GET("/post/:id", func(c *Context) {}) router.GET("/view/:id", func(c *Context) {}) router.GET("/favicon.ico", func(c *Context) {}) router.GET("/robots.txt", func(c *Context) {}) router.GET("/delete/:id", func(c *Context) {}) router.GET("/user/:id/:mode", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, "GET", "/viewfake") } type mockWriter struct { headers http.Header } func newMockWriter() *mockWriter { return &mockWriter{ http.Header{}, } } func (m *mockWriter) Header() (h http.Header) { return m.headers } func (m *mockWriter) Write(p []byte) (n int, err error) { return len(p), nil } func (m *mockWriter) WriteString(s string) (n int, err error) { return len(s), nil } func (m *mockWriter) WriteHeader(int) {} func runRequest(B *testing.B, r *Engine, method, path string) { // create fake request req, err := http.NewRequest(method, path, nil) if err != nil { panic(err) } w := newMockWriter() B.ReportAllocs() B.ResetTimer() for i := 0; i < B.N; i++ { r.ServeHTTP(w, req) } }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./AUTHORS.md
List of all the awesome people working to make Gin the best Web Framework in Go. ## gin 1.x series authors **Gin Core Team:** Bo-Yi Wu (@appleboy), thinkerou (@thinkerou), Javier Provecho (@javierprovecho) ## gin 0.x series authors **Maintainers:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) ------ People and companies, who have contributed, in alphabetical order. - 178inaba <[email protected]> - A. F <[email protected]> - ABHISHEK SONI <[email protected]> - Abhishek Chanda <[email protected]> - Abner Chen <[email protected]> - AcoNCodes <[email protected]> - Adam Dratwinski <[email protected]> - Adam Mckaig <[email protected]> - Adam Zielinski <[email protected]> - Adonis <[email protected]> - Alan Wang <[email protected]> - Albin Gilles <[email protected]> - Aleksandr Didenko <[email protected]> - Alessandro (Ale) Segala <[email protected]> - Alex <[email protected]> - Alexander <[email protected]> - Alexander Lokhman <[email protected]> - Alexander Melentyev <[email protected]> - Alexander Nyquist <[email protected]> - Allen Ren <[email protected]> - AllinGo <[email protected]> - Ammar Bandukwala <[email protected]> - An Xiao (Luffy) <[email protected]> - Andre Dublin <[email protected]> - Andrew Szeto <[email protected]> - Andrey Abramov <[email protected]> - Andrey Nering <[email protected]> - Andrey Smirnov <[email protected]> - Andrii Bubis <[email protected]> - André Bazaglia <[email protected]> - Andy Pan <[email protected]> - Antoine GIRARD <[email protected]> - Anup Kumar Panwar <[email protected]> - Aravinth Sundaram <[email protected]> - Artem <[email protected]> - Ashwani <[email protected]> - Aurelien Regat-Barrel <[email protected]> - Austin Heap <[email protected]> - Barnabus <[email protected]> - Bo-Yi Wu <[email protected]> - Boris Borshevsky <[email protected]> - Boyi Wu <[email protected]> - BradyBromley <[email protected]> - Brendan Fosberry <[email protected]> - Brian Wigginton <[email protected]> - Carlos Eduardo <[email protected]> - Chad Russell <[email protected]> - Charles <[email protected]> - Christian Muehlhaeuser <[email protected]> - Christian Persson <[email protected]> - Christopher Harrington <[email protected]> - Damon Zhao <[email protected]> - Dan Markham <[email protected]> - Dang Nguyen <[email protected]> - Daniel Krom <[email protected]> - Daniel M. Lambea <[email protected]> - Danieliu <[email protected]> - David Irvine <[email protected]> - David Zhang <[email protected]> - Davor Kapsa <[email protected]> - DeathKing <[email protected]> - Dennis Cho <[email protected]> - Dmitry Dorogin <[email protected]> - Dmitry Kutakov <[email protected]> - Dmitry Sedykh <[email protected]> - Don2Quixote <[email protected]> - Donn Pebe <[email protected]> - Dustin Decker <[email protected]> - Eason Lin <[email protected]> - Edward Betts <[email protected]> - Egor Seredin <[email protected]> - Emmanuel Goh <[email protected]> - Equim <[email protected]> - Eren A. Akyol <[email protected]> - Eric_Lee <[email protected]> - Erik Bender <[email protected]> - Ethan Kan <[email protected]> - Evgeny Persienko <[email protected]> - Faisal Alam <[email protected]> - Fareed Dudhia <[email protected]> - Filip Figiel <[email protected]> - Florian Polster <[email protected]> - Frank Bille <[email protected]> - Franz Bettag <[email protected]> - Ganlv <[email protected]> - Gaozhen Ying <[email protected]> - George Gabolaev <[email protected]> - George Kirilenko <[email protected]> - Georges Varouchas <[email protected]> - Gordon Tyler <[email protected]> - Harindu Perera <[email protected]> - Helios <[email protected]> - Henry Kwan <[email protected]> - Henry Yee <[email protected]> - Himanshu Mishra <[email protected]> - Hiroyuki Tanaka <[email protected]> - Ibraheem Ahmed <[email protected]> - Ignacio Galindo <[email protected]> - Igor H. Vieira <[email protected]> - Ildar1111 <[email protected]> - Iskander (Alex) Sharipov <[email protected]> - Ismail Gjevori <[email protected]> - Ivan Chen <[email protected]> - JINNOUCHI Yasushi <[email protected]> - James Pettyjohn <[email protected]> - Jamie Stackhouse <[email protected]> - Jason Lee <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho Fernandez <[email protected]> - Javier Provecho Fernandez <[email protected]> - Jean-Christophe Lebreton <[email protected]> - Jeff <[email protected]> - Jeremy Loy <[email protected]> - Jim Filippou <[email protected]> - Jimmy Pettersson <[email protected]> - John Bampton <[email protected]> - Johnny Dallas <[email protected]> - Johnny Dallas <[email protected]> - Jonathan (JC) Chen <[email protected]> - Josep Jesus Bigorra Algaba <[email protected]> - Josh Horowitz <[email protected]> - Joshua Loper <[email protected]> - Julien Schmidt <[email protected]> - Jun Kimura <[email protected]> - Justin Beckwith <[email protected]> - Justin Israel <[email protected]> - Justin Mayhew <[email protected]> - Jérôme Laforge <[email protected]> - Kacper Bąk <[email protected]> - Kamron Batman <[email protected]> - Kane Rogers <[email protected]> - Kaushik Neelichetty <[email protected]> - Keiji Yoshida <[email protected]> - Kel Cecil <[email protected]> - Kevin Mulvey <[email protected]> - Kevin Zhu <[email protected]> - Kirill Motkov <[email protected]> - Klemen Sever <[email protected]> - Kristoffer A. Iversen <[email protected]> - Krzysztof Szafrański <[email protected]> - Kumar McMillan <[email protected]> - Kyle Mcgill <[email protected]> - Lanco <[email protected]> - Levi Olson <[email protected]> - Lin Kao-Yuan <[email protected]> - Linus Unnebäck <[email protected]> - Lucas Clemente <[email protected]> - Ludwig Valda Vasquez <[email protected]> - Luis GG <[email protected]> - MW Lim <[email protected]> - Maksimov Sergey <[email protected]> - Manjusaka <[email protected]> - Manu MA <[email protected]> - Manu MA <[email protected]> - Manu Mtz-Almeida <[email protected]> - Manu Mtz.-Almeida <[email protected]> - Manuel Alonso <[email protected]> - Mara Kim <[email protected]> - Mario Kostelac <[email protected]> - Martin Karlsch <[email protected]> - Matt Newberry <[email protected]> - Matt Williams <[email protected]> - Matthieu MOREL <[email protected]> - Max Hilbrunner <[email protected]> - Maxime Soulé <[email protected]> - MetalBreaker <[email protected]> - Michael Puncel <[email protected]> - MichaelDeSteven <[email protected]> - Mike <[email protected]> - Mike Stipicevic <[email protected]> - Miki Tebeka <[email protected]> - Miles <[email protected]> - Mirza Ceric <[email protected]> - Mykyta Semenistyi <[email protected]> - Naoki Takano <[email protected]> - Ngalim Siregar <[email protected]> - Ni Hao <[email protected]> - Nick Gerakines <[email protected]> - Nikifor Seryakov <[email protected]> - Notealot <[email protected]> - Olivier Mengué <[email protected]> - Olivier Robardet <[email protected]> - Pablo Moncada <[email protected]> - Pablo Moncada <[email protected]> - Panmax <[email protected]> - Peperoncino <[email protected]> - Philipp Meinen <[email protected]> - Pierre Massat <[email protected]> - Qt <[email protected]> - Quentin ROYER <[email protected]> - README Bot <[email protected]> - Rafal Zajac <[email protected]> - Rahul Datta Roy <[email protected]> - Rajiv Kilaparti <[email protected]> - Raphael Gavache <[email protected]> - Ray Rodriguez <[email protected]> - Regner Blok-Andersen <[email protected]> - Remco <[email protected]> - Rex Lee(李俊) <[email protected]> - Richard Lee <[email protected]> - Riverside <[email protected]> - Robert Wilkinson <[email protected]> - Rogier Lommers <[email protected]> - Rohan Pai <[email protected]> - Romain Beuque <[email protected]> - Roman Belyakovsky <[email protected]> - Roman Zaynetdinov <[email protected]> - Roman Zaynetdinov <[email protected]> - Ronald Petty <[email protected]> - Ross Wolf <[email protected]> - Roy Lou <[email protected]> - Rubi <[email protected]> - Ryan <[email protected]> - Ryan J. Yoder <[email protected]> - SRK.Lyu <[email protected]> - Sai <[email protected]> - Samuel Abreu <[email protected]> - Santhosh Kumar <[email protected]> - Sasha Melentyev <[email protected]> - Sasha Myasoedov <[email protected]> - Segev Finer <[email protected]> - Sergey Egorov <[email protected]> - Sergey Fedchenko <[email protected]> - Sergey Gonimar <[email protected]> - Sergey Ponomarev <[email protected]> - Serica <[email protected]> - Shamus Taylor <[email protected]> - Shilin Wang <[email protected]> - Shuo <[email protected]> - Skuli Oskarsson <[email protected]> - Snawoot <[email protected]> - Sridhar Ratnakumar <[email protected]> - Steeve Chailloux <[email protected]> - Sudhir Mishra <[email protected]> - Suhas Karanth <[email protected]> - TaeJun Park <[email protected]> - Tatsuya Hoshino <[email protected]> - Tevic <[email protected]> - Tevin Jeffrey <[email protected]> - The Gitter Badger <[email protected]> - Thibault Jamet <[email protected]> - Thomas Boerger <[email protected]> - Thomas Schaffer <[email protected]> - Tommy Chu <[email protected]> - Tudor Roman <[email protected]> - Uwe Dauernheim <[email protected]> - Valentine Oragbakosi <[email protected]> - Vas N <[email protected]> - Vasilyuk Vasiliy <[email protected]> - Victor Castell <[email protected]> - Vince Yuan <[email protected]> - Vyacheslav Dubinin <[email protected]> - Waynerv <[email protected]> - Weilin Shi <[email protected]> - Xudong Cai <[email protected]> - Yasuhiro Matsumoto <[email protected]> - Yehezkiel Syamsuhadi <[email protected]> - Yoshiki Nakagawa <[email protected]> - Yoshiyuki Kinjo <[email protected]> - Yue Yang <[email protected]> - ZYunH <[email protected]> - Zach Newburgh <[email protected]> - Zasda Yusuf Mikail <[email protected]> - ZhangYunHao <[email protected]> - ZhiFeng Hu <[email protected]> - Zhu Xi <[email protected]> - a2tt <[email protected]> - ahuigo <[email protected]> - ali <[email protected]> - aljun <[email protected]> - andrea <[email protected]> - andriikushch <[email protected]> - anoty <[email protected]> - awkj <[email protected]> - axiaoxin <[email protected]> - bbiao <[email protected]> - bestgopher <[email protected]> - betahu <[email protected]> - bigwheel <[email protected]> - bn4t <[email protected]> - bullgare <[email protected]> - chainhelen <[email protected]> - chenyang929 <[email protected]> - chriswhelix <[email protected]> - collinmsn <[email protected]> - cssivision <[email protected]> - danielalves <[email protected]> - delphinus <[email protected]> - dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> - dickeyxxx <[email protected]> - edebernis <[email protected]> - error10 <[email protected]> - esplo <[email protected]> - eudore <[email protected]> - ffhelicopter <[email protected]> - filikos <[email protected]> - forging2012 <[email protected]> - goqihoo <[email protected]> - grapeVine <[email protected]> - guonaihong <[email protected]> - heige <[email protected]> - heige <[email protected]> - hellojukay <[email protected]> - henrylee2cn <[email protected]> - htobenothing <[email protected]> - iamhesir <[email protected]> - ijaa <[email protected]> - ishanray <[email protected]> - ishanray <[email protected]> - itcloudy <[email protected]> - jarodsong6 <[email protected]> - jasonrhansen <[email protected]> - jincheng9 <[email protected]> - joeADSP <[email protected]> - junfengye <[email protected]> - kaiiak <[email protected]> - kebo <[email protected]> - keke <[email protected]> - kishor kunal raj <[email protected]> - kyledinh <[email protected]> - lantw44 <[email protected]> - likakuli <[email protected]> - linfangrong <[email protected]> - linzi <[email protected]> - llgoer <[email protected]> - long-road <[email protected]> - mbesancon <[email protected]> - mehdy <[email protected]> - metal A-wing <[email protected]> - micanzhang <[email protected]> - minarc <[email protected]> - mllu <[email protected]> - mopemoepe <[email protected]> - msoedov <[email protected]> - mstmdev <[email protected]> - novaeye <[email protected]> - olebedev <[email protected]> - phithon <[email protected]> - pjgg <[email protected]> - qm012 <[email protected]> - raymonder jin <[email protected]> - rns <[email protected]> - root@andrea:~# <[email protected]> - sekky0905 <[email protected]> - senhtry <[email protected]> - shadrus <[email protected]> - silasb <[email protected]> - solos <[email protected]> - songjiayang <[email protected]> - sope <[email protected]> - srt180 <[email protected]> - stackerzzq <[email protected]> - sunshineplan <[email protected]> - syssam <[email protected]> - techjanitor <[email protected]> - techjanitor <[email protected]> - thinkerou <[email protected]> - thinkgo <[email protected]> - tsirolnik <[email protected]> - tyltr <[email protected]> - vinhha96 <[email protected]> - voidman <[email protected]> - vz <[email protected]> - wei <[email protected]> - weibaohui <[email protected]> - whirosan <[email protected]> - willnewrelic <[email protected]> - wssccc <[email protected]> - wuhuizuo <[email protected]> - xyb <[email protected]> - y-yagi <[email protected]> - yiranzai <[email protected]> - youzeliang <[email protected]> - yugu <[email protected]> - yuyabe <[email protected]> - zebozhuang <[email protected]> - zero11-0203 <[email protected]> - zesani <[email protected]> - zhanweidu <[email protected]> - zhing <[email protected]> - ziheng <[email protected]> - zzjin <[email protected]> - 森 優太 <[email protected]> - 杰哥 <[email protected]> - 涛叔 <[email protected]> - 市民233 <[email protected]> - 尹宝强 <[email protected]> - 梦溪笔谈 <[email protected]> - 飞雪无情 <[email protected]> - 寻寻觅觅的Gopher <[email protected]>
List of all the awesome people working to make Gin the best Web Framework in Go. ## gin 1.x series authors **Gin Core Team:** Bo-Yi Wu (@appleboy), thinkerou (@thinkerou), Javier Provecho (@javierprovecho) ## gin 0.x series authors **Maintainers:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) ------ People and companies, who have contributed, in alphabetical order. - 178inaba <[email protected]> - A. F <[email protected]> - ABHISHEK SONI <[email protected]> - Abhishek Chanda <[email protected]> - Abner Chen <[email protected]> - AcoNCodes <[email protected]> - Adam Dratwinski <[email protected]> - Adam Mckaig <[email protected]> - Adam Zielinski <[email protected]> - Adonis <[email protected]> - Alan Wang <[email protected]> - Albin Gilles <[email protected]> - Aleksandr Didenko <[email protected]> - Alessandro (Ale) Segala <[email protected]> - Alex <[email protected]> - Alexander <[email protected]> - Alexander Lokhman <[email protected]> - Alexander Melentyev <[email protected]> - Alexander Nyquist <[email protected]> - Allen Ren <[email protected]> - AllinGo <[email protected]> - Ammar Bandukwala <[email protected]> - An Xiao (Luffy) <[email protected]> - Andre Dublin <[email protected]> - Andrew Szeto <[email protected]> - Andrey Abramov <[email protected]> - Andrey Nering <[email protected]> - Andrey Smirnov <[email protected]> - Andrii Bubis <[email protected]> - André Bazaglia <[email protected]> - Andy Pan <[email protected]> - Antoine GIRARD <[email protected]> - Anup Kumar Panwar <[email protected]> - Aravinth Sundaram <[email protected]> - Artem <[email protected]> - Ashwani <[email protected]> - Aurelien Regat-Barrel <[email protected]> - Austin Heap <[email protected]> - Barnabus <[email protected]> - Bo-Yi Wu <[email protected]> - Boris Borshevsky <[email protected]> - Boyi Wu <[email protected]> - BradyBromley <[email protected]> - Brendan Fosberry <[email protected]> - Brian Wigginton <[email protected]> - Carlos Eduardo <[email protected]> - Chad Russell <[email protected]> - Charles <[email protected]> - Christian Muehlhaeuser <[email protected]> - Christian Persson <[email protected]> - Christopher Harrington <[email protected]> - Damon Zhao <[email protected]> - Dan Markham <[email protected]> - Dang Nguyen <[email protected]> - Daniel Krom <[email protected]> - Daniel M. Lambea <[email protected]> - Danieliu <[email protected]> - David Irvine <[email protected]> - David Zhang <[email protected]> - Davor Kapsa <[email protected]> - DeathKing <[email protected]> - Dennis Cho <[email protected]> - Dmitry Dorogin <[email protected]> - Dmitry Kutakov <[email protected]> - Dmitry Sedykh <[email protected]> - Don2Quixote <[email protected]> - Donn Pebe <[email protected]> - Dustin Decker <[email protected]> - Eason Lin <[email protected]> - Edward Betts <[email protected]> - Egor Seredin <[email protected]> - Emmanuel Goh <[email protected]> - Equim <[email protected]> - Eren A. Akyol <[email protected]> - Eric_Lee <[email protected]> - Erik Bender <[email protected]> - Ethan Kan <[email protected]> - Evgeny Persienko <[email protected]> - Faisal Alam <[email protected]> - Fareed Dudhia <[email protected]> - Filip Figiel <[email protected]> - Florian Polster <[email protected]> - Frank Bille <[email protected]> - Franz Bettag <[email protected]> - Ganlv <[email protected]> - Gaozhen Ying <[email protected]> - George Gabolaev <[email protected]> - George Kirilenko <[email protected]> - Georges Varouchas <[email protected]> - Gordon Tyler <[email protected]> - Harindu Perera <[email protected]> - Helios <[email protected]> - Henry Kwan <[email protected]> - Henry Yee <[email protected]> - Himanshu Mishra <[email protected]> - Hiroyuki Tanaka <[email protected]> - Ibraheem Ahmed <[email protected]> - Ignacio Galindo <[email protected]> - Igor H. Vieira <[email protected]> - Ildar1111 <[email protected]> - Iskander (Alex) Sharipov <[email protected]> - Ismail Gjevori <[email protected]> - Ivan Chen <[email protected]> - JINNOUCHI Yasushi <[email protected]> - James Pettyjohn <[email protected]> - Jamie Stackhouse <[email protected]> - Jason Lee <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho Fernandez <[email protected]> - Javier Provecho Fernandez <[email protected]> - Jean-Christophe Lebreton <[email protected]> - Jeff <[email protected]> - Jeremy Loy <[email protected]> - Jim Filippou <[email protected]> - Jimmy Pettersson <[email protected]> - John Bampton <[email protected]> - Johnny Dallas <[email protected]> - Johnny Dallas <[email protected]> - Jonathan (JC) Chen <[email protected]> - Josep Jesus Bigorra Algaba <[email protected]> - Josh Horowitz <[email protected]> - Joshua Loper <[email protected]> - Julien Schmidt <[email protected]> - Jun Kimura <[email protected]> - Justin Beckwith <[email protected]> - Justin Israel <[email protected]> - Justin Mayhew <[email protected]> - Jérôme Laforge <[email protected]> - Kacper Bąk <[email protected]> - Kamron Batman <[email protected]> - Kane Rogers <[email protected]> - Kaushik Neelichetty <[email protected]> - Keiji Yoshida <[email protected]> - Kel Cecil <[email protected]> - Kevin Mulvey <[email protected]> - Kevin Zhu <[email protected]> - Kirill Motkov <[email protected]> - Klemen Sever <[email protected]> - Kristoffer A. Iversen <[email protected]> - Krzysztof Szafrański <[email protected]> - Kumar McMillan <[email protected]> - Kyle Mcgill <[email protected]> - Lanco <[email protected]> - Levi Olson <[email protected]> - Lin Kao-Yuan <[email protected]> - Linus Unnebäck <[email protected]> - Lucas Clemente <[email protected]> - Ludwig Valda Vasquez <[email protected]> - Luis GG <[email protected]> - MW Lim <[email protected]> - Maksimov Sergey <[email protected]> - Manjusaka <[email protected]> - Manu MA <[email protected]> - Manu MA <[email protected]> - Manu Mtz-Almeida <[email protected]> - Manu Mtz.-Almeida <[email protected]> - Manuel Alonso <[email protected]> - Mara Kim <[email protected]> - Mario Kostelac <[email protected]> - Martin Karlsch <[email protected]> - Matt Newberry <[email protected]> - Matt Williams <[email protected]> - Matthieu MOREL <[email protected]> - Max Hilbrunner <[email protected]> - Maxime Soulé <[email protected]> - MetalBreaker <[email protected]> - Michael Puncel <[email protected]> - MichaelDeSteven <[email protected]> - Mike <[email protected]> - Mike Stipicevic <[email protected]> - Miki Tebeka <[email protected]> - Miles <[email protected]> - Mirza Ceric <[email protected]> - Mykyta Semenistyi <[email protected]> - Naoki Takano <[email protected]> - Ngalim Siregar <[email protected]> - Ni Hao <[email protected]> - Nick Gerakines <[email protected]> - Nikifor Seryakov <[email protected]> - Notealot <[email protected]> - Olivier Mengué <[email protected]> - Olivier Robardet <[email protected]> - Pablo Moncada <[email protected]> - Pablo Moncada <[email protected]> - Panmax <[email protected]> - Peperoncino <[email protected]> - Philipp Meinen <[email protected]> - Pierre Massat <[email protected]> - Qt <[email protected]> - Quentin ROYER <[email protected]> - README Bot <[email protected]> - Rafal Zajac <[email protected]> - Rahul Datta Roy <[email protected]> - Rajiv Kilaparti <[email protected]> - Raphael Gavache <[email protected]> - Ray Rodriguez <[email protected]> - Regner Blok-Andersen <[email protected]> - Remco <[email protected]> - Rex Lee(李俊) <[email protected]> - Richard Lee <[email protected]> - Riverside <[email protected]> - Robert Wilkinson <[email protected]> - Rogier Lommers <[email protected]> - Rohan Pai <[email protected]> - Romain Beuque <[email protected]> - Roman Belyakovsky <[email protected]> - Roman Zaynetdinov <[email protected]> - Roman Zaynetdinov <[email protected]> - Ronald Petty <[email protected]> - Ross Wolf <[email protected]> - Roy Lou <[email protected]> - Rubi <[email protected]> - Ryan <[email protected]> - Ryan J. Yoder <[email protected]> - SRK.Lyu <[email protected]> - Sai <[email protected]> - Samuel Abreu <[email protected]> - Santhosh Kumar <[email protected]> - Sasha Melentyev <[email protected]> - Sasha Myasoedov <[email protected]> - Segev Finer <[email protected]> - Sergey Egorov <[email protected]> - Sergey Fedchenko <[email protected]> - Sergey Gonimar <[email protected]> - Sergey Ponomarev <[email protected]> - Serica <[email protected]> - Shamus Taylor <[email protected]> - Shilin Wang <[email protected]> - Shuo <[email protected]> - Skuli Oskarsson <[email protected]> - Snawoot <[email protected]> - Sridhar Ratnakumar <[email protected]> - Steeve Chailloux <[email protected]> - Sudhir Mishra <[email protected]> - Suhas Karanth <[email protected]> - TaeJun Park <[email protected]> - Tatsuya Hoshino <[email protected]> - Tevic <[email protected]> - Tevin Jeffrey <[email protected]> - The Gitter Badger <[email protected]> - Thibault Jamet <[email protected]> - Thomas Boerger <[email protected]> - Thomas Schaffer <[email protected]> - Tommy Chu <[email protected]> - Tudor Roman <[email protected]> - Uwe Dauernheim <[email protected]> - Valentine Oragbakosi <[email protected]> - Vas N <[email protected]> - Vasilyuk Vasiliy <[email protected]> - Victor Castell <[email protected]> - Vince Yuan <[email protected]> - Vyacheslav Dubinin <[email protected]> - Waynerv <[email protected]> - Weilin Shi <[email protected]> - Xudong Cai <[email protected]> - Yasuhiro Matsumoto <[email protected]> - Yehezkiel Syamsuhadi <[email protected]> - Yoshiki Nakagawa <[email protected]> - Yoshiyuki Kinjo <[email protected]> - Yue Yang <[email protected]> - ZYunH <[email protected]> - Zach Newburgh <[email protected]> - Zasda Yusuf Mikail <[email protected]> - ZhangYunHao <[email protected]> - ZhiFeng Hu <[email protected]> - Zhu Xi <[email protected]> - a2tt <[email protected]> - ahuigo <[email protected]> - ali <[email protected]> - aljun <[email protected]> - andrea <[email protected]> - andriikushch <[email protected]> - anoty <[email protected]> - awkj <[email protected]> - axiaoxin <[email protected]> - bbiao <[email protected]> - bestgopher <[email protected]> - betahu <[email protected]> - bigwheel <[email protected]> - bn4t <[email protected]> - bullgare <[email protected]> - chainhelen <[email protected]> - chenyang929 <[email protected]> - chriswhelix <[email protected]> - collinmsn <[email protected]> - cssivision <[email protected]> - danielalves <[email protected]> - delphinus <[email protected]> - dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> - dickeyxxx <[email protected]> - edebernis <[email protected]> - error10 <[email protected]> - esplo <[email protected]> - eudore <[email protected]> - ffhelicopter <[email protected]> - filikos <[email protected]> - forging2012 <[email protected]> - goqihoo <[email protected]> - grapeVine <[email protected]> - guonaihong <[email protected]> - heige <[email protected]> - heige <[email protected]> - hellojukay <[email protected]> - henrylee2cn <[email protected]> - htobenothing <[email protected]> - iamhesir <[email protected]> - ijaa <[email protected]> - ishanray <[email protected]> - ishanray <[email protected]> - itcloudy <[email protected]> - jarodsong6 <[email protected]> - jasonrhansen <[email protected]> - jincheng9 <[email protected]> - joeADSP <[email protected]> - junfengye <[email protected]> - kaiiak <[email protected]> - kebo <[email protected]> - keke <[email protected]> - kishor kunal raj <[email protected]> - kyledinh <[email protected]> - lantw44 <[email protected]> - likakuli <[email protected]> - linfangrong <[email protected]> - linzi <[email protected]> - llgoer <[email protected]> - long-road <[email protected]> - mbesancon <[email protected]> - mehdy <[email protected]> - metal A-wing <[email protected]> - micanzhang <[email protected]> - minarc <[email protected]> - mllu <[email protected]> - mopemoepe <[email protected]> - msoedov <[email protected]> - mstmdev <[email protected]> - novaeye <[email protected]> - olebedev <[email protected]> - phithon <[email protected]> - pjgg <[email protected]> - qm012 <[email protected]> - raymonder jin <[email protected]> - rns <[email protected]> - root@andrea:~# <[email protected]> - sekky0905 <[email protected]> - senhtry <[email protected]> - shadrus <[email protected]> - silasb <[email protected]> - solos <[email protected]> - songjiayang <[email protected]> - sope <[email protected]> - srt180 <[email protected]> - stackerzzq <[email protected]> - sunshineplan <[email protected]> - syssam <[email protected]> - techjanitor <[email protected]> - techjanitor <[email protected]> - thinkerou <[email protected]> - thinkgo <[email protected]> - tsirolnik <[email protected]> - tyltr <[email protected]> - vinhha96 <[email protected]> - voidman <[email protected]> - vz <[email protected]> - wei <[email protected]> - weibaohui <[email protected]> - whirosan <[email protected]> - willnewrelic <[email protected]> - wssccc <[email protected]> - wuhuizuo <[email protected]> - xyb <[email protected]> - y-yagi <[email protected]> - yiranzai <[email protected]> - youzeliang <[email protected]> - yugu <[email protected]> - yuyabe <[email protected]> - zebozhuang <[email protected]> - zero11-0203 <[email protected]> - zesani <[email protected]> - zhanweidu <[email protected]> - zhing <[email protected]> - ziheng <[email protected]> - zzjin <[email protected]> - 森 優太 <[email protected]> - 杰哥 <[email protected]> - 涛叔 <[email protected]> - 市民233 <[email protected]> - 尹宝强 <[email protected]> - 梦溪笔谈 <[email protected]> - 飞雪无情 <[email protected]> - 寻寻觅觅的Gopher <[email protected]>
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./binding/any.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package binding type any = interface{}
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package binding type any = interface{}
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./internal/json/go_json.go
// Copyright 2017 Bo-Yi Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build go_json // +build go_json package json import json "github.com/goccy/go-json" var ( // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
// Copyright 2017 Bo-Yi Wu. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build go_json // +build go_json package json import json "github.com/goccy/go-json" var ( // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./render/render_msgpack_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package render import ( "bytes" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/ugorji/go/codec" ) // TODO unit tests // test errors func TestRenderMsgPack(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (MsgPack{data}).WriteContentType(w) assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) err := (MsgPack{data}).Render(w) assert.NoError(t, err) h := new(codec.MsgpackHandle) assert.NotNil(t, h) buf := bytes.NewBuffer([]byte{}) assert.NotNil(t, buf) err = codec.NewEncoder(buf, h).Encode(data) assert.NoError(t, err) assert.Equal(t, w.Body.String(), buf.String()) assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package render import ( "bytes" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/ugorji/go/codec" ) // TODO unit tests // test errors func TestRenderMsgPack(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (MsgPack{data}).WriteContentType(w) assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) err := (MsgPack{data}).Render(w) assert.NoError(t, err) h := new(codec.MsgpackHandle) assert.NotNil(t, h) buf := bytes.NewBuffer([]byte{}) assert.NotNil(t, buf) err = codec.NewEncoder(buf, h).Encode(data) assert.NoError(t, err) assert.Equal(t, w.Body.String(), buf.String()) assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) }
-1
gin-gonic/gin
3,395
remove deprecated of package io/ioutil
remove io/ioutil
0x2d3c
"2022-11-13T02:31:08Z"
"2022-11-17T14:35:55Z"
234a1d33f7b329a6d701a7b249167f72de57c901
6150c488e73518f119cfed53094d6179a0d33bf7
remove deprecated of package io/ioutil. remove io/ioutil
./gin.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "net" "net/http" "os" "path" "strings" "sync" "github.com/gin-gonic/gin/internal/bytesconv" "github.com/gin-gonic/gin/render" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) const defaultMultipartMemory = 32 << 20 // 32 MB var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") ) var defaultPlatform string var defaultTrustedCIDRs = []*net.IPNet{ { // 0.0.0.0/0 (IPv4) IP: net.IP{0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0}, }, { // ::/0 (IPv6) IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, }, } // HandlerFunc defines the handler used by gin middleware as return value. type HandlerFunc func(*Context) // HandlersChain defines a HandlerFunc slice. type HandlersChain []HandlerFunc // Last returns the last handler in the chain. i.e. the last handler is the main one. func (c HandlersChain) Last() HandlerFunc { if length := len(c); length > 0 { return c[length-1] } return nil } // RouteInfo represents a request route's specification which contains method and path and its handler. type RouteInfo struct { Method string Path string Handler string HandlerFunc HandlerFunc } // RoutesInfo defines a RouteInfo slice. type RoutesInfo []RouteInfo // Trusted platforms const ( // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP PlatformGoogleAppEngine = "X-Appengine-Remote-Addr" // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP PlatformCloudflare = "CF-Connecting-IP" ) // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. // Create an instance of Engine, by using New() or Default() type Engine struct { RouterGroup // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // RedirectFixedPath if enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was // fetched, it falls back to the IP obtained from // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool // AppEngine was deprecated. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // UseRawPath if enabled, the url.RawPath will be used to find parameters. UseRawPath bool // UnescapePathValues if true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. // See the PR #1817 and issue #1644 RemoveExtraSlash bool // RemoteIPHeaders list of headers used to obtain the client IP when // `(*gin.Engine).ForwardedByClientIP` is `true` and // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // UseH2C enable h2c support. UseH2C bool // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil. ContextWithFallback bool delims render.Delims secureJSONPrefix string HTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees maxParams uint16 maxSections uint16 trustedProxies []string trustedCIDRs []*net.IPNet } var _ IRouter = (*Engine)(nil) // New returns a new blank Engine instance without any middleware attached. // By default, the configuration is: // - RedirectTrailingSlash: true // - RedirectFixedPath: false // - HandleMethodNotAllowed: false // - ForwardedByClientIP: true // - UseRawPath: false // - UnescapePathValues: true func New() *Engine { debugPrintWARNINGNew() engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedPlatform: defaultPlatform, UseRawPath: false, RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", trustedProxies: []string{"0.0.0.0/0", "::/0"}, trustedCIDRs: defaultTrustedCIDRs, } engine.RouterGroup.engine = engine engine.pool.New = func() any { return engine.allocateContext(engine.maxParams) } return engine } // Default returns an Engine instance with the Logger and Recovery middleware already attached. func Default() *Engine { debugPrintWARNINGDefault() engine := New() engine.Use(Logger(), Recovery()) return engine } func (engine *Engine) Handler() http.Handler { if !engine.UseH2C { return engine } h2s := &http2.Server{} return h2c.NewHandler(engine, h2s) } func (engine *Engine) allocateContext(maxParams uint16) *Context { v := make(Params, 0, maxParams) skippedNodes := make([]skippedNode, 0, engine.maxSections) return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} return engine } // SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { engine.secureJSONPrefix = prefix return engine } // LoadHTMLGlob loads HTML files identified by glob pattern // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLGlob(pattern string) { left := engine.delims.Left right := engine.delims.Right templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) if IsDebugging() { debugPrintLoadTemplate(templ) engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} return } engine.SetHTMLTemplate(templ) } // LoadHTMLFiles loads a slice of HTML files // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLFiles(files ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} return } templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) engine.SetHTMLTemplate(templ) } // SetHTMLTemplate associate a template with HTML renderer. func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 { debugPrintWARNINGSetHTMLTemplate() } engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} } // SetFuncMap sets the FuncMap used for template.FuncMap. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } // NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true. func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } // Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } func (engine *Engine) rebuild404Handlers() { engine.allNoRoute = engine.combineHandlers(engine.noRoute) } func (engine *Engine) rebuild405Handlers() { engine.allNoMethod = engine.combineHandlers(engine.noMethod) } func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { assert1(path[0] == '/', "path must begin with '/'") assert1(method != "", "HTTP method can not be empty") assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers) root := engine.trees.get(method) if root == nil { root = new(node) root.fullPath = "/" engine.trees = append(engine.trees, methodTree{method: method, root: root}) } root.addRoute(path, handlers) // Update maxParams if paramsCount := countParams(path); paramsCount > engine.maxParams { engine.maxParams = paramsCount } if sectionsCount := countSections(path); sectionsCount > engine.maxSections { engine.maxSections = sectionsCount } } // Routes returns a slice of registered routes, including some useful information, such as: // the http method, path and the handler name. func (engine *Engine) Routes() (routes RoutesInfo) { for _, tree := range engine.trees { routes = iterate("", tree.method, routes, tree.root) } return routes } func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { path += root.path if len(root.handlers) > 0 { handlerFunc := root.handlers.Last() routes = append(routes, RouteInfo{ Method: method, Path: path, Handler: nameOfFunction(handlerFunc), HandlerFunc: handlerFunc, }) } for _, child := range root.children { routes = iterate(path, method, routes, child) } return routes } // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) err = http.ListenAndServe(address, engine.Handler()) return } func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { if engine.trustedProxies == nil { return nil, nil } cidr := make([]*net.IPNet, 0, len(engine.trustedProxies)) for _, trustedProxy := range engine.trustedProxies { if !strings.Contains(trustedProxy, "/") { ip := parseIP(trustedProxy) if ip == nil { return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} } switch len(ip) { case net.IPv4len: trustedProxy += "/32" case net.IPv6len: trustedProxy += "/128" } } _, cidrNet, err := net.ParseCIDR(trustedProxy) if err != nil { return cidr, err } cidr = append(cidr, cidrNet) } return cidr, nil } // SetTrustedProxies set a list of network origins (IPv4 addresses, // IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust // request's headers that contain alternative client IP when // `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` // feature is enabled by default, and it also trusts all proxies // by default. If you want to disable this feature, use // Engine.SetTrustedProxies(nil), then Context.ClientIP() will // return the remote address directly. func (engine *Engine) SetTrustedProxies(trustedProxies []string) error { engine.trustedProxies = trustedProxies return engine.parseTrustedProxies() } // isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true) func (engine *Engine) isUnsafeTrustedProxies() bool { return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::")) } // parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs func (engine *Engine) parseTrustedProxies() error { trustedCIDRs, err := engine.prepareTrustedCIDRs() engine.trustedCIDRs = trustedCIDRs return err } // isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs func (engine *Engine) isTrustedProxy(ip net.IP) bool { if engine.trustedCIDRs == nil { return false } for _, cidr := range engine.trustedCIDRs { if cidr.Contains(ip) { return true } } return false } // validateHeader will parse X-Forwarded-For header and return the trusted client IP address func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) { if header == "" { return "", false } items := strings.Split(header, ",") for i := len(items) - 1; i >= 0; i-- { ipStr := strings.TrimSpace(items[i]) ip := net.ParseIP(ipStr) if ip == nil { break } // X-Forwarded-For is appended by proxy // Check IPs in reverse order and stop when find untrusted proxy if (i == 0) || (!engine.isTrustedProxy(ip)) { return ipStr, true } } return "", false } // parseIP parse a string representation of an IP and returns a net.IP with the // minimum byte representation or nil if input is invalid. func parseIP(ip string) net.IP { parsedIP := net.ParseIP(ip) if ipv4 := parsedIP.To4(); ipv4 != nil { // return ip in a 4-byte representation return ipv4 } // return ip in a 16-byte representation or nil return parsedIP } // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { debugPrint("Listening and serving HTTPS on %s\n", addr) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.ListenAndServeTLS(addr, certFile, keyFile, engine.Handler()) return } // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file). // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunUnix(file string) (err error) { debugPrint("Listening and serving HTTP on unix:/%s", file) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() defer os.Remove(file) err = http.Serve(listener, engine.Handler()) return } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunFd(fd int) (err error) { debugPrint("Listening and serving HTTP on fd@%d", fd) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) listener, err := net.FileListener(f) if err != nil { return } defer listener.Close() err = engine.RunListener(listener) return } // RunListener attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified net.Listener func (engine *Engine) RunListener(listener net.Listener) (err error) { debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.Serve(listener, engine.Handler()) return } // ServeHTTP conforms to the http.Handler interface. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } // HandleContext re-enters a context that has been rewritten. // This can be done by setting c.Request.URL.Path to your new target. // Disclaimer: You can loop yourself to deal with this, use wisely. func (engine *Engine) HandleContext(c *Context) { oldIndexValue := c.index c.reset() engine.handleHTTPRequest(c) c.index = oldIndexValue } func (engine *Engine) handleHTTPRequest(c *Context) { httpMethod := c.Request.Method rPath := c.Request.URL.Path unescape := false if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { rPath = c.Request.URL.RawPath unescape = engine.UnescapePathValues } if engine.RemoveExtraSlash { rPath = cleanPath(rPath) } // Find root of the tree for the given HTTP method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method != httpMethod { continue } root := t[i].root // Find route in tree value := root.getValue(rPath, c.params, c.skippedNodes, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } if httpMethod != http.MethodConnect && rPath != "/" { if value.tsr && engine.RedirectTrailingSlash { redirectTrailingSlash(c) return } if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { return } } break } if engine.HandleMethodNotAllowed { for _, tree := range engine.trees { if tree.method == httpMethod { continue } if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil { c.handlers = engine.allNoMethod serveError(c, http.StatusMethodNotAllowed, default405Body) return } } } c.handlers = engine.allNoRoute serveError(c, http.StatusNotFound, default404Body) } var mimePlain = []string{MIMEPlain} func serveError(c *Context, code int, defaultMessage []byte) { c.writermem.status = code c.Next() if c.writermem.Written() { return } if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain _, err := c.Writer.Write(defaultMessage) if err != nil { debugPrint("cannot write message to writer during serve error: %v", err) } return } c.writermem.WriteHeaderNow() } func redirectTrailingSlash(c *Context) { req := c.Request p := req.URL.Path if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { p = prefix + "/" + req.URL.Path } req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } redirectRequest(c) } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { req := c.Request rPath := req.URL.Path if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { req.URL.Path = bytesconv.BytesToString(fixedPath) redirectRequest(c) return true } return false } func redirectRequest(c *Context) { req := c.Request rPath := req.URL.Path rURL := req.URL.String() code := http.StatusMovedPermanently // Permanent redirect, request with GET method if req.Method != http.MethodGet { code = http.StatusTemporaryRedirect } debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) http.Redirect(c.Writer, req, rURL, code) c.writermem.WriteHeaderNow() }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "net" "net/http" "os" "path" "strings" "sync" "github.com/gin-gonic/gin/internal/bytesconv" "github.com/gin-gonic/gin/render" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) const defaultMultipartMemory = 32 << 20 // 32 MB var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") ) var defaultPlatform string var defaultTrustedCIDRs = []*net.IPNet{ { // 0.0.0.0/0 (IPv4) IP: net.IP{0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0}, }, { // ::/0 (IPv6) IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, }, } // HandlerFunc defines the handler used by gin middleware as return value. type HandlerFunc func(*Context) // HandlersChain defines a HandlerFunc slice. type HandlersChain []HandlerFunc // Last returns the last handler in the chain. i.e. the last handler is the main one. func (c HandlersChain) Last() HandlerFunc { if length := len(c); length > 0 { return c[length-1] } return nil } // RouteInfo represents a request route's specification which contains method and path and its handler. type RouteInfo struct { Method string Path string Handler string HandlerFunc HandlerFunc } // RoutesInfo defines a RouteInfo slice. type RoutesInfo []RouteInfo // Trusted platforms const ( // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP PlatformGoogleAppEngine = "X-Appengine-Remote-Addr" // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP PlatformCloudflare = "CF-Connecting-IP" ) // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. // Create an instance of Engine, by using New() or Default() type Engine struct { RouterGroup // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // RedirectFixedPath if enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was // fetched, it falls back to the IP obtained from // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool // AppEngine was deprecated. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // UseRawPath if enabled, the url.RawPath will be used to find parameters. UseRawPath bool // UnescapePathValues if true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. // See the PR #1817 and issue #1644 RemoveExtraSlash bool // RemoteIPHeaders list of headers used to obtain the client IP when // `(*gin.Engine).ForwardedByClientIP` is `true` and // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // UseH2C enable h2c support. UseH2C bool // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil. ContextWithFallback bool delims render.Delims secureJSONPrefix string HTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees maxParams uint16 maxSections uint16 trustedProxies []string trustedCIDRs []*net.IPNet } var _ IRouter = (*Engine)(nil) // New returns a new blank Engine instance without any middleware attached. // By default, the configuration is: // - RedirectTrailingSlash: true // - RedirectFixedPath: false // - HandleMethodNotAllowed: false // - ForwardedByClientIP: true // - UseRawPath: false // - UnescapePathValues: true func New() *Engine { debugPrintWARNINGNew() engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedPlatform: defaultPlatform, UseRawPath: false, RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", trustedProxies: []string{"0.0.0.0/0", "::/0"}, trustedCIDRs: defaultTrustedCIDRs, } engine.RouterGroup.engine = engine engine.pool.New = func() any { return engine.allocateContext(engine.maxParams) } return engine } // Default returns an Engine instance with the Logger and Recovery middleware already attached. func Default() *Engine { debugPrintWARNINGDefault() engine := New() engine.Use(Logger(), Recovery()) return engine } func (engine *Engine) Handler() http.Handler { if !engine.UseH2C { return engine } h2s := &http2.Server{} return h2c.NewHandler(engine, h2s) } func (engine *Engine) allocateContext(maxParams uint16) *Context { v := make(Params, 0, maxParams) skippedNodes := make([]skippedNode, 0, engine.maxSections) return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} return engine } // SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { engine.secureJSONPrefix = prefix return engine } // LoadHTMLGlob loads HTML files identified by glob pattern // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLGlob(pattern string) { left := engine.delims.Left right := engine.delims.Right templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) if IsDebugging() { debugPrintLoadTemplate(templ) engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} return } engine.SetHTMLTemplate(templ) } // LoadHTMLFiles loads a slice of HTML files // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLFiles(files ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} return } templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) engine.SetHTMLTemplate(templ) } // SetHTMLTemplate associate a template with HTML renderer. func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 { debugPrintWARNINGSetHTMLTemplate() } engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} } // SetFuncMap sets the FuncMap used for template.FuncMap. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } // NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true. func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } // Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } func (engine *Engine) rebuild404Handlers() { engine.allNoRoute = engine.combineHandlers(engine.noRoute) } func (engine *Engine) rebuild405Handlers() { engine.allNoMethod = engine.combineHandlers(engine.noMethod) } func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { assert1(path[0] == '/', "path must begin with '/'") assert1(method != "", "HTTP method can not be empty") assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers) root := engine.trees.get(method) if root == nil { root = new(node) root.fullPath = "/" engine.trees = append(engine.trees, methodTree{method: method, root: root}) } root.addRoute(path, handlers) // Update maxParams if paramsCount := countParams(path); paramsCount > engine.maxParams { engine.maxParams = paramsCount } if sectionsCount := countSections(path); sectionsCount > engine.maxSections { engine.maxSections = sectionsCount } } // Routes returns a slice of registered routes, including some useful information, such as: // the http method, path and the handler name. func (engine *Engine) Routes() (routes RoutesInfo) { for _, tree := range engine.trees { routes = iterate("", tree.method, routes, tree.root) } return routes } func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { path += root.path if len(root.handlers) > 0 { handlerFunc := root.handlers.Last() routes = append(routes, RouteInfo{ Method: method, Path: path, Handler: nameOfFunction(handlerFunc), HandlerFunc: handlerFunc, }) } for _, child := range root.children { routes = iterate(path, method, routes, child) } return routes } // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) err = http.ListenAndServe(address, engine.Handler()) return } func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { if engine.trustedProxies == nil { return nil, nil } cidr := make([]*net.IPNet, 0, len(engine.trustedProxies)) for _, trustedProxy := range engine.trustedProxies { if !strings.Contains(trustedProxy, "/") { ip := parseIP(trustedProxy) if ip == nil { return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} } switch len(ip) { case net.IPv4len: trustedProxy += "/32" case net.IPv6len: trustedProxy += "/128" } } _, cidrNet, err := net.ParseCIDR(trustedProxy) if err != nil { return cidr, err } cidr = append(cidr, cidrNet) } return cidr, nil } // SetTrustedProxies set a list of network origins (IPv4 addresses, // IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust // request's headers that contain alternative client IP when // `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` // feature is enabled by default, and it also trusts all proxies // by default. If you want to disable this feature, use // Engine.SetTrustedProxies(nil), then Context.ClientIP() will // return the remote address directly. func (engine *Engine) SetTrustedProxies(trustedProxies []string) error { engine.trustedProxies = trustedProxies return engine.parseTrustedProxies() } // isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true) func (engine *Engine) isUnsafeTrustedProxies() bool { return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::")) } // parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs func (engine *Engine) parseTrustedProxies() error { trustedCIDRs, err := engine.prepareTrustedCIDRs() engine.trustedCIDRs = trustedCIDRs return err } // isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs func (engine *Engine) isTrustedProxy(ip net.IP) bool { if engine.trustedCIDRs == nil { return false } for _, cidr := range engine.trustedCIDRs { if cidr.Contains(ip) { return true } } return false } // validateHeader will parse X-Forwarded-For header and return the trusted client IP address func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) { if header == "" { return "", false } items := strings.Split(header, ",") for i := len(items) - 1; i >= 0; i-- { ipStr := strings.TrimSpace(items[i]) ip := net.ParseIP(ipStr) if ip == nil { break } // X-Forwarded-For is appended by proxy // Check IPs in reverse order and stop when find untrusted proxy if (i == 0) || (!engine.isTrustedProxy(ip)) { return ipStr, true } } return "", false } // parseIP parse a string representation of an IP and returns a net.IP with the // minimum byte representation or nil if input is invalid. func parseIP(ip string) net.IP { parsedIP := net.ParseIP(ip) if ipv4 := parsedIP.To4(); ipv4 != nil { // return ip in a 4-byte representation return ipv4 } // return ip in a 16-byte representation or nil return parsedIP } // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { debugPrint("Listening and serving HTTPS on %s\n", addr) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.ListenAndServeTLS(addr, certFile, keyFile, engine.Handler()) return } // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file). // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunUnix(file string) (err error) { debugPrint("Listening and serving HTTP on unix:/%s", file) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() defer os.Remove(file) err = http.Serve(listener, engine.Handler()) return } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunFd(fd int) (err error) { debugPrint("Listening and serving HTTP on fd@%d", fd) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) listener, err := net.FileListener(f) if err != nil { return } defer listener.Close() err = engine.RunListener(listener) return } // RunListener attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified net.Listener func (engine *Engine) RunListener(listener net.Listener) (err error) { debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.Serve(listener, engine.Handler()) return } // ServeHTTP conforms to the http.Handler interface. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } // HandleContext re-enters a context that has been rewritten. // This can be done by setting c.Request.URL.Path to your new target. // Disclaimer: You can loop yourself to deal with this, use wisely. func (engine *Engine) HandleContext(c *Context) { oldIndexValue := c.index c.reset() engine.handleHTTPRequest(c) c.index = oldIndexValue } func (engine *Engine) handleHTTPRequest(c *Context) { httpMethod := c.Request.Method rPath := c.Request.URL.Path unescape := false if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { rPath = c.Request.URL.RawPath unescape = engine.UnescapePathValues } if engine.RemoveExtraSlash { rPath = cleanPath(rPath) } // Find root of the tree for the given HTTP method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method != httpMethod { continue } root := t[i].root // Find route in tree value := root.getValue(rPath, c.params, c.skippedNodes, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } if httpMethod != http.MethodConnect && rPath != "/" { if value.tsr && engine.RedirectTrailingSlash { redirectTrailingSlash(c) return } if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { return } } break } if engine.HandleMethodNotAllowed { for _, tree := range engine.trees { if tree.method == httpMethod { continue } if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil { c.handlers = engine.allNoMethod serveError(c, http.StatusMethodNotAllowed, default405Body) return } } } c.handlers = engine.allNoRoute serveError(c, http.StatusNotFound, default404Body) } var mimePlain = []string{MIMEPlain} func serveError(c *Context, code int, defaultMessage []byte) { c.writermem.status = code c.Next() if c.writermem.Written() { return } if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain _, err := c.Writer.Write(defaultMessage) if err != nil { debugPrint("cannot write message to writer during serve error: %v", err) } return } c.writermem.WriteHeaderNow() } func redirectTrailingSlash(c *Context) { req := c.Request p := req.URL.Path if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { p = prefix + "/" + req.URL.Path } req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } redirectRequest(c) } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { req := c.Request rPath := req.URL.Path if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { req.URL.Path = bytesconv.BytesToString(fixedPath) redirectRequest(c) return true } return false } func redirectRequest(c *Context) { req := c.Request rPath := req.URL.Path rURL := req.URL.String() code := http.StatusMovedPermanently // Permanent redirect, request with GET method if req.Method != http.MethodGet { code = http.StatusTemporaryRedirect } debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) http.Redirect(c.Writer, req, rURL, code) c.writermem.WriteHeaderNow() }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./README.md
# Gin Web Framework <img align="right" width="159px" src="https://raw.githubusercontent.com/gin-gonic/logo/master/color.png"> [![Build Status](https://github.com/gin-gonic/gin/workflows/Run%20Tests/badge.svg?branch=master)](https://github.com/gin-gonic/gin/actions?query=branch%3Amaster) [![codecov](https://codecov.io/gh/gin-gonic/gin/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-gonic/gin) [![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin) [![GoDoc](https://pkg.go.dev/badge/github.com/gin-gonic/gin?status.svg)](https://pkg.go.dev/github.com/gin-gonic/gin?tab=doc) [![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Sourcegraph](https://sourcegraph.com/github.com/gin-gonic/gin/-/badge.svg)](https://sourcegraph.com/github.com/gin-gonic/gin?badge) [![Open Source Helpers](https://www.codetriage.com/gin-gonic/gin/badges/users.svg)](https://www.codetriage.com/gin-gonic/gin) [![Release](https://img.shields.io/github/release/gin-gonic/gin.svg?style=flat-square)](https://github.com/gin-gonic/gin/releases) [![TODOs](https://badgen.net/https/api.tickgit.com/badgen/github.com/gin-gonic/gin)](https://www.tickgit.com/browse?repo=github.com/gin-gonic/gin) Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin. ## Contents - [Gin Web Framework](#gin-web-framework) - [Contents](#contents) - [Installation](#installation) - [Quick start](#quick-start) - [Benchmarks](#benchmarks) - [Gin v1. stable](#gin-v1-stable) - [Build with json replacement](#build-with-json-replacement) - [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature) - [API Examples](#api-examples) - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options) - [Parameters in path](#parameters-in-path) - [Querystring parameters](#querystring-parameters) - [Multipart/Urlencoded Form](#multiparturlencoded-form) - [Another example: query + post form](#another-example-query--post-form) - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters) - [Upload files](#upload-files) - [Single file](#single-file) - [Multiple files](#multiple-files) - [Grouping routes](#grouping-routes) - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default) - [Using middleware](#using-middleware) - [Custom Recovery behavior](#custom-recovery-behavior) - [How to write log file](#how-to-write-log-file) - [Custom Log Format](#custom-log-format) - [Controlling Log output coloring](#controlling-log-output-coloring) - [Model binding and validation](#model-binding-and-validation) - [Custom Validators](#custom-validators) - [Only Bind Query String](#only-bind-query-string) - [Bind Query String or Post Data](#bind-query-string-or-post-data) - [Bind Uri](#bind-uri) - [Bind Header](#bind-header) - [Bind HTML checkboxes](#bind-html-checkboxes) - [Multipart/Urlencoded binding](#multiparturlencoded-binding) - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering) - [SecureJSON](#securejson) - [JSONP](#jsonp) - [AsciiJSON](#asciijson) - [PureJSON](#purejson) - [Serving static files](#serving-static-files) - [Serving data from file](#serving-data-from-file) - [Serving data from reader](#serving-data-from-reader) - [HTML rendering](#html-rendering) - [Custom Template renderer](#custom-template-renderer) - [Custom Delimiters](#custom-delimiters) - [Custom Template Funcs](#custom-template-funcs) - [Multitemplate](#multitemplate) - [Redirects](#redirects) - [Custom Middleware](#custom-middleware) - [Using BasicAuth() middleware](#using-basicauth-middleware) - [Goroutines inside a middleware](#goroutines-inside-a-middleware) - [Custom HTTP configuration](#custom-http-configuration) - [Support Let's Encrypt](#support-lets-encrypt) - [Run multiple service using Gin](#run-multiple-service-using-gin) - [Graceful shutdown or restart](#graceful-shutdown-or-restart) - [Third-party packages](#third-party-packages) - [Manually](#manually) - [Build a single binary with templates](#build-a-single-binary-with-templates) - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct) - [Try to bind body into different structs](#try-to-bind-body-into-different-structs) - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag) - [http2 server push](#http2-server-push) - [Define format for the log of routes](#define-format-for-the-log-of-routes) - [Set and get a cookie](#set-and-get-a-cookie) - [Don't trust all proxies](#dont-trust-all-proxies) - [Testing](#testing) - [Users](#users) ## Installation To install Gin package, you need to install Go and set your Go workspace first. 1. You first need [Go](https://golang.org/) installed (**version 1.15+ is required**), then you can use the below Go command to install Gin. ```sh go get -u github.com/gin-gonic/gin ``` 2. Import it in your code: ```go import "github.com/gin-gonic/gin" ``` 3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`. ```go import "net/http" ``` ## Quick start ```sh # assume the following codes in example.go file $ cat example.go ``` ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") } ``` ``` # run example.go and visit 0.0.0.0:8080/ping (for windows "localhost:8080/ping") on browser $ go run example.go ``` ## Benchmarks Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) [See all benchmarks](/BENCHMARKS.md) | Benchmark name | (1) | (2) | (3) | (4) | | ------------------------------ | ---------:| ---------------:| ------------:| ---------------:| | BenchmarkGin_GithubAll | **43550** | **27364 ns/op** | **0 B/op** | **0 allocs/op** | | BenchmarkAce_GithubAll | 40543 | 29670 ns/op | 0 B/op | 0 allocs/op | | BenchmarkAero_GithubAll | 57632 | 20648 ns/op | 0 B/op | 0 allocs/op | | BenchmarkBear_GithubAll | 9234 | 216179 ns/op | 86448 B/op | 943 allocs/op | | BenchmarkBeego_GithubAll | 7407 | 243496 ns/op | 71456 B/op | 609 allocs/op | | BenchmarkBone_GithubAll | 420 | 2922835 ns/op | 720160 B/op | 8620 allocs/op | | BenchmarkChi_GithubAll | 7620 | 238331 ns/op | 87696 B/op | 609 allocs/op | | BenchmarkDenco_GithubAll | 18355 | 64494 ns/op | 20224 B/op | 167 allocs/op | | BenchmarkEcho_GithubAll | 31251 | 38479 ns/op | 0 B/op | 0 allocs/op | | BenchmarkGocraftWeb_GithubAll | 4117 | 300062 ns/op | 131656 B/op | 1686 allocs/op | | BenchmarkGoji_GithubAll | 3274 | 416158 ns/op | 56112 B/op | 334 allocs/op | | BenchmarkGojiv2_GithubAll | 1402 | 870518 ns/op | 352720 B/op | 4321 allocs/op | | BenchmarkGoJsonRest_GithubAll | 2976 | 401507 ns/op | 134371 B/op | 2737 allocs/op | | BenchmarkGoRestful_GithubAll | 410 | 2913158 ns/op | 910144 B/op | 2938 allocs/op | | BenchmarkGorillaMux_GithubAll | 346 | 3384987 ns/op | 251650 B/op | 1994 allocs/op | | BenchmarkGowwwRouter_GithubAll | 10000 | 143025 ns/op | 72144 B/op | 501 allocs/op | | BenchmarkHttpRouter_GithubAll | 55938 | 21360 ns/op | 0 B/op | 0 allocs/op | | BenchmarkHttpTreeMux_GithubAll | 10000 | 153944 ns/op | 65856 B/op | 671 allocs/op | | BenchmarkKocha_GithubAll | 10000 | 106315 ns/op | 23304 B/op | 843 allocs/op | | BenchmarkLARS_GithubAll | 47779 | 25084 ns/op | 0 B/op | 0 allocs/op | | BenchmarkMacaron_GithubAll | 3266 | 371907 ns/op | 149409 B/op | 1624 allocs/op | | BenchmarkMartini_GithubAll | 331 | 3444706 ns/op | 226551 B/op | 2325 allocs/op | | BenchmarkPat_GithubAll | 273 | 4381818 ns/op | 1483152 B/op | 26963 allocs/op | | BenchmarkPossum_GithubAll | 10000 | 164367 ns/op | 84448 B/op | 609 allocs/op | | BenchmarkR2router_GithubAll | 10000 | 160220 ns/op | 77328 B/op | 979 allocs/op | | BenchmarkRivet_GithubAll | 14625 | 82453 ns/op | 16272 B/op | 167 allocs/op | | BenchmarkTango_GithubAll | 6255 | 279611 ns/op | 63826 B/op | 1618 allocs/op | | BenchmarkTigerTonic_GithubAll | 2008 | 687874 ns/op | 193856 B/op | 4474 allocs/op | | BenchmarkTraffic_GithubAll | 355 | 3478508 ns/op | 820744 B/op | 14114 allocs/op | | BenchmarkVulcan_GithubAll | 6885 | 193333 ns/op | 19894 B/op | 609 allocs/op | - (1): Total Repetitions achieved in constant time, higher means more confident result - (2): Single Repetition Duration (ns/op), lower is better - (3): Heap Memory (B/op), lower is better - (4): Average Allocations per Repetition (allocs/op), lower is better ## Gin v1. stable - [x] Zero allocation router. - [x] Still the fastest http router and framework. From routing to writing. - [x] Complete suite of unit tests. - [x] Battle tested. - [x] API frozen, new releases will not break your code. ## Build with json replacement Gin uses `encoding/json` as default json package but you can change it by build from other tags. [jsoniter](https://github.com/json-iterator/go) ```sh go build -tags=jsoniter . ``` [go-json](https://github.com/goccy/go-json) ```sh go build -tags=go_json . ``` [sonic](https://github.com/bytedance/sonic) (you have to ensure that your cpu support avx instruction.) ```sh $ go build -tags="sonic avx" . ``` ## Build without `MsgPack` rendering feature Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag. ```sh go build -tags=nomsgpack . ``` This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852). ## API Examples You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples). ### Using GET, POST, PUT, PATCH, DELETE and OPTIONS ```go func main() { // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/someGet", getting) router.POST("/somePost", posting) router.PUT("/somePut", putting) router.DELETE("/someDelete", deleting) router.PATCH("/somePatch", patching) router.HEAD("/someHead", head) router.OPTIONS("/someOptions", options) // By default it serves on :8080 unless a // PORT environment variable was defined. router.Run() // router.Run(":3000") for a hard coded port } ``` ### Parameters in path ```go func main() { router := gin.Default() // This handler will match /user/john but will not match /user/ or /user router.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) // However, this one will match /user/john/ and also /user/john/send // If no other routers match /user/john, it will redirect to /user/john/ router.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") message := name + " is " + action c.String(http.StatusOK, message) }) // For each matched request Context will hold the route definition router.POST("/user/:name/*action", func(c *gin.Context) { b := c.FullPath() == "/user/:name/*action" // true c.String(http.StatusOK, "%t", b) }) // This handler will add a new router for /user/groups. // Exact routes are resolved before param routes, regardless of the order they were defined. // Routes starting with /user/groups are never interpreted as /user/:name/... routes router.GET("/user/groups", func(c *gin.Context) { c.String(http.StatusOK, "The available groups are [...]") }) router.Run(":8080") } ``` ### Querystring parameters ```go func main() { router := gin.Default() // Query string parameters are parsed using the existing underlying request object. // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe router.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname", "Guest") lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname") c.String(http.StatusOK, "Hello %s %s", firstname, lastname) }) router.Run(":8080") } ``` ### Multipart/Urlencoded Form ```go func main() { router := gin.Default() router.POST("/form_post", func(c *gin.Context) { message := c.PostForm("message") nick := c.DefaultPostForm("nick", "anonymous") c.JSON(http.StatusOK, gin.H{ "status": "posted", "message": message, "nick": nick, }) }) router.Run(":8080") } ``` ### Another example: query + post form ```sh POST /post?id=1234&page=1 HTTP/1.1 Content-Type: application/x-www-form-urlencoded name=manu&message=this_is_great ``` ```go func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { id := c.Query("id") page := c.DefaultQuery("page", "0") name := c.PostForm("name") message := c.PostForm("message") fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message) }) router.Run(":8080") } ``` ```sh id: 1234; page: 1; name: manu; message: this_is_great ``` ### Map as querystring or postform parameters ```sh POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1 Content-Type: application/x-www-form-urlencoded names[first]=thinkerou&names[second]=tianou ``` ```go func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { ids := c.QueryMap("ids") names := c.PostFormMap("names") fmt.Printf("ids: %v; names: %v", ids, names) }) router.Run(":8080") } ``` ```sh ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou] ``` ### Upload files #### Single file References issue [#774](https://github.com/gin-gonic/gin/issues/774) and detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/single). `file.Filename` **SHOULD NOT** be trusted. See [`Content-Disposition` on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives) and [#1693](https://github.com/gin-gonic/gin/issues/1693) > The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. ```go func main() { router := gin.Default() // Set a lower memory limit for multipart forms (default is 32 MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // Single file file, _ := c.FormFile("file") log.Println(file.Filename) // Upload the file to specific dst. c.SaveUploadedFile(file, dst) c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) }) router.Run(":8080") } ``` How to `curl`: ```bash curl -X POST http://localhost:8080/upload \ -F "file=@/Users/appleboy/test.zip" \ -H "Content-Type: multipart/form-data" ``` #### Multiple files See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple). ```go func main() { router := gin.Default() // Set a lower memory limit for multipart forms (default is 32 MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // Multipart form form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { log.Println(file.Filename) // Upload the file to specific dst. c.SaveUploadedFile(file, dst) } c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) }) router.Run(":8080") } ``` How to `curl`: ```bash curl -X POST http://localhost:8080/upload \ -F "upload[]=@/Users/appleboy/test1.zip" \ -F "upload[]=@/Users/appleboy/test2.zip" \ -H "Content-Type: multipart/form-data" ``` ### Grouping routes ```go func main() { router := gin.Default() // Simple group: v1 v1 := router.Group("/v1") { v1.POST("/login", loginEndpoint) v1.POST("/submit", submitEndpoint) v1.POST("/read", readEndpoint) } // Simple group: v2 v2 := router.Group("/v2") { v2.POST("/login", loginEndpoint) v2.POST("/submit", submitEndpoint) v2.POST("/read", readEndpoint) } router.Run(":8080") } ``` ### Blank Gin without middleware by default Use ```go r := gin.New() ``` instead of ```go // Default With the Logger and Recovery middleware already attached r := gin.Default() ``` ### Using middleware ```go func main() { // Creates a router without any middleware by default r := gin.New() // Global middleware // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. // By default gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) // Recovery middleware recovers from any panics and writes a 500 if there was one. r.Use(gin.Recovery()) // Per route middleware, you can add as many as you desire. r.GET("/benchmark", MyBenchLogger(), benchEndpoint) // Authorization group // authorized := r.Group("/", AuthRequired()) // exactly the same as: authorized := r.Group("/") // per group middleware! in this case we use the custom created // AuthRequired() middleware just in the "authorized" group. authorized.Use(AuthRequired()) { authorized.POST("/login", loginEndpoint) authorized.POST("/submit", submitEndpoint) authorized.POST("/read", readEndpoint) // nested group testing := authorized.Group("testing") // visit 0.0.0.0:8080/testing/analytics testing.GET("/analytics", analyticsEndpoint) } // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Custom Recovery behavior ```go func main() { // Creates a router without any middleware by default r := gin.New() // Global middleware // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. // By default gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) // Recovery middleware recovers from any panics and writes a 500 if there was one. r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) { if err, ok := recovered.(string); ok { c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) } c.AbortWithStatus(http.StatusInternalServerError) })) r.GET("/panic", func(c *gin.Context) { // panic with a string -- the custom middleware could save this to a database or report it to the user panic("foo") }) r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "ohai") }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### How to write log file ```go func main() { // Disable Console Color, you don't need console color when writing the logs to file. gin.DisableConsoleColor() // Logging to a file. f, _ := os.Create("gin.log") gin.DefaultWriter = io.MultiWriter(f) // Use the following code if you need to write the logs to file and console at the same time. // gin.DefaultWriter = io.MultiWriter(f, os.Stdout) router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })    router.Run(":8080") } ``` ### Custom Log Format ```go func main() { router := gin.New() // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter // By default gin.DefaultWriter = os.Stdout router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { // your custom format return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n", param.ClientIP, param.TimeStamp.Format(time.RFC1123), param.Method, param.Path, param.Request.Proto, param.StatusCode, param.Latency, param.Request.UserAgent(), param.ErrorMessage, ) })) router.Use(gin.Recovery()) router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) router.Run(":8080") } ``` Sample Output ```sh ::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" " ``` ### Controlling Log output coloring By default, logs output on console should be colorized depending on the detected TTY. Never colorize logs: ```go func main() { // Disable log's color gin.DisableConsoleColor() // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) router.Run(":8080") } ``` Always colorize logs: ```go func main() { // Force log's color gin.ForceConsoleColor() // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) router.Run(":8080") } ``` ### Model binding and validation To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML, TOML and standard form values (foo=bar&boo=baz). Gin uses [**go-playground/validator/v10**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](https://godoc.org/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags). 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"`. Also, Gin provides two sets of methods for binding: - **Type** - Must bind - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML` - **Behavior** - These methods use `MustBindWith` under the hood. If there is a binding error, the request is aborted with `c.AbortWithError(400, err).SetType(ErrorTypeBind)`. This sets the response status code to 400 and the `Content-Type` header is set to `text/plain; charset=utf-8`. Note that if you try to set the response code after this, it will result in a warning `[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422`. If you wish to have greater control over the behavior, consider using the `ShouldBind` equivalent method. - **Type** - Should bind - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`, - **Behavior** - These methods use `ShouldBindWith` under the hood. If there is a binding error, the error is returned and it is the developer's responsibility to handle the request and error appropriately. 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 `MustBindWith` or `ShouldBindWith`. You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, an error will be returned. ```go // Binding from JSON type Login struct { User string `form:"user" json:"user" xml:"user" binding:"required"` Password string `form:"password" json:"password" xml:"password" binding:"required"` } func main() { router := gin.Default() // Example for binding JSON ({"user": "manu", "password": "123"}) router.POST("/loginJSON", func(c *gin.Context) { var json Login if err := c.ShouldBindJSON(&json); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if json.User != "manu" || json.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // Example for binding XML ( // <?xml version="1.0" encoding="UTF-8"?> // <root> // <user>manu</user> // <password>123</password> // </root>) router.POST("/loginXML", func(c *gin.Context) { var xml Login if err := c.ShouldBindXML(&xml); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if xml.User != "manu" || xml.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // Example for binding a HTML form (user=manu&password=123) router.POST("/loginForm", func(c *gin.Context) { var form Login // This will infer what binder to use depending on the content-type header. if err := c.ShouldBind(&form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if form.User != "manu" || form.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` Sample request ```sh $ curl -v -X POST \ http://localhost:8080/loginJSON \ -H 'content-type: application/json' \ -d '{ "user": "manu" }' > POST /loginJSON HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.51.0 > Accept: */* > content-type: application/json > Content-Length: 18 > * upload completely sent off: 18 out of 18 bytes < HTTP/1.1 400 Bad Request < Content-Type: application/json; charset=utf-8 < Date: Fri, 04 Aug 2017 03:51:31 GMT < Content-Length: 100 < {"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"} ``` Skip validate: when running the above example using the above the `curl` command, it returns error. Because the example use `binding:"required"` for `Password`. If use `binding:"-"` for `Password`, then it will not return error when running the above example again. ### Custom Validators It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go). ```go package main import ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/go-playground/validator/v10" ) // Booking contains binded and validated data. type Booking struct { CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` } var bookableDate validator.Func = func(fl validator.FieldLevel) bool { date, ok := fl.Field().Interface().(time.Time) if ok { today := time.Now() if today.After(date) { return false } } return true } func main() { route := gin.Default() if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("bookabledate", bookableDate) } route.GET("/bookable", getBookable) route.Run(":8085") } func getBookable(c *gin.Context) { var b Booking if err := c.ShouldBindWith(&b, binding.Query); err == nil { c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } } ``` ```console $ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17" {"message":"Booking dates are valid!"} $ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09" {"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"} $ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10" {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}% ``` [Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way. See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more. ### Only Bind Query String `ShouldBindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017). ```go package main import ( "log" "net/http" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` } func main() { route := gin.Default() route.Any("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person if c.ShouldBindQuery(&person) == nil { log.Println("====== Only Bind By Query String ======") log.Println(person.Name) log.Println(person.Address) } c.String(http.StatusOK, "Success") } ``` ### Bind Query String or Post Data See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292). ```go package main import ( "log" "net/http" "time" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` CreateTime time.Time `form:"createTime" time_format:"unixNano"` UnixTime time.Time `form:"unixTime" time_format:"unix"` } func main() { route := gin.Default() route.GET("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person // If `GET`, only `Form` binding engine (`query`) used. // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`). // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88 if c.ShouldBind(&person) == nil { log.Println(person.Name) log.Println(person.Address) log.Println(person.Birthday) log.Println(person.CreateTime) log.Println(person.UnixTime) } c.String(http.StatusOK, "Success") } ``` Test it with: ```sh curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" ``` ### Bind Uri See the [detail information](https://github.com/gin-gonic/gin/issues/846). ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) type Person struct { ID string `uri:"id" binding:"required,uuid"` Name string `uri:"name" binding:"required"` } func main() { route := gin.Default() route.GET("/:name/:id", func(c *gin.Context) { var person Person if err := c.ShouldBindUri(&person); err != nil { c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID}) }) route.Run(":8088") } ``` Test it with: ```sh curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 curl -v localhost:8088/thinkerou/not-uuid ``` ### Bind Header ```go package main import ( "fmt" "net/http" "github.com/gin-gonic/gin" ) type testHeader struct { Rate int `header:"Rate"` Domain string `header:"Domain"` } func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { h := testHeader{} if err := c.ShouldBindHeader(&h); err != nil { c.JSON(http.StatusOK, err) } fmt.Printf("%#v\n", h) c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain}) }) r.Run() // client // curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/ // output // {"Domain":"music","Rate":300} } ``` ### Bind HTML checkboxes See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092) main.go ```go ... type myForm struct { Colors []string `form:"colors[]"` } ... func formHandler(c *gin.Context) { var fakeForm myForm c.ShouldBind(&fakeForm) c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors}) } ... ``` form.html ```html <form action="/" method="POST"> <p>Check some colors</p> <label for="red">Red</label> <input type="checkbox" name="colors[]" value="red" id="red"> <label for="green">Green</label> <input type="checkbox" name="colors[]" value="green" id="green"> <label for="blue">Blue</label> <input type="checkbox" name="colors[]" value="blue" id="blue"> <input type="submit"> </form> ``` result: ```json {"color":["red","green","blue"]} ``` ### Multipart/Urlencoded binding ```go type ProfileForm struct { Name string `form:"name" binding:"required"` Avatar *multipart.FileHeader `form:"avatar" binding:"required"` // or for multiple files // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"` } func main() { router := gin.Default() router.POST("/profile", func(c *gin.Context) { // you can bind multipart form with explicit binding declaration: // c.ShouldBindWith(&form, binding.Form) // or you can simply use autobinding with ShouldBind method: var form ProfileForm // in this case proper binding will be automatically selected if err := c.ShouldBind(&form); err != nil { c.String(http.StatusBadRequest, "bad request") return } err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename) if err != nil { c.String(http.StatusInternalServerError, "unknown error") return } // db.Save(&form) c.String(http.StatusOK, "ok") }) router.Run(":8080") } ``` Test it with: ```sh curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile ``` ### XML, JSON, YAML and ProtoBuf rendering ```go func main() { r := gin.Default() // gin.H is a shortcut for map[string]interface{} r.GET("/someJSON", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/moreJSON", func(c *gin.Context) { // You also can use a struct var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // Note that msg.Name becomes "user" in the JSON // Will output : {"user": "Lena", "Message": "hey", "Number": 123} c.JSON(http.StatusOK, msg) }) r.GET("/someXML", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // The specific definition of protobuf is written in the testdata/protoexample file. data := &protoexample.Test{ Label: &label, Reps: reps, } // Note that data becomes binary data in the response // Will output protoexample.Test protobuf serialized data c.ProtoBuf(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` #### SecureJSON Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values. ```go func main() { r := gin.Default() // You can also use your own secure json prefix // r.SecureJsonPrefix(")]}',\n") r.GET("/someJSON", func(c *gin.Context) { names := []string{"lena", "austin", "foo"} // Will output : while(1);["lena","austin","foo"] c.SecureJSON(http.StatusOK, names) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` #### JSONP Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists. ```go func main() { r := gin.Default() r.GET("/JSONP", func(c *gin.Context) { data := gin.H{ "foo": "bar", } //callback is x // Will output : x({\"foo\":\"bar\"}) c.JSONP(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") // client // curl http://127.0.0.1:8080/JSONP?callback=x } ``` #### AsciiJSON Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters. ```go func main() { r := gin.Default() r.GET("/someJSON", func(c *gin.Context) { data := gin.H{ "lang": "GO语言", "tag": "<br>", } // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"} c.AsciiJSON(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` #### PureJSON Normally, JSON replaces special HTML characters with their unicode entities, e.g. `<` becomes `\u003c`. If you want to encode such characters literally, you can use PureJSON instead. This feature is unavailable in Go 1.6 and lower. ```go func main() { r := gin.Default() // Serves unicode entities r.GET("/json", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "html": "<b>Hello, world!</b>", }) }) // Serves literal characters r.GET("/purejson", func(c *gin.Context) { c.PureJSON(http.StatusOK, gin.H{ "html": "<b>Hello, world!</b>", }) }) // listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Serving static files ```go func main() { router := gin.Default() router.Static("/assets", "./assets") router.StaticFS("/more_static", http.Dir("my_file_system")) router.StaticFile("/favicon.ico", "./resources/favicon.ico") router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system")) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` ### Serving data from file ```go func main() { router := gin.Default() router.GET("/local/file", func(c *gin.Context) { c.File("local/file.go") }) var fs http.FileSystem = // ... router.GET("/fs/file", func(c *gin.Context) { c.FileFromFS("fs/file.go", fs) }) } ``` ### Serving data from reader ```go func main() { router := gin.Default() router.GET("/someDataFromReader", func(c *gin.Context) { response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png") if err != nil || response.StatusCode != http.StatusOK { c.Status(http.StatusServiceUnavailable) return } reader := response.Body defer reader.Close() contentLength := response.ContentLength contentType := response.Header.Get("Content-Type") extraHeaders := map[string]string{ "Content-Disposition": `attachment; filename="gopher.png"`, } c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) }) router.Run(":8080") } ``` ### HTML rendering Using LoadHTMLGlob() or LoadHTMLFiles() ```go func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", }) }) router.Run(":8080") } ``` templates/index.tmpl ```html <html> <h1> {{ .title }} </h1> </html> ``` Using templates with same name in different directories ```go func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ "title": "Posts", }) }) router.GET("/users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ "title": "Users", }) }) router.Run(":8080") } ``` templates/posts/index.tmpl ```html {{ define "posts/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using posts/index.tmpl</p> </html> {{ end }} ``` templates/users/index.tmpl ```html {{ define "users/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using users/index.tmpl</p> </html> {{ end }} ``` #### Custom Template renderer You can also use your own html template render ```go import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") } ``` #### Custom Delimiters You may use custom delims ```go r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates") ``` #### Custom Template Funcs See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template). main.go ```go import ( "fmt" "html/template" "net/http" "time" "github.com/gin-gonic/gin" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d/%02d/%02d", year, month, day) } func main() { router := gin.Default() router.Delims("{[{", "}]}") router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) router.LoadHTMLFiles("./testdata/template/raw.tmpl") router.GET("/raw", func(c *gin.Context) { c.HTML(http.StatusOK, "raw.tmpl", gin.H{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) router.Run(":8080") } ``` raw.tmpl ```html Date: {[{.now | formatAsDate}]} ``` Result: ```sh Date: 2017/07/01 ``` ### Multitemplate Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`. ### Redirects Issuing a HTTP redirect is easy. Both internal and external locations are supported. ```go r.GET("/test", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") }) ``` Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444) ```go r.POST("/test", func(c *gin.Context) { c.Redirect(http.StatusFound, "/foo") }) ``` Issuing a Router redirect, use `HandleContext` like below. ``` go r.GET("/test", func(c *gin.Context) { c.Request.URL.Path = "/test2" r.HandleContext(c) }) r.GET("/test2", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"hello": "world"}) }) ``` ### Custom Middleware ```go func Logger() gin.HandlerFunc { return func(c *gin.Context) { t := time.Now() // Set example variable c.Set("example", "12345") // before request c.Next() // after request latency := time.Since(t) log.Print(latency) // access the status we are sending status := c.Writer.Status() log.Println(status) } } func main() { r := gin.New() r.Use(Logger()) r.GET("/test", func(c *gin.Context) { example := c.MustGet("example").(string) // it would print: "12345" log.Println(example) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Using BasicAuth() middleware ```go // simulate some private data var secrets = gin.H{ "foo": gin.H{"email": "[email protected]", "phone": "123433"}, "austin": gin.H{"email": "[email protected]", "phone": "666"}, "lena": gin.H{"email": "[email protected]", "phone": "523443"}, } func main() { r := gin.Default() // Group using gin.BasicAuth() middleware // gin.Accounts is a shortcut for map[string]string authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{ "foo": "bar", "austin": "1234", "lena": "hello2", "manu": "4321", })) // /admin/secrets endpoint // hit "localhost:8080/admin/secrets authorized.GET("/secrets", func(c *gin.Context) { // get user, it was set by the BasicAuth middleware user := c.MustGet(gin.AuthUserKey).(string) if secret, ok := secrets[user]; ok { c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret}) } else { c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("}) } }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Goroutines inside a middleware When starting new Goroutines inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy. ```go func main() { r := gin.Default() r.GET("/long_async", func(c *gin.Context) { // create copy to be used inside the goroutine cCp := c.Copy() go func() { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) // note that you are using the copied context "cCp", IMPORTANT log.Println("Done! in path " + cCp.Request.URL.Path) }() }) r.GET("/long_sync", func(c *gin.Context) { // simulate a long task with time.Sleep(). 5 seconds 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.Request.URL.Path) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Custom HTTP configuration Use `http.ListenAndServe()` directly, like this: ```go func main() { router := gin.Default() http.ListenAndServe(":8080", router) } ``` or ```go func main() { router := gin.Default() s := &http.Server{ Addr: ":8080", Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() } ``` ### Support Let's Encrypt example for 1-line LetsEncrypt HTTPS servers. ```go package main import ( "log" "net/http" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) log.Fatal(autotls.Run(r, "example1.com", "example2.com")) } ``` example for custom autocert manager. ```go package main import ( "log" "net/http" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" "golang.org/x/crypto/acme/autocert" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) m := autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"), Cache: autocert.DirCache("/var/www/.cache"), } log.Fatal(autotls.RunWithManager(r, &m)) } ``` ### Run multiple service using Gin See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example: ```go package main import ( "log" "net/http" "time" "github.com/gin-gonic/gin" "golang.org/x/sync/errgroup" ) var ( g errgroup.Group ) func router01() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 01", }, ) }) return e } func router02() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 02", }, ) }) return e } func main() { server01 := &http.Server{ Addr: ":8080", Handler: router01(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } server02 := &http.Server{ Addr: ":8081", Handler: router02(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } g.Go(func() error { err := server01.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) g.Go(func() error { err := server02.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) if err := g.Wait(); err != nil { log.Fatal(err) } } ``` ### Graceful shutdown or restart There are a few approaches you can use to perform a graceful shutdown or restart. You can make use of third-party packages specifically built for that, or you can manually do the same with the functions and methods from the built-in packages. #### Third-party packages We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer to issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details. ```go router := gin.Default() router.GET("/", handler) // [...] endless.ListenAndServe(":4242", router) ``` Alternatives: * [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers. * [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server. * [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. #### Manually In case you are using Go 1.8 or a later version, you may not need to use those libraries. Consider using `http.Server`'s built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. The example below describes its usage, and we've got more examples using gin [here](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown). ```go // +build go1.8 package main import ( "context" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { time.Sleep(5 * time.Second) c.String(http.StatusOK, "Welcome Gin Server") }) srv := &http.Server{ Addr: ":8080", Handler: router, } // Initializing the server in a goroutine so that // it won't block the graceful shutdown handling below go func() { if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) { log.Printf("listen: %s\n", err) } }() // Wait for interrupt signal to gracefully shutdown the server with // a timeout of 5 seconds. quit := make(chan os.Signal) // kill (no param) default send syscall.SIGTERM // kill -2 is syscall.SIGINT // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("Shutting down server...") // The context is used to inform the server it has 5 seconds to finish // the request it is currently handling ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server forced to shutdown:", err) } log.Println("Server exiting") } ``` ### Build a single binary with templates You can build a server into a single binary containing templates by using [go-assets][]. [go-assets]: https://github.com/jessevdk/go-assets ```go func main() { r := gin.New() t, err := loadTemplate() if err != nil { panic(err) } r.SetHTMLTemplate(t) r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "/html/index.tmpl",nil) }) r.Run(":8080") } // loadTemplate loads templates embedded by go-assets-builder func loadTemplate() (*template.Template, error) { t := template.New("") for name, file := range Assets.Files { defer file.Close() if file.IsDir() || !strings.HasSuffix(name, ".tmpl") { continue } h, err := ioutil.ReadAll(file) if err != nil { return nil, err } t, err = t.New(name).Parse(string(h)) if err != nil { return nil, err } } return t, nil } ``` See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary` directory. ### Bind form-data request with custom struct The follow example using custom struct: ```go type StructA struct { FieldA string `form:"field_a"` } type StructB struct { NestedStruct StructA FieldB string `form:"field_b"` } type StructC struct { NestedStructPointer *StructA FieldC string `form:"field_c"` } type StructD struct { NestedAnonyStruct struct { FieldX string `form:"field_x"` } FieldD string `form:"field_d"` } func GetDataB(c *gin.Context) { var b StructB c.Bind(&b) c.JSON(http.StatusOK, gin.H{ "a": b.NestedStruct, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(http.StatusOK, gin.H{ "a": b.NestedStructPointer, "c": b.FieldC, }) } func GetDataD(c *gin.Context) { var b StructD c.Bind(&b) c.JSON(http.StatusOK, gin.H{ "x": b.NestedAnonyStruct, "d": b.FieldD, }) } func main() { r := gin.Default() r.GET("/getb", GetDataB) r.GET("/getc", GetDataC) r.GET("/getd", GetDataD) r.Run() } ``` Using the command `curl` command result: ```sh $ curl "http://localhost:8080/getb?field_a=hello&field_b=world" {"a":{"FieldA":"hello"},"b":"world"} $ curl "http://localhost:8080/getc?field_a=hello&field_c=world" {"a":{"FieldA":"hello"},"c":"world"} $ curl "http://localhost:8080/getd?field_x=hello&field_d=world" {"d":"world","x":{"FieldX":"hello"}} ``` ### Try to bind body into different structs The normal methods for binding request body consumes `c.Request.Body` and they cannot be called multiple times. ```go type formA struct { Foo string `json:"foo" xml:"foo" binding:"required"` } type formB struct { Bar string `json:"bar" xml:"bar" binding:"required"` } func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} // This c.ShouldBind consumes c.Request.Body and it cannot be reused. if errA := c.ShouldBind(&objA); errA == nil { c.String(http.StatusOK, `the body should be formA`) // Always an error is occurred by this because c.Request.Body is EOF now. } else if errB := c.ShouldBind(&objB); errB == nil { c.String(http.StatusOK, `the body should be formB`) } else { ... } } ``` For this, you can use `c.ShouldBindBodyWith`. ```go func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} // This reads c.Request.Body and stores the result into the context. if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil { c.String(http.StatusOK, `the body should be formA`) // At this time, it reuses body stored in the context. } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { c.String(http.StatusOK, `the body should be formB JSON`) // And it can accepts other formats } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil { c.String(http.StatusOK, `the body should be formB XML`) } else { ... } } ``` 1. `c.ShouldBindBodyWith` stores body into the context before binding. This has a slight impact to performance, so you should not use this method if you are enough to call binding at once. 2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`, `ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`, can be called by `c.ShouldBind()` multiple times without any damage to performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)). ### Bind form-data request with custom struct and custom tag ```go const ( customerTag = "url" defaultMemory = 32 << 20 ) type customerBinding struct {} func (customerBinding) Name() string { return "form" } func (customerBinding) Bind(req *http.Request, obj interface{}) error { if err := req.ParseForm(); err != nil { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil { if err != http.ErrNotMultipart { return err } } if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil { return err } return validate(obj) } func validate(obj interface{}) error { if binding.Validator == nil { return nil } return binding.Validator.ValidateStruct(obj) } // Now we can do this!!! // FormA is a external type that we can't modify it's tag type FormA struct { FieldA string `url:"field_a"` } func ListHandler(s *Service) func(ctx *gin.Context) { return func(ctx *gin.Context) { var urlBinding = customerBinding{} var opt FormA err := ctx.MustBindWith(&opt, urlBinding) if err != nil { ... } ... } } ``` ### http2 server push http.Pusher is supported only **go1.8+**. See the [golang blog](https://blog.golang.org/h2push) for detail information. ```go package main import ( "html/template" "log" "net/http" "github.com/gin-gonic/gin" ) var html = template.Must(template.New("https").Parse(` <html> <head> <title>Https Test</title> <script src="/assets/app.js"></script> </head> <body> <h1 style="color:red;">Welcome, Ginner!</h1> </body> </html> `)) func main() { r := gin.Default() r.Static("/assets", "./assets") r.SetHTMLTemplate(html) r.GET("/", func(c *gin.Context) { if pusher := c.Writer.Pusher(); pusher != nil { // use pusher.Push() to do server push if err := pusher.Push("/assets/app.js", nil); err != nil { log.Printf("Failed to push: %v", err) } } c.HTML(http.StatusOK, "https", gin.H{ "status": "success", }) }) // Listen and Server in https://127.0.0.1:8080 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key") } ``` ### Define format for the log of routes The default log of routes is: ```sh [GIN-debug] POST /foo --> main.main.func1 (3 handlers) [GIN-debug] GET /bar --> main.main.func2 (3 handlers) [GIN-debug] GET /status --> main.main.func3 (3 handlers) ``` If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`. In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs. ```go import ( "log" "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) } r.POST("/foo", func(c *gin.Context) { c.JSON(http.StatusOK, "foo") }) r.GET("/bar", func(c *gin.Context) { c.JSON(http.StatusOK, "bar") }) r.GET("/status", func(c *gin.Context) { c.JSON(http.StatusOK, "ok") }) // Listen and Server in http://0.0.0.0:8080 r.Run() } ``` ### Set and get a cookie ```go import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/cookie", func(c *gin.Context) { cookie, err := c.Cookie("gin_cookie") if err != nil { cookie = "NotSet" c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) } fmt.Printf("Cookie value: %s \n", cookie) }) router.Run() } ``` ## Don't trust all proxies Gin lets you specify which headers to hold the real client IP (if any), as well as specifying which proxies (or direct clients) you trust to specify one of these headers. Use function `SetTrustedProxies()` on your `gin.Engine` to specify network addresses or network CIDRs from where clients which their request headers related to client IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs. **Attention:** Gin trust all proxies by default if you don't specify a trusted proxy using the function above, **this is NOT safe**. At the same time, if you don't use any proxy, you can disable this feature by using `Engine.SetTrustedProxies(nil)`, then `Context.ClientIP()` will return the remote address directly to avoid some unnecessary computation. ```go import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.SetTrustedProxies([]string{"192.168.1.2"}) router.GET("/", func(c *gin.Context) { // If the client is 192.168.1.2, use the X-Forwarded-For // header to deduce the original client IP from the trust- // worthy parts of that header. // Otherwise, simply return the direct client IP fmt.Printf("ClientIP: %s\n", c.ClientIP()) }) router.Run() } ``` **Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform` to skip TrustedProxies check, it has a higher priority than TrustedProxies. Look at the example below: ```go import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() // Use predefined header gin.PlatformXXX router.TrustedPlatform = gin.PlatformGoogleAppEngine // Or set your own trusted request header for another trusted proxy service // Don't set it to any suspect request header, it's unsafe router.TrustedPlatform = "X-CDN-IP" router.GET("/", func(c *gin.Context) { // If you set TrustedPlatform, ClientIP() will resolve the // corresponding header and return IP directly fmt.Printf("ClientIP: %s\n", c.ClientIP()) }) router.Run() } ``` ## Testing The `net/http/httptest` package is preferable way for HTTP testing. ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func setupRouter() *gin.Engine { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) return r } func main() { r := setupRouter() r.Run(":8080") } ``` Test for code example above: ```go package main import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestPingRoute(t *testing.T) { router := setupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/ping", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "pong", w.Body.String()) } ``` ## Users Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework. * [gorush](https://github.com/appleboy/gorush): A push notification server written in Go. * [fnproject](https://github.com/fnproject/fn): The container native, cloud agnostic serverless platform. * [photoprism](https://github.com/photoprism/photoprism): Personal photo management powered by Go and Google TensorFlow. * [krakend](https://github.com/devopsfaith/krakend): Ultra performant API Gateway with middlewares. * [picfit](https://github.com/thoas/picfit): An image resizing server written in Go. * [brigade](https://github.com/brigadecore/brigade): Event-based Scripting for Kubernetes. * [dkron](https://github.com/distribworks/dkron): Distributed, fault tolerant job scheduling system.
# Gin Web Framework <img align="right" width="159px" src="https://raw.githubusercontent.com/gin-gonic/logo/master/color.png"> [![Build Status](https://github.com/gin-gonic/gin/workflows/Run%20Tests/badge.svg?branch=master)](https://github.com/gin-gonic/gin/actions?query=branch%3Amaster) [![codecov](https://codecov.io/gh/gin-gonic/gin/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-gonic/gin) [![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin) [![GoDoc](https://pkg.go.dev/badge/github.com/gin-gonic/gin?status.svg)](https://pkg.go.dev/github.com/gin-gonic/gin?tab=doc) [![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Sourcegraph](https://sourcegraph.com/github.com/gin-gonic/gin/-/badge.svg)](https://sourcegraph.com/github.com/gin-gonic/gin?badge) [![Open Source Helpers](https://www.codetriage.com/gin-gonic/gin/badges/users.svg)](https://www.codetriage.com/gin-gonic/gin) [![Release](https://img.shields.io/github/release/gin-gonic/gin.svg?style=flat-square)](https://github.com/gin-gonic/gin/releases) [![TODOs](https://badgen.net/https/api.tickgit.com/badgen/github.com/gin-gonic/gin)](https://www.tickgit.com/browse?repo=github.com/gin-gonic/gin) Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin. ## Contents - [Gin Web Framework](#gin-web-framework) - [Contents](#contents) - [Installation](#installation) - [Quick start](#quick-start) - [Benchmarks](#benchmarks) - [Gin v1. stable](#gin-v1-stable) - [Build with json replacement](#build-with-json-replacement) - [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature) - [API Examples](#api-examples) - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options) - [Parameters in path](#parameters-in-path) - [Querystring parameters](#querystring-parameters) - [Multipart/Urlencoded Form](#multiparturlencoded-form) - [Another example: query + post form](#another-example-query--post-form) - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters) - [Upload files](#upload-files) - [Single file](#single-file) - [Multiple files](#multiple-files) - [Grouping routes](#grouping-routes) - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default) - [Using middleware](#using-middleware) - [Custom Recovery behavior](#custom-recovery-behavior) - [How to write log file](#how-to-write-log-file) - [Custom Log Format](#custom-log-format) - [Controlling Log output coloring](#controlling-log-output-coloring) - [Model binding and validation](#model-binding-and-validation) - [Custom Validators](#custom-validators) - [Only Bind Query String](#only-bind-query-string) - [Bind Query String or Post Data](#bind-query-string-or-post-data) - [Bind Uri](#bind-uri) - [Bind Header](#bind-header) - [Bind HTML checkboxes](#bind-html-checkboxes) - [Multipart/Urlencoded binding](#multiparturlencoded-binding) - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering) - [SecureJSON](#securejson) - [JSONP](#jsonp) - [AsciiJSON](#asciijson) - [PureJSON](#purejson) - [Serving static files](#serving-static-files) - [Serving data from file](#serving-data-from-file) - [Serving data from reader](#serving-data-from-reader) - [HTML rendering](#html-rendering) - [Custom Template renderer](#custom-template-renderer) - [Custom Delimiters](#custom-delimiters) - [Custom Template Funcs](#custom-template-funcs) - [Multitemplate](#multitemplate) - [Redirects](#redirects) - [Custom Middleware](#custom-middleware) - [Using BasicAuth() middleware](#using-basicauth-middleware) - [Goroutines inside a middleware](#goroutines-inside-a-middleware) - [Custom HTTP configuration](#custom-http-configuration) - [Support Let's Encrypt](#support-lets-encrypt) - [Run multiple service using Gin](#run-multiple-service-using-gin) - [Graceful shutdown or restart](#graceful-shutdown-or-restart) - [Third-party packages](#third-party-packages) - [Manually](#manually) - [Build a single binary with templates](#build-a-single-binary-with-templates) - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct) - [Try to bind body into different structs](#try-to-bind-body-into-different-structs) - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag) - [http2 server push](#http2-server-push) - [Define format for the log of routes](#define-format-for-the-log-of-routes) - [Set and get a cookie](#set-and-get-a-cookie) - [Don't trust all proxies](#dont-trust-all-proxies) - [Testing](#testing) - [Users](#users) ## Installation To install Gin package, you need to install Go and set your Go workspace first. 1. You first need [Go](https://golang.org/) installed (**version 1.16+ is required**), then you can use the below Go command to install Gin. ```sh go get -u github.com/gin-gonic/gin ``` 2. Import it in your code: ```go import "github.com/gin-gonic/gin" ``` 3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`. ```go import "net/http" ``` ## Quick start ```sh # assume the following codes in example.go file $ cat example.go ``` ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") } ``` ``` # run example.go and visit 0.0.0.0:8080/ping (for windows "localhost:8080/ping") on browser $ go run example.go ``` ## Benchmarks Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) [See all benchmarks](/BENCHMARKS.md) | Benchmark name | (1) | (2) | (3) | (4) | | ------------------------------ | ---------:| ---------------:| ------------:| ---------------:| | BenchmarkGin_GithubAll | **43550** | **27364 ns/op** | **0 B/op** | **0 allocs/op** | | BenchmarkAce_GithubAll | 40543 | 29670 ns/op | 0 B/op | 0 allocs/op | | BenchmarkAero_GithubAll | 57632 | 20648 ns/op | 0 B/op | 0 allocs/op | | BenchmarkBear_GithubAll | 9234 | 216179 ns/op | 86448 B/op | 943 allocs/op | | BenchmarkBeego_GithubAll | 7407 | 243496 ns/op | 71456 B/op | 609 allocs/op | | BenchmarkBone_GithubAll | 420 | 2922835 ns/op | 720160 B/op | 8620 allocs/op | | BenchmarkChi_GithubAll | 7620 | 238331 ns/op | 87696 B/op | 609 allocs/op | | BenchmarkDenco_GithubAll | 18355 | 64494 ns/op | 20224 B/op | 167 allocs/op | | BenchmarkEcho_GithubAll | 31251 | 38479 ns/op | 0 B/op | 0 allocs/op | | BenchmarkGocraftWeb_GithubAll | 4117 | 300062 ns/op | 131656 B/op | 1686 allocs/op | | BenchmarkGoji_GithubAll | 3274 | 416158 ns/op | 56112 B/op | 334 allocs/op | | BenchmarkGojiv2_GithubAll | 1402 | 870518 ns/op | 352720 B/op | 4321 allocs/op | | BenchmarkGoJsonRest_GithubAll | 2976 | 401507 ns/op | 134371 B/op | 2737 allocs/op | | BenchmarkGoRestful_GithubAll | 410 | 2913158 ns/op | 910144 B/op | 2938 allocs/op | | BenchmarkGorillaMux_GithubAll | 346 | 3384987 ns/op | 251650 B/op | 1994 allocs/op | | BenchmarkGowwwRouter_GithubAll | 10000 | 143025 ns/op | 72144 B/op | 501 allocs/op | | BenchmarkHttpRouter_GithubAll | 55938 | 21360 ns/op | 0 B/op | 0 allocs/op | | BenchmarkHttpTreeMux_GithubAll | 10000 | 153944 ns/op | 65856 B/op | 671 allocs/op | | BenchmarkKocha_GithubAll | 10000 | 106315 ns/op | 23304 B/op | 843 allocs/op | | BenchmarkLARS_GithubAll | 47779 | 25084 ns/op | 0 B/op | 0 allocs/op | | BenchmarkMacaron_GithubAll | 3266 | 371907 ns/op | 149409 B/op | 1624 allocs/op | | BenchmarkMartini_GithubAll | 331 | 3444706 ns/op | 226551 B/op | 2325 allocs/op | | BenchmarkPat_GithubAll | 273 | 4381818 ns/op | 1483152 B/op | 26963 allocs/op | | BenchmarkPossum_GithubAll | 10000 | 164367 ns/op | 84448 B/op | 609 allocs/op | | BenchmarkR2router_GithubAll | 10000 | 160220 ns/op | 77328 B/op | 979 allocs/op | | BenchmarkRivet_GithubAll | 14625 | 82453 ns/op | 16272 B/op | 167 allocs/op | | BenchmarkTango_GithubAll | 6255 | 279611 ns/op | 63826 B/op | 1618 allocs/op | | BenchmarkTigerTonic_GithubAll | 2008 | 687874 ns/op | 193856 B/op | 4474 allocs/op | | BenchmarkTraffic_GithubAll | 355 | 3478508 ns/op | 820744 B/op | 14114 allocs/op | | BenchmarkVulcan_GithubAll | 6885 | 193333 ns/op | 19894 B/op | 609 allocs/op | - (1): Total Repetitions achieved in constant time, higher means more confident result - (2): Single Repetition Duration (ns/op), lower is better - (3): Heap Memory (B/op), lower is better - (4): Average Allocations per Repetition (allocs/op), lower is better ## Gin v1. stable - [x] Zero allocation router. - [x] Still the fastest http router and framework. From routing to writing. - [x] Complete suite of unit tests. - [x] Battle tested. - [x] API frozen, new releases will not break your code. ## Build with json replacement Gin uses `encoding/json` as default json package but you can change it by build from other tags. [jsoniter](https://github.com/json-iterator/go) ```sh go build -tags=jsoniter . ``` [go-json](https://github.com/goccy/go-json) ```sh go build -tags=go_json . ``` [sonic](https://github.com/bytedance/sonic) (you have to ensure that your cpu support avx instruction.) ```sh $ go build -tags="sonic avx" . ``` ## Build without `MsgPack` rendering feature Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag. ```sh go build -tags=nomsgpack . ``` This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852). ## API Examples You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples). ### Using GET, POST, PUT, PATCH, DELETE and OPTIONS ```go func main() { // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/someGet", getting) router.POST("/somePost", posting) router.PUT("/somePut", putting) router.DELETE("/someDelete", deleting) router.PATCH("/somePatch", patching) router.HEAD("/someHead", head) router.OPTIONS("/someOptions", options) // By default it serves on :8080 unless a // PORT environment variable was defined. router.Run() // router.Run(":3000") for a hard coded port } ``` ### Parameters in path ```go func main() { router := gin.Default() // This handler will match /user/john but will not match /user/ or /user router.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) // However, this one will match /user/john/ and also /user/john/send // If no other routers match /user/john, it will redirect to /user/john/ router.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") message := name + " is " + action c.String(http.StatusOK, message) }) // For each matched request Context will hold the route definition router.POST("/user/:name/*action", func(c *gin.Context) { b := c.FullPath() == "/user/:name/*action" // true c.String(http.StatusOK, "%t", b) }) // This handler will add a new router for /user/groups. // Exact routes are resolved before param routes, regardless of the order they were defined. // Routes starting with /user/groups are never interpreted as /user/:name/... routes router.GET("/user/groups", func(c *gin.Context) { c.String(http.StatusOK, "The available groups are [...]") }) router.Run(":8080") } ``` ### Querystring parameters ```go func main() { router := gin.Default() // Query string parameters are parsed using the existing underlying request object. // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe router.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname", "Guest") lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname") c.String(http.StatusOK, "Hello %s %s", firstname, lastname) }) router.Run(":8080") } ``` ### Multipart/Urlencoded Form ```go func main() { router := gin.Default() router.POST("/form_post", func(c *gin.Context) { message := c.PostForm("message") nick := c.DefaultPostForm("nick", "anonymous") c.JSON(http.StatusOK, gin.H{ "status": "posted", "message": message, "nick": nick, }) }) router.Run(":8080") } ``` ### Another example: query + post form ```sh POST /post?id=1234&page=1 HTTP/1.1 Content-Type: application/x-www-form-urlencoded name=manu&message=this_is_great ``` ```go func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { id := c.Query("id") page := c.DefaultQuery("page", "0") name := c.PostForm("name") message := c.PostForm("message") fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message) }) router.Run(":8080") } ``` ```sh id: 1234; page: 1; name: manu; message: this_is_great ``` ### Map as querystring or postform parameters ```sh POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1 Content-Type: application/x-www-form-urlencoded names[first]=thinkerou&names[second]=tianou ``` ```go func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { ids := c.QueryMap("ids") names := c.PostFormMap("names") fmt.Printf("ids: %v; names: %v", ids, names) }) router.Run(":8080") } ``` ```sh ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou] ``` ### Upload files #### Single file References issue [#774](https://github.com/gin-gonic/gin/issues/774) and detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/single). `file.Filename` **SHOULD NOT** be trusted. See [`Content-Disposition` on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives) and [#1693](https://github.com/gin-gonic/gin/issues/1693) > The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. ```go func main() { router := gin.Default() // Set a lower memory limit for multipart forms (default is 32 MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // Single file file, _ := c.FormFile("file") log.Println(file.Filename) // Upload the file to specific dst. c.SaveUploadedFile(file, dst) c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) }) router.Run(":8080") } ``` How to `curl`: ```bash curl -X POST http://localhost:8080/upload \ -F "file=@/Users/appleboy/test.zip" \ -H "Content-Type: multipart/form-data" ``` #### Multiple files See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple). ```go func main() { router := gin.Default() // Set a lower memory limit for multipart forms (default is 32 MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // Multipart form form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { log.Println(file.Filename) // Upload the file to specific dst. c.SaveUploadedFile(file, dst) } c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) }) router.Run(":8080") } ``` How to `curl`: ```bash curl -X POST http://localhost:8080/upload \ -F "upload[]=@/Users/appleboy/test1.zip" \ -F "upload[]=@/Users/appleboy/test2.zip" \ -H "Content-Type: multipart/form-data" ``` ### Grouping routes ```go func main() { router := gin.Default() // Simple group: v1 v1 := router.Group("/v1") { v1.POST("/login", loginEndpoint) v1.POST("/submit", submitEndpoint) v1.POST("/read", readEndpoint) } // Simple group: v2 v2 := router.Group("/v2") { v2.POST("/login", loginEndpoint) v2.POST("/submit", submitEndpoint) v2.POST("/read", readEndpoint) } router.Run(":8080") } ``` ### Blank Gin without middleware by default Use ```go r := gin.New() ``` instead of ```go // Default With the Logger and Recovery middleware already attached r := gin.Default() ``` ### Using middleware ```go func main() { // Creates a router without any middleware by default r := gin.New() // Global middleware // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. // By default gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) // Recovery middleware recovers from any panics and writes a 500 if there was one. r.Use(gin.Recovery()) // Per route middleware, you can add as many as you desire. r.GET("/benchmark", MyBenchLogger(), benchEndpoint) // Authorization group // authorized := r.Group("/", AuthRequired()) // exactly the same as: authorized := r.Group("/") // per group middleware! in this case we use the custom created // AuthRequired() middleware just in the "authorized" group. authorized.Use(AuthRequired()) { authorized.POST("/login", loginEndpoint) authorized.POST("/submit", submitEndpoint) authorized.POST("/read", readEndpoint) // nested group testing := authorized.Group("testing") // visit 0.0.0.0:8080/testing/analytics testing.GET("/analytics", analyticsEndpoint) } // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Custom Recovery behavior ```go func main() { // Creates a router without any middleware by default r := gin.New() // Global middleware // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. // By default gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) // Recovery middleware recovers from any panics and writes a 500 if there was one. r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) { if err, ok := recovered.(string); ok { c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) } c.AbortWithStatus(http.StatusInternalServerError) })) r.GET("/panic", func(c *gin.Context) { // panic with a string -- the custom middleware could save this to a database or report it to the user panic("foo") }) r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "ohai") }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### How to write log file ```go func main() { // Disable Console Color, you don't need console color when writing the logs to file. gin.DisableConsoleColor() // Logging to a file. f, _ := os.Create("gin.log") gin.DefaultWriter = io.MultiWriter(f) // Use the following code if you need to write the logs to file and console at the same time. // gin.DefaultWriter = io.MultiWriter(f, os.Stdout) router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })    router.Run(":8080") } ``` ### Custom Log Format ```go func main() { router := gin.New() // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter // By default gin.DefaultWriter = os.Stdout router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { // your custom format return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n", param.ClientIP, param.TimeStamp.Format(time.RFC1123), param.Method, param.Path, param.Request.Proto, param.StatusCode, param.Latency, param.Request.UserAgent(), param.ErrorMessage, ) })) router.Use(gin.Recovery()) router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) router.Run(":8080") } ``` Sample Output ```sh ::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" " ``` ### Controlling Log output coloring By default, logs output on console should be colorized depending on the detected TTY. Never colorize logs: ```go func main() { // Disable log's color gin.DisableConsoleColor() // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) router.Run(":8080") } ``` Always colorize logs: ```go func main() { // Force log's color gin.ForceConsoleColor() // Creates a gin router with default middleware: // logger and recovery (crash-free) middleware router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) router.Run(":8080") } ``` ### Model binding and validation To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML, TOML and standard form values (foo=bar&boo=baz). Gin uses [**go-playground/validator/v10**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](https://godoc.org/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags). 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"`. Also, Gin provides two sets of methods for binding: - **Type** - Must bind - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML` - **Behavior** - These methods use `MustBindWith` under the hood. If there is a binding error, the request is aborted with `c.AbortWithError(400, err).SetType(ErrorTypeBind)`. This sets the response status code to 400 and the `Content-Type` header is set to `text/plain; charset=utf-8`. Note that if you try to set the response code after this, it will result in a warning `[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422`. If you wish to have greater control over the behavior, consider using the `ShouldBind` equivalent method. - **Type** - Should bind - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`, - **Behavior** - These methods use `ShouldBindWith` under the hood. If there is a binding error, the error is returned and it is the developer's responsibility to handle the request and error appropriately. 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 `MustBindWith` or `ShouldBindWith`. You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, an error will be returned. ```go // Binding from JSON type Login struct { User string `form:"user" json:"user" xml:"user" binding:"required"` Password string `form:"password" json:"password" xml:"password" binding:"required"` } func main() { router := gin.Default() // Example for binding JSON ({"user": "manu", "password": "123"}) router.POST("/loginJSON", func(c *gin.Context) { var json Login if err := c.ShouldBindJSON(&json); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if json.User != "manu" || json.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // Example for binding XML ( // <?xml version="1.0" encoding="UTF-8"?> // <root> // <user>manu</user> // <password>123</password> // </root>) router.POST("/loginXML", func(c *gin.Context) { var xml Login if err := c.ShouldBindXML(&xml); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if xml.User != "manu" || xml.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // Example for binding a HTML form (user=manu&password=123) router.POST("/loginForm", func(c *gin.Context) { var form Login // This will infer what binder to use depending on the content-type header. if err := c.ShouldBind(&form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if form.User != "manu" || form.Password != "123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` Sample request ```sh $ curl -v -X POST \ http://localhost:8080/loginJSON \ -H 'content-type: application/json' \ -d '{ "user": "manu" }' > POST /loginJSON HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.51.0 > Accept: */* > content-type: application/json > Content-Length: 18 > * upload completely sent off: 18 out of 18 bytes < HTTP/1.1 400 Bad Request < Content-Type: application/json; charset=utf-8 < Date: Fri, 04 Aug 2017 03:51:31 GMT < Content-Length: 100 < {"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"} ``` Skip validate: when running the above example using the above the `curl` command, it returns error. Because the example use `binding:"required"` for `Password`. If use `binding:"-"` for `Password`, then it will not return error when running the above example again. ### Custom Validators It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go). ```go package main import ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/go-playground/validator/v10" ) // Booking contains binded and validated data. type Booking struct { CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` } var bookableDate validator.Func = func(fl validator.FieldLevel) bool { date, ok := fl.Field().Interface().(time.Time) if ok { today := time.Now() if today.After(date) { return false } } return true } func main() { route := gin.Default() if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("bookabledate", bookableDate) } route.GET("/bookable", getBookable) route.Run(":8085") } func getBookable(c *gin.Context) { var b Booking if err := c.ShouldBindWith(&b, binding.Query); err == nil { c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } } ``` ```console $ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17" {"message":"Booking dates are valid!"} $ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09" {"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"} $ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10" {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}% ``` [Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way. See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more. ### Only Bind Query String `ShouldBindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017). ```go package main import ( "log" "net/http" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` } func main() { route := gin.Default() route.Any("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person if c.ShouldBindQuery(&person) == nil { log.Println("====== Only Bind By Query String ======") log.Println(person.Name) log.Println(person.Address) } c.String(http.StatusOK, "Success") } ``` ### Bind Query String or Post Data See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292). ```go package main import ( "log" "net/http" "time" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` CreateTime time.Time `form:"createTime" time_format:"unixNano"` UnixTime time.Time `form:"unixTime" time_format:"unix"` } func main() { route := gin.Default() route.GET("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person // If `GET`, only `Form` binding engine (`query`) used. // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`). // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88 if c.ShouldBind(&person) == nil { log.Println(person.Name) log.Println(person.Address) log.Println(person.Birthday) log.Println(person.CreateTime) log.Println(person.UnixTime) } c.String(http.StatusOK, "Success") } ``` Test it with: ```sh curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" ``` ### Bind Uri See the [detail information](https://github.com/gin-gonic/gin/issues/846). ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) type Person struct { ID string `uri:"id" binding:"required,uuid"` Name string `uri:"name" binding:"required"` } func main() { route := gin.Default() route.GET("/:name/:id", func(c *gin.Context) { var person Person if err := c.ShouldBindUri(&person); err != nil { c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID}) }) route.Run(":8088") } ``` Test it with: ```sh curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 curl -v localhost:8088/thinkerou/not-uuid ``` ### Bind Header ```go package main import ( "fmt" "net/http" "github.com/gin-gonic/gin" ) type testHeader struct { Rate int `header:"Rate"` Domain string `header:"Domain"` } func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { h := testHeader{} if err := c.ShouldBindHeader(&h); err != nil { c.JSON(http.StatusOK, err) } fmt.Printf("%#v\n", h) c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain}) }) r.Run() // client // curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/ // output // {"Domain":"music","Rate":300} } ``` ### Bind HTML checkboxes See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092) main.go ```go ... type myForm struct { Colors []string `form:"colors[]"` } ... func formHandler(c *gin.Context) { var fakeForm myForm c.ShouldBind(&fakeForm) c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors}) } ... ``` form.html ```html <form action="/" method="POST"> <p>Check some colors</p> <label for="red">Red</label> <input type="checkbox" name="colors[]" value="red" id="red"> <label for="green">Green</label> <input type="checkbox" name="colors[]" value="green" id="green"> <label for="blue">Blue</label> <input type="checkbox" name="colors[]" value="blue" id="blue"> <input type="submit"> </form> ``` result: ```json {"color":["red","green","blue"]} ``` ### Multipart/Urlencoded binding ```go type ProfileForm struct { Name string `form:"name" binding:"required"` Avatar *multipart.FileHeader `form:"avatar" binding:"required"` // or for multiple files // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"` } func main() { router := gin.Default() router.POST("/profile", func(c *gin.Context) { // you can bind multipart form with explicit binding declaration: // c.ShouldBindWith(&form, binding.Form) // or you can simply use autobinding with ShouldBind method: var form ProfileForm // in this case proper binding will be automatically selected if err := c.ShouldBind(&form); err != nil { c.String(http.StatusBadRequest, "bad request") return } err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename) if err != nil { c.String(http.StatusInternalServerError, "unknown error") return } // db.Save(&form) c.String(http.StatusOK, "ok") }) router.Run(":8080") } ``` Test it with: ```sh curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile ``` ### XML, JSON, YAML and ProtoBuf rendering ```go func main() { r := gin.Default() // gin.H is a shortcut for map[string]interface{} r.GET("/someJSON", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/moreJSON", func(c *gin.Context) { // You also can use a struct var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // Note that msg.Name becomes "user" in the JSON // Will output : {"user": "Lena", "Message": "hey", "Number": 123} c.JSON(http.StatusOK, msg) }) r.GET("/someXML", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // The specific definition of protobuf is written in the testdata/protoexample file. data := &protoexample.Test{ Label: &label, Reps: reps, } // Note that data becomes binary data in the response // Will output protoexample.Test protobuf serialized data c.ProtoBuf(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` #### SecureJSON Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values. ```go func main() { r := gin.Default() // You can also use your own secure json prefix // r.SecureJsonPrefix(")]}',\n") r.GET("/someJSON", func(c *gin.Context) { names := []string{"lena", "austin", "foo"} // Will output : while(1);["lena","austin","foo"] c.SecureJSON(http.StatusOK, names) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` #### JSONP Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists. ```go func main() { r := gin.Default() r.GET("/JSONP", func(c *gin.Context) { data := gin.H{ "foo": "bar", } //callback is x // Will output : x({\"foo\":\"bar\"}) c.JSONP(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") // client // curl http://127.0.0.1:8080/JSONP?callback=x } ``` #### AsciiJSON Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters. ```go func main() { r := gin.Default() r.GET("/someJSON", func(c *gin.Context) { data := gin.H{ "lang": "GO语言", "tag": "<br>", } // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"} c.AsciiJSON(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` #### PureJSON Normally, JSON replaces special HTML characters with their unicode entities, e.g. `<` becomes `\u003c`. If you want to encode such characters literally, you can use PureJSON instead. This feature is unavailable in Go 1.6 and lower. ```go func main() { r := gin.Default() // Serves unicode entities r.GET("/json", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "html": "<b>Hello, world!</b>", }) }) // Serves literal characters r.GET("/purejson", func(c *gin.Context) { c.PureJSON(http.StatusOK, gin.H{ "html": "<b>Hello, world!</b>", }) }) // listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Serving static files ```go func main() { router := gin.Default() router.Static("/assets", "./assets") router.StaticFS("/more_static", http.Dir("my_file_system")) router.StaticFile("/favicon.ico", "./resources/favicon.ico") router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system")) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") } ``` ### Serving data from file ```go func main() { router := gin.Default() router.GET("/local/file", func(c *gin.Context) { c.File("local/file.go") }) var fs http.FileSystem = // ... router.GET("/fs/file", func(c *gin.Context) { c.FileFromFS("fs/file.go", fs) }) } ``` ### Serving data from reader ```go func main() { router := gin.Default() router.GET("/someDataFromReader", func(c *gin.Context) { response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png") if err != nil || response.StatusCode != http.StatusOK { c.Status(http.StatusServiceUnavailable) return } reader := response.Body defer reader.Close() contentLength := response.ContentLength contentType := response.Header.Get("Content-Type") extraHeaders := map[string]string{ "Content-Disposition": `attachment; filename="gopher.png"`, } c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders) }) router.Run(":8080") } ``` ### HTML rendering Using LoadHTMLGlob() or LoadHTMLFiles() ```go func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", }) }) router.Run(":8080") } ``` templates/index.tmpl ```html <html> <h1> {{ .title }} </h1> </html> ``` Using templates with same name in different directories ```go func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ "title": "Posts", }) }) router.GET("/users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ "title": "Users", }) }) router.Run(":8080") } ``` templates/posts/index.tmpl ```html {{ define "posts/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using posts/index.tmpl</p> </html> {{ end }} ``` templates/users/index.tmpl ```html {{ define "users/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using users/index.tmpl</p> </html> {{ end }} ``` #### Custom Template renderer You can also use your own html template render ```go import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") } ``` #### Custom Delimiters You may use custom delims ```go r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates") ``` #### Custom Template Funcs See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template). main.go ```go import ( "fmt" "html/template" "net/http" "time" "github.com/gin-gonic/gin" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d/%02d/%02d", year, month, day) } func main() { router := gin.Default() router.Delims("{[{", "}]}") router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) router.LoadHTMLFiles("./testdata/template/raw.tmpl") router.GET("/raw", func(c *gin.Context) { c.HTML(http.StatusOK, "raw.tmpl", gin.H{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) router.Run(":8080") } ``` raw.tmpl ```html Date: {[{.now | formatAsDate}]} ``` Result: ```sh Date: 2017/07/01 ``` ### Multitemplate Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`. ### Redirects Issuing a HTTP redirect is easy. Both internal and external locations are supported. ```go r.GET("/test", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") }) ``` Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444) ```go r.POST("/test", func(c *gin.Context) { c.Redirect(http.StatusFound, "/foo") }) ``` Issuing a Router redirect, use `HandleContext` like below. ``` go r.GET("/test", func(c *gin.Context) { c.Request.URL.Path = "/test2" r.HandleContext(c) }) r.GET("/test2", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"hello": "world"}) }) ``` ### Custom Middleware ```go func Logger() gin.HandlerFunc { return func(c *gin.Context) { t := time.Now() // Set example variable c.Set("example", "12345") // before request c.Next() // after request latency := time.Since(t) log.Print(latency) // access the status we are sending status := c.Writer.Status() log.Println(status) } } func main() { r := gin.New() r.Use(Logger()) r.GET("/test", func(c *gin.Context) { example := c.MustGet("example").(string) // it would print: "12345" log.Println(example) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Using BasicAuth() middleware ```go // simulate some private data var secrets = gin.H{ "foo": gin.H{"email": "[email protected]", "phone": "123433"}, "austin": gin.H{"email": "[email protected]", "phone": "666"}, "lena": gin.H{"email": "[email protected]", "phone": "523443"}, } func main() { r := gin.Default() // Group using gin.BasicAuth() middleware // gin.Accounts is a shortcut for map[string]string authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{ "foo": "bar", "austin": "1234", "lena": "hello2", "manu": "4321", })) // /admin/secrets endpoint // hit "localhost:8080/admin/secrets authorized.GET("/secrets", func(c *gin.Context) { // get user, it was set by the BasicAuth middleware user := c.MustGet(gin.AuthUserKey).(string) if secret, ok := secrets[user]; ok { c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret}) } else { c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("}) } }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Goroutines inside a middleware When starting new Goroutines inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy. ```go func main() { r := gin.Default() r.GET("/long_async", func(c *gin.Context) { // create copy to be used inside the goroutine cCp := c.Copy() go func() { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) // note that you are using the copied context "cCp", IMPORTANT log.Println("Done! in path " + cCp.Request.URL.Path) }() }) r.GET("/long_sync", func(c *gin.Context) { // simulate a long task with time.Sleep(). 5 seconds 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.Request.URL.Path) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` ### Custom HTTP configuration Use `http.ListenAndServe()` directly, like this: ```go func main() { router := gin.Default() http.ListenAndServe(":8080", router) } ``` or ```go func main() { router := gin.Default() s := &http.Server{ Addr: ":8080", Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } s.ListenAndServe() } ``` ### Support Let's Encrypt example for 1-line LetsEncrypt HTTPS servers. ```go package main import ( "log" "net/http" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) log.Fatal(autotls.Run(r, "example1.com", "example2.com")) } ``` example for custom autocert manager. ```go package main import ( "log" "net/http" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" "golang.org/x/crypto/acme/autocert" ) func main() { r := gin.Default() // Ping handler r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) m := autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"), Cache: autocert.DirCache("/var/www/.cache"), } log.Fatal(autotls.RunWithManager(r, &m)) } ``` ### Run multiple service using Gin See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example: ```go package main import ( "log" "net/http" "time" "github.com/gin-gonic/gin" "golang.org/x/sync/errgroup" ) var ( g errgroup.Group ) func router01() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 01", }, ) }) return e } func router02() http.Handler { e := gin.New() e.Use(gin.Recovery()) e.GET("/", func(c *gin.Context) { c.JSON( http.StatusOK, gin.H{ "code": http.StatusOK, "error": "Welcome server 02", }, ) }) return e } func main() { server01 := &http.Server{ Addr: ":8080", Handler: router01(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } server02 := &http.Server{ Addr: ":8081", Handler: router02(), ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } g.Go(func() error { err := server01.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) g.Go(func() error { err := server02.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatal(err) } return err }) if err := g.Wait(); err != nil { log.Fatal(err) } } ``` ### Graceful shutdown or restart There are a few approaches you can use to perform a graceful shutdown or restart. You can make use of third-party packages specifically built for that, or you can manually do the same with the functions and methods from the built-in packages. #### Third-party packages We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer to issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details. ```go router := gin.Default() router.GET("/", handler) // [...] endless.ListenAndServe(":4242", router) ``` Alternatives: * [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers. * [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server. * [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. #### Manually In case you are using Go 1.8 or a later version, you may not need to use those libraries. Consider using `http.Server`'s built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. The example below describes its usage, and we've got more examples using gin [here](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown). ```go // +build go1.8 package main import ( "context" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { time.Sleep(5 * time.Second) c.String(http.StatusOK, "Welcome Gin Server") }) srv := &http.Server{ Addr: ":8080", Handler: router, } // Initializing the server in a goroutine so that // it won't block the graceful shutdown handling below go func() { if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) { log.Printf("listen: %s\n", err) } }() // Wait for interrupt signal to gracefully shutdown the server with // a timeout of 5 seconds. quit := make(chan os.Signal) // kill (no param) default send syscall.SIGTERM // kill -2 is syscall.SIGINT // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("Shutting down server...") // The context is used to inform the server it has 5 seconds to finish // the request it is currently handling ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server forced to shutdown:", err) } log.Println("Server exiting") } ``` ### Build a single binary with templates You can build a server into a single binary containing templates by using [go-assets][]. [go-assets]: https://github.com/jessevdk/go-assets ```go func main() { r := gin.New() t, err := loadTemplate() if err != nil { panic(err) } r.SetHTMLTemplate(t) r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "/html/index.tmpl",nil) }) r.Run(":8080") } // loadTemplate loads templates embedded by go-assets-builder func loadTemplate() (*template.Template, error) { t := template.New("") for name, file := range Assets.Files { defer file.Close() if file.IsDir() || !strings.HasSuffix(name, ".tmpl") { continue } h, err := ioutil.ReadAll(file) if err != nil { return nil, err } t, err = t.New(name).Parse(string(h)) if err != nil { return nil, err } } return t, nil } ``` See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary` directory. ### Bind form-data request with custom struct The follow example using custom struct: ```go type StructA struct { FieldA string `form:"field_a"` } type StructB struct { NestedStruct StructA FieldB string `form:"field_b"` } type StructC struct { NestedStructPointer *StructA FieldC string `form:"field_c"` } type StructD struct { NestedAnonyStruct struct { FieldX string `form:"field_x"` } FieldD string `form:"field_d"` } func GetDataB(c *gin.Context) { var b StructB c.Bind(&b) c.JSON(http.StatusOK, gin.H{ "a": b.NestedStruct, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(http.StatusOK, gin.H{ "a": b.NestedStructPointer, "c": b.FieldC, }) } func GetDataD(c *gin.Context) { var b StructD c.Bind(&b) c.JSON(http.StatusOK, gin.H{ "x": b.NestedAnonyStruct, "d": b.FieldD, }) } func main() { r := gin.Default() r.GET("/getb", GetDataB) r.GET("/getc", GetDataC) r.GET("/getd", GetDataD) r.Run() } ``` Using the command `curl` command result: ```sh $ curl "http://localhost:8080/getb?field_a=hello&field_b=world" {"a":{"FieldA":"hello"},"b":"world"} $ curl "http://localhost:8080/getc?field_a=hello&field_c=world" {"a":{"FieldA":"hello"},"c":"world"} $ curl "http://localhost:8080/getd?field_x=hello&field_d=world" {"d":"world","x":{"FieldX":"hello"}} ``` ### Try to bind body into different structs The normal methods for binding request body consumes `c.Request.Body` and they cannot be called multiple times. ```go type formA struct { Foo string `json:"foo" xml:"foo" binding:"required"` } type formB struct { Bar string `json:"bar" xml:"bar" binding:"required"` } func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} // This c.ShouldBind consumes c.Request.Body and it cannot be reused. if errA := c.ShouldBind(&objA); errA == nil { c.String(http.StatusOK, `the body should be formA`) // Always an error is occurred by this because c.Request.Body is EOF now. } else if errB := c.ShouldBind(&objB); errB == nil { c.String(http.StatusOK, `the body should be formB`) } else { ... } } ``` For this, you can use `c.ShouldBindBodyWith`. ```go func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} // This reads c.Request.Body and stores the result into the context. if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil { c.String(http.StatusOK, `the body should be formA`) // At this time, it reuses body stored in the context. } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { c.String(http.StatusOK, `the body should be formB JSON`) // And it can accepts other formats } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil { c.String(http.StatusOK, `the body should be formB XML`) } else { ... } } ``` 1. `c.ShouldBindBodyWith` stores body into the context before binding. This has a slight impact to performance, so you should not use this method if you are enough to call binding at once. 2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`, `ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`, can be called by `c.ShouldBind()` multiple times without any damage to performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)). ### Bind form-data request with custom struct and custom tag ```go const ( customerTag = "url" defaultMemory = 32 << 20 ) type customerBinding struct {} func (customerBinding) Name() string { return "form" } func (customerBinding) Bind(req *http.Request, obj interface{}) error { if err := req.ParseForm(); err != nil { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil { if err != http.ErrNotMultipart { return err } } if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil { return err } return validate(obj) } func validate(obj interface{}) error { if binding.Validator == nil { return nil } return binding.Validator.ValidateStruct(obj) } // Now we can do this!!! // FormA is a external type that we can't modify it's tag type FormA struct { FieldA string `url:"field_a"` } func ListHandler(s *Service) func(ctx *gin.Context) { return func(ctx *gin.Context) { var urlBinding = customerBinding{} var opt FormA err := ctx.MustBindWith(&opt, urlBinding) if err != nil { ... } ... } } ``` ### http2 server push http.Pusher is supported only **go1.8+**. See the [golang blog](https://blog.golang.org/h2push) for detail information. ```go package main import ( "html/template" "log" "net/http" "github.com/gin-gonic/gin" ) var html = template.Must(template.New("https").Parse(` <html> <head> <title>Https Test</title> <script src="/assets/app.js"></script> </head> <body> <h1 style="color:red;">Welcome, Ginner!</h1> </body> </html> `)) func main() { r := gin.Default() r.Static("/assets", "./assets") r.SetHTMLTemplate(html) r.GET("/", func(c *gin.Context) { if pusher := c.Writer.Pusher(); pusher != nil { // use pusher.Push() to do server push if err := pusher.Push("/assets/app.js", nil); err != nil { log.Printf("Failed to push: %v", err) } } c.HTML(http.StatusOK, "https", gin.H{ "status": "success", }) }) // Listen and Server in https://127.0.0.1:8080 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key") } ``` ### Define format for the log of routes The default log of routes is: ```sh [GIN-debug] POST /foo --> main.main.func1 (3 handlers) [GIN-debug] GET /bar --> main.main.func2 (3 handlers) [GIN-debug] GET /status --> main.main.func3 (3 handlers) ``` If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`. In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs. ```go import ( "log" "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers) } r.POST("/foo", func(c *gin.Context) { c.JSON(http.StatusOK, "foo") }) r.GET("/bar", func(c *gin.Context) { c.JSON(http.StatusOK, "bar") }) r.GET("/status", func(c *gin.Context) { c.JSON(http.StatusOK, "ok") }) // Listen and Server in http://0.0.0.0:8080 r.Run() } ``` ### Set and get a cookie ```go import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/cookie", func(c *gin.Context) { cookie, err := c.Cookie("gin_cookie") if err != nil { cookie = "NotSet" c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) } fmt.Printf("Cookie value: %s \n", cookie) }) router.Run() } ``` ## Don't trust all proxies Gin lets you specify which headers to hold the real client IP (if any), as well as specifying which proxies (or direct clients) you trust to specify one of these headers. Use function `SetTrustedProxies()` on your `gin.Engine` to specify network addresses or network CIDRs from where clients which their request headers related to client IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs. **Attention:** Gin trust all proxies by default if you don't specify a trusted proxy using the function above, **this is NOT safe**. At the same time, if you don't use any proxy, you can disable this feature by using `Engine.SetTrustedProxies(nil)`, then `Context.ClientIP()` will return the remote address directly to avoid some unnecessary computation. ```go import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.SetTrustedProxies([]string{"192.168.1.2"}) router.GET("/", func(c *gin.Context) { // If the client is 192.168.1.2, use the X-Forwarded-For // header to deduce the original client IP from the trust- // worthy parts of that header. // Otherwise, simply return the direct client IP fmt.Printf("ClientIP: %s\n", c.ClientIP()) }) router.Run() } ``` **Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform` to skip TrustedProxies check, it has a higher priority than TrustedProxies. Look at the example below: ```go import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() // Use predefined header gin.PlatformXXX router.TrustedPlatform = gin.PlatformGoogleAppEngine // Or set your own trusted request header for another trusted proxy service // Don't set it to any suspect request header, it's unsafe router.TrustedPlatform = "X-CDN-IP" router.GET("/", func(c *gin.Context) { // If you set TrustedPlatform, ClientIP() will resolve the // corresponding header and return IP directly fmt.Printf("ClientIP: %s\n", c.ClientIP()) }) router.Run() } ``` ## Testing The `net/http/httptest` package is preferable way for HTTP testing. ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func setupRouter() *gin.Engine { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") }) return r } func main() { r := setupRouter() r.Run(":8080") } ``` Test for code example above: ```go package main import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestPingRoute(t *testing.T) { router := setupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/ping", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "pong", w.Body.String()) } ``` ## Users Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework. * [gorush](https://github.com/appleboy/gorush): A push notification server written in Go. * [fnproject](https://github.com/fnproject/fn): The container native, cloud agnostic serverless platform. * [photoprism](https://github.com/photoprism/photoprism): Personal photo management powered by Go and Google TensorFlow. * [krakend](https://github.com/devopsfaith/krakend): Ultra performant API Gateway with middlewares. * [picfit](https://github.com/thoas/picfit): An image resizing server written in Go. * [brigade](https://github.com/brigadecore/brigade): Event-based Scripting for Kubernetes. * [dkron](https://github.com/distribworks/dkron): Distributed, fault tolerant job scheduling system.
1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./debug.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "runtime" "strconv" "strings" ) const ginSupportMinGoVer = 15 // IsDebugging returns true if the framework is running in debug mode. // Use SetMode(gin.ReleaseMode) to disable debug mode. func IsDebugging() bool { return ginMode == debugCode } // DebugPrintRouteFunc indicates debug log output format. var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int) func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) handlerName := nameOfFunction(handlers.Last()) if DebugPrintRouteFunc == nil { debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } else { DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) } } } func debugPrintLoadTemplate(tmpl *template.Template) { if IsDebugging() { var buf strings.Builder for _, tmpl := range tmpl.Templates() { buf.WriteString("\t- ") buf.WriteString(tmpl.Name()) buf.WriteString("\n") } debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) } } func debugPrint(format string, values ...any) { if IsDebugging() { if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) } } func getMinVer(v string) (uint64, error) { first := strings.IndexByte(v, '.') last := strings.LastIndexByte(v, '.') if first == last { return strconv.ParseUint(v[first+1:], 10, 64) } return strconv.ParseUint(v[first+1:last], 10, 64) } func debugPrintWARNINGDefault() { if v, e := getMinVer(runtime.Version()); e == nil && v < ginSupportMinGoVer { debugPrint(`[WARNING] Now Gin requires Go 1.15+. `) } debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. `) } func debugPrintWARNINGNew() { debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) `) } func debugPrintWARNINGSetHTMLTemplate() { debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization. ie. before any route is registered or the router is listening in a socket: router := gin.Default() router.SetHTMLTemplate(template) // << good place `) } func debugPrintError(err error) { if err != nil && IsDebugging() { fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) } }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "runtime" "strconv" "strings" ) const ginSupportMinGoVer = 16 // IsDebugging returns true if the framework is running in debug mode. // Use SetMode(gin.ReleaseMode) to disable debug mode. func IsDebugging() bool { return ginMode == debugCode } // DebugPrintRouteFunc indicates debug log output format. var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int) func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) handlerName := nameOfFunction(handlers.Last()) if DebugPrintRouteFunc == nil { debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } else { DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) } } } func debugPrintLoadTemplate(tmpl *template.Template) { if IsDebugging() { var buf strings.Builder for _, tmpl := range tmpl.Templates() { buf.WriteString("\t- ") buf.WriteString(tmpl.Name()) buf.WriteString("\n") } debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) } } func debugPrint(format string, values ...any) { if IsDebugging() { if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) } } func getMinVer(v string) (uint64, error) { first := strings.IndexByte(v, '.') last := strings.LastIndexByte(v, '.') if first == last { return strconv.ParseUint(v[first+1:], 10, 64) } return strconv.ParseUint(v[first+1:last], 10, 64) } func debugPrintWARNINGDefault() { if v, e := getMinVer(runtime.Version()); e == nil && v < ginSupportMinGoVer { debugPrint(`[WARNING] Now Gin requires Go 1.16+. `) } debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. `) } func debugPrintWARNINGNew() { debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) `) } func debugPrintWARNINGSetHTMLTemplate() { debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization. ie. before any route is registered or the router is listening in a socket: router := gin.Default() router.SetHTMLTemplate(template) // << good place `) } func debugPrintError(err error) { if err != nil && IsDebugging() { fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) } }
1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./debug_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "html/template" "io" "log" "os" "runtime" "sync" "testing" "github.com/stretchr/testify/assert" ) // TODO // func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) { // func debugPrint(format string, values ...interface{}) { func TestIsDebugging(t *testing.T) { SetMode(DebugMode) assert.True(t, IsDebugging()) SetMode(ReleaseMode) assert.False(t, IsDebugging()) SetMode(TestMode) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) debugPrint("DEBUG this!") SetMode(DebugMode) debugPrint("these are %d %s", 2, "error messages") SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] these are 2 error messages\n", re) } func TestDebugPrintError(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintError(nil) debugPrintError(errors.New("this is an error")) SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [ERROR] this is an error\n", re) } func TestDebugPrintRoutes(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintRouteFunc(t *testing.T) { DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintLoadTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl")) debugPrintLoadTemplate(templ) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] Loaded HTML Templates \(2\): \n(\t- \n|\t- hello\.tmpl\n){2}\n`, re) } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGSetHTMLTemplate() SetMode(TestMode) }) 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", re) } func TestDebugPrintWARNINGDefault(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) m, e := getMinVer(runtime.Version()) if e == nil && m < ginSupportMinGoVer { assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.15+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } else { assert.Equal(t, "[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } } func TestDebugPrintWARNINGNew(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGNew() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n", re) } func captureOutput(t *testing.T, f func()) string { reader, writer, err := os.Pipe() if err != nil { panic(err) } defaultWriter := DefaultWriter defaultErrorWriter := DefaultErrorWriter defer func() { DefaultWriter = defaultWriter DefaultErrorWriter = defaultErrorWriter log.SetOutput(os.Stderr) }() DefaultWriter = writer DefaultErrorWriter = writer log.SetOutput(writer) out := make(chan string) wg := new(sync.WaitGroup) wg.Add(1) go func() { var buf bytes.Buffer wg.Done() _, err := io.Copy(&buf, reader) assert.NoError(t, err) out <- buf.String() }() wg.Wait() f() writer.Close() return <-out } func TestGetMinVer(t *testing.T) { var m uint64 var e error _, e = getMinVer("go1") assert.NotNil(t, e) m, e = getMinVer("go1.1") assert.Equal(t, uint64(1), m) assert.Nil(t, e) m, e = getMinVer("go1.1.1") assert.Nil(t, e) assert.Equal(t, uint64(1), m) _, e = getMinVer("go1.1.1.1") assert.NotNil(t, e) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "html/template" "io" "log" "os" "runtime" "sync" "testing" "github.com/stretchr/testify/assert" ) // TODO // func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) { // func debugPrint(format string, values ...interface{}) { func TestIsDebugging(t *testing.T) { SetMode(DebugMode) assert.True(t, IsDebugging()) SetMode(ReleaseMode) assert.False(t, IsDebugging()) SetMode(TestMode) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) debugPrint("DEBUG this!") SetMode(DebugMode) debugPrint("these are %d %s", 2, "error messages") SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] these are 2 error messages\n", re) } func TestDebugPrintError(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintError(nil) debugPrintError(errors.New("this is an error")) SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [ERROR] this is an error\n", re) } func TestDebugPrintRoutes(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintRouteFunc(t *testing.T) { DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintLoadTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl")) debugPrintLoadTemplate(templ) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] Loaded HTML Templates \(2\): \n(\t- \n|\t- hello\.tmpl\n){2}\n`, re) } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGSetHTMLTemplate() SetMode(TestMode) }) 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", re) } func TestDebugPrintWARNINGDefault(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) m, e := getMinVer(runtime.Version()) if e == nil && m < ginSupportMinGoVer { assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.16+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } else { assert.Equal(t, "[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } } func TestDebugPrintWARNINGNew(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGNew() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n", re) } func captureOutput(t *testing.T, f func()) string { reader, writer, err := os.Pipe() if err != nil { panic(err) } defaultWriter := DefaultWriter defaultErrorWriter := DefaultErrorWriter defer func() { DefaultWriter = defaultWriter DefaultErrorWriter = defaultErrorWriter log.SetOutput(os.Stderr) }() DefaultWriter = writer DefaultErrorWriter = writer log.SetOutput(writer) out := make(chan string) wg := new(sync.WaitGroup) wg.Add(1) go func() { var buf bytes.Buffer wg.Done() _, err := io.Copy(&buf, reader) assert.NoError(t, err) out <- buf.String() }() wg.Wait() f() writer.Close() return <-out } func TestGetMinVer(t *testing.T) { var m uint64 var e error _, e = getMinVer("go1") assert.NotNil(t, e) m, e = getMinVer("go1.1") assert.Equal(t, uint64(1), m) assert.Nil(t, e) m, e = getMinVer("go1.1.1") assert.Nil(t, e) assert.Equal(t, uint64(1), m) _, e = getMinVer("go1.1.1.1") assert.NotNil(t, e) }
1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/form_mapping_test.go
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "reflect" "testing" "time" "github.com/stretchr/testify/assert" ) func TestMappingBaseTypes(t *testing.T) { intPtr := func(i int) *int { return &i } for _, tt := range []struct { name string value any form string expect any }{ {"base type", struct{ F int }{}, "9", int(9)}, {"base type", struct{ F int8 }{}, "9", int8(9)}, {"base type", struct{ F int16 }{}, "9", int16(9)}, {"base type", struct{ F int32 }{}, "9", int32(9)}, {"base type", struct{ F int64 }{}, "9", int64(9)}, {"base type", struct{ F uint }{}, "9", uint(9)}, {"base type", struct{ F uint8 }{}, "9", uint8(9)}, {"base type", struct{ F uint16 }{}, "9", uint16(9)}, {"base type", struct{ F uint32 }{}, "9", uint32(9)}, {"base type", struct{ F uint64 }{}, "9", uint64(9)}, {"base type", struct{ F bool }{}, "True", true}, {"base type", struct{ F float32 }{}, "9.1", float32(9.1)}, {"base type", struct{ F float64 }{}, "9.1", float64(9.1)}, {"base type", struct{ F string }{}, "test", string("test")}, {"base type", struct{ F *int }{}, "9", intPtr(9)}, // zero values {"zero value", struct{ F int }{}, "", int(0)}, {"zero value", struct{ F uint }{}, "", uint(0)}, {"zero value", struct{ F bool }{}, "", false}, {"zero value", struct{ F float32 }{}, "", float32(0)}, } { tp := reflect.TypeOf(tt.value) testName := tt.name + ":" + tp.Field(0).Type.String() val := reflect.New(reflect.TypeOf(tt.value)) val.Elem().Set(reflect.ValueOf(tt.value)) field := val.Elem().Type().Field(0) _, err := mapping(val, emptyField, formSource{field.Name: {tt.form}}, "form") assert.NoError(t, err, testName) actual := val.Elem().Field(0).Interface() assert.Equal(t, tt.expect, actual, testName) } } func TestMappingDefault(t *testing.T) { var s struct { Int int `form:",default=9"` Slice []int `form:",default=9"` Array [1]int `form:",default=9"` } err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.Int) assert.Equal(t, []int{9}, s.Slice) assert.Equal(t, [1]int{9}, s.Array) } func TestMappingSkipField(t *testing.T) { var s struct { A int } err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) assert.Equal(t, 0, s.A) } func TestMappingIgnoreField(t *testing.T) { var s struct { A int `form:"A"` B int `form:"-"` } err := mappingByPtr(&s, formSource{"A": {"9"}, "B": {"9"}}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.A) assert.Equal(t, 0, s.B) } func TestMappingUnexportedField(t *testing.T) { var s struct { A int `form:"a"` b int `form:"b"` } err := mappingByPtr(&s, formSource{"a": {"9"}, "b": {"9"}}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.A) assert.Equal(t, 0, s.b) } func TestMappingPrivateField(t *testing.T) { var s struct { f int `form:"field"` } err := mappingByPtr(&s, formSource{"field": {"6"}}, "form") assert.NoError(t, err) assert.Equal(t, int(0), s.f) } func TestMappingUnknownFieldType(t *testing.T) { var s struct { U uintptr } err := mappingByPtr(&s, formSource{"U": {"unknown"}}, "form") assert.Error(t, err) assert.Equal(t, errUnknownType, err) } func TestMappingURI(t *testing.T) { var s struct { F int `uri:"field"` } err := mapURI(&s, map[string][]string{"field": {"6"}}) assert.NoError(t, err) assert.Equal(t, int(6), s.F) } func TestMappingForm(t *testing.T) { var s struct { F int `form:"field"` } err := mapForm(&s, map[string][]string{"field": {"6"}}) assert.NoError(t, err) assert.Equal(t, int(6), s.F) } func TestMapFormWithTag(t *testing.T) { var s struct { F int `externalTag:"field"` } err := MapFormWithTag(&s, map[string][]string{"field": {"6"}}, "externalTag") assert.NoError(t, err) assert.Equal(t, int(6), s.F) } func TestMappingTime(t *testing.T) { var s struct { Time time.Time LocalTime time.Time `time_format:"2006-01-02"` ZeroValue time.Time CSTTime time.Time `time_format:"2006-01-02" time_location:"Asia/Shanghai"` UTCTime time.Time `time_format:"2006-01-02" time_utc:"1"` } var err error time.Local, err = time.LoadLocation("Europe/Berlin") assert.NoError(t, err) err = mapForm(&s, map[string][]string{ "Time": {"2019-01-20T16:02:58Z"}, "LocalTime": {"2019-01-20"}, "ZeroValue": {}, "CSTTime": {"2019-01-20"}, "UTCTime": {"2019-01-20"}, }) assert.NoError(t, err) assert.Equal(t, "2019-01-20 16:02:58 +0000 UTC", s.Time.String()) assert.Equal(t, "2019-01-20 00:00:00 +0100 CET", s.LocalTime.String()) assert.Equal(t, "2019-01-19 23:00:00 +0000 UTC", s.LocalTime.UTC().String()) assert.Equal(t, "0001-01-01 00:00:00 +0000 UTC", s.ZeroValue.String()) assert.Equal(t, "2019-01-20 00:00:00 +0800 CST", s.CSTTime.String()) assert.Equal(t, "2019-01-19 16:00:00 +0000 UTC", s.CSTTime.UTC().String()) assert.Equal(t, "2019-01-20 00:00:00 +0000 UTC", s.UTCTime.String()) // wrong location var wrongLoc struct { Time time.Time `time_location:"wrong"` } err = mapForm(&wrongLoc, map[string][]string{"Time": {"2019-01-20T16:02:58Z"}}) assert.Error(t, err) // wrong time value var wrongTime struct { Time time.Time } err = mapForm(&wrongTime, map[string][]string{"Time": {"wrong"}}) assert.Error(t, err) } func TestMappingTimeDuration(t *testing.T) { var s struct { D time.Duration } // ok err := mappingByPtr(&s, formSource{"D": {"5s"}}, "form") assert.NoError(t, err) assert.Equal(t, 5*time.Second, s.D) // error err = mappingByPtr(&s, formSource{"D": {"wrong"}}, "form") assert.Error(t, err) } func TestMappingSlice(t *testing.T) { var s struct { Slice []int `form:"slice,default=9"` } // default value err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) assert.Equal(t, []int{9}, s.Slice) // ok err = mappingByPtr(&s, formSource{"slice": {"3", "4"}}, "form") assert.NoError(t, err) assert.Equal(t, []int{3, 4}, s.Slice) // error err = mappingByPtr(&s, formSource{"slice": {"wrong"}}, "form") assert.Error(t, err) } func TestMappingArray(t *testing.T) { var s struct { Array [2]int `form:"array,default=9"` } // wrong default err := mappingByPtr(&s, formSource{}, "form") assert.Error(t, err) // ok err = mappingByPtr(&s, formSource{"array": {"3", "4"}}, "form") assert.NoError(t, err) assert.Equal(t, [2]int{3, 4}, s.Array) // error - not enough vals err = mappingByPtr(&s, formSource{"array": {"3"}}, "form") assert.Error(t, err) // error - wrong value err = mappingByPtr(&s, formSource{"array": {"wrong"}}, "form") assert.Error(t, err) } func TestMappingStructField(t *testing.T) { var s struct { J struct { I int } } err := mappingByPtr(&s, formSource{"J": {`{"I": 9}`}}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.J.I) } func TestMappingMapField(t *testing.T) { var s struct { M map[string]int } err := mappingByPtr(&s, formSource{"M": {`{"one": 1}`}}, "form") assert.NoError(t, err) assert.Equal(t, map[string]int{"one": 1}, s.M) } func TestMappingIgnoredCircularRef(t *testing.T) { type S struct { S *S `form:"-"` } var s S err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) }
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "reflect" "testing" "time" "github.com/stretchr/testify/assert" ) func TestMappingBaseTypes(t *testing.T) { intPtr := func(i int) *int { return &i } for _, tt := range []struct { name string value any form string expect any }{ {"base type", struct{ F int }{}, "9", int(9)}, {"base type", struct{ F int8 }{}, "9", int8(9)}, {"base type", struct{ F int16 }{}, "9", int16(9)}, {"base type", struct{ F int32 }{}, "9", int32(9)}, {"base type", struct{ F int64 }{}, "9", int64(9)}, {"base type", struct{ F uint }{}, "9", uint(9)}, {"base type", struct{ F uint8 }{}, "9", uint8(9)}, {"base type", struct{ F uint16 }{}, "9", uint16(9)}, {"base type", struct{ F uint32 }{}, "9", uint32(9)}, {"base type", struct{ F uint64 }{}, "9", uint64(9)}, {"base type", struct{ F bool }{}, "True", true}, {"base type", struct{ F float32 }{}, "9.1", float32(9.1)}, {"base type", struct{ F float64 }{}, "9.1", float64(9.1)}, {"base type", struct{ F string }{}, "test", string("test")}, {"base type", struct{ F *int }{}, "9", intPtr(9)}, // zero values {"zero value", struct{ F int }{}, "", int(0)}, {"zero value", struct{ F uint }{}, "", uint(0)}, {"zero value", struct{ F bool }{}, "", false}, {"zero value", struct{ F float32 }{}, "", float32(0)}, } { tp := reflect.TypeOf(tt.value) testName := tt.name + ":" + tp.Field(0).Type.String() val := reflect.New(reflect.TypeOf(tt.value)) val.Elem().Set(reflect.ValueOf(tt.value)) field := val.Elem().Type().Field(0) _, err := mapping(val, emptyField, formSource{field.Name: {tt.form}}, "form") assert.NoError(t, err, testName) actual := val.Elem().Field(0).Interface() assert.Equal(t, tt.expect, actual, testName) } } func TestMappingDefault(t *testing.T) { var s struct { Int int `form:",default=9"` Slice []int `form:",default=9"` Array [1]int `form:",default=9"` } err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.Int) assert.Equal(t, []int{9}, s.Slice) assert.Equal(t, [1]int{9}, s.Array) } func TestMappingSkipField(t *testing.T) { var s struct { A int } err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) assert.Equal(t, 0, s.A) } func TestMappingIgnoreField(t *testing.T) { var s struct { A int `form:"A"` B int `form:"-"` } err := mappingByPtr(&s, formSource{"A": {"9"}, "B": {"9"}}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.A) assert.Equal(t, 0, s.B) } func TestMappingUnexportedField(t *testing.T) { var s struct { A int `form:"a"` b int `form:"b"` } err := mappingByPtr(&s, formSource{"a": {"9"}, "b": {"9"}}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.A) assert.Equal(t, 0, s.b) } func TestMappingPrivateField(t *testing.T) { var s struct { f int `form:"field"` } err := mappingByPtr(&s, formSource{"field": {"6"}}, "form") assert.NoError(t, err) assert.Equal(t, int(0), s.f) } func TestMappingUnknownFieldType(t *testing.T) { var s struct { U uintptr } err := mappingByPtr(&s, formSource{"U": {"unknown"}}, "form") assert.Error(t, err) assert.Equal(t, errUnknownType, err) } func TestMappingURI(t *testing.T) { var s struct { F int `uri:"field"` } err := mapURI(&s, map[string][]string{"field": {"6"}}) assert.NoError(t, err) assert.Equal(t, int(6), s.F) } func TestMappingForm(t *testing.T) { var s struct { F int `form:"field"` } err := mapForm(&s, map[string][]string{"field": {"6"}}) assert.NoError(t, err) assert.Equal(t, int(6), s.F) } func TestMapFormWithTag(t *testing.T) { var s struct { F int `externalTag:"field"` } err := MapFormWithTag(&s, map[string][]string{"field": {"6"}}, "externalTag") assert.NoError(t, err) assert.Equal(t, int(6), s.F) } func TestMappingTime(t *testing.T) { var s struct { Time time.Time LocalTime time.Time `time_format:"2006-01-02"` ZeroValue time.Time CSTTime time.Time `time_format:"2006-01-02" time_location:"Asia/Shanghai"` UTCTime time.Time `time_format:"2006-01-02" time_utc:"1"` } var err error time.Local, err = time.LoadLocation("Europe/Berlin") assert.NoError(t, err) err = mapForm(&s, map[string][]string{ "Time": {"2019-01-20T16:02:58Z"}, "LocalTime": {"2019-01-20"}, "ZeroValue": {}, "CSTTime": {"2019-01-20"}, "UTCTime": {"2019-01-20"}, }) assert.NoError(t, err) assert.Equal(t, "2019-01-20 16:02:58 +0000 UTC", s.Time.String()) assert.Equal(t, "2019-01-20 00:00:00 +0100 CET", s.LocalTime.String()) assert.Equal(t, "2019-01-19 23:00:00 +0000 UTC", s.LocalTime.UTC().String()) assert.Equal(t, "0001-01-01 00:00:00 +0000 UTC", s.ZeroValue.String()) assert.Equal(t, "2019-01-20 00:00:00 +0800 CST", s.CSTTime.String()) assert.Equal(t, "2019-01-19 16:00:00 +0000 UTC", s.CSTTime.UTC().String()) assert.Equal(t, "2019-01-20 00:00:00 +0000 UTC", s.UTCTime.String()) // wrong location var wrongLoc struct { Time time.Time `time_location:"wrong"` } err = mapForm(&wrongLoc, map[string][]string{"Time": {"2019-01-20T16:02:58Z"}}) assert.Error(t, err) // wrong time value var wrongTime struct { Time time.Time } err = mapForm(&wrongTime, map[string][]string{"Time": {"wrong"}}) assert.Error(t, err) } func TestMappingTimeDuration(t *testing.T) { var s struct { D time.Duration } // ok err := mappingByPtr(&s, formSource{"D": {"5s"}}, "form") assert.NoError(t, err) assert.Equal(t, 5*time.Second, s.D) // error err = mappingByPtr(&s, formSource{"D": {"wrong"}}, "form") assert.Error(t, err) } func TestMappingSlice(t *testing.T) { var s struct { Slice []int `form:"slice,default=9"` } // default value err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) assert.Equal(t, []int{9}, s.Slice) // ok err = mappingByPtr(&s, formSource{"slice": {"3", "4"}}, "form") assert.NoError(t, err) assert.Equal(t, []int{3, 4}, s.Slice) // error err = mappingByPtr(&s, formSource{"slice": {"wrong"}}, "form") assert.Error(t, err) } func TestMappingArray(t *testing.T) { var s struct { Array [2]int `form:"array,default=9"` } // wrong default err := mappingByPtr(&s, formSource{}, "form") assert.Error(t, err) // ok err = mappingByPtr(&s, formSource{"array": {"3", "4"}}, "form") assert.NoError(t, err) assert.Equal(t, [2]int{3, 4}, s.Array) // error - not enough vals err = mappingByPtr(&s, formSource{"array": {"3"}}, "form") assert.Error(t, err) // error - wrong value err = mappingByPtr(&s, formSource{"array": {"wrong"}}, "form") assert.Error(t, err) } func TestMappingStructField(t *testing.T) { var s struct { J struct { I int } } err := mappingByPtr(&s, formSource{"J": {`{"I": 9}`}}, "form") assert.NoError(t, err) assert.Equal(t, 9, s.J.I) } func TestMappingMapField(t *testing.T) { var s struct { M map[string]int } err := mappingByPtr(&s, formSource{"M": {`{"one": 1}`}}, "form") assert.NoError(t, err) assert.Equal(t, map[string]int{"one": 1}, s.M) } func TestMappingIgnoredCircularRef(t *testing.T) { type S struct { S *S `form:"-"` } var s S err := mappingByPtr(&s, formSource{}, "form") assert.NoError(t, err) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./render/render_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "encoding/xml" "errors" "html/template" "net/http" "net/http/httptest" "strconv" "strings" "testing" testdata "github.com/gin-gonic/gin/testdata/protoexample" "github.com/stretchr/testify/assert" "google.golang.org/protobuf/proto" ) // TODO unit tests // test errors func TestRenderJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "html": "<b>", } (JSON{data}).WriteContentType(w) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) err := (JSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderJSONPanics(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int assert.Panics(t, func() { assert.NoError(t, (JSON{data}).Render(w)) }) } func TestRenderIndentedJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "bar": "foo", } err := (IndentedJSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderIndentedJSONPanics(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (IndentedJSON{data}).Render(w) assert.Error(t, err) } func TestRenderSecureJSON(t *testing.T) { w1 := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (SecureJSON{"while(1);", data}).WriteContentType(w1) assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type")) err1 := (SecureJSON{"while(1);", data}).Render(w1) assert.NoError(t, err1) assert.Equal(t, "{\"foo\":\"bar\"}", w1.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() datas := []map[string]any{{ "foo": "bar", }, { "bar": "foo", }} err2 := (SecureJSON{"while(1);", datas}).Render(w2) assert.NoError(t, err2) assert.Equal(t, "while(1);[{\"foo\":\"bar\"},{\"bar\":\"foo\"}]", w2.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("Content-Type")) } func TestRenderSecureJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (SecureJSON{"while(1);", data}).Render(w) assert.Error(t, err) } func TestRenderJsonpJSON(t *testing.T) { w1 := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (JsonpJSON{"x", data}).WriteContentType(w1) assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type")) err1 := (JsonpJSON{"x", data}).Render(w1) assert.NoError(t, err1) assert.Equal(t, "x({\"foo\":\"bar\"});", w1.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() datas := []map[string]any{{ "foo": "bar", }, { "bar": "foo", }} err2 := (JsonpJSON{"x", datas}).Render(w2) assert.NoError(t, err2) assert.Equal(t, "x([{\"foo\":\"bar\"},{\"bar\":\"foo\"}]);", w2.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w2.Header().Get("Content-Type")) } func TestRenderJsonpJSONError2(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (JsonpJSON{"", data}).WriteContentType(w) assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type")) e := (JsonpJSON{"", data}).Render(w) assert.NoError(t, e) assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderJsonpJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (JsonpJSON{"x", data}).Render(w) assert.Error(t, err) } func TestRenderAsciiJSON(t *testing.T) { w1 := httptest.NewRecorder() data1 := map[string]any{ "lang": "GO语言", "tag": "<br>", } err := (AsciiJSON{data1}).Render(w1) assert.NoError(t, err) assert.Equal(t, "{\"lang\":\"GO\\u8bed\\u8a00\",\"tag\":\"\\u003cbr\\u003e\"}", w1.Body.String()) assert.Equal(t, "application/json", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() data2 := float64(3.1415926) err = (AsciiJSON{data2}).Render(w2) assert.NoError(t, err) assert.Equal(t, "3.1415926", w2.Body.String()) } func TestRenderAsciiJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int assert.Error(t, (AsciiJSON{data}).Render(w)) } func TestRenderPureJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "html": "<b>", } err := (PureJSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } type xmlmap map[string]any // Allows type H to be used with xml.Marshal func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } return e.EncodeToken(xml.EndElement{Name: start.Name}) } func TestRenderYAML(t *testing.T) { w := httptest.NewRecorder() data := ` a : Easy! b: c: 2 d: [3, 4] ` (YAML{data}).WriteContentType(w) assert.Equal(t, "application/x-yaml; charset=utf-8", w.Header().Get("Content-Type")) err := (YAML{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "\"\\na : Easy!\\nb:\\n\\tc: 2\\n\\td: [3, 4]\\n\\t\"\n", w.Body.String()) assert.Equal(t, "application/x-yaml; charset=utf-8", w.Header().Get("Content-Type")) } type fail struct{} // Hook MarshalYAML func (ft *fail) MarshalYAML() (any, error) { return nil, errors.New("fail") } func TestRenderYAMLFail(t *testing.T) { w := httptest.NewRecorder() err := (YAML{&fail{}}).Render(w) assert.Error(t, err) } // test Protobuf rendering func TestRenderProtoBuf(t *testing.T) { w := httptest.NewRecorder() reps := []int64{int64(1), int64(2)} label := "test" data := &testdata.Test{ Label: &label, Reps: reps, } (ProtoBuf{data}).WriteContentType(w) protoData, err := proto.Marshal(data) assert.NoError(t, err) assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type")) err = (ProtoBuf{data}).Render(w) assert.NoError(t, err) assert.Equal(t, string(protoData), w.Body.String()) assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type")) } func TestRenderProtoBufFail(t *testing.T) { w := httptest.NewRecorder() data := &testdata.Test{} err := (ProtoBuf{data}).Render(w) assert.Error(t, err) } func TestRenderXML(t *testing.T) { w := httptest.NewRecorder() data := xmlmap{ "foo": "bar", } (XML{data}).WriteContentType(w) assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) err := (XML{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String()) assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderRedirect(t *testing.T) { req, err := http.NewRequest("GET", "/test-redirect", nil) assert.NoError(t, err) data1 := Redirect{ Code: http.StatusMovedPermanently, Request: req, Location: "/new/location", } w := httptest.NewRecorder() err = data1.Render(w) assert.NoError(t, err) data2 := Redirect{ Code: http.StatusOK, Request: req, Location: "/new/location", } w = httptest.NewRecorder() assert.PanicsWithValue(t, "Cannot redirect with status code 200", func() { err := data2.Render(w) assert.NoError(t, err) }) data3 := Redirect{ Code: http.StatusCreated, Request: req, Location: "/new/location", } w = httptest.NewRecorder() err = data3.Render(w) assert.NoError(t, err) // only improve coverage data2.WriteContentType(w) } func TestRenderData(t *testing.T) { w := httptest.NewRecorder() data := []byte("#!PNG some raw data") err := (Data{ ContentType: "image/png", Data: data, }).Render(w) assert.NoError(t, err) assert.Equal(t, "#!PNG some raw data", w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) } func TestRenderString(t *testing.T) { w := httptest.NewRecorder() (String{ Format: "hello %s %d", Data: []any{}, }).WriteContentType(w) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) err := (String{ Format: "hola %s %d", Data: []any{"manu", 2}, }).Render(w) assert.NoError(t, err) assert.Equal(t, "hola manu 2", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderStringLenZero(t *testing.T) { w := httptest.NewRecorder() err := (String{ Format: "hola %s %d", Data: []any{}, }).Render(w) assert.NoError(t, err) assert.Equal(t, "hola %s %d", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLTemplate(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("t").Parse(`Hello {{.name}}`)) htmlRender := HTMLProduction{Template: templ} instance := htmlRender.Instance("t", map[string]any{ "name": "alexandernyquist", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "Hello alexandernyquist", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLTemplateEmptyName(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("").Parse(`Hello {{.name}}`)) htmlRender := HTMLProduction{Template: templ} instance := htmlRender.Instance("", map[string]any{ "name": "alexandernyquist", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "Hello alexandernyquist", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugFiles(t *testing.T) { w := httptest.NewRecorder() htmlRender := HTMLDebug{ Files: []string{"../testdata/template/hello.tmpl"}, Glob: "", Delims: Delims{Left: "{[{", Right: "}]}"}, FuncMap: nil, } instance := htmlRender.Instance("hello.tmpl", map[string]any{ "name": "thinkerou", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugGlob(t *testing.T) { w := httptest.NewRecorder() htmlRender := HTMLDebug{ Files: nil, Glob: "../testdata/template/hello*", Delims: Delims{Left: "{[{", Right: "}]}"}, FuncMap: nil, } instance := htmlRender.Instance("hello.tmpl", map[string]any{ "name": "thinkerou", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugPanics(t *testing.T) { htmlRender := HTMLDebug{ Files: nil, Glob: "", Delims: Delims{"{{", "}}"}, FuncMap: nil, } assert.Panics(t, func() { htmlRender.Instance("", nil) }) } func TestRenderReader(t *testing.T) { w := httptest.NewRecorder() body := "#!PNG some raw data" headers := make(map[string]string) headers["Content-Disposition"] = `attachment; filename="filename.png"` headers["x-request-id"] = "requestId" err := (Reader{ ContentLength: int64(len(body)), ContentType: "image/png", Reader: strings.NewReader(body), Headers: headers, }).Render(w) assert.NoError(t, err) assert.Equal(t, body, w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) assert.Equal(t, strconv.Itoa(len(body)), w.Header().Get("Content-Length")) assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition")) assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id")) } func TestRenderReaderNoContentLength(t *testing.T) { w := httptest.NewRecorder() body := "#!PNG some raw data" headers := make(map[string]string) headers["Content-Disposition"] = `attachment; filename="filename.png"` headers["x-request-id"] = "requestId" err := (Reader{ ContentLength: -1, ContentType: "image/png", Reader: strings.NewReader(body), Headers: headers, }).Render(w) assert.NoError(t, err) assert.Equal(t, body, w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) assert.NotContains(t, "Content-Length", w.Header()) assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition")) assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id")) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "encoding/xml" "errors" "html/template" "net/http" "net/http/httptest" "strconv" "strings" "testing" testdata "github.com/gin-gonic/gin/testdata/protoexample" "github.com/stretchr/testify/assert" "google.golang.org/protobuf/proto" ) // TODO unit tests // test errors func TestRenderJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "html": "<b>", } (JSON{data}).WriteContentType(w) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) err := (JSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderJSONPanics(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int assert.Panics(t, func() { assert.NoError(t, (JSON{data}).Render(w)) }) } func TestRenderIndentedJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "bar": "foo", } err := (IndentedJSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderIndentedJSONPanics(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (IndentedJSON{data}).Render(w) assert.Error(t, err) } func TestRenderSecureJSON(t *testing.T) { w1 := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (SecureJSON{"while(1);", data}).WriteContentType(w1) assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type")) err1 := (SecureJSON{"while(1);", data}).Render(w1) assert.NoError(t, err1) assert.Equal(t, "{\"foo\":\"bar\"}", w1.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() datas := []map[string]any{{ "foo": "bar", }, { "bar": "foo", }} err2 := (SecureJSON{"while(1);", datas}).Render(w2) assert.NoError(t, err2) assert.Equal(t, "while(1);[{\"foo\":\"bar\"},{\"bar\":\"foo\"}]", w2.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("Content-Type")) } func TestRenderSecureJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (SecureJSON{"while(1);", data}).Render(w) assert.Error(t, err) } func TestRenderJsonpJSON(t *testing.T) { w1 := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (JsonpJSON{"x", data}).WriteContentType(w1) assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type")) err1 := (JsonpJSON{"x", data}).Render(w1) assert.NoError(t, err1) assert.Equal(t, "x({\"foo\":\"bar\"});", w1.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() datas := []map[string]any{{ "foo": "bar", }, { "bar": "foo", }} err2 := (JsonpJSON{"x", datas}).Render(w2) assert.NoError(t, err2) assert.Equal(t, "x([{\"foo\":\"bar\"},{\"bar\":\"foo\"}]);", w2.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w2.Header().Get("Content-Type")) } func TestRenderJsonpJSONError2(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (JsonpJSON{"", data}).WriteContentType(w) assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type")) e := (JsonpJSON{"", data}).Render(w) assert.NoError(t, e) assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderJsonpJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (JsonpJSON{"x", data}).Render(w) assert.Error(t, err) } func TestRenderAsciiJSON(t *testing.T) { w1 := httptest.NewRecorder() data1 := map[string]any{ "lang": "GO语言", "tag": "<br>", } err := (AsciiJSON{data1}).Render(w1) assert.NoError(t, err) assert.Equal(t, "{\"lang\":\"GO\\u8bed\\u8a00\",\"tag\":\"\\u003cbr\\u003e\"}", w1.Body.String()) assert.Equal(t, "application/json", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() data2 := float64(3.1415926) err = (AsciiJSON{data2}).Render(w2) assert.NoError(t, err) assert.Equal(t, "3.1415926", w2.Body.String()) } func TestRenderAsciiJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int assert.Error(t, (AsciiJSON{data}).Render(w)) } func TestRenderPureJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "html": "<b>", } err := (PureJSON{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } type xmlmap map[string]any // Allows type H to be used with xml.Marshal func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } return e.EncodeToken(xml.EndElement{Name: start.Name}) } func TestRenderYAML(t *testing.T) { w := httptest.NewRecorder() data := ` a : Easy! b: c: 2 d: [3, 4] ` (YAML{data}).WriteContentType(w) assert.Equal(t, "application/x-yaml; charset=utf-8", w.Header().Get("Content-Type")) err := (YAML{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "\"\\na : Easy!\\nb:\\n\\tc: 2\\n\\td: [3, 4]\\n\\t\"\n", w.Body.String()) assert.Equal(t, "application/x-yaml; charset=utf-8", w.Header().Get("Content-Type")) } type fail struct{} // Hook MarshalYAML func (ft *fail) MarshalYAML() (any, error) { return nil, errors.New("fail") } func TestRenderYAMLFail(t *testing.T) { w := httptest.NewRecorder() err := (YAML{&fail{}}).Render(w) assert.Error(t, err) } // test Protobuf rendering func TestRenderProtoBuf(t *testing.T) { w := httptest.NewRecorder() reps := []int64{int64(1), int64(2)} label := "test" data := &testdata.Test{ Label: &label, Reps: reps, } (ProtoBuf{data}).WriteContentType(w) protoData, err := proto.Marshal(data) assert.NoError(t, err) assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type")) err = (ProtoBuf{data}).Render(w) assert.NoError(t, err) assert.Equal(t, string(protoData), w.Body.String()) assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type")) } func TestRenderProtoBufFail(t *testing.T) { w := httptest.NewRecorder() data := &testdata.Test{} err := (ProtoBuf{data}).Render(w) assert.Error(t, err) } func TestRenderXML(t *testing.T) { w := httptest.NewRecorder() data := xmlmap{ "foo": "bar", } (XML{data}).WriteContentType(w) assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) err := (XML{data}).Render(w) assert.NoError(t, err) assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String()) assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderRedirect(t *testing.T) { req, err := http.NewRequest("GET", "/test-redirect", nil) assert.NoError(t, err) data1 := Redirect{ Code: http.StatusMovedPermanently, Request: req, Location: "/new/location", } w := httptest.NewRecorder() err = data1.Render(w) assert.NoError(t, err) data2 := Redirect{ Code: http.StatusOK, Request: req, Location: "/new/location", } w = httptest.NewRecorder() assert.PanicsWithValue(t, "Cannot redirect with status code 200", func() { err := data2.Render(w) assert.NoError(t, err) }) data3 := Redirect{ Code: http.StatusCreated, Request: req, Location: "/new/location", } w = httptest.NewRecorder() err = data3.Render(w) assert.NoError(t, err) // only improve coverage data2.WriteContentType(w) } func TestRenderData(t *testing.T) { w := httptest.NewRecorder() data := []byte("#!PNG some raw data") err := (Data{ ContentType: "image/png", Data: data, }).Render(w) assert.NoError(t, err) assert.Equal(t, "#!PNG some raw data", w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) } func TestRenderString(t *testing.T) { w := httptest.NewRecorder() (String{ Format: "hello %s %d", Data: []any{}, }).WriteContentType(w) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) err := (String{ Format: "hola %s %d", Data: []any{"manu", 2}, }).Render(w) assert.NoError(t, err) assert.Equal(t, "hola manu 2", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderStringLenZero(t *testing.T) { w := httptest.NewRecorder() err := (String{ Format: "hola %s %d", Data: []any{}, }).Render(w) assert.NoError(t, err) assert.Equal(t, "hola %s %d", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLTemplate(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("t").Parse(`Hello {{.name}}`)) htmlRender := HTMLProduction{Template: templ} instance := htmlRender.Instance("t", map[string]any{ "name": "alexandernyquist", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "Hello alexandernyquist", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLTemplateEmptyName(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("").Parse(`Hello {{.name}}`)) htmlRender := HTMLProduction{Template: templ} instance := htmlRender.Instance("", map[string]any{ "name": "alexandernyquist", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "Hello alexandernyquist", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugFiles(t *testing.T) { w := httptest.NewRecorder() htmlRender := HTMLDebug{ Files: []string{"../testdata/template/hello.tmpl"}, Glob: "", Delims: Delims{Left: "{[{", Right: "}]}"}, FuncMap: nil, } instance := htmlRender.Instance("hello.tmpl", map[string]any{ "name": "thinkerou", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugGlob(t *testing.T) { w := httptest.NewRecorder() htmlRender := HTMLDebug{ Files: nil, Glob: "../testdata/template/hello*", Delims: Delims{Left: "{[{", Right: "}]}"}, FuncMap: nil, } instance := htmlRender.Instance("hello.tmpl", map[string]any{ "name": "thinkerou", }) err := instance.Render(w) assert.NoError(t, err) assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugPanics(t *testing.T) { htmlRender := HTMLDebug{ Files: nil, Glob: "", Delims: Delims{"{{", "}}"}, FuncMap: nil, } assert.Panics(t, func() { htmlRender.Instance("", nil) }) } func TestRenderReader(t *testing.T) { w := httptest.NewRecorder() body := "#!PNG some raw data" headers := make(map[string]string) headers["Content-Disposition"] = `attachment; filename="filename.png"` headers["x-request-id"] = "requestId" err := (Reader{ ContentLength: int64(len(body)), ContentType: "image/png", Reader: strings.NewReader(body), Headers: headers, }).Render(w) assert.NoError(t, err) assert.Equal(t, body, w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) assert.Equal(t, strconv.Itoa(len(body)), w.Header().Get("Content-Length")) assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition")) assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id")) } func TestRenderReaderNoContentLength(t *testing.T) { w := httptest.NewRecorder() body := "#!PNG some raw data" headers := make(map[string]string) headers["Content-Disposition"] = `attachment; filename="filename.png"` headers["x-request-id"] = "requestId" err := (Reader{ ContentLength: -1, ContentType: "image/png", Reader: strings.NewReader(body), Headers: headers, }).Render(w) assert.NoError(t, err) assert.Equal(t, body, w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) assert.NotContains(t, "Content-Length", w.Header()) assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition")) assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id")) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/binding_nomsgpack.go
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build nomsgpack // +build nomsgpack package binding import "net/http" // Content-Type MIME of the most common data formats. const ( MIMEJSON = "application/json" MIMEHTML = "text/html" MIMEXML = "application/xml" MIMEXML2 = "text/xml" MIMEPlain = "text/plain" MIMEPOSTForm = "application/x-www-form-urlencoded" MIMEMultipartPOSTForm = "multipart/form-data" MIMEPROTOBUF = "application/x-protobuf" MIMEYAML = "application/x-yaml" MIMETOML = "application/toml" ) // Binding describes the interface which needs to be implemented for binding the // data present in the request such as JSON request body, query parameters or // the form POST. type Binding interface { Name() string Bind(*http.Request, any) error } // BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // but it reads the body from supplied bytes instead of req.Body. type BindingBody interface { Binding BindBody([]byte, any) error } // BindingUri adds BindUri method to Binding. BindUri is similar with Bind, // but it reads the Params. type BindingUri interface { Name() string BindUri(map[string][]string, any) error } // StructValidator is the minimal interface which needs to be implemented in // order for it to be used as the validator engine for ensuring the correctness // of the request. Gin provides a default implementation for this using // https://github.com/go-playground/validator/tree/v10.6.1. type StructValidator interface { // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. // If the received type is not a struct, any validation should be skipped and nil must be returned. // If the received type is a struct or pointer to a struct, the validation should be performed. // If the struct is not valid or the validation itself fails, a descriptive error should be returned. // Otherwise nil must be returned. ValidateStruct(any) error // Engine returns the underlying validator engine which powers the // StructValidator implementation. Engine() any } // Validator is the default validator which implements the StructValidator // interface. It uses https://github.com/go-playground/validator/tree/v10.6.1 // under the hood. var Validator StructValidator = &defaultValidator{} // These implement the Binding interface and can be used to bind the data // present in the request to struct instances. var ( JSON = jsonBinding{} XML = xmlBinding{} Form = formBinding{} Query = queryBinding{} FormPost = formPostBinding{} FormMultipart = formMultipartBinding{} ProtoBuf = protobufBinding{} YAML = yamlBinding{} Uri = uriBinding{} Header = headerBinding{} TOML = tomlBinding{} ) // Default returns the appropriate Binding instance based on the HTTP method // and the content type. func Default(method, contentType string) Binding { if method == "GET" { return Form } switch contentType { case MIMEJSON: return JSON case MIMEXML, MIMEXML2: return XML case MIMEPROTOBUF: return ProtoBuf case MIMEYAML: return YAML case MIMEMultipartPOSTForm: return FormMultipart case MIMETOML: return TOML default: // case MIMEPOSTForm: return Form } } func validate(obj any) error { if Validator == nil { return nil } return Validator.ValidateStruct(obj) }
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build nomsgpack // +build nomsgpack package binding import "net/http" // Content-Type MIME of the most common data formats. const ( MIMEJSON = "application/json" MIMEHTML = "text/html" MIMEXML = "application/xml" MIMEXML2 = "text/xml" MIMEPlain = "text/plain" MIMEPOSTForm = "application/x-www-form-urlencoded" MIMEMultipartPOSTForm = "multipart/form-data" MIMEPROTOBUF = "application/x-protobuf" MIMEYAML = "application/x-yaml" MIMETOML = "application/toml" ) // Binding describes the interface which needs to be implemented for binding the // data present in the request such as JSON request body, query parameters or // the form POST. type Binding interface { Name() string Bind(*http.Request, any) error } // BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // but it reads the body from supplied bytes instead of req.Body. type BindingBody interface { Binding BindBody([]byte, any) error } // BindingUri adds BindUri method to Binding. BindUri is similar with Bind, // but it reads the Params. type BindingUri interface { Name() string BindUri(map[string][]string, any) error } // StructValidator is the minimal interface which needs to be implemented in // order for it to be used as the validator engine for ensuring the correctness // of the request. Gin provides a default implementation for this using // https://github.com/go-playground/validator/tree/v10.6.1. type StructValidator interface { // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right. // If the received type is not a struct, any validation should be skipped and nil must be returned. // If the received type is a struct or pointer to a struct, the validation should be performed. // If the struct is not valid or the validation itself fails, a descriptive error should be returned. // Otherwise nil must be returned. ValidateStruct(any) error // Engine returns the underlying validator engine which powers the // StructValidator implementation. Engine() any } // Validator is the default validator which implements the StructValidator // interface. It uses https://github.com/go-playground/validator/tree/v10.6.1 // under the hood. var Validator StructValidator = &defaultValidator{} // These implement the Binding interface and can be used to bind the data // present in the request to struct instances. var ( JSON = jsonBinding{} XML = xmlBinding{} Form = formBinding{} Query = queryBinding{} FormPost = formPostBinding{} FormMultipart = formMultipartBinding{} ProtoBuf = protobufBinding{} YAML = yamlBinding{} Uri = uriBinding{} Header = headerBinding{} TOML = tomlBinding{} ) // Default returns the appropriate Binding instance based on the HTTP method // and the content type. func Default(method, contentType string) Binding { if method == "GET" { return Form } switch contentType { case MIMEJSON: return JSON case MIMEXML, MIMEXML2: return XML case MIMEPROTOBUF: return ProtoBuf case MIMEYAML: return YAML case MIMEMultipartPOSTForm: return FormMultipart case MIMETOML: return TOML default: // case MIMEPOSTForm: return Form } } func validate(obj any) error { if Validator == nil { return nil } return Validator.ValidateStruct(obj) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./CODE_OF_CONDUCT.md
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./gin.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "net" "net/http" "os" "path" "strings" "sync" "github.com/gin-gonic/gin/internal/bytesconv" "github.com/gin-gonic/gin/render" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) const defaultMultipartMemory = 32 << 20 // 32 MB var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") ) var defaultPlatform string var defaultTrustedCIDRs = []*net.IPNet{ { // 0.0.0.0/0 (IPv4) IP: net.IP{0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0}, }, { // ::/0 (IPv6) IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, }, } // HandlerFunc defines the handler used by gin middleware as return value. type HandlerFunc func(*Context) // HandlersChain defines a HandlerFunc slice. type HandlersChain []HandlerFunc // Last returns the last handler in the chain. i.e. the last handler is the main one. func (c HandlersChain) Last() HandlerFunc { if length := len(c); length > 0 { return c[length-1] } return nil } // RouteInfo represents a request route's specification which contains method and path and its handler. type RouteInfo struct { Method string Path string Handler string HandlerFunc HandlerFunc } // RoutesInfo defines a RouteInfo slice. type RoutesInfo []RouteInfo // Trusted platforms const ( // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP PlatformGoogleAppEngine = "X-Appengine-Remote-Addr" // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP PlatformCloudflare = "CF-Connecting-IP" ) // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. // Create an instance of Engine, by using New() or Default() type Engine struct { RouterGroup // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // RedirectFixedPath if enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was // fetched, it falls back to the IP obtained from // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool // AppEngine was deprecated. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // UseRawPath if enabled, the url.RawPath will be used to find parameters. UseRawPath bool // UnescapePathValues if true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. // See the PR #1817 and issue #1644 RemoveExtraSlash bool // RemoteIPHeaders list of headers used to obtain the client IP when // `(*gin.Engine).ForwardedByClientIP` is `true` and // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // UseH2C enable h2c support. UseH2C bool // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil. ContextWithFallback bool delims render.Delims secureJSONPrefix string HTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees maxParams uint16 maxSections uint16 trustedProxies []string trustedCIDRs []*net.IPNet } var _ IRouter = &Engine{} // New returns a new blank Engine instance without any middleware attached. // By default, the configuration is: // - RedirectTrailingSlash: true // - RedirectFixedPath: false // - HandleMethodNotAllowed: false // - ForwardedByClientIP: true // - UseRawPath: false // - UnescapePathValues: true func New() *Engine { debugPrintWARNINGNew() engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedPlatform: defaultPlatform, UseRawPath: false, RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", trustedProxies: []string{"0.0.0.0/0", "::/0"}, trustedCIDRs: defaultTrustedCIDRs, } engine.RouterGroup.engine = engine engine.pool.New = func() any { return engine.allocateContext() } return engine } // Default returns an Engine instance with the Logger and Recovery middleware already attached. func Default() *Engine { debugPrintWARNINGDefault() engine := New() engine.Use(Logger(), Recovery()) return engine } func (engine *Engine) Handler() http.Handler { if !engine.UseH2C { return engine } h2s := &http2.Server{} return h2c.NewHandler(engine, h2s) } func (engine *Engine) allocateContext() *Context { v := make(Params, 0, engine.maxParams) skippedNodes := make([]skippedNode, 0, engine.maxSections) return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} return engine } // SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { engine.secureJSONPrefix = prefix return engine } // LoadHTMLGlob loads HTML files identified by glob pattern // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLGlob(pattern string) { left := engine.delims.Left right := engine.delims.Right templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) if IsDebugging() { debugPrintLoadTemplate(templ) engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} return } engine.SetHTMLTemplate(templ) } // LoadHTMLFiles loads a slice of HTML files // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLFiles(files ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} return } templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) engine.SetHTMLTemplate(templ) } // SetHTMLTemplate associate a template with HTML renderer. func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 { debugPrintWARNINGSetHTMLTemplate() } engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} } // SetFuncMap sets the FuncMap used for template.FuncMap. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } // NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true. func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } // Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } func (engine *Engine) rebuild404Handlers() { engine.allNoRoute = engine.combineHandlers(engine.noRoute) } func (engine *Engine) rebuild405Handlers() { engine.allNoMethod = engine.combineHandlers(engine.noMethod) } func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { assert1(path[0] == '/', "path must begin with '/'") assert1(method != "", "HTTP method can not be empty") assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers) root := engine.trees.get(method) if root == nil { root = new(node) root.fullPath = "/" engine.trees = append(engine.trees, methodTree{method: method, root: root}) } root.addRoute(path, handlers) // Update maxParams if paramsCount := countParams(path); paramsCount > engine.maxParams { engine.maxParams = paramsCount } if sectionsCount := countSections(path); sectionsCount > engine.maxSections { engine.maxSections = sectionsCount } } // Routes returns a slice of registered routes, including some useful information, such as: // the http method, path and the handler name. func (engine *Engine) Routes() (routes RoutesInfo) { for _, tree := range engine.trees { routes = iterate("", tree.method, routes, tree.root) } return routes } func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { path += root.path if len(root.handlers) > 0 { handlerFunc := root.handlers.Last() routes = append(routes, RouteInfo{ Method: method, Path: path, Handler: nameOfFunction(handlerFunc), HandlerFunc: handlerFunc, }) } for _, child := range root.children { routes = iterate(path, method, routes, child) } return routes } // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) err = http.ListenAndServe(address, engine.Handler()) return } func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { if engine.trustedProxies == nil { return nil, nil } cidr := make([]*net.IPNet, 0, len(engine.trustedProxies)) for _, trustedProxy := range engine.trustedProxies { if !strings.Contains(trustedProxy, "/") { ip := parseIP(trustedProxy) if ip == nil { return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} } switch len(ip) { case net.IPv4len: trustedProxy += "/32" case net.IPv6len: trustedProxy += "/128" } } _, cidrNet, err := net.ParseCIDR(trustedProxy) if err != nil { return cidr, err } cidr = append(cidr, cidrNet) } return cidr, nil } // SetTrustedProxies set a list of network origins (IPv4 addresses, // IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust // request's headers that contain alternative client IP when // `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` // feature is enabled by default, and it also trusts all proxies // by default. If you want to disable this feature, use // Engine.SetTrustedProxies(nil), then Context.ClientIP() will // return the remote address directly. func (engine *Engine) SetTrustedProxies(trustedProxies []string) error { engine.trustedProxies = trustedProxies return engine.parseTrustedProxies() } // isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true) func (engine *Engine) isUnsafeTrustedProxies() bool { return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::")) } // parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs func (engine *Engine) parseTrustedProxies() error { trustedCIDRs, err := engine.prepareTrustedCIDRs() engine.trustedCIDRs = trustedCIDRs return err } // isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs func (engine *Engine) isTrustedProxy(ip net.IP) bool { if engine.trustedCIDRs == nil { return false } for _, cidr := range engine.trustedCIDRs { if cidr.Contains(ip) { return true } } return false } // validateHeader will parse X-Forwarded-For header and return the trusted client IP address func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) { if header == "" { return "", false } items := strings.Split(header, ",") for i := len(items) - 1; i >= 0; i-- { ipStr := strings.TrimSpace(items[i]) ip := net.ParseIP(ipStr) if ip == nil { break } // X-Forwarded-For is appended by proxy // Check IPs in reverse order and stop when find untrusted proxy if (i == 0) || (!engine.isTrustedProxy(ip)) { return ipStr, true } } return "", false } // parseIP parse a string representation of an IP and returns a net.IP with the // minimum byte representation or nil if input is invalid. func parseIP(ip string) net.IP { parsedIP := net.ParseIP(ip) if ipv4 := parsedIP.To4(); ipv4 != nil { // return ip in a 4-byte representation return ipv4 } // return ip in a 16-byte representation or nil return parsedIP } // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { debugPrint("Listening and serving HTTPS on %s\n", addr) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.ListenAndServeTLS(addr, certFile, keyFile, engine.Handler()) return } // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file). // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunUnix(file string) (err error) { debugPrint("Listening and serving HTTP on unix:/%s", file) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() defer os.Remove(file) err = http.Serve(listener, engine.Handler()) return } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunFd(fd int) (err error) { debugPrint("Listening and serving HTTP on fd@%d", fd) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) listener, err := net.FileListener(f) if err != nil { return } defer listener.Close() err = engine.RunListener(listener) return } // RunListener attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified net.Listener func (engine *Engine) RunListener(listener net.Listener) (err error) { debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.Serve(listener, engine.Handler()) return } // ServeHTTP conforms to the http.Handler interface. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } // HandleContext re-enters a context that has been rewritten. // This can be done by setting c.Request.URL.Path to your new target. // Disclaimer: You can loop yourself to deal with this, use wisely. func (engine *Engine) HandleContext(c *Context) { oldIndexValue := c.index c.reset() engine.handleHTTPRequest(c) c.index = oldIndexValue } func (engine *Engine) handleHTTPRequest(c *Context) { httpMethod := c.Request.Method rPath := c.Request.URL.Path unescape := false if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { rPath = c.Request.URL.RawPath unescape = engine.UnescapePathValues } if engine.RemoveExtraSlash { rPath = cleanPath(rPath) } // Find root of the tree for the given HTTP method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method != httpMethod { continue } root := t[i].root // Find route in tree value := root.getValue(rPath, c.params, c.skippedNodes, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } if httpMethod != http.MethodConnect && rPath != "/" { if value.tsr && engine.RedirectTrailingSlash { redirectTrailingSlash(c) return } if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { return } } break } if engine.HandleMethodNotAllowed { for _, tree := range engine.trees { if tree.method == httpMethod { continue } if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil { c.handlers = engine.allNoMethod serveError(c, http.StatusMethodNotAllowed, default405Body) return } } } c.handlers = engine.allNoRoute serveError(c, http.StatusNotFound, default404Body) } var mimePlain = []string{MIMEPlain} func serveError(c *Context, code int, defaultMessage []byte) { c.writermem.status = code c.Next() if c.writermem.Written() { return } if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain _, err := c.Writer.Write(defaultMessage) if err != nil { debugPrint("cannot write message to writer during serve error: %v", err) } return } c.writermem.WriteHeaderNow() } func redirectTrailingSlash(c *Context) { req := c.Request p := req.URL.Path if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { p = prefix + "/" + req.URL.Path } req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } redirectRequest(c) } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { req := c.Request rPath := req.URL.Path if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { req.URL.Path = bytesconv.BytesToString(fixedPath) redirectRequest(c) return true } return false } func redirectRequest(c *Context) { req := c.Request rPath := req.URL.Path rURL := req.URL.String() code := http.StatusMovedPermanently // Permanent redirect, request with GET method if req.Method != http.MethodGet { code = http.StatusTemporaryRedirect } debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) http.Redirect(c.Writer, req, rURL, code) c.writermem.WriteHeaderNow() }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "html/template" "net" "net/http" "os" "path" "strings" "sync" "github.com/gin-gonic/gin/internal/bytesconv" "github.com/gin-gonic/gin/render" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) const defaultMultipartMemory = 32 << 20 // 32 MB var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") ) var defaultPlatform string var defaultTrustedCIDRs = []*net.IPNet{ { // 0.0.0.0/0 (IPv4) IP: net.IP{0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0}, }, { // ::/0 (IPv6) IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, }, } // HandlerFunc defines the handler used by gin middleware as return value. type HandlerFunc func(*Context) // HandlersChain defines a HandlerFunc slice. type HandlersChain []HandlerFunc // Last returns the last handler in the chain. i.e. the last handler is the main one. func (c HandlersChain) Last() HandlerFunc { if length := len(c); length > 0 { return c[length-1] } return nil } // RouteInfo represents a request route's specification which contains method and path and its handler. type RouteInfo struct { Method string Path string Handler string HandlerFunc HandlerFunc } // RoutesInfo defines a RouteInfo slice. type RoutesInfo []RouteInfo // Trusted platforms const ( // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP PlatformGoogleAppEngine = "X-Appengine-Remote-Addr" // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP PlatformCloudflare = "CF-Connecting-IP" ) // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. // Create an instance of Engine, by using New() or Default() type Engine struct { RouterGroup // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // RedirectFixedPath if enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was // fetched, it falls back to the IP obtained from // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool // AppEngine was deprecated. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // UseRawPath if enabled, the url.RawPath will be used to find parameters. UseRawPath bool // UnescapePathValues if true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. // See the PR #1817 and issue #1644 RemoveExtraSlash bool // RemoteIPHeaders list of headers used to obtain the client IP when // `(*gin.Engine).ForwardedByClientIP` is `true` and // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // UseH2C enable h2c support. UseH2C bool // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil. ContextWithFallback bool delims render.Delims secureJSONPrefix string HTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees maxParams uint16 maxSections uint16 trustedProxies []string trustedCIDRs []*net.IPNet } var _ IRouter = &Engine{} // New returns a new blank Engine instance without any middleware attached. // By default, the configuration is: // - RedirectTrailingSlash: true // - RedirectFixedPath: false // - HandleMethodNotAllowed: false // - ForwardedByClientIP: true // - UseRawPath: false // - UnescapePathValues: true func New() *Engine { debugPrintWARNINGNew() engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedPlatform: defaultPlatform, UseRawPath: false, RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", trustedProxies: []string{"0.0.0.0/0", "::/0"}, trustedCIDRs: defaultTrustedCIDRs, } engine.RouterGroup.engine = engine engine.pool.New = func() any { return engine.allocateContext() } return engine } // Default returns an Engine instance with the Logger and Recovery middleware already attached. func Default() *Engine { debugPrintWARNINGDefault() engine := New() engine.Use(Logger(), Recovery()) return engine } func (engine *Engine) Handler() http.Handler { if !engine.UseH2C { return engine } h2s := &http2.Server{} return h2c.NewHandler(engine, h2s) } func (engine *Engine) allocateContext() *Context { v := make(Params, 0, engine.maxParams) skippedNodes := make([]skippedNode, 0, engine.maxSections) return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} return engine } // SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { engine.secureJSONPrefix = prefix return engine } // LoadHTMLGlob loads HTML files identified by glob pattern // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLGlob(pattern string) { left := engine.delims.Left right := engine.delims.Right templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) if IsDebugging() { debugPrintLoadTemplate(templ) engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} return } engine.SetHTMLTemplate(templ) } // LoadHTMLFiles loads a slice of HTML files // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLFiles(files ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} return } templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) engine.SetHTMLTemplate(templ) } // SetHTMLTemplate associate a template with HTML renderer. func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 { debugPrintWARNINGSetHTMLTemplate() } engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} } // SetFuncMap sets the FuncMap used for template.FuncMap. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } // NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true. func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } // Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } func (engine *Engine) rebuild404Handlers() { engine.allNoRoute = engine.combineHandlers(engine.noRoute) } func (engine *Engine) rebuild405Handlers() { engine.allNoMethod = engine.combineHandlers(engine.noMethod) } func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { assert1(path[0] == '/', "path must begin with '/'") assert1(method != "", "HTTP method can not be empty") assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers) root := engine.trees.get(method) if root == nil { root = new(node) root.fullPath = "/" engine.trees = append(engine.trees, methodTree{method: method, root: root}) } root.addRoute(path, handlers) // Update maxParams if paramsCount := countParams(path); paramsCount > engine.maxParams { engine.maxParams = paramsCount } if sectionsCount := countSections(path); sectionsCount > engine.maxSections { engine.maxSections = sectionsCount } } // Routes returns a slice of registered routes, including some useful information, such as: // the http method, path and the handler name. func (engine *Engine) Routes() (routes RoutesInfo) { for _, tree := range engine.trees { routes = iterate("", tree.method, routes, tree.root) } return routes } func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { path += root.path if len(root.handlers) > 0 { handlerFunc := root.handlers.Last() routes = append(routes, RouteInfo{ Method: method, Path: path, Handler: nameOfFunction(handlerFunc), HandlerFunc: handlerFunc, }) } for _, child := range root.children { routes = iterate(path, method, routes, child) } return routes } // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) err = http.ListenAndServe(address, engine.Handler()) return } func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { if engine.trustedProxies == nil { return nil, nil } cidr := make([]*net.IPNet, 0, len(engine.trustedProxies)) for _, trustedProxy := range engine.trustedProxies { if !strings.Contains(trustedProxy, "/") { ip := parseIP(trustedProxy) if ip == nil { return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} } switch len(ip) { case net.IPv4len: trustedProxy += "/32" case net.IPv6len: trustedProxy += "/128" } } _, cidrNet, err := net.ParseCIDR(trustedProxy) if err != nil { return cidr, err } cidr = append(cidr, cidrNet) } return cidr, nil } // SetTrustedProxies set a list of network origins (IPv4 addresses, // IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust // request's headers that contain alternative client IP when // `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` // feature is enabled by default, and it also trusts all proxies // by default. If you want to disable this feature, use // Engine.SetTrustedProxies(nil), then Context.ClientIP() will // return the remote address directly. func (engine *Engine) SetTrustedProxies(trustedProxies []string) error { engine.trustedProxies = trustedProxies return engine.parseTrustedProxies() } // isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true) func (engine *Engine) isUnsafeTrustedProxies() bool { return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::")) } // parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs func (engine *Engine) parseTrustedProxies() error { trustedCIDRs, err := engine.prepareTrustedCIDRs() engine.trustedCIDRs = trustedCIDRs return err } // isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs func (engine *Engine) isTrustedProxy(ip net.IP) bool { if engine.trustedCIDRs == nil { return false } for _, cidr := range engine.trustedCIDRs { if cidr.Contains(ip) { return true } } return false } // validateHeader will parse X-Forwarded-For header and return the trusted client IP address func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) { if header == "" { return "", false } items := strings.Split(header, ",") for i := len(items) - 1; i >= 0; i-- { ipStr := strings.TrimSpace(items[i]) ip := net.ParseIP(ipStr) if ip == nil { break } // X-Forwarded-For is appended by proxy // Check IPs in reverse order and stop when find untrusted proxy if (i == 0) || (!engine.isTrustedProxy(ip)) { return ipStr, true } } return "", false } // parseIP parse a string representation of an IP and returns a net.IP with the // minimum byte representation or nil if input is invalid. func parseIP(ip string) net.IP { parsedIP := net.ParseIP(ip) if ipv4 := parsedIP.To4(); ipv4 != nil { // return ip in a 4-byte representation return ipv4 } // return ip in a 16-byte representation or nil return parsedIP } // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { debugPrint("Listening and serving HTTPS on %s\n", addr) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.ListenAndServeTLS(addr, certFile, keyFile, engine.Handler()) return } // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file). // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunUnix(file string) (err error) { debugPrint("Listening and serving HTTP on unix:/%s", file) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() defer os.Remove(file) err = http.Serve(listener, engine.Handler()) return } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunFd(fd int) (err error) { debugPrint("Listening and serving HTTP on fd@%d", fd) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) listener, err := net.FileListener(f) if err != nil { return } defer listener.Close() err = engine.RunListener(listener) return } // RunListener attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified net.Listener func (engine *Engine) RunListener(listener net.Listener) (err error) { debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.") } err = http.Serve(listener, engine.Handler()) return } // ServeHTTP conforms to the http.Handler interface. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } // HandleContext re-enters a context that has been rewritten. // This can be done by setting c.Request.URL.Path to your new target. // Disclaimer: You can loop yourself to deal with this, use wisely. func (engine *Engine) HandleContext(c *Context) { oldIndexValue := c.index c.reset() engine.handleHTTPRequest(c) c.index = oldIndexValue } func (engine *Engine) handleHTTPRequest(c *Context) { httpMethod := c.Request.Method rPath := c.Request.URL.Path unescape := false if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { rPath = c.Request.URL.RawPath unescape = engine.UnescapePathValues } if engine.RemoveExtraSlash { rPath = cleanPath(rPath) } // Find root of the tree for the given HTTP method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method != httpMethod { continue } root := t[i].root // Find route in tree value := root.getValue(rPath, c.params, c.skippedNodes, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } if httpMethod != http.MethodConnect && rPath != "/" { if value.tsr && engine.RedirectTrailingSlash { redirectTrailingSlash(c) return } if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { return } } break } if engine.HandleMethodNotAllowed { for _, tree := range engine.trees { if tree.method == httpMethod { continue } if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil { c.handlers = engine.allNoMethod serveError(c, http.StatusMethodNotAllowed, default405Body) return } } } c.handlers = engine.allNoRoute serveError(c, http.StatusNotFound, default404Body) } var mimePlain = []string{MIMEPlain} func serveError(c *Context, code int, defaultMessage []byte) { c.writermem.status = code c.Next() if c.writermem.Written() { return } if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain _, err := c.Writer.Write(defaultMessage) if err != nil { debugPrint("cannot write message to writer during serve error: %v", err) } return } c.writermem.WriteHeaderNow() } func redirectTrailingSlash(c *Context) { req := c.Request p := req.URL.Path if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { p = prefix + "/" + req.URL.Path } req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } redirectRequest(c) } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { req := c.Request rPath := req.URL.Path if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { req.URL.Path = bytesconv.BytesToString(fixedPath) redirectRequest(c) return true } return false } func redirectRequest(c *Context) { req := c.Request rPath := req.URL.Path rURL := req.URL.String() code := http.StatusMovedPermanently // Permanent redirect, request with GET method if req.Method != http.MethodGet { code = http.StatusTemporaryRedirect } debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) http.Redirect(c.Writer, req, rURL, code) c.writermem.WriteHeaderNow() }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./response_writer.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bufio" "io" "net" "net/http" ) const ( noWritten = -1 defaultStatus = http.StatusOK ) // ResponseWriter ... type ResponseWriter interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // Status returns the HTTP response status code of the current request. Status() int // Size returns the number of bytes already written into the response http body. // See Written() Size() int // WriteString writes the string into the response body. WriteString(string) (int, error) // Written returns true if the response body was already written. Written() bool // WriteHeaderNow forces to write the http header (status code + headers). WriteHeaderNow() // Pusher get the http.Pusher for server push Pusher() http.Pusher } type responseWriter struct { http.ResponseWriter size int status int } var _ ResponseWriter = &responseWriter{} func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer w.size = noWritten w.status = defaultStatus } func (w *responseWriter) WriteHeader(code int) { if code > 0 && w.status != code { if w.Written() { debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) } w.status = code } } func (w *responseWriter) WriteHeaderNow() { if !w.Written() { w.size = 0 w.ResponseWriter.WriteHeader(w.status) } } func (w *responseWriter) Write(data []byte) (n int, err error) { w.WriteHeaderNow() n, err = w.ResponseWriter.Write(data) w.size += n return } func (w *responseWriter) WriteString(s string) (n int, err error) { w.WriteHeaderNow() n, err = io.WriteString(w.ResponseWriter, s) w.size += n return } func (w *responseWriter) Status() int { return w.status } func (w *responseWriter) Size() int { return w.size } func (w *responseWriter) Written() bool { return w.size != noWritten } // Hijack implements the http.Hijacker interface. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() } // CloseNotify implements the http.CloseNotifier interface. func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Flush implements the http.Flusher interface. func (w *responseWriter) Flush() { w.WriteHeaderNow() w.ResponseWriter.(http.Flusher).Flush() } func (w *responseWriter) Pusher() (pusher http.Pusher) { if pusher, ok := w.ResponseWriter.(http.Pusher); ok { return pusher } return nil }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bufio" "io" "net" "net/http" ) const ( noWritten = -1 defaultStatus = http.StatusOK ) // ResponseWriter ... type ResponseWriter interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // Status returns the HTTP response status code of the current request. Status() int // Size returns the number of bytes already written into the response http body. // See Written() Size() int // WriteString writes the string into the response body. WriteString(string) (int, error) // Written returns true if the response body was already written. Written() bool // WriteHeaderNow forces to write the http header (status code + headers). WriteHeaderNow() // Pusher get the http.Pusher for server push Pusher() http.Pusher } type responseWriter struct { http.ResponseWriter size int status int } var _ ResponseWriter = &responseWriter{} func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer w.size = noWritten w.status = defaultStatus } func (w *responseWriter) WriteHeader(code int) { if code > 0 && w.status != code { if w.Written() { debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) } w.status = code } } func (w *responseWriter) WriteHeaderNow() { if !w.Written() { w.size = 0 w.ResponseWriter.WriteHeader(w.status) } } func (w *responseWriter) Write(data []byte) (n int, err error) { w.WriteHeaderNow() n, err = w.ResponseWriter.Write(data) w.size += n return } func (w *responseWriter) WriteString(s string) (n int, err error) { w.WriteHeaderNow() n, err = io.WriteString(w.ResponseWriter, s) w.size += n return } func (w *responseWriter) Status() int { return w.status } func (w *responseWriter) Size() int { return w.size } func (w *responseWriter) Written() bool { return w.size != noWritten } // Hijack implements the http.Hijacker interface. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() } // CloseNotify implements the http.CloseNotifier interface. func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Flush implements the http.Flusher interface. func (w *responseWriter) Flush() { w.WriteHeaderNow() w.ResponseWriter.(http.Flusher).Flush() } func (w *responseWriter) Pusher() (pusher http.Pusher) { if pusher, ok := w.ResponseWriter.(http.Pusher); ok { return pusher } return nil }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/validate_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "testing" "time" "github.com/go-playground/validator/v10" "github.com/stretchr/testify/assert" ) type testInterface interface { String() string } type substructNoValidation struct { IString string IInt int } type mapNoValidationSub map[string]substructNoValidation type structNoValidationValues struct { substructNoValidation Boolean bool Uinteger uint Integer int Integer8 int8 Integer16 int16 Integer32 int32 Integer64 int64 Uinteger8 uint8 Uinteger16 uint16 Uinteger32 uint32 Uinteger64 uint64 Float32 float32 Float64 float64 String string Date time.Time Struct substructNoValidation InlinedStruct struct { String []string Integer int } IntSlice []int IntPointerSlice []*int StructPointerSlice []*substructNoValidation StructSlice []substructNoValidation InterfaceSlice []testInterface UniversalInterface any CustomInterface testInterface FloatMap map[string]float32 StructMap mapNoValidationSub } func createNoValidationValues() structNoValidationValues { integer := 1 s := structNoValidationValues{ Boolean: true, Uinteger: 1 << 29, Integer: -10000, Integer8: 120, Integer16: -20000, Integer32: 1 << 29, Integer64: 1 << 61, Uinteger8: 250, Uinteger16: 50000, Uinteger32: 1 << 31, Uinteger64: 1 << 62, Float32: 123.456, Float64: 123.456789, String: "text", Date: time.Time{}, CustomInterface: &bytes.Buffer{}, Struct: substructNoValidation{}, IntSlice: []int{-3, -2, 1, 0, 1, 2, 3}, IntPointerSlice: []*int{&integer}, StructSlice: []substructNoValidation{}, UniversalInterface: 1.2, FloatMap: map[string]float32{ "foo": 1.23, "bar": 232.323, }, StructMap: mapNoValidationSub{ "foo": substructNoValidation{}, "bar": substructNoValidation{}, }, // StructPointerSlice []noValidationSub // InterfaceSlice []testInterface } s.InlinedStruct.Integer = 1000 s.InlinedStruct.String = []string{"first", "second"} s.IString = "substring" s.IInt = 987654 return s } func TestValidateNoValidationValues(t *testing.T) { origin := createNoValidationValues() test := createNoValidationValues() empty := structNoValidationValues{} assert.Nil(t, validate(test)) assert.Nil(t, validate(&test)) assert.Nil(t, validate(empty)) assert.Nil(t, validate(&empty)) assert.Equal(t, origin, test) } type structNoValidationPointer struct { substructNoValidation Boolean bool Uinteger *uint Integer *int Integer8 *int8 Integer16 *int16 Integer32 *int32 Integer64 *int64 Uinteger8 *uint8 Uinteger16 *uint16 Uinteger32 *uint32 Uinteger64 *uint64 Float32 *float32 Float64 *float64 String *string Date *time.Time Struct *substructNoValidation IntSlice *[]int IntPointerSlice *[]*int StructPointerSlice *[]*substructNoValidation StructSlice *[]substructNoValidation InterfaceSlice *[]testInterface FloatMap *map[string]float32 StructMap *mapNoValidationSub } func TestValidateNoValidationPointers(t *testing.T) { //origin := createNoValidation_values() //test := createNoValidation_values() empty := structNoValidationPointer{} //assert.Nil(t, validate(test)) //assert.Nil(t, validate(&test)) assert.Nil(t, validate(empty)) assert.Nil(t, validate(&empty)) //assert.Equal(t, origin, test) } type Object map[string]any func TestValidatePrimitives(t *testing.T) { obj := Object{"foo": "bar", "bar": 1} assert.NoError(t, validate(obj)) assert.NoError(t, validate(&obj)) assert.Equal(t, Object{"foo": "bar", "bar": 1}, obj) obj2 := []Object{{"foo": "bar", "bar": 1}, {"foo": "bar", "bar": 1}} assert.NoError(t, validate(obj2)) assert.NoError(t, validate(&obj2)) nu := 10 assert.NoError(t, validate(nu)) assert.NoError(t, validate(&nu)) assert.Equal(t, 10, nu) str := "value" assert.NoError(t, validate(str)) assert.NoError(t, validate(&str)) assert.Equal(t, "value", str) } // structCustomValidation is a helper struct we use to check that // custom validation can be registered on it. // The `notone` binding directive is for custom validation and registered later. type structCustomValidation struct { Integer int `binding:"notone"` } func notOne(f1 validator.FieldLevel) bool { if val, ok := f1.Field().Interface().(int); ok { return val != 1 } return false } func TestValidatorEngine(t *testing.T) { // This validates that the function `notOne` matches // the expected function signature by `defaultValidator` // and by extension the validator library. engine, ok := Validator.Engine().(*validator.Validate) assert.True(t, ok) err := engine.RegisterValidation("notone", notOne) // Check that we can register custom validation without error assert.Nil(t, err) // Create an instance which will fail validation withOne := structCustomValidation{Integer: 1} errs := validate(withOne) // Check that we got back non-nil errs assert.NotNil(t, errs) // Check that the error matches expectation assert.Error(t, errs, "", "", "notone") }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "testing" "time" "github.com/go-playground/validator/v10" "github.com/stretchr/testify/assert" ) type testInterface interface { String() string } type substructNoValidation struct { IString string IInt int } type mapNoValidationSub map[string]substructNoValidation type structNoValidationValues struct { substructNoValidation Boolean bool Uinteger uint Integer int Integer8 int8 Integer16 int16 Integer32 int32 Integer64 int64 Uinteger8 uint8 Uinteger16 uint16 Uinteger32 uint32 Uinteger64 uint64 Float32 float32 Float64 float64 String string Date time.Time Struct substructNoValidation InlinedStruct struct { String []string Integer int } IntSlice []int IntPointerSlice []*int StructPointerSlice []*substructNoValidation StructSlice []substructNoValidation InterfaceSlice []testInterface UniversalInterface any CustomInterface testInterface FloatMap map[string]float32 StructMap mapNoValidationSub } func createNoValidationValues() structNoValidationValues { integer := 1 s := structNoValidationValues{ Boolean: true, Uinteger: 1 << 29, Integer: -10000, Integer8: 120, Integer16: -20000, Integer32: 1 << 29, Integer64: 1 << 61, Uinteger8: 250, Uinteger16: 50000, Uinteger32: 1 << 31, Uinteger64: 1 << 62, Float32: 123.456, Float64: 123.456789, String: "text", Date: time.Time{}, CustomInterface: &bytes.Buffer{}, Struct: substructNoValidation{}, IntSlice: []int{-3, -2, 1, 0, 1, 2, 3}, IntPointerSlice: []*int{&integer}, StructSlice: []substructNoValidation{}, UniversalInterface: 1.2, FloatMap: map[string]float32{ "foo": 1.23, "bar": 232.323, }, StructMap: mapNoValidationSub{ "foo": substructNoValidation{}, "bar": substructNoValidation{}, }, // StructPointerSlice []noValidationSub // InterfaceSlice []testInterface } s.InlinedStruct.Integer = 1000 s.InlinedStruct.String = []string{"first", "second"} s.IString = "substring" s.IInt = 987654 return s } func TestValidateNoValidationValues(t *testing.T) { origin := createNoValidationValues() test := createNoValidationValues() empty := structNoValidationValues{} assert.Nil(t, validate(test)) assert.Nil(t, validate(&test)) assert.Nil(t, validate(empty)) assert.Nil(t, validate(&empty)) assert.Equal(t, origin, test) } type structNoValidationPointer struct { substructNoValidation Boolean bool Uinteger *uint Integer *int Integer8 *int8 Integer16 *int16 Integer32 *int32 Integer64 *int64 Uinteger8 *uint8 Uinteger16 *uint16 Uinteger32 *uint32 Uinteger64 *uint64 Float32 *float32 Float64 *float64 String *string Date *time.Time Struct *substructNoValidation IntSlice *[]int IntPointerSlice *[]*int StructPointerSlice *[]*substructNoValidation StructSlice *[]substructNoValidation InterfaceSlice *[]testInterface FloatMap *map[string]float32 StructMap *mapNoValidationSub } func TestValidateNoValidationPointers(t *testing.T) { //origin := createNoValidation_values() //test := createNoValidation_values() empty := structNoValidationPointer{} //assert.Nil(t, validate(test)) //assert.Nil(t, validate(&test)) assert.Nil(t, validate(empty)) assert.Nil(t, validate(&empty)) //assert.Equal(t, origin, test) } type Object map[string]any func TestValidatePrimitives(t *testing.T) { obj := Object{"foo": "bar", "bar": 1} assert.NoError(t, validate(obj)) assert.NoError(t, validate(&obj)) assert.Equal(t, Object{"foo": "bar", "bar": 1}, obj) obj2 := []Object{{"foo": "bar", "bar": 1}, {"foo": "bar", "bar": 1}} assert.NoError(t, validate(obj2)) assert.NoError(t, validate(&obj2)) nu := 10 assert.NoError(t, validate(nu)) assert.NoError(t, validate(&nu)) assert.Equal(t, 10, nu) str := "value" assert.NoError(t, validate(str)) assert.NoError(t, validate(&str)) assert.Equal(t, "value", str) } // structCustomValidation is a helper struct we use to check that // custom validation can be registered on it. // The `notone` binding directive is for custom validation and registered later. type structCustomValidation struct { Integer int `binding:"notone"` } func notOne(f1 validator.FieldLevel) bool { if val, ok := f1.Field().Interface().(int); ok { return val != 1 } return false } func TestValidatorEngine(t *testing.T) { // This validates that the function `notOne` matches // the expected function signature by `defaultValidator` // and by extension the validator library. engine, ok := Validator.Engine().(*validator.Validate) assert.True(t, ok) err := engine.RegisterValidation("notone", notOne) // Check that we can register custom validation without error assert.Nil(t, err) // Create an instance which will fail validation withOne := structCustomValidation{Integer: 1} errs := validate(withOne) // Check that we got back non-nil errs assert.NotNil(t, errs) // Check that the error matches expectation assert.Error(t, errs, "", "", "notone") }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./routes_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" ) type header struct { Key string Value string } // PerformRequest for testing gin router. func PerformRequest(r http.Handler, method, path string, headers ...header) *httptest.ResponseRecorder { req := httptest.NewRequest(method, path, nil) for _, h := range headers { req.Header.Add(h.Key, h.Value) } w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } func testRouteOK(method string, t *testing.T) { passed := false passedAny := false r := New() r.Any("/test2", func(c *Context) { passedAny = true }) r.Handle(method, "/test", func(c *Context) { passed = true }) w := PerformRequest(r, method, "/test") assert.True(t, passed) assert.Equal(t, http.StatusOK, w.Code) PerformRequest(r, method, "/test2") assert.True(t, passedAny) } // TestSingleRouteOK tests that POST route is correctly invoked. func testRouteNotOK(method string, t *testing.T) { passed := false router := New() router.Handle(method, "/test_2", func(c *Context) { passed = true }) w := PerformRequest(router, method, "/test") assert.False(t, passed) assert.Equal(t, http.StatusNotFound, w.Code) } // TestSingleRouteOK tests that POST route is correctly invoked. func testRouteNotOK2(method string, t *testing.T) { passed := false router := New() router.HandleMethodNotAllowed = true var methodRoute string if method == http.MethodPost { methodRoute = http.MethodGet } else { methodRoute = http.MethodPost } router.Handle(methodRoute, "/test", func(c *Context) { passed = true }) w := PerformRequest(router, method, "/test") assert.False(t, passed) assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } func TestRouterMethod(t *testing.T) { router := New() router.PUT("/hey2", func(c *Context) { c.String(http.StatusOK, "sup2") }) router.PUT("/hey", func(c *Context) { c.String(http.StatusOK, "called") }) router.PUT("/hey3", func(c *Context) { c.String(http.StatusOK, "sup3") }) w := PerformRequest(router, http.MethodPut, "/hey") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "called", w.Body.String()) } func TestRouterGroupRouteOK(t *testing.T) { testRouteOK(http.MethodGet, t) testRouteOK(http.MethodPost, t) testRouteOK(http.MethodPut, t) testRouteOK(http.MethodPatch, t) testRouteOK(http.MethodHead, t) testRouteOK(http.MethodOptions, t) testRouteOK(http.MethodDelete, t) testRouteOK(http.MethodConnect, t) testRouteOK(http.MethodTrace, t) } func TestRouteNotOK(t *testing.T) { testRouteNotOK(http.MethodGet, t) testRouteNotOK(http.MethodPost, t) testRouteNotOK(http.MethodPut, t) testRouteNotOK(http.MethodPatch, t) testRouteNotOK(http.MethodHead, t) testRouteNotOK(http.MethodOptions, t) testRouteNotOK(http.MethodDelete, t) testRouteNotOK(http.MethodConnect, t) testRouteNotOK(http.MethodTrace, t) } func TestRouteNotOK2(t *testing.T) { testRouteNotOK2(http.MethodGet, t) testRouteNotOK2(http.MethodPost, t) testRouteNotOK2(http.MethodPut, t) testRouteNotOK2(http.MethodPatch, t) testRouteNotOK2(http.MethodHead, t) testRouteNotOK2(http.MethodOptions, t) testRouteNotOK2(http.MethodDelete, t) testRouteNotOK2(http.MethodConnect, t) testRouteNotOK2(http.MethodTrace, t) } func TestRouteRedirectTrailingSlash(t *testing.T) { router := New() router.RedirectFixedPath = false router.RedirectTrailingSlash = true router.GET("/path", func(c *Context) {}) router.GET("/path2/", func(c *Context) {}) router.POST("/path3", func(c *Context) {}) router.PUT("/path4/", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path/") assert.Equal(t, "/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, "/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodPost, "/path3/") assert.Equal(t, "/path3", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodPut, "/path4") assert.Equal(t, "/path4/", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodGet, "/path2/") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodPost, "/path3") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodPut, "/path4/") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/api"}) assert.Equal(t, "/api/path2/", w.Header().Get("Location")) assert.Equal(t, 301, w.Code) w = PerformRequest(router, http.MethodGet, "/path2/", header{Key: "X-Forwarded-Prefix", Value: "/api/"}) assert.Equal(t, 200, w.Code) router.RedirectTrailingSlash = false w = PerformRequest(router, http.MethodGet, "/path/") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodPost, "/path3/") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodPut, "/path4") assert.Equal(t, http.StatusNotFound, w.Code) } func TestRouteRedirectFixedPath(t *testing.T) { router := New() router.RedirectFixedPath = true router.RedirectTrailingSlash = false router.GET("/path", func(c *Context) {}) router.GET("/Path2", func(c *Context) {}) router.POST("/PATH3", func(c *Context) {}) router.POST("/Path4/", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/PATH") assert.Equal(t, "/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, "/Path2", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodPost, "/path3") assert.Equal(t, "/PATH3", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodPost, "/path4") assert.Equal(t, "/Path4/", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) } // TestContextParamsGet tests that a parameter can be parsed from the URL. func TestRouteParamsByName(t *testing.T) { name := "" lastName := "" wild := "" router := New() router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w := PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "john", name) assert.Equal(t, "smith", lastName) assert.Equal(t, "/is/super/great", wild) } // TestContextParamsGet tests that a parameter can be parsed from the URL even with extra slashes. func TestRouteParamsByNameWithExtraSlash(t *testing.T) { name := "" lastName := "" wild := "" router := New() router.RemoveExtraSlash = true router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w := PerformRequest(router, http.MethodGet, "//test//john//smith//is//super//great") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "john", name) assert.Equal(t, "smith", lastName) assert.Equal(t, "/is/super/great", wild) } // TestHandleStaticFile - ensure the static file handles properly func TestRouteStaticFile(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() f, err := ioutil.TempFile(testRoot, "") if err != nil { t.Error(err) } defer os.Remove(f.Name()) _, err = f.WriteString("Gin Web Framework") assert.NoError(t, err) f.Close() dir, filename := filepath.Split(f.Name()) // SETUP gin router := New() router.Static("/using_static", dir) router.StaticFile("/result", f.Name()) w := PerformRequest(router, http.MethodGet, "/using_static/"+filename) w2 := PerformRequest(router, http.MethodGet, "/result") assert.Equal(t, w, w2) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "Gin Web Framework", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename) w4 := PerformRequest(router, http.MethodHead, "/result") assert.Equal(t, w3, w4) assert.Equal(t, http.StatusOK, w3.Code) } // TestHandleStaticFile - ensure the static file handles properly func TestRouteStaticFileFS(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() f, err := ioutil.TempFile(testRoot, "") if err != nil { t.Error(err) } defer os.Remove(f.Name()) _, err = f.WriteString("Gin Web Framework") assert.NoError(t, err) f.Close() dir, filename := filepath.Split(f.Name()) // SETUP gin router := New() router.Static("/using_static", dir) router.StaticFileFS("/result_fs", filename, Dir(dir, false)) w := PerformRequest(router, http.MethodGet, "/using_static/"+filename) w2 := PerformRequest(router, http.MethodGet, "/result_fs") assert.Equal(t, w, w2) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "Gin Web Framework", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename) w4 := PerformRequest(router, http.MethodHead, "/result_fs") assert.Equal(t, w3, w4) assert.Equal(t, http.StatusOK, w3.Code) } // TestHandleStaticDir - ensure the root/sub dir handles properly func TestRouteStaticListingDir(t *testing.T) { router := New() router.StaticFS("/", Dir("./", true)) w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "gin.go") assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } // TestHandleHeadToDir - ensure the root/sub dir handles properly func TestRouteStaticNoListing(t *testing.T) { router := New() router.Static("/", "./") w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusNotFound, w.Code) assert.NotContains(t, w.Body.String(), "gin.go") } func TestRouterMiddlewareAndStatic(t *testing.T) { router := New() static := router.Group("/", func(c *Context) { c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("X-GIN", "Gin Framework") }) static.Static("/", "./") w := PerformRequest(router, http.MethodGet, "/gin.go") assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "package gin") // Content-Type='text/plain; charset=utf-8' when go version <= 1.16, // else, Content-Type='text/x-go; charset=utf-8' assert.NotEqual(t, "", w.Header().Get("Content-Type")) assert.NotEqual(t, w.Header().Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST") assert.Equal(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Expires")) assert.Equal(t, "Gin Framework", w.Header().Get("x-GIN")) } func TestRouteNotAllowedEnabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = true router.POST("/path", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, "responseText", w.Body.String()) assert.Equal(t, http.StatusTeapot, w.Code) } func TestRouteNotAllowedEnabled2(t *testing.T) { router := New() router.HandleMethodNotAllowed = true // add one methodTree to trees router.addRoute(http.MethodPost, "/", HandlersChain{func(_ *Context) {}}) router.GET("/path2", func(c *Context) {}) w := PerformRequest(router, http.MethodPost, "/path2") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } func TestRouteNotAllowedDisabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = false router.POST("/path", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusNotFound, w.Code) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, "404 page not found", w.Body.String()) assert.Equal(t, http.StatusNotFound, w.Code) } func TestRouterNotFoundWithRemoveExtraSlash(t *testing.T) { router := New() router.RemoveExtraSlash = true router.GET("/path", func(c *Context) {}) router.GET("/", func(c *Context) {}) testRoutes := []struct { route string code int location string }{ {"/../path", http.StatusOK, ""}, // CleanPath {"/nope", http.StatusNotFound, ""}, // NotFound } for _, tr := range testRoutes { w := PerformRequest(router, "GET", tr.route) assert.Equal(t, tr.code, w.Code) if w.Code != http.StatusNotFound { assert.Equal(t, tr.location, fmt.Sprint(w.Header().Get("Location"))) } } } func TestRouterNotFound(t *testing.T) { router := New() router.RedirectFixedPath = true router.GET("/path", func(c *Context) {}) router.GET("/dir/", func(c *Context) {}) router.GET("/", func(c *Context) {}) testRoutes := []struct { route string code int location string }{ {"/path/", http.StatusMovedPermanently, "/path"}, // TSR -/ {"/dir", http.StatusMovedPermanently, "/dir/"}, // TSR +/ {"/PATH", http.StatusMovedPermanently, "/path"}, // Fixed Case {"/DIR/", http.StatusMovedPermanently, "/dir/"}, // Fixed Case {"/PATH/", http.StatusMovedPermanently, "/path"}, // Fixed Case -/ {"/DIR", http.StatusMovedPermanently, "/dir/"}, // Fixed Case +/ {"/../path", http.StatusMovedPermanently, "/path"}, // Without CleanPath {"/nope", http.StatusNotFound, ""}, // NotFound } for _, tr := range testRoutes { w := PerformRequest(router, http.MethodGet, tr.route) assert.Equal(t, tr.code, w.Code) if w.Code != http.StatusNotFound { assert.Equal(t, tr.location, fmt.Sprint(w.Header().Get("Location"))) } } // Test custom not found handler var notFound bool router.NoRoute(func(c *Context) { c.AbortWithStatus(http.StatusNotFound) notFound = true }) w := PerformRequest(router, http.MethodGet, "/nope") assert.Equal(t, http.StatusNotFound, w.Code) assert.True(t, notFound) // Test other method than GET (want 307 instead of 301) router.PATCH("/path", func(c *Context) {}) w = PerformRequest(router, http.MethodPatch, "/path/") assert.Equal(t, http.StatusTemporaryRedirect, w.Code) assert.Equal(t, "map[Location:[/path]]", fmt.Sprint(w.Header())) // Test special case where no node for the prefix "/" exists router = New() router.GET("/a", func(c *Context) {}) w = PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusNotFound, w.Code) // Reproduction test for the bug of issue #2843 router = New() router.NoRoute(func(c *Context) { if c.Request.RequestURI == "/login" { c.String(200, "login") } }) router.GET("/logout", func(c *Context) { c.String(200, "logout") }) w = PerformRequest(router, http.MethodGet, "/login") assert.Equal(t, "login", w.Body.String()) w = PerformRequest(router, http.MethodGet, "/logout") assert.Equal(t, "logout", w.Body.String()) } func TestRouterStaticFSNotFound(t *testing.T) { router := New() router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/"))) router.NoRoute(func(c *Context) { c.String(404, "non existent") }) w := PerformRequest(router, http.MethodGet, "/nonexistent") assert.Equal(t, "non existent", w.Body.String()) w = PerformRequest(router, http.MethodHead, "/nonexistent") assert.Equal(t, "non existent", w.Body.String()) } func TestRouterStaticFSFileNotFound(t *testing.T) { router := New() router.StaticFS("/", http.FileSystem(http.Dir("."))) assert.NotPanics(t, func() { PerformRequest(router, http.MethodGet, "/nonexistent") }) } // Reproduction test for the bug of issue #1805 func TestMiddlewareCalledOnceByRouterStaticFSNotFound(t *testing.T) { router := New() // Middleware must be called just only once by per request. middlewareCalledNum := 0 router.Use(func(c *Context) { middlewareCalledNum++ }) router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/"))) // First access PerformRequest(router, http.MethodGet, "/nonexistent") assert.Equal(t, 1, middlewareCalledNum) // Second access PerformRequest(router, http.MethodHead, "/nonexistent") assert.Equal(t, 2, middlewareCalledNum) } func TestRouteRawPath(t *testing.T) { route := New() route.UseRawPath = true route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, name, c.Param("name")) assert.Equal(t, num, c.Param("num")) assert.Equal(t, "Some/Other/Project", name) assert.Equal(t, "222", num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/222") assert.Equal(t, http.StatusOK, w.Code) } func TestRouteRawPathNoUnescape(t *testing.T) { route := New() route.UseRawPath = true route.UnescapePathValues = false route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, name, c.Param("name")) assert.Equal(t, num, c.Param("num")) assert.Equal(t, "Some%2FOther%2FProject", name) assert.Equal(t, "333", num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/333") assert.Equal(t, http.StatusOK, w.Code) } func TestRouteServeErrorWithWriteHeader(t *testing.T) { route := New() route.Use(func(c *Context) { c.Status(421) c.Next() }) w := PerformRequest(route, http.MethodGet, "/NotFound") assert.Equal(t, 421, w.Code) assert.Equal(t, 0, w.Body.Len()) } func TestRouteContextHoldsFullPath(t *testing.T) { router := New() // Test routes routes := []string{ "/simple", "/project/:name", "/", "/news/home", "/news", "/simple-two/one", "/simple-two/one-two", "/project/:name/build/*params", "/project/:name/bui", "/user/:id/status", "/user/:id", "/user/:id/profile", } for _, route := range routes { actualRoute := route router.GET(route, func(c *Context) { // For each defined route context should contain its full path assert.Equal(t, actualRoute, c.FullPath()) c.AbortWithStatus(http.StatusOK) }) } for _, route := range routes { w := PerformRequest(router, http.MethodGet, route) assert.Equal(t, http.StatusOK, w.Code) } // Test not found router.Use(func(c *Context) { // For not found routes full path is empty assert.Equal(t, "", c.FullPath()) }) w := PerformRequest(router, http.MethodGet, "/not-found") assert.Equal(t, http.StatusNotFound, w.Code) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" ) type header struct { Key string Value string } // PerformRequest for testing gin router. func PerformRequest(r http.Handler, method, path string, headers ...header) *httptest.ResponseRecorder { req := httptest.NewRequest(method, path, nil) for _, h := range headers { req.Header.Add(h.Key, h.Value) } w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } func testRouteOK(method string, t *testing.T) { passed := false passedAny := false r := New() r.Any("/test2", func(c *Context) { passedAny = true }) r.Handle(method, "/test", func(c *Context) { passed = true }) w := PerformRequest(r, method, "/test") assert.True(t, passed) assert.Equal(t, http.StatusOK, w.Code) PerformRequest(r, method, "/test2") assert.True(t, passedAny) } // TestSingleRouteOK tests that POST route is correctly invoked. func testRouteNotOK(method string, t *testing.T) { passed := false router := New() router.Handle(method, "/test_2", func(c *Context) { passed = true }) w := PerformRequest(router, method, "/test") assert.False(t, passed) assert.Equal(t, http.StatusNotFound, w.Code) } // TestSingleRouteOK tests that POST route is correctly invoked. func testRouteNotOK2(method string, t *testing.T) { passed := false router := New() router.HandleMethodNotAllowed = true var methodRoute string if method == http.MethodPost { methodRoute = http.MethodGet } else { methodRoute = http.MethodPost } router.Handle(methodRoute, "/test", func(c *Context) { passed = true }) w := PerformRequest(router, method, "/test") assert.False(t, passed) assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } func TestRouterMethod(t *testing.T) { router := New() router.PUT("/hey2", func(c *Context) { c.String(http.StatusOK, "sup2") }) router.PUT("/hey", func(c *Context) { c.String(http.StatusOK, "called") }) router.PUT("/hey3", func(c *Context) { c.String(http.StatusOK, "sup3") }) w := PerformRequest(router, http.MethodPut, "/hey") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "called", w.Body.String()) } func TestRouterGroupRouteOK(t *testing.T) { testRouteOK(http.MethodGet, t) testRouteOK(http.MethodPost, t) testRouteOK(http.MethodPut, t) testRouteOK(http.MethodPatch, t) testRouteOK(http.MethodHead, t) testRouteOK(http.MethodOptions, t) testRouteOK(http.MethodDelete, t) testRouteOK(http.MethodConnect, t) testRouteOK(http.MethodTrace, t) } func TestRouteNotOK(t *testing.T) { testRouteNotOK(http.MethodGet, t) testRouteNotOK(http.MethodPost, t) testRouteNotOK(http.MethodPut, t) testRouteNotOK(http.MethodPatch, t) testRouteNotOK(http.MethodHead, t) testRouteNotOK(http.MethodOptions, t) testRouteNotOK(http.MethodDelete, t) testRouteNotOK(http.MethodConnect, t) testRouteNotOK(http.MethodTrace, t) } func TestRouteNotOK2(t *testing.T) { testRouteNotOK2(http.MethodGet, t) testRouteNotOK2(http.MethodPost, t) testRouteNotOK2(http.MethodPut, t) testRouteNotOK2(http.MethodPatch, t) testRouteNotOK2(http.MethodHead, t) testRouteNotOK2(http.MethodOptions, t) testRouteNotOK2(http.MethodDelete, t) testRouteNotOK2(http.MethodConnect, t) testRouteNotOK2(http.MethodTrace, t) } func TestRouteRedirectTrailingSlash(t *testing.T) { router := New() router.RedirectFixedPath = false router.RedirectTrailingSlash = true router.GET("/path", func(c *Context) {}) router.GET("/path2/", func(c *Context) {}) router.POST("/path3", func(c *Context) {}) router.PUT("/path4/", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path/") assert.Equal(t, "/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, "/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodPost, "/path3/") assert.Equal(t, "/path3", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodPut, "/path4") assert.Equal(t, "/path4/", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodGet, "/path2/") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodPost, "/path3") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodPut, "/path4/") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/api"}) assert.Equal(t, "/api/path2/", w.Header().Get("Location")) assert.Equal(t, 301, w.Code) w = PerformRequest(router, http.MethodGet, "/path2/", header{Key: "X-Forwarded-Prefix", Value: "/api/"}) assert.Equal(t, 200, w.Code) router.RedirectTrailingSlash = false w = PerformRequest(router, http.MethodGet, "/path/") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodPost, "/path3/") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodPut, "/path4") assert.Equal(t, http.StatusNotFound, w.Code) } func TestRouteRedirectFixedPath(t *testing.T) { router := New() router.RedirectFixedPath = true router.RedirectTrailingSlash = false router.GET("/path", func(c *Context) {}) router.GET("/Path2", func(c *Context) {}) router.POST("/PATH3", func(c *Context) {}) router.POST("/Path4/", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/PATH") assert.Equal(t, "/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, "/Path2", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodPost, "/path3") assert.Equal(t, "/PATH3", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodPost, "/path4") assert.Equal(t, "/Path4/", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) } // TestContextParamsGet tests that a parameter can be parsed from the URL. func TestRouteParamsByName(t *testing.T) { name := "" lastName := "" wild := "" router := New() router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w := PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "john", name) assert.Equal(t, "smith", lastName) assert.Equal(t, "/is/super/great", wild) } // TestContextParamsGet tests that a parameter can be parsed from the URL even with extra slashes. func TestRouteParamsByNameWithExtraSlash(t *testing.T) { name := "" lastName := "" wild := "" router := New() router.RemoveExtraSlash = true router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w := PerformRequest(router, http.MethodGet, "//test//john//smith//is//super//great") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "john", name) assert.Equal(t, "smith", lastName) assert.Equal(t, "/is/super/great", wild) } // TestHandleStaticFile - ensure the static file handles properly func TestRouteStaticFile(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() f, err := ioutil.TempFile(testRoot, "") if err != nil { t.Error(err) } defer os.Remove(f.Name()) _, err = f.WriteString("Gin Web Framework") assert.NoError(t, err) f.Close() dir, filename := filepath.Split(f.Name()) // SETUP gin router := New() router.Static("/using_static", dir) router.StaticFile("/result", f.Name()) w := PerformRequest(router, http.MethodGet, "/using_static/"+filename) w2 := PerformRequest(router, http.MethodGet, "/result") assert.Equal(t, w, w2) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "Gin Web Framework", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename) w4 := PerformRequest(router, http.MethodHead, "/result") assert.Equal(t, w3, w4) assert.Equal(t, http.StatusOK, w3.Code) } // TestHandleStaticFile - ensure the static file handles properly func TestRouteStaticFileFS(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() f, err := ioutil.TempFile(testRoot, "") if err != nil { t.Error(err) } defer os.Remove(f.Name()) _, err = f.WriteString("Gin Web Framework") assert.NoError(t, err) f.Close() dir, filename := filepath.Split(f.Name()) // SETUP gin router := New() router.Static("/using_static", dir) router.StaticFileFS("/result_fs", filename, Dir(dir, false)) w := PerformRequest(router, http.MethodGet, "/using_static/"+filename) w2 := PerformRequest(router, http.MethodGet, "/result_fs") assert.Equal(t, w, w2) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "Gin Web Framework", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename) w4 := PerformRequest(router, http.MethodHead, "/result_fs") assert.Equal(t, w3, w4) assert.Equal(t, http.StatusOK, w3.Code) } // TestHandleStaticDir - ensure the root/sub dir handles properly func TestRouteStaticListingDir(t *testing.T) { router := New() router.StaticFS("/", Dir("./", true)) w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "gin.go") assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } // TestHandleHeadToDir - ensure the root/sub dir handles properly func TestRouteStaticNoListing(t *testing.T) { router := New() router.Static("/", "./") w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusNotFound, w.Code) assert.NotContains(t, w.Body.String(), "gin.go") } func TestRouterMiddlewareAndStatic(t *testing.T) { router := New() static := router.Group("/", func(c *Context) { c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("X-GIN", "Gin Framework") }) static.Static("/", "./") w := PerformRequest(router, http.MethodGet, "/gin.go") assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "package gin") // Content-Type='text/plain; charset=utf-8' when go version <= 1.16, // else, Content-Type='text/x-go; charset=utf-8' assert.NotEqual(t, "", w.Header().Get("Content-Type")) assert.NotEqual(t, w.Header().Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST") assert.Equal(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Expires")) assert.Equal(t, "Gin Framework", w.Header().Get("x-GIN")) } func TestRouteNotAllowedEnabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = true router.POST("/path", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, "responseText", w.Body.String()) assert.Equal(t, http.StatusTeapot, w.Code) } func TestRouteNotAllowedEnabled2(t *testing.T) { router := New() router.HandleMethodNotAllowed = true // add one methodTree to trees router.addRoute(http.MethodPost, "/", HandlersChain{func(_ *Context) {}}) router.GET("/path2", func(c *Context) {}) w := PerformRequest(router, http.MethodPost, "/path2") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } func TestRouteNotAllowedDisabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = false router.POST("/path", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusNotFound, w.Code) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, "404 page not found", w.Body.String()) assert.Equal(t, http.StatusNotFound, w.Code) } func TestRouterNotFoundWithRemoveExtraSlash(t *testing.T) { router := New() router.RemoveExtraSlash = true router.GET("/path", func(c *Context) {}) router.GET("/", func(c *Context) {}) testRoutes := []struct { route string code int location string }{ {"/../path", http.StatusOK, ""}, // CleanPath {"/nope", http.StatusNotFound, ""}, // NotFound } for _, tr := range testRoutes { w := PerformRequest(router, "GET", tr.route) assert.Equal(t, tr.code, w.Code) if w.Code != http.StatusNotFound { assert.Equal(t, tr.location, fmt.Sprint(w.Header().Get("Location"))) } } } func TestRouterNotFound(t *testing.T) { router := New() router.RedirectFixedPath = true router.GET("/path", func(c *Context) {}) router.GET("/dir/", func(c *Context) {}) router.GET("/", func(c *Context) {}) testRoutes := []struct { route string code int location string }{ {"/path/", http.StatusMovedPermanently, "/path"}, // TSR -/ {"/dir", http.StatusMovedPermanently, "/dir/"}, // TSR +/ {"/PATH", http.StatusMovedPermanently, "/path"}, // Fixed Case {"/DIR/", http.StatusMovedPermanently, "/dir/"}, // Fixed Case {"/PATH/", http.StatusMovedPermanently, "/path"}, // Fixed Case -/ {"/DIR", http.StatusMovedPermanently, "/dir/"}, // Fixed Case +/ {"/../path", http.StatusMovedPermanently, "/path"}, // Without CleanPath {"/nope", http.StatusNotFound, ""}, // NotFound } for _, tr := range testRoutes { w := PerformRequest(router, http.MethodGet, tr.route) assert.Equal(t, tr.code, w.Code) if w.Code != http.StatusNotFound { assert.Equal(t, tr.location, fmt.Sprint(w.Header().Get("Location"))) } } // Test custom not found handler var notFound bool router.NoRoute(func(c *Context) { c.AbortWithStatus(http.StatusNotFound) notFound = true }) w := PerformRequest(router, http.MethodGet, "/nope") assert.Equal(t, http.StatusNotFound, w.Code) assert.True(t, notFound) // Test other method than GET (want 307 instead of 301) router.PATCH("/path", func(c *Context) {}) w = PerformRequest(router, http.MethodPatch, "/path/") assert.Equal(t, http.StatusTemporaryRedirect, w.Code) assert.Equal(t, "map[Location:[/path]]", fmt.Sprint(w.Header())) // Test special case where no node for the prefix "/" exists router = New() router.GET("/a", func(c *Context) {}) w = PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusNotFound, w.Code) // Reproduction test for the bug of issue #2843 router = New() router.NoRoute(func(c *Context) { if c.Request.RequestURI == "/login" { c.String(200, "login") } }) router.GET("/logout", func(c *Context) { c.String(200, "logout") }) w = PerformRequest(router, http.MethodGet, "/login") assert.Equal(t, "login", w.Body.String()) w = PerformRequest(router, http.MethodGet, "/logout") assert.Equal(t, "logout", w.Body.String()) } func TestRouterStaticFSNotFound(t *testing.T) { router := New() router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/"))) router.NoRoute(func(c *Context) { c.String(404, "non existent") }) w := PerformRequest(router, http.MethodGet, "/nonexistent") assert.Equal(t, "non existent", w.Body.String()) w = PerformRequest(router, http.MethodHead, "/nonexistent") assert.Equal(t, "non existent", w.Body.String()) } func TestRouterStaticFSFileNotFound(t *testing.T) { router := New() router.StaticFS("/", http.FileSystem(http.Dir("."))) assert.NotPanics(t, func() { PerformRequest(router, http.MethodGet, "/nonexistent") }) } // Reproduction test for the bug of issue #1805 func TestMiddlewareCalledOnceByRouterStaticFSNotFound(t *testing.T) { router := New() // Middleware must be called just only once by per request. middlewareCalledNum := 0 router.Use(func(c *Context) { middlewareCalledNum++ }) router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/"))) // First access PerformRequest(router, http.MethodGet, "/nonexistent") assert.Equal(t, 1, middlewareCalledNum) // Second access PerformRequest(router, http.MethodHead, "/nonexistent") assert.Equal(t, 2, middlewareCalledNum) } func TestRouteRawPath(t *testing.T) { route := New() route.UseRawPath = true route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, name, c.Param("name")) assert.Equal(t, num, c.Param("num")) assert.Equal(t, "Some/Other/Project", name) assert.Equal(t, "222", num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/222") assert.Equal(t, http.StatusOK, w.Code) } func TestRouteRawPathNoUnescape(t *testing.T) { route := New() route.UseRawPath = true route.UnescapePathValues = false route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, name, c.Param("name")) assert.Equal(t, num, c.Param("num")) assert.Equal(t, "Some%2FOther%2FProject", name) assert.Equal(t, "333", num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/333") assert.Equal(t, http.StatusOK, w.Code) } func TestRouteServeErrorWithWriteHeader(t *testing.T) { route := New() route.Use(func(c *Context) { c.Status(421) c.Next() }) w := PerformRequest(route, http.MethodGet, "/NotFound") assert.Equal(t, 421, w.Code) assert.Equal(t, 0, w.Body.Len()) } func TestRouteContextHoldsFullPath(t *testing.T) { router := New() // Test routes routes := []string{ "/simple", "/project/:name", "/", "/news/home", "/news", "/simple-two/one", "/simple-two/one-two", "/project/:name/build/*params", "/project/:name/bui", "/user/:id/status", "/user/:id", "/user/:id/profile", } for _, route := range routes { actualRoute := route router.GET(route, func(c *Context) { // For each defined route context should contain its full path assert.Equal(t, actualRoute, c.FullPath()) c.AbortWithStatus(http.StatusOK) }) } for _, route := range routes { w := PerformRequest(router, http.MethodGet, route) assert.Equal(t, http.StatusOK, w.Code) } // Test not found router.Use(func(c *Context) { // For not found routes full path is empty assert.Equal(t, "", c.FullPath()) }) w := PerformRequest(router, http.MethodGet, "/not-found") assert.Equal(t, http.StatusNotFound, w.Code) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./render/toml.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "github.com/pelletier/go-toml/v2" ) // TOML contains the given interface object. type TOML struct { Data any } var TOMLContentType = []string{"application/toml; charset=utf-8"} // Render (TOML) marshals the given interface object and writes data with custom ContentType. func (r TOML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := toml.Marshal(r.Data) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (TOML) writes TOML ContentType for response. func (r TOML) WriteContentType(w http.ResponseWriter) { writeContentType(w, TOMLContentType) }
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "github.com/pelletier/go-toml/v2" ) // TOML contains the given interface object. type TOML struct { Data any } var TOMLContentType = []string{"application/toml; charset=utf-8"} // Render (TOML) marshals the given interface object and writes data with custom ContentType. func (r TOML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := toml.Marshal(r.Data) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (TOML) writes TOML ContentType for response. func (r TOML) WriteContentType(w http.ResponseWriter) { writeContentType(w, TOMLContentType) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/toml_test.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTOMLBindingBindBody(t *testing.T) { var s struct { Foo string `toml:"foo"` } tomlBody := `foo="FOO"` err := tomlBinding{}.BindBody([]byte(tomlBody), &s) require.NoError(t, err) assert.Equal(t, "FOO", s.Foo) }
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTOMLBindingBindBody(t *testing.T) { var s struct { Foo string `toml:"foo"` } tomlBody := `foo="FOO"` err := tomlBinding{}.BindBody([]byte(tomlBody), &s) require.NoError(t, err) assert.Equal(t, "FOO", s.Foo) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./AUTHORS.md
List of all the awesome people working to make Gin the best Web Framework in Go. ## gin 1.x series authors **Gin Core Team:** Bo-Yi Wu (@appleboy), thinkerou (@thinkerou), Javier Provecho (@javierprovecho) ## gin 0.x series authors **Maintainers:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) ------ People and companies, who have contributed, in alphabetical order. - 178inaba <[email protected]> - A. F <[email protected]> - ABHISHEK SONI <[email protected]> - Abhishek Chanda <[email protected]> - Abner Chen <[email protected]> - AcoNCodes <[email protected]> - Adam Dratwinski <[email protected]> - Adam Mckaig <[email protected]> - Adam Zielinski <[email protected]> - Adonis <[email protected]> - Alan Wang <[email protected]> - Albin Gilles <[email protected]> - Aleksandr Didenko <[email protected]> - Alessandro (Ale) Segala <[email protected]> - Alex <[email protected]> - Alexander <[email protected]> - Alexander Lokhman <[email protected]> - Alexander Melentyev <[email protected]> - Alexander Nyquist <[email protected]> - Allen Ren <[email protected]> - AllinGo <[email protected]> - Ammar Bandukwala <[email protected]> - An Xiao (Luffy) <[email protected]> - Andre Dublin <[email protected]> - Andrew Szeto <[email protected]> - Andrey Abramov <[email protected]> - Andrey Nering <[email protected]> - Andrey Smirnov <[email protected]> - Andrii Bubis <[email protected]> - André Bazaglia <[email protected]> - Andy Pan <[email protected]> - Antoine GIRARD <[email protected]> - Anup Kumar Panwar <[email protected]> - Aravinth Sundaram <[email protected]> - Artem <[email protected]> - Ashwani <[email protected]> - Aurelien Regat-Barrel <[email protected]> - Austin Heap <[email protected]> - Barnabus <[email protected]> - Bo-Yi Wu <[email protected]> - Boris Borshevsky <[email protected]> - Boyi Wu <[email protected]> - BradyBromley <[email protected]> - Brendan Fosberry <[email protected]> - Brian Wigginton <[email protected]> - Carlos Eduardo <[email protected]> - Chad Russell <[email protected]> - Charles <[email protected]> - Christian Muehlhaeuser <[email protected]> - Christian Persson <[email protected]> - Christopher Harrington <[email protected]> - Damon Zhao <[email protected]> - Dan Markham <[email protected]> - Dang Nguyen <[email protected]> - Daniel Krom <[email protected]> - Daniel M. Lambea <[email protected]> - Danieliu <[email protected]> - David Irvine <[email protected]> - David Zhang <[email protected]> - Davor Kapsa <[email protected]> - DeathKing <[email protected]> - Dennis Cho <[email protected]> - Dmitry Dorogin <[email protected]> - Dmitry Kutakov <[email protected]> - Dmitry Sedykh <[email protected]> - Don2Quixote <[email protected]> - Donn Pebe <[email protected]> - Dustin Decker <[email protected]> - Eason Lin <[email protected]> - Edward Betts <[email protected]> - Egor Seredin <[email protected]> - Emmanuel Goh <[email protected]> - Equim <[email protected]> - Eren A. Akyol <[email protected]> - Eric_Lee <[email protected]> - Erik Bender <[email protected]> - Ethan Kan <[email protected]> - Evgeny Persienko <[email protected]> - Faisal Alam <[email protected]> - Fareed Dudhia <[email protected]> - Filip Figiel <[email protected]> - Florian Polster <[email protected]> - Frank Bille <[email protected]> - Franz Bettag <[email protected]> - Ganlv <[email protected]> - Gaozhen Ying <[email protected]> - George Gabolaev <[email protected]> - George Kirilenko <[email protected]> - Georges Varouchas <[email protected]> - Gordon Tyler <[email protected]> - Harindu Perera <[email protected]> - Helios <[email protected]> - Henry Kwan <[email protected]> - Henry Yee <[email protected]> - Himanshu Mishra <[email protected]> - Hiroyuki Tanaka <[email protected]> - Ibraheem Ahmed <[email protected]> - Ignacio Galindo <[email protected]> - Igor H. Vieira <[email protected]> - Ildar1111 <[email protected]> - Iskander (Alex) Sharipov <[email protected]> - Ismail Gjevori <[email protected]> - Ivan Chen <[email protected]> - JINNOUCHI Yasushi <[email protected]> - James Pettyjohn <[email protected]> - Jamie Stackhouse <[email protected]> - Jason Lee <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho Fernandez <[email protected]> - Javier Provecho Fernandez <[email protected]> - Jean-Christophe Lebreton <[email protected]> - Jeff <[email protected]> - Jeremy Loy <[email protected]> - Jim Filippou <[email protected]> - Jimmy Pettersson <[email protected]> - John Bampton <[email protected]> - Johnny Dallas <[email protected]> - Johnny Dallas <[email protected]> - Jonathan (JC) Chen <[email protected]> - Josep Jesus Bigorra Algaba <[email protected]> - Josh Horowitz <[email protected]> - Joshua Loper <[email protected]> - Julien Schmidt <[email protected]> - Jun Kimura <[email protected]> - Justin Beckwith <[email protected]> - Justin Israel <[email protected]> - Justin Mayhew <[email protected]> - Jérôme Laforge <[email protected]> - Kacper Bąk <[email protected]> - Kamron Batman <[email protected]> - Kane Rogers <[email protected]> - Kaushik Neelichetty <[email protected]> - Keiji Yoshida <[email protected]> - Kel Cecil <[email protected]> - Kevin Mulvey <[email protected]> - Kevin Zhu <[email protected]> - Kirill Motkov <[email protected]> - Klemen Sever <[email protected]> - Kristoffer A. Iversen <[email protected]> - Krzysztof Szafrański <[email protected]> - Kumar McMillan <[email protected]> - Kyle Mcgill <[email protected]> - Lanco <[email protected]> - Levi Olson <[email protected]> - Lin Kao-Yuan <[email protected]> - Linus Unnebäck <[email protected]> - Lucas Clemente <[email protected]> - Ludwig Valda Vasquez <[email protected]> - Luis GG <[email protected]> - MW Lim <[email protected]> - Maksimov Sergey <[email protected]> - Manjusaka <[email protected]> - Manu MA <[email protected]> - Manu MA <[email protected]> - Manu Mtz-Almeida <[email protected]> - Manu Mtz.-Almeida <[email protected]> - Manuel Alonso <[email protected]> - Mara Kim <[email protected]> - Mario Kostelac <[email protected]> - Martin Karlsch <[email protected]> - Matt Newberry <[email protected]> - Matt Williams <[email protected]> - Matthieu MOREL <[email protected]> - Max Hilbrunner <[email protected]> - Maxime Soulé <[email protected]> - MetalBreaker <[email protected]> - Michael Puncel <[email protected]> - MichaelDeSteven <[email protected]> - Mike <[email protected]> - Mike Stipicevic <[email protected]> - Miki Tebeka <[email protected]> - Miles <[email protected]> - Mirza Ceric <[email protected]> - Mykyta Semenistyi <[email protected]> - Naoki Takano <[email protected]> - Ngalim Siregar <[email protected]> - Ni Hao <[email protected]> - Nick Gerakines <[email protected]> - Nikifor Seryakov <[email protected]> - Notealot <[email protected]> - Olivier Mengué <[email protected]> - Olivier Robardet <[email protected]> - Pablo Moncada <[email protected]> - Pablo Moncada <[email protected]> - Panmax <[email protected]> - Peperoncino <[email protected]> - Philipp Meinen <[email protected]> - Pierre Massat <[email protected]> - Qt <[email protected]> - Quentin ROYER <[email protected]> - README Bot <[email protected]> - Rafal Zajac <[email protected]> - Rahul Datta Roy <[email protected]> - Rajiv Kilaparti <[email protected]> - Raphael Gavache <[email protected]> - Ray Rodriguez <[email protected]> - Regner Blok-Andersen <[email protected]> - Remco <[email protected]> - Rex Lee(李俊) <[email protected]> - Richard Lee <[email protected]> - Riverside <[email protected]> - Robert Wilkinson <[email protected]> - Rogier Lommers <[email protected]> - Rohan Pai <[email protected]> - Romain Beuque <[email protected]> - Roman Belyakovsky <[email protected]> - Roman Zaynetdinov <[email protected]> - Roman Zaynetdinov <[email protected]> - Ronald Petty <[email protected]> - Ross Wolf <[email protected]> - Roy Lou <[email protected]> - Rubi <[email protected]> - Ryan <[email protected]> - Ryan J. Yoder <[email protected]> - SRK.Lyu <[email protected]> - Sai <[email protected]> - Samuel Abreu <[email protected]> - Santhosh Kumar <[email protected]> - Sasha Melentyev <[email protected]> - Sasha Myasoedov <[email protected]> - Segev Finer <[email protected]> - Sergey Egorov <[email protected]> - Sergey Fedchenko <[email protected]> - Sergey Gonimar <[email protected]> - Sergey Ponomarev <[email protected]> - Serica <[email protected]> - Shamus Taylor <[email protected]> - Shilin Wang <[email protected]> - Shuo <[email protected]> - Skuli Oskarsson <[email protected]> - Snawoot <[email protected]> - Sridhar Ratnakumar <[email protected]> - Steeve Chailloux <[email protected]> - Sudhir Mishra <[email protected]> - Suhas Karanth <[email protected]> - TaeJun Park <[email protected]> - Tatsuya Hoshino <[email protected]> - Tevic <[email protected]> - Tevin Jeffrey <[email protected]> - The Gitter Badger <[email protected]> - Thibault Jamet <[email protected]> - Thomas Boerger <[email protected]> - Thomas Schaffer <[email protected]> - Tommy Chu <[email protected]> - Tudor Roman <[email protected]> - Uwe Dauernheim <[email protected]> - Valentine Oragbakosi <[email protected]> - Vas N <[email protected]> - Vasilyuk Vasiliy <[email protected]> - Victor Castell <[email protected]> - Vince Yuan <[email protected]> - Vyacheslav Dubinin <[email protected]> - Waynerv <[email protected]> - Weilin Shi <[email protected]> - Xudong Cai <[email protected]> - Yasuhiro Matsumoto <[email protected]> - Yehezkiel Syamsuhadi <[email protected]> - Yoshiki Nakagawa <[email protected]> - Yoshiyuki Kinjo <[email protected]> - Yue Yang <[email protected]> - ZYunH <[email protected]> - Zach Newburgh <[email protected]> - Zasda Yusuf Mikail <[email protected]> - ZhangYunHao <[email protected]> - ZhiFeng Hu <[email protected]> - Zhu Xi <[email protected]> - a2tt <[email protected]> - ahuigo <[email protected]> - ali <[email protected]> - aljun <[email protected]> - andrea <[email protected]> - andriikushch <[email protected]> - anoty <[email protected]> - awkj <[email protected]> - axiaoxin <[email protected]> - bbiao <[email protected]> - bestgopher <[email protected]> - betahu <[email protected]> - bigwheel <[email protected]> - bn4t <[email protected]> - bullgare <[email protected]> - chainhelen <[email protected]> - chenyang929 <[email protected]> - chriswhelix <[email protected]> - collinmsn <[email protected]> - cssivision <[email protected]> - danielalves <[email protected]> - delphinus <[email protected]> - dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> - dickeyxxx <[email protected]> - edebernis <[email protected]> - error10 <[email protected]> - esplo <[email protected]> - eudore <[email protected]> - ffhelicopter <[email protected]> - filikos <[email protected]> - forging2012 <[email protected]> - goqihoo <[email protected]> - grapeVine <[email protected]> - guonaihong <[email protected]> - heige <[email protected]> - heige <[email protected]> - hellojukay <[email protected]> - henrylee2cn <[email protected]> - htobenothing <[email protected]> - iamhesir <[email protected]> - ijaa <[email protected]> - ishanray <[email protected]> - ishanray <[email protected]> - itcloudy <[email protected]> - jarodsong6 <[email protected]> - jasonrhansen <[email protected]> - jincheng9 <[email protected]> - joeADSP <[email protected]> - junfengye <[email protected]> - kaiiak <[email protected]> - kebo <[email protected]> - keke <[email protected]> - kishor kunal raj <[email protected]> - kyledinh <[email protected]> - lantw44 <[email protected]> - likakuli <[email protected]> - linfangrong <[email protected]> - linzi <[email protected]> - llgoer <[email protected]> - long-road <[email protected]> - mbesancon <[email protected]> - mehdy <[email protected]> - metal A-wing <[email protected]> - micanzhang <[email protected]> - minarc <[email protected]> - mllu <[email protected]> - mopemoepe <[email protected]> - msoedov <[email protected]> - mstmdev <[email protected]> - novaeye <[email protected]> - olebedev <[email protected]> - phithon <[email protected]> - pjgg <[email protected]> - qm012 <[email protected]> - raymonder jin <[email protected]> - rns <[email protected]> - root@andrea:~# <[email protected]> - sekky0905 <[email protected]> - senhtry <[email protected]> - shadrus <[email protected]> - silasb <[email protected]> - solos <[email protected]> - songjiayang <[email protected]> - sope <[email protected]> - srt180 <[email protected]> - stackerzzq <[email protected]> - sunshineplan <[email protected]> - syssam <[email protected]> - techjanitor <[email protected]> - techjanitor <[email protected]> - thinkerou <[email protected]> - thinkgo <[email protected]> - tsirolnik <[email protected]> - tyltr <[email protected]> - vinhha96 <[email protected]> - voidman <[email protected]> - vz <[email protected]> - wei <[email protected]> - weibaohui <[email protected]> - whirosan <[email protected]> - willnewrelic <[email protected]> - wssccc <[email protected]> - wuhuizuo <[email protected]> - xyb <[email protected]> - y-yagi <[email protected]> - yiranzai <[email protected]> - youzeliang <[email protected]> - yugu <[email protected]> - yuyabe <[email protected]> - zebozhuang <[email protected]> - zero11-0203 <[email protected]> - zesani <[email protected]> - zhanweidu <[email protected]> - zhing <[email protected]> - ziheng <[email protected]> - zzjin <[email protected]> - 森 優太 <[email protected]> - 杰哥 <[email protected]> - 涛叔 <[email protected]> - 市民233 <[email protected]> - 尹宝强 <[email protected]> - 梦溪笔谈 <[email protected]> - 飞雪无情 <[email protected]> - 寻寻觅觅的Gopher <[email protected]>
List of all the awesome people working to make Gin the best Web Framework in Go. ## gin 1.x series authors **Gin Core Team:** Bo-Yi Wu (@appleboy), thinkerou (@thinkerou), Javier Provecho (@javierprovecho) ## gin 0.x series authors **Maintainers:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho) ------ People and companies, who have contributed, in alphabetical order. - 178inaba <[email protected]> - A. F <[email protected]> - ABHISHEK SONI <[email protected]> - Abhishek Chanda <[email protected]> - Abner Chen <[email protected]> - AcoNCodes <[email protected]> - Adam Dratwinski <[email protected]> - Adam Mckaig <[email protected]> - Adam Zielinski <[email protected]> - Adonis <[email protected]> - Alan Wang <[email protected]> - Albin Gilles <[email protected]> - Aleksandr Didenko <[email protected]> - Alessandro (Ale) Segala <[email protected]> - Alex <[email protected]> - Alexander <[email protected]> - Alexander Lokhman <[email protected]> - Alexander Melentyev <[email protected]> - Alexander Nyquist <[email protected]> - Allen Ren <[email protected]> - AllinGo <[email protected]> - Ammar Bandukwala <[email protected]> - An Xiao (Luffy) <[email protected]> - Andre Dublin <[email protected]> - Andrew Szeto <[email protected]> - Andrey Abramov <[email protected]> - Andrey Nering <[email protected]> - Andrey Smirnov <[email protected]> - Andrii Bubis <[email protected]> - André Bazaglia <[email protected]> - Andy Pan <[email protected]> - Antoine GIRARD <[email protected]> - Anup Kumar Panwar <[email protected]> - Aravinth Sundaram <[email protected]> - Artem <[email protected]> - Ashwani <[email protected]> - Aurelien Regat-Barrel <[email protected]> - Austin Heap <[email protected]> - Barnabus <[email protected]> - Bo-Yi Wu <[email protected]> - Boris Borshevsky <[email protected]> - Boyi Wu <[email protected]> - BradyBromley <[email protected]> - Brendan Fosberry <[email protected]> - Brian Wigginton <[email protected]> - Carlos Eduardo <[email protected]> - Chad Russell <[email protected]> - Charles <[email protected]> - Christian Muehlhaeuser <[email protected]> - Christian Persson <[email protected]> - Christopher Harrington <[email protected]> - Damon Zhao <[email protected]> - Dan Markham <[email protected]> - Dang Nguyen <[email protected]> - Daniel Krom <[email protected]> - Daniel M. Lambea <[email protected]> - Danieliu <[email protected]> - David Irvine <[email protected]> - David Zhang <[email protected]> - Davor Kapsa <[email protected]> - DeathKing <[email protected]> - Dennis Cho <[email protected]> - Dmitry Dorogin <[email protected]> - Dmitry Kutakov <[email protected]> - Dmitry Sedykh <[email protected]> - Don2Quixote <[email protected]> - Donn Pebe <[email protected]> - Dustin Decker <[email protected]> - Eason Lin <[email protected]> - Edward Betts <[email protected]> - Egor Seredin <[email protected]> - Emmanuel Goh <[email protected]> - Equim <[email protected]> - Eren A. Akyol <[email protected]> - Eric_Lee <[email protected]> - Erik Bender <[email protected]> - Ethan Kan <[email protected]> - Evgeny Persienko <[email protected]> - Faisal Alam <[email protected]> - Fareed Dudhia <[email protected]> - Filip Figiel <[email protected]> - Florian Polster <[email protected]> - Frank Bille <[email protected]> - Franz Bettag <[email protected]> - Ganlv <[email protected]> - Gaozhen Ying <[email protected]> - George Gabolaev <[email protected]> - George Kirilenko <[email protected]> - Georges Varouchas <[email protected]> - Gordon Tyler <[email protected]> - Harindu Perera <[email protected]> - Helios <[email protected]> - Henry Kwan <[email protected]> - Henry Yee <[email protected]> - Himanshu Mishra <[email protected]> - Hiroyuki Tanaka <[email protected]> - Ibraheem Ahmed <[email protected]> - Ignacio Galindo <[email protected]> - Igor H. Vieira <[email protected]> - Ildar1111 <[email protected]> - Iskander (Alex) Sharipov <[email protected]> - Ismail Gjevori <[email protected]> - Ivan Chen <[email protected]> - JINNOUCHI Yasushi <[email protected]> - James Pettyjohn <[email protected]> - Jamie Stackhouse <[email protected]> - Jason Lee <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho <[email protected]> - Javier Provecho Fernandez <[email protected]> - Javier Provecho Fernandez <[email protected]> - Jean-Christophe Lebreton <[email protected]> - Jeff <[email protected]> - Jeremy Loy <[email protected]> - Jim Filippou <[email protected]> - Jimmy Pettersson <[email protected]> - John Bampton <[email protected]> - Johnny Dallas <[email protected]> - Johnny Dallas <[email protected]> - Jonathan (JC) Chen <[email protected]> - Josep Jesus Bigorra Algaba <[email protected]> - Josh Horowitz <[email protected]> - Joshua Loper <[email protected]> - Julien Schmidt <[email protected]> - Jun Kimura <[email protected]> - Justin Beckwith <[email protected]> - Justin Israel <[email protected]> - Justin Mayhew <[email protected]> - Jérôme Laforge <[email protected]> - Kacper Bąk <[email protected]> - Kamron Batman <[email protected]> - Kane Rogers <[email protected]> - Kaushik Neelichetty <[email protected]> - Keiji Yoshida <[email protected]> - Kel Cecil <[email protected]> - Kevin Mulvey <[email protected]> - Kevin Zhu <[email protected]> - Kirill Motkov <[email protected]> - Klemen Sever <[email protected]> - Kristoffer A. Iversen <[email protected]> - Krzysztof Szafrański <[email protected]> - Kumar McMillan <[email protected]> - Kyle Mcgill <[email protected]> - Lanco <[email protected]> - Levi Olson <[email protected]> - Lin Kao-Yuan <[email protected]> - Linus Unnebäck <[email protected]> - Lucas Clemente <[email protected]> - Ludwig Valda Vasquez <[email protected]> - Luis GG <[email protected]> - MW Lim <[email protected]> - Maksimov Sergey <[email protected]> - Manjusaka <[email protected]> - Manu MA <[email protected]> - Manu MA <[email protected]> - Manu Mtz-Almeida <[email protected]> - Manu Mtz.-Almeida <[email protected]> - Manuel Alonso <[email protected]> - Mara Kim <[email protected]> - Mario Kostelac <[email protected]> - Martin Karlsch <[email protected]> - Matt Newberry <[email protected]> - Matt Williams <[email protected]> - Matthieu MOREL <[email protected]> - Max Hilbrunner <[email protected]> - Maxime Soulé <[email protected]> - MetalBreaker <[email protected]> - Michael Puncel <[email protected]> - MichaelDeSteven <[email protected]> - Mike <[email protected]> - Mike Stipicevic <[email protected]> - Miki Tebeka <[email protected]> - Miles <[email protected]> - Mirza Ceric <[email protected]> - Mykyta Semenistyi <[email protected]> - Naoki Takano <[email protected]> - Ngalim Siregar <[email protected]> - Ni Hao <[email protected]> - Nick Gerakines <[email protected]> - Nikifor Seryakov <[email protected]> - Notealot <[email protected]> - Olivier Mengué <[email protected]> - Olivier Robardet <[email protected]> - Pablo Moncada <[email protected]> - Pablo Moncada <[email protected]> - Panmax <[email protected]> - Peperoncino <[email protected]> - Philipp Meinen <[email protected]> - Pierre Massat <[email protected]> - Qt <[email protected]> - Quentin ROYER <[email protected]> - README Bot <[email protected]> - Rafal Zajac <[email protected]> - Rahul Datta Roy <[email protected]> - Rajiv Kilaparti <[email protected]> - Raphael Gavache <[email protected]> - Ray Rodriguez <[email protected]> - Regner Blok-Andersen <[email protected]> - Remco <[email protected]> - Rex Lee(李俊) <[email protected]> - Richard Lee <[email protected]> - Riverside <[email protected]> - Robert Wilkinson <[email protected]> - Rogier Lommers <[email protected]> - Rohan Pai <[email protected]> - Romain Beuque <[email protected]> - Roman Belyakovsky <[email protected]> - Roman Zaynetdinov <[email protected]> - Roman Zaynetdinov <[email protected]> - Ronald Petty <[email protected]> - Ross Wolf <[email protected]> - Roy Lou <[email protected]> - Rubi <[email protected]> - Ryan <[email protected]> - Ryan J. Yoder <[email protected]> - SRK.Lyu <[email protected]> - Sai <[email protected]> - Samuel Abreu <[email protected]> - Santhosh Kumar <[email protected]> - Sasha Melentyev <[email protected]> - Sasha Myasoedov <[email protected]> - Segev Finer <[email protected]> - Sergey Egorov <[email protected]> - Sergey Fedchenko <[email protected]> - Sergey Gonimar <[email protected]> - Sergey Ponomarev <[email protected]> - Serica <[email protected]> - Shamus Taylor <[email protected]> - Shilin Wang <[email protected]> - Shuo <[email protected]> - Skuli Oskarsson <[email protected]> - Snawoot <[email protected]> - Sridhar Ratnakumar <[email protected]> - Steeve Chailloux <[email protected]> - Sudhir Mishra <[email protected]> - Suhas Karanth <[email protected]> - TaeJun Park <[email protected]> - Tatsuya Hoshino <[email protected]> - Tevic <[email protected]> - Tevin Jeffrey <[email protected]> - The Gitter Badger <[email protected]> - Thibault Jamet <[email protected]> - Thomas Boerger <[email protected]> - Thomas Schaffer <[email protected]> - Tommy Chu <[email protected]> - Tudor Roman <[email protected]> - Uwe Dauernheim <[email protected]> - Valentine Oragbakosi <[email protected]> - Vas N <[email protected]> - Vasilyuk Vasiliy <[email protected]> - Victor Castell <[email protected]> - Vince Yuan <[email protected]> - Vyacheslav Dubinin <[email protected]> - Waynerv <[email protected]> - Weilin Shi <[email protected]> - Xudong Cai <[email protected]> - Yasuhiro Matsumoto <[email protected]> - Yehezkiel Syamsuhadi <[email protected]> - Yoshiki Nakagawa <[email protected]> - Yoshiyuki Kinjo <[email protected]> - Yue Yang <[email protected]> - ZYunH <[email protected]> - Zach Newburgh <[email protected]> - Zasda Yusuf Mikail <[email protected]> - ZhangYunHao <[email protected]> - ZhiFeng Hu <[email protected]> - Zhu Xi <[email protected]> - a2tt <[email protected]> - ahuigo <[email protected]> - ali <[email protected]> - aljun <[email protected]> - andrea <[email protected]> - andriikushch <[email protected]> - anoty <[email protected]> - awkj <[email protected]> - axiaoxin <[email protected]> - bbiao <[email protected]> - bestgopher <[email protected]> - betahu <[email protected]> - bigwheel <[email protected]> - bn4t <[email protected]> - bullgare <[email protected]> - chainhelen <[email protected]> - chenyang929 <[email protected]> - chriswhelix <[email protected]> - collinmsn <[email protected]> - cssivision <[email protected]> - danielalves <[email protected]> - delphinus <[email protected]> - dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> - dickeyxxx <[email protected]> - edebernis <[email protected]> - error10 <[email protected]> - esplo <[email protected]> - eudore <[email protected]> - ffhelicopter <[email protected]> - filikos <[email protected]> - forging2012 <[email protected]> - goqihoo <[email protected]> - grapeVine <[email protected]> - guonaihong <[email protected]> - heige <[email protected]> - heige <[email protected]> - hellojukay <[email protected]> - henrylee2cn <[email protected]> - htobenothing <[email protected]> - iamhesir <[email protected]> - ijaa <[email protected]> - ishanray <[email protected]> - ishanray <[email protected]> - itcloudy <[email protected]> - jarodsong6 <[email protected]> - jasonrhansen <[email protected]> - jincheng9 <[email protected]> - joeADSP <[email protected]> - junfengye <[email protected]> - kaiiak <[email protected]> - kebo <[email protected]> - keke <[email protected]> - kishor kunal raj <[email protected]> - kyledinh <[email protected]> - lantw44 <[email protected]> - likakuli <[email protected]> - linfangrong <[email protected]> - linzi <[email protected]> - llgoer <[email protected]> - long-road <[email protected]> - mbesancon <[email protected]> - mehdy <[email protected]> - metal A-wing <[email protected]> - micanzhang <[email protected]> - minarc <[email protected]> - mllu <[email protected]> - mopemoepe <[email protected]> - msoedov <[email protected]> - mstmdev <[email protected]> - novaeye <[email protected]> - olebedev <[email protected]> - phithon <[email protected]> - pjgg <[email protected]> - qm012 <[email protected]> - raymonder jin <[email protected]> - rns <[email protected]> - root@andrea:~# <[email protected]> - sekky0905 <[email protected]> - senhtry <[email protected]> - shadrus <[email protected]> - silasb <[email protected]> - solos <[email protected]> - songjiayang <[email protected]> - sope <[email protected]> - srt180 <[email protected]> - stackerzzq <[email protected]> - sunshineplan <[email protected]> - syssam <[email protected]> - techjanitor <[email protected]> - techjanitor <[email protected]> - thinkerou <[email protected]> - thinkgo <[email protected]> - tsirolnik <[email protected]> - tyltr <[email protected]> - vinhha96 <[email protected]> - voidman <[email protected]> - vz <[email protected]> - wei <[email protected]> - weibaohui <[email protected]> - whirosan <[email protected]> - willnewrelic <[email protected]> - wssccc <[email protected]> - wuhuizuo <[email protected]> - xyb <[email protected]> - y-yagi <[email protected]> - yiranzai <[email protected]> - youzeliang <[email protected]> - yugu <[email protected]> - yuyabe <[email protected]> - zebozhuang <[email protected]> - zero11-0203 <[email protected]> - zesani <[email protected]> - zhanweidu <[email protected]> - zhing <[email protected]> - ziheng <[email protected]> - zzjin <[email protected]> - 森 優太 <[email protected]> - 杰哥 <[email protected]> - 涛叔 <[email protected]> - 市民233 <[email protected]> - 尹宝强 <[email protected]> - 梦溪笔谈 <[email protected]> - 飞雪无情 <[email protected]> - 寻寻觅觅的Gopher <[email protected]>
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./utils.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "encoding/xml" "net/http" "os" "path" "reflect" "runtime" "strings" "unicode" ) // BindKey indicates a default bind key. const BindKey = "_gin-gonic/gin/bindkey" // Bind is a helper function for given interface object and returns a Gin middleware. func Bind(val any) HandlerFunc { value := reflect.ValueOf(val) if value.Kind() == reflect.Ptr { panic(`Bind struct can not be a pointer. Example: Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{}) `) } typ := value.Type() return func(c *Context) { obj := reflect.New(typ).Interface() if c.Bind(obj) == nil { c.Set(BindKey, obj) } } } // WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware. func WrapF(f http.HandlerFunc) HandlerFunc { return func(c *Context) { f(c.Writer, c.Request) } } // WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. func WrapH(h http.Handler) HandlerFunc { return func(c *Context) { h.ServeHTTP(c.Writer, c.Request) } } // H is a shortcut for map[string]interface{} type H map[string]any // MarshalXML allows type H to be used with xml.Marshal. func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } return e.EncodeToken(xml.EndElement{Name: start.Name}) } func assert1(guard bool, text string) { if !guard { panic(text) } } func filterFlags(content string) string { for i, char := range content { if char == ' ' || char == ';' { return content[:i] } } return content } func chooseData(custom, wildcard any) any { if custom != nil { return custom } if wildcard != nil { return wildcard } panic("negotiation config is invalid") } func parseAccept(acceptHeader string) []string { parts := strings.Split(acceptHeader, ",") out := make([]string, 0, len(parts)) for _, part := range parts { if i := strings.IndexByte(part, ';'); i > 0 { part = part[:i] } if part = strings.TrimSpace(part); part != "" { out = append(out, part) } } return out } func lastChar(str string) uint8 { if str == "" { panic("The length of the string can't be 0") } return str[len(str)-1] } func nameOfFunction(f any) string { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } func joinPaths(absolutePath, relativePath string) string { if relativePath == "" { return absolutePath } finalPath := path.Join(absolutePath, relativePath) if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' { return finalPath + "/" } return finalPath } func resolveAddress(addr []string) string { switch len(addr) { case 0: if port := os.Getenv("PORT"); port != "" { debugPrint("Environment variable PORT=\"%s\"", port) return ":" + port } debugPrint("Environment variable PORT is undefined. Using port :8080 by default") return ":8080" case 1: return addr[0] default: panic("too many parameters") } } // https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters func isASCII(s string) bool { for i := 0; i < len(s); i++ { if s[i] > unicode.MaxASCII { return false } } return true }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "encoding/xml" "net/http" "os" "path" "reflect" "runtime" "strings" "unicode" ) // BindKey indicates a default bind key. const BindKey = "_gin-gonic/gin/bindkey" // Bind is a helper function for given interface object and returns a Gin middleware. func Bind(val any) HandlerFunc { value := reflect.ValueOf(val) if value.Kind() == reflect.Ptr { panic(`Bind struct can not be a pointer. Example: Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{}) `) } typ := value.Type() return func(c *Context) { obj := reflect.New(typ).Interface() if c.Bind(obj) == nil { c.Set(BindKey, obj) } } } // WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware. func WrapF(f http.HandlerFunc) HandlerFunc { return func(c *Context) { f(c.Writer, c.Request) } } // WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. func WrapH(h http.Handler) HandlerFunc { return func(c *Context) { h.ServeHTTP(c.Writer, c.Request) } } // H is a shortcut for map[string]interface{} type H map[string]any // MarshalXML allows type H to be used with xml.Marshal. func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } return e.EncodeToken(xml.EndElement{Name: start.Name}) } func assert1(guard bool, text string) { if !guard { panic(text) } } func filterFlags(content string) string { for i, char := range content { if char == ' ' || char == ';' { return content[:i] } } return content } func chooseData(custom, wildcard any) any { if custom != nil { return custom } if wildcard != nil { return wildcard } panic("negotiation config is invalid") } func parseAccept(acceptHeader string) []string { parts := strings.Split(acceptHeader, ",") out := make([]string, 0, len(parts)) for _, part := range parts { if i := strings.IndexByte(part, ';'); i > 0 { part = part[:i] } if part = strings.TrimSpace(part); part != "" { out = append(out, part) } } return out } func lastChar(str string) uint8 { if str == "" { panic("The length of the string can't be 0") } return str[len(str)-1] } func nameOfFunction(f any) string { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } func joinPaths(absolutePath, relativePath string) string { if relativePath == "" { return absolutePath } finalPath := path.Join(absolutePath, relativePath) if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' { return finalPath + "/" } return finalPath } func resolveAddress(addr []string) string { switch len(addr) { case 0: if port := os.Getenv("PORT"); port != "" { debugPrint("Environment variable PORT=\"%s\"", port) return ":" + port } debugPrint("Environment variable PORT is undefined. Using port :8080 by default") return ":8080" case 1: return addr[0] default: panic("too many parameters") } } // https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters func isASCII(s string) bool { for i := 0; i < len(s); i++ { if s[i] > unicode.MaxASCII { return false } } return true }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./version.go
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin // Version is the current gin framework's version. const Version = "v1.8.1"
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin // Version is the current gin framework's version. const Version = "v1.8.1"
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/default_validator.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "fmt" "reflect" "strings" "sync" "github.com/go-playground/validator/v10" ) type defaultValidator struct { once sync.Once validate *validator.Validate } type SliceValidationError []error // Error concatenates all error elements in SliceValidationError into a single string separated by \n. func (err SliceValidationError) Error() string { n := len(err) switch n { case 0: return "" default: var b strings.Builder if err[0] != nil { fmt.Fprintf(&b, "[%d]: %s", 0, err[0].Error()) } if n > 1 { for i := 1; i < n; i++ { if err[i] != nil { b.WriteString("\n") fmt.Fprintf(&b, "[%d]: %s", i, err[i].Error()) } } } return b.String() } } var _ StructValidator = &defaultValidator{} // ValidateStruct receives any kind of type, but only performed struct or pointer to struct type. func (v *defaultValidator) ValidateStruct(obj any) error { if obj == nil { return nil } value := reflect.ValueOf(obj) switch value.Kind() { case reflect.Ptr: return v.ValidateStruct(value.Elem().Interface()) case reflect.Struct: return v.validateStruct(obj) case reflect.Slice, reflect.Array: count := value.Len() validateRet := make(SliceValidationError, 0) for i := 0; i < count; i++ { if err := v.ValidateStruct(value.Index(i).Interface()); err != nil { validateRet = append(validateRet, err) } } if len(validateRet) == 0 { return nil } return validateRet default: return nil } } // validateStruct receives struct type func (v *defaultValidator) validateStruct(obj any) error { v.lazyinit() return v.validate.Struct(obj) } // Engine returns the underlying validator engine which powers the default // Validator instance. This is useful if you want to register custom validations // or struct level validations. See validator GoDoc for more info - // https://pkg.go.dev/github.com/go-playground/validator/v10 func (v *defaultValidator) Engine() any { v.lazyinit() return v.validate } func (v *defaultValidator) lazyinit() { v.once.Do(func() { v.validate = validator.New() v.validate.SetTagName("binding") }) }
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "fmt" "reflect" "strings" "sync" "github.com/go-playground/validator/v10" ) type defaultValidator struct { once sync.Once validate *validator.Validate } type SliceValidationError []error // Error concatenates all error elements in SliceValidationError into a single string separated by \n. func (err SliceValidationError) Error() string { n := len(err) switch n { case 0: return "" default: var b strings.Builder if err[0] != nil { fmt.Fprintf(&b, "[%d]: %s", 0, err[0].Error()) } if n > 1 { for i := 1; i < n; i++ { if err[i] != nil { b.WriteString("\n") fmt.Fprintf(&b, "[%d]: %s", i, err[i].Error()) } } } return b.String() } } var _ StructValidator = &defaultValidator{} // ValidateStruct receives any kind of type, but only performed struct or pointer to struct type. func (v *defaultValidator) ValidateStruct(obj any) error { if obj == nil { return nil } value := reflect.ValueOf(obj) switch value.Kind() { case reflect.Ptr: return v.ValidateStruct(value.Elem().Interface()) case reflect.Struct: return v.validateStruct(obj) case reflect.Slice, reflect.Array: count := value.Len() validateRet := make(SliceValidationError, 0) for i := 0; i < count; i++ { if err := v.ValidateStruct(value.Index(i).Interface()); err != nil { validateRet = append(validateRet, err) } } if len(validateRet) == 0 { return nil } return validateRet default: return nil } } // validateStruct receives struct type func (v *defaultValidator) validateStruct(obj any) error { v.lazyinit() return v.validate.Struct(obj) } // Engine returns the underlying validator engine which powers the default // Validator instance. This is useful if you want to register custom validations // or struct level validations. See validator GoDoc for more info - // https://pkg.go.dev/github.com/go-playground/validator/v10 func (v *defaultValidator) Engine() any { v.lazyinit() return v.validate } func (v *defaultValidator) lazyinit() { v.once.Do(func() { v.validate = validator.New() v.validate.SetTagName("binding") }) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./errors_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "fmt" "testing" "github.com/gin-gonic/gin/internal/json" "github.com/stretchr/testify/assert" ) func TestError(t *testing.T) { baseError := errors.New("test error") err := &Error{ Err: baseError, Type: ErrorTypePrivate, } assert.Equal(t, err.Error(), baseError.Error()) assert.Equal(t, H{"error": baseError.Error()}, err.JSON()) assert.Equal(t, err.SetType(ErrorTypePublic), err) assert.Equal(t, ErrorTypePublic, err.Type) assert.Equal(t, err.SetMeta("some data"), err) assert.Equal(t, "some data", err.Meta) assert.Equal(t, H{ "error": baseError.Error(), "meta": "some data", }, err.JSON()) jsonBytes, _ := json.Marshal(err) assert.Equal(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes)) err.SetMeta(H{ //nolint: errcheck "status": "200", "data": "some data", }) assert.Equal(t, H{ "error": baseError.Error(), "status": "200", "data": "some data", }, err.JSON()) err.SetMeta(H{ //nolint: errcheck "error": "custom error", "status": "200", "data": "some data", }) assert.Equal(t, H{ "error": "custom error", "status": "200", "data": "some data", }, err.JSON()) type customError struct { status string data string } err.SetMeta(customError{status: "200", data: "other data"}) //nolint: errcheck assert.Equal(t, customError{status: "200", data: "other data"}, err.JSON()) } func TestErrorSlice(t *testing.T) { errs := errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"}, {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}}, } assert.Equal(t, errs, errs.ByType(ErrorTypeAny)) assert.Equal(t, "third", errs.Last().Error()) assert.Equal(t, []string{"first", "second", "third"}, errs.Errors()) assert.Equal(t, []string{"third"}, errs.ByType(ErrorTypePublic).Errors()) assert.Equal(t, []string{"first", "second"}, errs.ByType(ErrorTypePrivate).Errors()) assert.Equal(t, []string{"first", "second", "third"}, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors()) assert.Empty(t, errs.ByType(ErrorTypeBind)) assert.Empty(t, errs.ByType(ErrorTypeBind).String()) assert.Equal(t, `Error #01: first Error #02: second Meta: some data Error #03: third Meta: map[status:400] `, errs.String()) assert.Equal(t, []any{ H{"error": "first"}, H{"error": "second", "meta": "some data"}, H{"error": "third", "status": "400"}, }, errs.JSON()) jsonBytes, _ := json.Marshal(errs) assert.Equal(t, "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]", string(jsonBytes)) errs = errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, } assert.Equal(t, H{"error": "first"}, errs.JSON()) jsonBytes, _ = json.Marshal(errs) assert.Equal(t, "{\"error\":\"first\"}", string(jsonBytes)) errs = errorMsgs{} assert.Nil(t, errs.Last()) assert.Nil(t, errs.JSON()) assert.Empty(t, errs.String()) } type TestErr string func (e TestErr) Error() string { return string(e) } // TestErrorUnwrap tests the behavior of gin.Error with "errors.Is()" and "errors.As()". // "errors.Is()" and "errors.As()" have been added to the standard library in go 1.13. func TestErrorUnwrap(t *testing.T) { innerErr := TestErr("some error") // 2 layers of wrapping : use 'fmt.Errorf("%w")' to wrap a gin.Error{}, which itself wraps innerErr err := fmt.Errorf("wrapped: %w", &Error{ Err: innerErr, Type: ErrorTypeAny, }) // check that 'errors.Is()' and 'errors.As()' behave as expected : assert.True(t, errors.Is(err, innerErr)) var testErr TestErr assert.True(t, errors.As(err, &testErr)) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "fmt" "testing" "github.com/gin-gonic/gin/internal/json" "github.com/stretchr/testify/assert" ) func TestError(t *testing.T) { baseError := errors.New("test error") err := &Error{ Err: baseError, Type: ErrorTypePrivate, } assert.Equal(t, err.Error(), baseError.Error()) assert.Equal(t, H{"error": baseError.Error()}, err.JSON()) assert.Equal(t, err.SetType(ErrorTypePublic), err) assert.Equal(t, ErrorTypePublic, err.Type) assert.Equal(t, err.SetMeta("some data"), err) assert.Equal(t, "some data", err.Meta) assert.Equal(t, H{ "error": baseError.Error(), "meta": "some data", }, err.JSON()) jsonBytes, _ := json.Marshal(err) assert.Equal(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes)) err.SetMeta(H{ //nolint: errcheck "status": "200", "data": "some data", }) assert.Equal(t, H{ "error": baseError.Error(), "status": "200", "data": "some data", }, err.JSON()) err.SetMeta(H{ //nolint: errcheck "error": "custom error", "status": "200", "data": "some data", }) assert.Equal(t, H{ "error": "custom error", "status": "200", "data": "some data", }, err.JSON()) type customError struct { status string data string } err.SetMeta(customError{status: "200", data: "other data"}) //nolint: errcheck assert.Equal(t, customError{status: "200", data: "other data"}, err.JSON()) } func TestErrorSlice(t *testing.T) { errs := errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"}, {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}}, } assert.Equal(t, errs, errs.ByType(ErrorTypeAny)) assert.Equal(t, "third", errs.Last().Error()) assert.Equal(t, []string{"first", "second", "third"}, errs.Errors()) assert.Equal(t, []string{"third"}, errs.ByType(ErrorTypePublic).Errors()) assert.Equal(t, []string{"first", "second"}, errs.ByType(ErrorTypePrivate).Errors()) assert.Equal(t, []string{"first", "second", "third"}, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors()) assert.Empty(t, errs.ByType(ErrorTypeBind)) assert.Empty(t, errs.ByType(ErrorTypeBind).String()) assert.Equal(t, `Error #01: first Error #02: second Meta: some data Error #03: third Meta: map[status:400] `, errs.String()) assert.Equal(t, []any{ H{"error": "first"}, H{"error": "second", "meta": "some data"}, H{"error": "third", "status": "400"}, }, errs.JSON()) jsonBytes, _ := json.Marshal(errs) assert.Equal(t, "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]", string(jsonBytes)) errs = errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, } assert.Equal(t, H{"error": "first"}, errs.JSON()) jsonBytes, _ = json.Marshal(errs) assert.Equal(t, "{\"error\":\"first\"}", string(jsonBytes)) errs = errorMsgs{} assert.Nil(t, errs.Last()) assert.Nil(t, errs.JSON()) assert.Empty(t, errs.String()) } type TestErr string func (e TestErr) Error() string { return string(e) } // TestErrorUnwrap tests the behavior of gin.Error with "errors.Is()" and "errors.As()". // "errors.Is()" and "errors.As()" have been added to the standard library in go 1.13. func TestErrorUnwrap(t *testing.T) { innerErr := TestErr("some error") // 2 layers of wrapping : use 'fmt.Errorf("%w")' to wrap a gin.Error{}, which itself wraps innerErr err := fmt.Errorf("wrapped: %w", &Error{ Err: innerErr, Type: ErrorTypeAny, }) // check that 'errors.Is()' and 'errors.As()' behave as expected : assert.True(t, errors.Is(err, innerErr)) var testErr TestErr assert.True(t, errors.As(err, &testErr)) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./tree.go
// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "bytes" "net/url" "strings" "unicode" "unicode/utf8" "github.com/gin-gonic/gin/internal/bytesconv" ) var ( strColon = []byte(":") strStar = []byte("*") strSlash = []byte("/") ) // Param is a single URL parameter, consisting of a key and a value. type Param struct { Key string Value string } // Params is a Param-slice, as returned by the router. // The slice is ordered, the first URL parameter is also the first slice value. // It is therefore safe to read values by the index. type Params []Param // Get returns the value of the first Param which key matches the given name and a boolean true. // If no matching Param is found, an empty string is returned and a boolean false . func (ps Params) Get(name string) (string, bool) { for _, entry := range ps { if entry.Key == name { return entry.Value, true } } return "", false } // ByName returns the value of the first Param which key matches the given name. // If no matching Param is found, an empty string is returned. func (ps Params) ByName(name string) (va string) { va, _ = ps.Get(name) return } type methodTree struct { method string root *node } type methodTrees []methodTree func (trees methodTrees) get(method string) *node { for _, tree := range trees { if tree.method == method { return tree.root } } return nil } func min(a, b int) int { if a <= b { return a } return b } func longestCommonPrefix(a, b string) int { i := 0 max := min(len(a), len(b)) for i < max && a[i] == b[i] { i++ } return i } // addChild will add a child node, keeping wildcardChild at the end func (n *node) addChild(child *node) { if n.wildChild && len(n.children) > 0 { wildcardChild := n.children[len(n.children)-1] n.children = append(n.children[:len(n.children)-1], child, wildcardChild) } else { n.children = append(n.children, child) } } func countParams(path string) uint16 { var n uint16 s := bytesconv.StringToBytes(path) n += uint16(bytes.Count(s, strColon)) n += uint16(bytes.Count(s, strStar)) return n } func countSections(path string) uint16 { s := bytesconv.StringToBytes(path) return uint16(bytes.Count(s, strSlash)) } type nodeType uint8 const ( root nodeType = iota + 1 param catchAll ) type node struct { path string indices string wildChild bool nType nodeType priority uint32 children []*node // child nodes, at most 1 :param style node at the end of the array handlers HandlersChain fullPath string } // Increments priority of the given child and reorders if necessary func (n *node) incrementChildPrio(pos int) int { cs := n.children cs[pos].priority++ prio := cs[pos].priority // Adjust position (move to front) newPos := pos for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- { // Swap node positions cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1] } // Build new index char string if newPos != pos { n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty n.indices[pos:pos+1] + // The index char we move n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos' } return newPos } // addRoute adds a node with the given handle to the path. // Not concurrency-safe! func (n *node) addRoute(path string, handlers HandlersChain) { fullPath := path n.priority++ // Empty tree if len(n.path) == 0 && len(n.children) == 0 { n.insertChild(path, fullPath, handlers) n.nType = root return } parentFullPathIndex := 0 walk: for { // Find the longest common prefix. // This also implies that the common prefix contains no ':' or '*' // since the existing key can't contain those chars. i := longestCommonPrefix(path, n.path) // Split edge if i < len(n.path) { child := node{ path: n.path[i:], wildChild: n.wildChild, indices: n.indices, children: n.children, handlers: n.handlers, priority: n.priority - 1, fullPath: n.fullPath, } n.children = []*node{&child} // []byte for proper unicode char conversion, see #65 n.indices = bytesconv.BytesToString([]byte{n.path[i]}) n.path = path[:i] n.handlers = nil n.wildChild = false n.fullPath = fullPath[:parentFullPathIndex+i] } // Make new node a child of this node if i < len(path) { path = path[i:] c := path[0] // '/' after param if n.nType == param && c == '/' && len(n.children) == 1 { parentFullPathIndex += len(n.path) n = n.children[0] n.priority++ continue walk } // Check if a child with the next path byte exists for i, max := 0, len(n.indices); i < max; i++ { if c == n.indices[i] { parentFullPathIndex += len(n.path) i = n.incrementChildPrio(i) n = n.children[i] continue walk } } // Otherwise insert it if c != ':' && c != '*' && n.nType != catchAll { // []byte for proper unicode char conversion, see #65 n.indices += bytesconv.BytesToString([]byte{c}) child := &node{ fullPath: fullPath, } n.addChild(child) n.incrementChildPrio(len(n.indices) - 1) n = child } else if n.wildChild { // inserting a wildcard node, need to check if it conflicts with the existing wildcard n = n.children[len(n.children)-1] n.priority++ // Check if the wildcard matches if len(path) >= len(n.path) && n.path == path[:len(n.path)] && // Adding a child to a catchAll is not possible n.nType != catchAll && // Check for longer wildcard, e.g. :name and :names (len(n.path) >= len(path) || path[len(n.path)] == '/') { continue walk } // Wildcard conflict pathSeg := path if n.nType != catchAll { pathSeg = strings.SplitN(pathSeg, "/", 2)[0] } prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path panic("'" + pathSeg + "' in new path '" + fullPath + "' conflicts with existing wildcard '" + n.path + "' in existing prefix '" + prefix + "'") } n.insertChild(path, fullPath, handlers) return } // Otherwise add handle to current node if n.handlers != nil { panic("handlers are already registered for path '" + fullPath + "'") } n.handlers = handlers n.fullPath = fullPath return } } // Search for a wildcard segment and check the name for invalid characters. // Returns -1 as index, if no wildcard was found. func findWildcard(path string) (wildcard string, i int, valid bool) { // Find start for start, c := range []byte(path) { // A wildcard starts with ':' (param) or '*' (catch-all) if c != ':' && c != '*' { continue } // Find end and check for invalid characters valid = true for end, c := range []byte(path[start+1:]) { switch c { case '/': return path[start : start+1+end], start, valid case ':', '*': valid = false } } return path[start:], start, valid } return "", -1, false } func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) { for { // Find prefix until first wildcard wildcard, i, valid := findWildcard(path) if i < 0 { // No wildcard found break } // The wildcard name must only contain one ':' or '*' character if !valid { panic("only one wildcard per path segment is allowed, has: '" + wildcard + "' in path '" + fullPath + "'") } // check if the wildcard has a name if len(wildcard) < 2 { panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") } if wildcard[0] == ':' { // param if i > 0 { // Insert prefix before the current wildcard n.path = path[:i] path = path[i:] } child := &node{ nType: param, path: wildcard, fullPath: fullPath, } n.addChild(child) n.wildChild = true n = child n.priority++ // if the path doesn't end with the wildcard, then there // will be another subpath starting with '/' if len(wildcard) < len(path) { path = path[len(wildcard):] child := &node{ priority: 1, fullPath: fullPath, } n.addChild(child) n = child continue } // Otherwise we're done. Insert the handle in the new leaf n.handlers = handlers return } // catchAll if i+len(wildcard) != len(path) { panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") } if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { pathSeg := strings.SplitN(n.children[0].path, "/", 2)[0] panic("catch-all wildcard '" + path + "' in new path '" + fullPath + "' conflicts with existing path segment '" + pathSeg + "' in existing prefix '" + n.path + pathSeg + "'") } // currently fixed width 1 for '/' i-- if path[i] != '/' { panic("no / before catch-all in path '" + fullPath + "'") } n.path = path[:i] // First node: catchAll node with empty path child := &node{ wildChild: true, nType: catchAll, fullPath: fullPath, } n.addChild(child) n.indices = string('/') n = child n.priority++ // second node: node holding the variable child = &node{ path: path[i:], nType: catchAll, handlers: handlers, priority: 1, fullPath: fullPath, } n.children = []*node{child} return } // If no wildcard was found, simply insert the path and handle n.path = path n.handlers = handlers n.fullPath = fullPath } // nodeValue holds return values of (*Node).getValue method type nodeValue struct { handlers HandlersChain params *Params tsr bool fullPath string } type skippedNode struct { path string node *node paramsCount int16 } // Returns the handle registered with the given path (key). The values of // wildcards are saved to a map. // If no handle can be found, a TSR (trailing slash redirect) recommendation is // made if a handle exists with an extra (without the) trailing slash for the // given path. func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) { var globalParamsCount int16 walk: // Outer loop for walking the tree for { prefix := n.path if len(path) > len(prefix) { if path[:len(prefix)] == prefix { path = path[len(prefix):] // Try all the non-wildcard children first by matching the indices idxc := path[0] for i, c := range []byte(n.indices) { if c == idxc { // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild if n.wildChild { index := len(*skippedNodes) *skippedNodes = (*skippedNodes)[:index+1] (*skippedNodes)[index] = skippedNode{ path: prefix + path, node: &node{ path: n.path, wildChild: n.wildChild, nType: n.nType, priority: n.priority, children: n.children, handlers: n.handlers, fullPath: n.fullPath, }, paramsCount: globalParamsCount, } } n = n.children[i] continue walk } } if !n.wildChild { // If the path at the end of the loop is not equal to '/' and the current node has no child nodes // the current node needs to roll back to last valid skippedNode if path != "/" { for l := len(*skippedNodes); l > 0; { skippedNode := (*skippedNodes)[l-1] *skippedNodes = (*skippedNodes)[:l-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } // Nothing found. // We can recommend to redirect to the same URL without a // trailing slash if a leaf exists for that path. value.tsr = path == "/" && n.handlers != nil return } // Handle wildcard child, which is always at the end of the array n = n.children[len(n.children)-1] globalParamsCount++ switch n.nType { case param: // fix truncate the parameter // tree_test.go line: 204 // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Save param value if params != nil && cap(*params) > 0 { if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path[:end] if unescape { if v, err := url.QueryUnescape(val); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[1:], Value: val, } } // we need to go deeper! if end < len(path) { if len(n.children) > 0 { path = path[end:] n = n.children[0] continue walk } // ... but we can't value.tsr = len(path) == end+1 return } if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return } if len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists for TSR recommendation n = n.children[0] value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/") } return case catchAll: // Save param value if params != nil { if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path if unescape { if v, err := url.QueryUnescape(path); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[2:], Value: val, } } value.handlers = n.handlers value.fullPath = n.fullPath return default: panic("invalid node type") } } } if path == prefix { // If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node // the current node needs to roll back to last valid skippedNode if n.handlers == nil && path != "/" { for l := len(*skippedNodes); l > 0; { skippedNode := (*skippedNodes)[l-1] *skippedNodes = (*skippedNodes)[:l-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } // n = latestNode.children[len(latestNode.children)-1] } // We should have reached the node containing the handle. // Check if this node has a handle registered. if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return } // If there is no handle for this route, but this route has a // wildcard child, there must be a handle for this path with an // additional trailing slash if path == "/" && n.wildChild && n.nType != root { value.tsr = true return } // No handle found. Check if a handle for this path + a // trailing slash exists for trailing slash recommendation for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] value.tsr = (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) return } } return } // Nothing found. We can recommend to redirect to the same URL with an // extra trailing slash if a leaf exists for that path value.tsr = path == "/" || (len(prefix) == len(path)+1 && prefix[len(path)] == '/' && path == prefix[:len(prefix)-1] && n.handlers != nil) // roll back to last valid skippedNode if !value.tsr && path != "/" { for l := len(*skippedNodes); l > 0; { skippedNode := (*skippedNodes)[l-1] *skippedNodes = (*skippedNodes)[:l-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } return } } // Makes a case-insensitive lookup of the given path and tries to find a handler. // It can optionally also fix trailing slashes. // It returns the case-corrected path and a bool indicating whether the lookup // was successful. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) { const stackBufSize = 128 // Use a static sized buffer on the stack in the common case. // If the path is too long, allocate a buffer on the heap instead. buf := make([]byte, 0, stackBufSize) if length := len(path) + 1; length > stackBufSize { buf = make([]byte, 0, length) } ciPath := n.findCaseInsensitivePathRec( path, buf, // Preallocate enough memory for new path [4]byte{}, // Empty rune buffer fixTrailingSlash, ) return ciPath, ciPath != nil } // Shift bytes in array by n bytes left func shiftNRuneBytes(rb [4]byte, n int) [4]byte { switch n { case 0: return rb case 1: return [4]byte{rb[1], rb[2], rb[3], 0} case 2: return [4]byte{rb[2], rb[3]} case 3: return [4]byte{rb[3]} default: return [4]byte{} } } // Recursive case-insensitive lookup function used by n.findCaseInsensitivePath func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte { npLen := len(n.path) walk: // Outer loop for walking the tree for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) { // Add common prefix to result oldPath := path path = path[npLen:] ciPath = append(ciPath, n.path...) if len(path) == 0 { // We should have reached the node containing the handle. // Check if this node has a handle registered. if n.handlers != nil { return ciPath } // No handle found. // Try to fix the path by adding a trailing slash if fixTrailingSlash { for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] if (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) { return append(ciPath, '/') } return nil } } } return nil } // If this node does not have a wildcard (param or catchAll) child, // we can just look up the next child node and continue to walk down // the tree if !n.wildChild { // Skip rune bytes already processed rb = shiftNRuneBytes(rb, npLen) if rb[0] != 0 { // Old rune not finished idxc := rb[0] for i, c := range []byte(n.indices) { if c == idxc { // continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } else { // Process a new rune var rv rune // Find rune start. // Runes are up to 4 byte long, // -4 would definitely be another rune. var off int for max := min(npLen, 3); off < max; off++ { if i := npLen - off; utf8.RuneStart(oldPath[i]) { // read rune from cached path rv, _ = utf8.DecodeRuneInString(oldPath[i:]) break } } // Calculate lowercase bytes of current rune lo := unicode.ToLower(rv) utf8.EncodeRune(rb[:], lo) // Skip already processed bytes rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Lowercase matches if c == idxc { // must use a recursive approach since both the // uppercase byte and the lowercase byte might exist // as an index if out := n.children[i].findCaseInsensitivePathRec( path, ciPath, rb, fixTrailingSlash, ); out != nil { return out } break } } // If we found no match, the same for the uppercase rune, // if it differs if up := unicode.ToUpper(rv); up != lo { utf8.EncodeRune(rb[:], up) rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Uppercase matches if c == idxc { // Continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } } // Nothing found. We can recommend to redirect to the same URL // without a trailing slash if a leaf exists for that path if fixTrailingSlash && path == "/" && n.handlers != nil { return ciPath } return nil } n = n.children[0] switch n.nType { case param: // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Add param value to case insensitive path ciPath = append(ciPath, path[:end]...) // We need to go deeper! if end < len(path) { if len(n.children) > 0 { // Continue with child node n = n.children[0] npLen = len(n.path) path = path[end:] continue } // ... but we can't if fixTrailingSlash && len(path) == end+1 { return ciPath } return nil } if n.handlers != nil { return ciPath } if fixTrailingSlash && len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists n = n.children[0] if n.path == "/" && n.handlers != nil { return append(ciPath, '/') } } return nil case catchAll: return append(ciPath, path...) default: panic("invalid node type") } } // Nothing found. // Try to fix the path by adding / removing a trailing slash if fixTrailingSlash { if path == "/" { return ciPath } if len(path)+1 == npLen && n.path[len(path)] == '/' && strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil { return append(ciPath, n.path...) } } return nil }
// Copyright 2013 Julien Schmidt. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE package gin import ( "bytes" "net/url" "strings" "unicode" "unicode/utf8" "github.com/gin-gonic/gin/internal/bytesconv" ) var ( strColon = []byte(":") strStar = []byte("*") strSlash = []byte("/") ) // Param is a single URL parameter, consisting of a key and a value. type Param struct { Key string Value string } // Params is a Param-slice, as returned by the router. // The slice is ordered, the first URL parameter is also the first slice value. // It is therefore safe to read values by the index. type Params []Param // Get returns the value of the first Param which key matches the given name and a boolean true. // If no matching Param is found, an empty string is returned and a boolean false . func (ps Params) Get(name string) (string, bool) { for _, entry := range ps { if entry.Key == name { return entry.Value, true } } return "", false } // ByName returns the value of the first Param which key matches the given name. // If no matching Param is found, an empty string is returned. func (ps Params) ByName(name string) (va string) { va, _ = ps.Get(name) return } type methodTree struct { method string root *node } type methodTrees []methodTree func (trees methodTrees) get(method string) *node { for _, tree := range trees { if tree.method == method { return tree.root } } return nil } func min(a, b int) int { if a <= b { return a } return b } func longestCommonPrefix(a, b string) int { i := 0 max := min(len(a), len(b)) for i < max && a[i] == b[i] { i++ } return i } // addChild will add a child node, keeping wildcardChild at the end func (n *node) addChild(child *node) { if n.wildChild && len(n.children) > 0 { wildcardChild := n.children[len(n.children)-1] n.children = append(n.children[:len(n.children)-1], child, wildcardChild) } else { n.children = append(n.children, child) } } func countParams(path string) uint16 { var n uint16 s := bytesconv.StringToBytes(path) n += uint16(bytes.Count(s, strColon)) n += uint16(bytes.Count(s, strStar)) return n } func countSections(path string) uint16 { s := bytesconv.StringToBytes(path) return uint16(bytes.Count(s, strSlash)) } type nodeType uint8 const ( root nodeType = iota + 1 param catchAll ) type node struct { path string indices string wildChild bool nType nodeType priority uint32 children []*node // child nodes, at most 1 :param style node at the end of the array handlers HandlersChain fullPath string } // Increments priority of the given child and reorders if necessary func (n *node) incrementChildPrio(pos int) int { cs := n.children cs[pos].priority++ prio := cs[pos].priority // Adjust position (move to front) newPos := pos for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- { // Swap node positions cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1] } // Build new index char string if newPos != pos { n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty n.indices[pos:pos+1] + // The index char we move n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos' } return newPos } // addRoute adds a node with the given handle to the path. // Not concurrency-safe! func (n *node) addRoute(path string, handlers HandlersChain) { fullPath := path n.priority++ // Empty tree if len(n.path) == 0 && len(n.children) == 0 { n.insertChild(path, fullPath, handlers) n.nType = root return } parentFullPathIndex := 0 walk: for { // Find the longest common prefix. // This also implies that the common prefix contains no ':' or '*' // since the existing key can't contain those chars. i := longestCommonPrefix(path, n.path) // Split edge if i < len(n.path) { child := node{ path: n.path[i:], wildChild: n.wildChild, indices: n.indices, children: n.children, handlers: n.handlers, priority: n.priority - 1, fullPath: n.fullPath, } n.children = []*node{&child} // []byte for proper unicode char conversion, see #65 n.indices = bytesconv.BytesToString([]byte{n.path[i]}) n.path = path[:i] n.handlers = nil n.wildChild = false n.fullPath = fullPath[:parentFullPathIndex+i] } // Make new node a child of this node if i < len(path) { path = path[i:] c := path[0] // '/' after param if n.nType == param && c == '/' && len(n.children) == 1 { parentFullPathIndex += len(n.path) n = n.children[0] n.priority++ continue walk } // Check if a child with the next path byte exists for i, max := 0, len(n.indices); i < max; i++ { if c == n.indices[i] { parentFullPathIndex += len(n.path) i = n.incrementChildPrio(i) n = n.children[i] continue walk } } // Otherwise insert it if c != ':' && c != '*' && n.nType != catchAll { // []byte for proper unicode char conversion, see #65 n.indices += bytesconv.BytesToString([]byte{c}) child := &node{ fullPath: fullPath, } n.addChild(child) n.incrementChildPrio(len(n.indices) - 1) n = child } else if n.wildChild { // inserting a wildcard node, need to check if it conflicts with the existing wildcard n = n.children[len(n.children)-1] n.priority++ // Check if the wildcard matches if len(path) >= len(n.path) && n.path == path[:len(n.path)] && // Adding a child to a catchAll is not possible n.nType != catchAll && // Check for longer wildcard, e.g. :name and :names (len(n.path) >= len(path) || path[len(n.path)] == '/') { continue walk } // Wildcard conflict pathSeg := path if n.nType != catchAll { pathSeg = strings.SplitN(pathSeg, "/", 2)[0] } prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path panic("'" + pathSeg + "' in new path '" + fullPath + "' conflicts with existing wildcard '" + n.path + "' in existing prefix '" + prefix + "'") } n.insertChild(path, fullPath, handlers) return } // Otherwise add handle to current node if n.handlers != nil { panic("handlers are already registered for path '" + fullPath + "'") } n.handlers = handlers n.fullPath = fullPath return } } // Search for a wildcard segment and check the name for invalid characters. // Returns -1 as index, if no wildcard was found. func findWildcard(path string) (wildcard string, i int, valid bool) { // Find start for start, c := range []byte(path) { // A wildcard starts with ':' (param) or '*' (catch-all) if c != ':' && c != '*' { continue } // Find end and check for invalid characters valid = true for end, c := range []byte(path[start+1:]) { switch c { case '/': return path[start : start+1+end], start, valid case ':', '*': valid = false } } return path[start:], start, valid } return "", -1, false } func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) { for { // Find prefix until first wildcard wildcard, i, valid := findWildcard(path) if i < 0 { // No wildcard found break } // The wildcard name must only contain one ':' or '*' character if !valid { panic("only one wildcard per path segment is allowed, has: '" + wildcard + "' in path '" + fullPath + "'") } // check if the wildcard has a name if len(wildcard) < 2 { panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") } if wildcard[0] == ':' { // param if i > 0 { // Insert prefix before the current wildcard n.path = path[:i] path = path[i:] } child := &node{ nType: param, path: wildcard, fullPath: fullPath, } n.addChild(child) n.wildChild = true n = child n.priority++ // if the path doesn't end with the wildcard, then there // will be another subpath starting with '/' if len(wildcard) < len(path) { path = path[len(wildcard):] child := &node{ priority: 1, fullPath: fullPath, } n.addChild(child) n = child continue } // Otherwise we're done. Insert the handle in the new leaf n.handlers = handlers return } // catchAll if i+len(wildcard) != len(path) { panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") } if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { pathSeg := strings.SplitN(n.children[0].path, "/", 2)[0] panic("catch-all wildcard '" + path + "' in new path '" + fullPath + "' conflicts with existing path segment '" + pathSeg + "' in existing prefix '" + n.path + pathSeg + "'") } // currently fixed width 1 for '/' i-- if path[i] != '/' { panic("no / before catch-all in path '" + fullPath + "'") } n.path = path[:i] // First node: catchAll node with empty path child := &node{ wildChild: true, nType: catchAll, fullPath: fullPath, } n.addChild(child) n.indices = string('/') n = child n.priority++ // second node: node holding the variable child = &node{ path: path[i:], nType: catchAll, handlers: handlers, priority: 1, fullPath: fullPath, } n.children = []*node{child} return } // If no wildcard was found, simply insert the path and handle n.path = path n.handlers = handlers n.fullPath = fullPath } // nodeValue holds return values of (*Node).getValue method type nodeValue struct { handlers HandlersChain params *Params tsr bool fullPath string } type skippedNode struct { path string node *node paramsCount int16 } // Returns the handle registered with the given path (key). The values of // wildcards are saved to a map. // If no handle can be found, a TSR (trailing slash redirect) recommendation is // made if a handle exists with an extra (without the) trailing slash for the // given path. func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) { var globalParamsCount int16 walk: // Outer loop for walking the tree for { prefix := n.path if len(path) > len(prefix) { if path[:len(prefix)] == prefix { path = path[len(prefix):] // Try all the non-wildcard children first by matching the indices idxc := path[0] for i, c := range []byte(n.indices) { if c == idxc { // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild if n.wildChild { index := len(*skippedNodes) *skippedNodes = (*skippedNodes)[:index+1] (*skippedNodes)[index] = skippedNode{ path: prefix + path, node: &node{ path: n.path, wildChild: n.wildChild, nType: n.nType, priority: n.priority, children: n.children, handlers: n.handlers, fullPath: n.fullPath, }, paramsCount: globalParamsCount, } } n = n.children[i] continue walk } } if !n.wildChild { // If the path at the end of the loop is not equal to '/' and the current node has no child nodes // the current node needs to roll back to last valid skippedNode if path != "/" { for l := len(*skippedNodes); l > 0; { skippedNode := (*skippedNodes)[l-1] *skippedNodes = (*skippedNodes)[:l-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } // Nothing found. // We can recommend to redirect to the same URL without a // trailing slash if a leaf exists for that path. value.tsr = path == "/" && n.handlers != nil return } // Handle wildcard child, which is always at the end of the array n = n.children[len(n.children)-1] globalParamsCount++ switch n.nType { case param: // fix truncate the parameter // tree_test.go line: 204 // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Save param value if params != nil && cap(*params) > 0 { if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path[:end] if unescape { if v, err := url.QueryUnescape(val); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[1:], Value: val, } } // we need to go deeper! if end < len(path) { if len(n.children) > 0 { path = path[end:] n = n.children[0] continue walk } // ... but we can't value.tsr = len(path) == end+1 return } if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return } if len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists for TSR recommendation n = n.children[0] value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/") } return case catchAll: // Save param value if params != nil { if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path if unescape { if v, err := url.QueryUnescape(path); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[2:], Value: val, } } value.handlers = n.handlers value.fullPath = n.fullPath return default: panic("invalid node type") } } } if path == prefix { // If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node // the current node needs to roll back to last valid skippedNode if n.handlers == nil && path != "/" { for l := len(*skippedNodes); l > 0; { skippedNode := (*skippedNodes)[l-1] *skippedNodes = (*skippedNodes)[:l-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } // n = latestNode.children[len(latestNode.children)-1] } // We should have reached the node containing the handle. // Check if this node has a handle registered. if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return } // If there is no handle for this route, but this route has a // wildcard child, there must be a handle for this path with an // additional trailing slash if path == "/" && n.wildChild && n.nType != root { value.tsr = true return } // No handle found. Check if a handle for this path + a // trailing slash exists for trailing slash recommendation for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] value.tsr = (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) return } } return } // Nothing found. We can recommend to redirect to the same URL with an // extra trailing slash if a leaf exists for that path value.tsr = path == "/" || (len(prefix) == len(path)+1 && prefix[len(path)] == '/' && path == prefix[:len(prefix)-1] && n.handlers != nil) // roll back to last valid skippedNode if !value.tsr && path != "/" { for l := len(*skippedNodes); l > 0; { skippedNode := (*skippedNodes)[l-1] *skippedNodes = (*skippedNodes)[:l-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } return } } // Makes a case-insensitive lookup of the given path and tries to find a handler. // It can optionally also fix trailing slashes. // It returns the case-corrected path and a bool indicating whether the lookup // was successful. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) { const stackBufSize = 128 // Use a static sized buffer on the stack in the common case. // If the path is too long, allocate a buffer on the heap instead. buf := make([]byte, 0, stackBufSize) if length := len(path) + 1; length > stackBufSize { buf = make([]byte, 0, length) } ciPath := n.findCaseInsensitivePathRec( path, buf, // Preallocate enough memory for new path [4]byte{}, // Empty rune buffer fixTrailingSlash, ) return ciPath, ciPath != nil } // Shift bytes in array by n bytes left func shiftNRuneBytes(rb [4]byte, n int) [4]byte { switch n { case 0: return rb case 1: return [4]byte{rb[1], rb[2], rb[3], 0} case 2: return [4]byte{rb[2], rb[3]} case 3: return [4]byte{rb[3]} default: return [4]byte{} } } // Recursive case-insensitive lookup function used by n.findCaseInsensitivePath func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte { npLen := len(n.path) walk: // Outer loop for walking the tree for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) { // Add common prefix to result oldPath := path path = path[npLen:] ciPath = append(ciPath, n.path...) if len(path) == 0 { // We should have reached the node containing the handle. // Check if this node has a handle registered. if n.handlers != nil { return ciPath } // No handle found. // Try to fix the path by adding a trailing slash if fixTrailingSlash { for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] if (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) { return append(ciPath, '/') } return nil } } } return nil } // If this node does not have a wildcard (param or catchAll) child, // we can just look up the next child node and continue to walk down // the tree if !n.wildChild { // Skip rune bytes already processed rb = shiftNRuneBytes(rb, npLen) if rb[0] != 0 { // Old rune not finished idxc := rb[0] for i, c := range []byte(n.indices) { if c == idxc { // continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } else { // Process a new rune var rv rune // Find rune start. // Runes are up to 4 byte long, // -4 would definitely be another rune. var off int for max := min(npLen, 3); off < max; off++ { if i := npLen - off; utf8.RuneStart(oldPath[i]) { // read rune from cached path rv, _ = utf8.DecodeRuneInString(oldPath[i:]) break } } // Calculate lowercase bytes of current rune lo := unicode.ToLower(rv) utf8.EncodeRune(rb[:], lo) // Skip already processed bytes rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Lowercase matches if c == idxc { // must use a recursive approach since both the // uppercase byte and the lowercase byte might exist // as an index if out := n.children[i].findCaseInsensitivePathRec( path, ciPath, rb, fixTrailingSlash, ); out != nil { return out } break } } // If we found no match, the same for the uppercase rune, // if it differs if up := unicode.ToUpper(rv); up != lo { utf8.EncodeRune(rb[:], up) rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Uppercase matches if c == idxc { // Continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } } // Nothing found. We can recommend to redirect to the same URL // without a trailing slash if a leaf exists for that path if fixTrailingSlash && path == "/" && n.handlers != nil { return ciPath } return nil } n = n.children[0] switch n.nType { case param: // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Add param value to case insensitive path ciPath = append(ciPath, path[:end]...) // We need to go deeper! if end < len(path) { if len(n.children) > 0 { // Continue with child node n = n.children[0] npLen = len(n.path) path = path[end:] continue } // ... but we can't if fixTrailingSlash && len(path) == end+1 { return ciPath } return nil } if n.handlers != nil { return ciPath } if fixTrailingSlash && len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists n = n.children[0] if n.path == "/" && n.handlers != nil { return append(ciPath, '/') } } return nil case catchAll: return append(ciPath, path...) default: panic("invalid node type") } } // Nothing found. // Try to fix the path by adding / removing a trailing slash if fixTrailingSlash { if path == "/" { return ciPath } if len(path)+1 == npLen && n.path[len(path)] == '/' && strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil { return append(ciPath, n.path...) } } return nil }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./internal/json/sonic.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build sonic && avx && (linux || windows || darwin) && amd64 // +build sonic // +build avx // +build linux windows darwin // +build amd64 package json import "github.com/bytedance/sonic" var ( json = sonic.ConfigStd // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build sonic && avx && (linux || windows || darwin) && amd64 // +build sonic // +build avx // +build linux windows darwin // +build amd64 package json import "github.com/bytedance/sonic" var ( json = sonic.ConfigStd // Marshal is exported by gin/json package. Marshal = json.Marshal // Unmarshal is exported by gin/json package. Unmarshal = json.Unmarshal // MarshalIndent is exported by gin/json package. MarshalIndent = json.MarshalIndent // NewDecoder is exported by gin/json package. NewDecoder = json.NewDecoder // NewEncoder is exported by gin/json package. NewEncoder = json.NewEncoder )
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./deprecated.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "log" "github.com/gin-gonic/gin/binding" ) // BindWith binds the passed struct pointer using the specified binding engine. // See the binding package. func (c *Context) BindWith(obj any, b binding.Binding) error { log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to be deprecated, please check issue #662 and either use MustBindWith() if you want HTTP 400 to be automatically returned if any error occur, or use ShouldBindWith() if you need to manage the error.`) return c.MustBindWith(obj, b) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "log" "github.com/gin-gonic/gin/binding" ) // BindWith binds the passed struct pointer using the specified binding engine. // See the binding package. func (c *Context) BindWith(obj any, b binding.Binding) error { log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to be deprecated, please check issue #662 and either use MustBindWith() if you want HTTP 400 to be automatically returned if any error occur, or use ShouldBindWith() if you need to manage the error.`) return c.MustBindWith(obj, b) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./utils_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "encoding/xml" "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func BenchmarkParseAccept(b *testing.B) { for i := 0; i < b.N; i++ { parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8") } } type testStruct struct { T *testing.T } func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) { assert.Equal(t.T, "POST", req.Method) assert.Equal(t.T, "/path", req.URL.Path) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "hello") } func TestWrap(t *testing.T) { router := New() router.POST("/path", WrapH(&testStruct{t})) router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) { assert.Equal(t, "GET", req.Method) assert.Equal(t, "/path2", req.URL.Path) w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, "hola!") })) w := PerformRequest(router, "POST", "/path") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hello", w.Body.String()) w = PerformRequest(router, "GET", "/path2") assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, "hola!", w.Body.String()) } func TestLastChar(t *testing.T) { assert.Equal(t, uint8('a'), lastChar("hola")) assert.Equal(t, uint8('s'), lastChar("adios")) assert.Panics(t, func() { lastChar("") }) } func TestParseAccept(t *testing.T) { parts := parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8") assert.Len(t, parts, 4) assert.Equal(t, "text/html", parts[0]) assert.Equal(t, "application/xhtml+xml", parts[1]) assert.Equal(t, "application/xml", parts[2]) assert.Equal(t, "*/*", parts[3]) } func TestChooseData(t *testing.T) { A := "a" B := "b" assert.Equal(t, A, chooseData(A, B)) assert.Equal(t, B, chooseData(nil, B)) assert.Panics(t, func() { chooseData(nil, nil) }) } func TestFilterFlags(t *testing.T) { result := filterFlags("text/html ") assert.Equal(t, "text/html", result) result = filterFlags("text/html;") assert.Equal(t, "text/html", result) } func TestFunctionName(t *testing.T) { assert.Regexp(t, `^(.*/vendor/)?github.com/gin-gonic/gin.somefunction$`, nameOfFunction(somefunction)) } func somefunction() { // this empty function is used by TestFunctionName() } func TestJoinPaths(t *testing.T) { assert.Equal(t, "", joinPaths("", "")) assert.Equal(t, "/", joinPaths("", "/")) assert.Equal(t, "/a", joinPaths("/a", "")) assert.Equal(t, "/a/", joinPaths("/a/", "")) assert.Equal(t, "/a/", joinPaths("/a/", "/")) assert.Equal(t, "/a/", joinPaths("/a", "/")) assert.Equal(t, "/a/hola", joinPaths("/a", "/hola")) assert.Equal(t, "/a/hola", joinPaths("/a/", "/hola")) assert.Equal(t, "/a/hola/", joinPaths("/a/", "/hola/")) assert.Equal(t, "/a/hola/", joinPaths("/a/", "/hola//")) } type bindTestStruct struct { Foo string `form:"foo" binding:"required"` Bar int `form:"bar" binding:"min=4"` } func TestBindMiddleware(t *testing.T) { var value *bindTestStruct var called bool router := New() router.GET("/", Bind(bindTestStruct{}), func(c *Context) { called = true value = c.MustGet(BindKey).(*bindTestStruct) }) PerformRequest(router, "GET", "/?foo=hola&bar=10") assert.True(t, called) assert.Equal(t, "hola", value.Foo) assert.Equal(t, 10, value.Bar) called = false PerformRequest(router, "GET", "/?foo=hola&bar=1") assert.False(t, called) assert.Panics(t, func() { Bind(&bindTestStruct{}) }) } func TestMarshalXMLforH(t *testing.T) { h := H{ "": "test", } var b bytes.Buffer enc := xml.NewEncoder(&b) var x xml.StartElement e := h.MarshalXML(enc, x) assert.Error(t, e) } func TestIsASCII(t *testing.T) { assert.Equal(t, isASCII("test"), true) assert.Equal(t, isASCII("🧡💛💚💙💜"), false) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "encoding/xml" "fmt" "net/http" "testing" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func BenchmarkParseAccept(b *testing.B) { for i := 0; i < b.N; i++ { parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8") } } type testStruct struct { T *testing.T } func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) { assert.Equal(t.T, "POST", req.Method) assert.Equal(t.T, "/path", req.URL.Path) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "hello") } func TestWrap(t *testing.T) { router := New() router.POST("/path", WrapH(&testStruct{t})) router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) { assert.Equal(t, "GET", req.Method) assert.Equal(t, "/path2", req.URL.Path) w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, "hola!") })) w := PerformRequest(router, "POST", "/path") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hello", w.Body.String()) w = PerformRequest(router, "GET", "/path2") assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, "hola!", w.Body.String()) } func TestLastChar(t *testing.T) { assert.Equal(t, uint8('a'), lastChar("hola")) assert.Equal(t, uint8('s'), lastChar("adios")) assert.Panics(t, func() { lastChar("") }) } func TestParseAccept(t *testing.T) { parts := parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8") assert.Len(t, parts, 4) assert.Equal(t, "text/html", parts[0]) assert.Equal(t, "application/xhtml+xml", parts[1]) assert.Equal(t, "application/xml", parts[2]) assert.Equal(t, "*/*", parts[3]) } func TestChooseData(t *testing.T) { A := "a" B := "b" assert.Equal(t, A, chooseData(A, B)) assert.Equal(t, B, chooseData(nil, B)) assert.Panics(t, func() { chooseData(nil, nil) }) } func TestFilterFlags(t *testing.T) { result := filterFlags("text/html ") assert.Equal(t, "text/html", result) result = filterFlags("text/html;") assert.Equal(t, "text/html", result) } func TestFunctionName(t *testing.T) { assert.Regexp(t, `^(.*/vendor/)?github.com/gin-gonic/gin.somefunction$`, nameOfFunction(somefunction)) } func somefunction() { // this empty function is used by TestFunctionName() } func TestJoinPaths(t *testing.T) { assert.Equal(t, "", joinPaths("", "")) assert.Equal(t, "/", joinPaths("", "/")) assert.Equal(t, "/a", joinPaths("/a", "")) assert.Equal(t, "/a/", joinPaths("/a/", "")) assert.Equal(t, "/a/", joinPaths("/a/", "/")) assert.Equal(t, "/a/", joinPaths("/a", "/")) assert.Equal(t, "/a/hola", joinPaths("/a", "/hola")) assert.Equal(t, "/a/hola", joinPaths("/a/", "/hola")) assert.Equal(t, "/a/hola/", joinPaths("/a/", "/hola/")) assert.Equal(t, "/a/hola/", joinPaths("/a/", "/hola//")) } type bindTestStruct struct { Foo string `form:"foo" binding:"required"` Bar int `form:"bar" binding:"min=4"` } func TestBindMiddleware(t *testing.T) { var value *bindTestStruct var called bool router := New() router.GET("/", Bind(bindTestStruct{}), func(c *Context) { called = true value = c.MustGet(BindKey).(*bindTestStruct) }) PerformRequest(router, "GET", "/?foo=hola&bar=10") assert.True(t, called) assert.Equal(t, "hola", value.Foo) assert.Equal(t, 10, value.Bar) called = false PerformRequest(router, "GET", "/?foo=hola&bar=1") assert.False(t, called) assert.Panics(t, func() { Bind(&bindTestStruct{}) }) } func TestMarshalXMLforH(t *testing.T) { h := H{ "": "test", } var b bytes.Buffer enc := xml.NewEncoder(&b) var x xml.StartElement e := h.MarshalXML(enc, x) assert.Error(t, e) } func TestIsASCII(t *testing.T) { assert.Equal(t, isASCII("test"), true) assert.Equal(t, isASCII("🧡💛💚💙💜"), false) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./routergroup.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "path" "regexp" "strings" ) var ( // regEnLetter matches english letters for http method name regEnLetter = regexp.MustCompile("^[A-Z]+$") // anyMethods for RouterGroup Any method anyMethods = []string{ http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect, http.MethodTrace, } ) // IRouter defines all router handle interface includes single and group router. type IRouter interface { IRoutes Group(string, ...HandlerFunc) *RouterGroup } // IRoutes defines all router handle interface. type IRoutes interface { Use(...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes DELETE(string, ...HandlerFunc) IRoutes PATCH(string, ...HandlerFunc) IRoutes PUT(string, ...HandlerFunc) IRoutes OPTIONS(string, ...HandlerFunc) IRoutes HEAD(string, ...HandlerFunc) IRoutes StaticFile(string, string) IRoutes StaticFileFS(string, string, http.FileSystem) IRoutes Static(string, string) IRoutes StaticFS(string, http.FileSystem) IRoutes } // RouterGroup is used internally to configure router, a RouterGroup is associated with // a prefix and an array of handlers (middleware). type RouterGroup struct { Handlers HandlersChain basePath string engine *Engine root bool } var _ IRouter = &RouterGroup{} // Use adds middleware to the group, see example code in GitHub. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() } // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } } // BasePath returns the base path of router group. // For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api". func (group *RouterGroup) BasePath() string { return group.basePath } func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { absolutePath := group.calculateAbsolutePath(relativePath) handlers = group.combineHandlers(handlers) group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() } // Handle registers a new request handle and middleware with the given path and method. // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. // See the example code in GitHub. // // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut // functions can be used. // // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { if matched := regEnLetter.MatchString(httpMethod); !matched { panic("http method " + httpMethod + " is not valid") } return group.handle(httpMethod, relativePath, handlers) } // POST is a shortcut for router.Handle("POST", path, handlers). func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPost, relativePath, handlers) } // GET is a shortcut for router.Handle("GET", path, handlers). func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodGet, relativePath, handlers) } // DELETE is a shortcut for router.Handle("DELETE", path, handlers). func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodDelete, relativePath, handlers) } // PATCH is a shortcut for router.Handle("PATCH", path, handlers). func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPatch, relativePath, handlers) } // PUT is a shortcut for router.Handle("PUT", path, handlers). func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPut, relativePath, handlers) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handlers). func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodOptions, relativePath, handlers) } // HEAD is a shortcut for router.Handle("HEAD", path, handlers). func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodHead, relativePath, handlers) } // Any registers a route that matches all the HTTP methods. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range anyMethods { group.handle(method, relativePath, handlers) } return group.returnObj() } // StaticFile registers a single route in order to serve a single file of the local filesystem. // router.StaticFile("favicon.ico", "./resources/favicon.ico") func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.File(filepath) }) } // StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.. // router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false}) // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.FileFromFS(filepath, fs) }) } func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static file") } group.GET(relativePath, handler) group.HEAD(relativePath, handler) return group.returnObj() } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // // router.Static("/static", "/var/www") func (group *RouterGroup) Static(relativePath, root string) IRoutes { return group.StaticFS(relativePath, Dir(root, false)) } // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static folder") } handler := group.createStaticHandler(relativePath, fs) urlPattern := path.Join(relativePath, "/*filepath") // Register GET and HEAD handlers group.GET(urlPattern, handler) group.HEAD(urlPattern, handler) return group.returnObj() } func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { absolutePath := group.calculateAbsolutePath(relativePath) fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) return func(c *Context) { if _, noListing := fs.(*onlyFilesFS); noListing { c.Writer.WriteHeader(http.StatusNotFound) } file := c.Param("filepath") // Check if file exists and/or if we have permission to access it f, err := fs.Open(file) if err != nil { c.Writer.WriteHeader(http.StatusNotFound) c.handlers = group.engine.noRoute // Reset index c.index = -1 return } f.Close() fileServer.ServeHTTP(c.Writer, c.Request) } } func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { finalSize := len(group.Handlers) + len(handlers) assert1(finalSize < int(abortIndex), "too many handlers") mergedHandlers := make(HandlersChain, finalSize) copy(mergedHandlers, group.Handlers) copy(mergedHandlers[len(group.Handlers):], handlers) return mergedHandlers } func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { return joinPaths(group.basePath, relativePath) } func (group *RouterGroup) returnObj() IRoutes { if group.root { return group.engine } return group }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "net/http" "path" "regexp" "strings" ) var ( // regEnLetter matches english letters for http method name regEnLetter = regexp.MustCompile("^[A-Z]+$") // anyMethods for RouterGroup Any method anyMethods = []string{ http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect, http.MethodTrace, } ) // IRouter defines all router handle interface includes single and group router. type IRouter interface { IRoutes Group(string, ...HandlerFunc) *RouterGroup } // IRoutes defines all router handle interface. type IRoutes interface { Use(...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes DELETE(string, ...HandlerFunc) IRoutes PATCH(string, ...HandlerFunc) IRoutes PUT(string, ...HandlerFunc) IRoutes OPTIONS(string, ...HandlerFunc) IRoutes HEAD(string, ...HandlerFunc) IRoutes StaticFile(string, string) IRoutes StaticFileFS(string, string, http.FileSystem) IRoutes Static(string, string) IRoutes StaticFS(string, http.FileSystem) IRoutes } // RouterGroup is used internally to configure router, a RouterGroup is associated with // a prefix and an array of handlers (middleware). type RouterGroup struct { Handlers HandlersChain basePath string engine *Engine root bool } var _ IRouter = &RouterGroup{} // Use adds middleware to the group, see example code in GitHub. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() } // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } } // BasePath returns the base path of router group. // For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api". func (group *RouterGroup) BasePath() string { return group.basePath } func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { absolutePath := group.calculateAbsolutePath(relativePath) handlers = group.combineHandlers(handlers) group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() } // Handle registers a new request handle and middleware with the given path and method. // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. // See the example code in GitHub. // // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut // functions can be used. // // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { if matched := regEnLetter.MatchString(httpMethod); !matched { panic("http method " + httpMethod + " is not valid") } return group.handle(httpMethod, relativePath, handlers) } // POST is a shortcut for router.Handle("POST", path, handlers). func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPost, relativePath, handlers) } // GET is a shortcut for router.Handle("GET", path, handlers). func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodGet, relativePath, handlers) } // DELETE is a shortcut for router.Handle("DELETE", path, handlers). func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodDelete, relativePath, handlers) } // PATCH is a shortcut for router.Handle("PATCH", path, handlers). func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPatch, relativePath, handlers) } // PUT is a shortcut for router.Handle("PUT", path, handlers). func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPut, relativePath, handlers) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handlers). func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodOptions, relativePath, handlers) } // HEAD is a shortcut for router.Handle("HEAD", path, handlers). func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodHead, relativePath, handlers) } // Any registers a route that matches all the HTTP methods. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range anyMethods { group.handle(method, relativePath, handlers) } return group.returnObj() } // StaticFile registers a single route in order to serve a single file of the local filesystem. // router.StaticFile("favicon.ico", "./resources/favicon.ico") func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.File(filepath) }) } // StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.. // router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false}) // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.FileFromFS(filepath, fs) }) } func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static file") } group.GET(relativePath, handler) group.HEAD(relativePath, handler) return group.returnObj() } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // // router.Static("/static", "/var/www") func (group *RouterGroup) Static(relativePath, root string) IRoutes { return group.StaticFS(relativePath, Dir(root, false)) } // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static folder") } handler := group.createStaticHandler(relativePath, fs) urlPattern := path.Join(relativePath, "/*filepath") // Register GET and HEAD handlers group.GET(urlPattern, handler) group.HEAD(urlPattern, handler) return group.returnObj() } func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { absolutePath := group.calculateAbsolutePath(relativePath) fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) return func(c *Context) { if _, noListing := fs.(*onlyFilesFS); noListing { c.Writer.WriteHeader(http.StatusNotFound) } file := c.Param("filepath") // Check if file exists and/or if we have permission to access it f, err := fs.Open(file) if err != nil { c.Writer.WriteHeader(http.StatusNotFound) c.handlers = group.engine.noRoute // Reset index c.index = -1 return } f.Close() fileServer.ServeHTTP(c.Writer, c.Request) } } func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { finalSize := len(group.Handlers) + len(handlers) assert1(finalSize < int(abortIndex), "too many handlers") mergedHandlers := make(HandlersChain, finalSize) copy(mergedHandlers, group.Handlers) copy(mergedHandlers[len(group.Handlers):], handlers) return mergedHandlers } func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { return joinPaths(group.basePath, relativePath) } func (group *RouterGroup) returnObj() IRoutes { if group.root { return group.engine } return group }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/multipart_form_mapping_test.go
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "io/ioutil" "mime/multipart" "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestFormMultipartBindingBindOneFile(t *testing.T) { var s struct { FileValue multipart.FileHeader `form:"file"` FilePtr *multipart.FileHeader `form:"file"` SliceValues []multipart.FileHeader `form:"file"` SlicePtrs []*multipart.FileHeader `form:"file"` ArrayValues [1]multipart.FileHeader `form:"file"` ArrayPtrs [1]*multipart.FileHeader `form:"file"` } file := testFile{"file", "file1", []byte("hello")} req := createRequestMultipartFiles(t, file) err := FormMultipart.Bind(req, &s) assert.NoError(t, err) assertMultipartFileHeader(t, &s.FileValue, file) assertMultipartFileHeader(t, s.FilePtr, file) assert.Len(t, s.SliceValues, 1) assertMultipartFileHeader(t, &s.SliceValues[0], file) assert.Len(t, s.SlicePtrs, 1) assertMultipartFileHeader(t, s.SlicePtrs[0], file) assertMultipartFileHeader(t, &s.ArrayValues[0], file) assertMultipartFileHeader(t, s.ArrayPtrs[0], file) } func TestFormMultipartBindingBindTwoFiles(t *testing.T) { var s struct { SliceValues []multipart.FileHeader `form:"file"` SlicePtrs []*multipart.FileHeader `form:"file"` ArrayValues [2]multipart.FileHeader `form:"file"` ArrayPtrs [2]*multipart.FileHeader `form:"file"` } files := []testFile{ {"file", "file1", []byte("hello")}, {"file", "file2", []byte("world")}, } req := createRequestMultipartFiles(t, files...) err := FormMultipart.Bind(req, &s) assert.NoError(t, err) assert.Len(t, s.SliceValues, len(files)) assert.Len(t, s.SlicePtrs, len(files)) assert.Len(t, s.ArrayValues, len(files)) assert.Len(t, s.ArrayPtrs, len(files)) for i, file := range files { assertMultipartFileHeader(t, &s.SliceValues[i], file) assertMultipartFileHeader(t, s.SlicePtrs[i], file) assertMultipartFileHeader(t, &s.ArrayValues[i], file) assertMultipartFileHeader(t, s.ArrayPtrs[i], file) } } func TestFormMultipartBindingBindError(t *testing.T) { files := []testFile{ {"file", "file1", []byte("hello")}, {"file", "file2", []byte("world")}, } for _, tt := range []struct { name string s any }{ {"wrong type", &struct { Files int `form:"file"` }{}}, {"wrong array size", &struct { Files [1]*multipart.FileHeader `form:"file"` }{}}, {"wrong slice type", &struct { Files []int `form:"file"` }{}}, } { req := createRequestMultipartFiles(t, files...) err := FormMultipart.Bind(req, tt.s) assert.Error(t, err) } } type testFile struct { Fieldname string Filename string Content []byte } func createRequestMultipartFiles(t *testing.T, files ...testFile) *http.Request { var body bytes.Buffer mw := multipart.NewWriter(&body) for _, file := range files { fw, err := mw.CreateFormFile(file.Fieldname, file.Filename) assert.NoError(t, err) n, err := fw.Write(file.Content) assert.NoError(t, err) assert.Equal(t, len(file.Content), n) } err := mw.Close() assert.NoError(t, err) req, err := http.NewRequest("POST", "/", &body) assert.NoError(t, err) req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+mw.Boundary()) return req } func assertMultipartFileHeader(t *testing.T, fh *multipart.FileHeader, file testFile) { assert.Equal(t, file.Filename, fh.Filename) assert.Equal(t, int64(len(file.Content)), fh.Size) fl, err := fh.Open() assert.NoError(t, err) body, err := ioutil.ReadAll(fl) assert.NoError(t, err) assert.Equal(t, string(file.Content), string(body)) err = fl.Close() assert.NoError(t, err) }
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "io/ioutil" "mime/multipart" "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestFormMultipartBindingBindOneFile(t *testing.T) { var s struct { FileValue multipart.FileHeader `form:"file"` FilePtr *multipart.FileHeader `form:"file"` SliceValues []multipart.FileHeader `form:"file"` SlicePtrs []*multipart.FileHeader `form:"file"` ArrayValues [1]multipart.FileHeader `form:"file"` ArrayPtrs [1]*multipart.FileHeader `form:"file"` } file := testFile{"file", "file1", []byte("hello")} req := createRequestMultipartFiles(t, file) err := FormMultipart.Bind(req, &s) assert.NoError(t, err) assertMultipartFileHeader(t, &s.FileValue, file) assertMultipartFileHeader(t, s.FilePtr, file) assert.Len(t, s.SliceValues, 1) assertMultipartFileHeader(t, &s.SliceValues[0], file) assert.Len(t, s.SlicePtrs, 1) assertMultipartFileHeader(t, s.SlicePtrs[0], file) assertMultipartFileHeader(t, &s.ArrayValues[0], file) assertMultipartFileHeader(t, s.ArrayPtrs[0], file) } func TestFormMultipartBindingBindTwoFiles(t *testing.T) { var s struct { SliceValues []multipart.FileHeader `form:"file"` SlicePtrs []*multipart.FileHeader `form:"file"` ArrayValues [2]multipart.FileHeader `form:"file"` ArrayPtrs [2]*multipart.FileHeader `form:"file"` } files := []testFile{ {"file", "file1", []byte("hello")}, {"file", "file2", []byte("world")}, } req := createRequestMultipartFiles(t, files...) err := FormMultipart.Bind(req, &s) assert.NoError(t, err) assert.Len(t, s.SliceValues, len(files)) assert.Len(t, s.SlicePtrs, len(files)) assert.Len(t, s.ArrayValues, len(files)) assert.Len(t, s.ArrayPtrs, len(files)) for i, file := range files { assertMultipartFileHeader(t, &s.SliceValues[i], file) assertMultipartFileHeader(t, s.SlicePtrs[i], file) assertMultipartFileHeader(t, &s.ArrayValues[i], file) assertMultipartFileHeader(t, s.ArrayPtrs[i], file) } } func TestFormMultipartBindingBindError(t *testing.T) { files := []testFile{ {"file", "file1", []byte("hello")}, {"file", "file2", []byte("world")}, } for _, tt := range []struct { name string s any }{ {"wrong type", &struct { Files int `form:"file"` }{}}, {"wrong array size", &struct { Files [1]*multipart.FileHeader `form:"file"` }{}}, {"wrong slice type", &struct { Files []int `form:"file"` }{}}, } { req := createRequestMultipartFiles(t, files...) err := FormMultipart.Bind(req, tt.s) assert.Error(t, err) } } type testFile struct { Fieldname string Filename string Content []byte } func createRequestMultipartFiles(t *testing.T, files ...testFile) *http.Request { var body bytes.Buffer mw := multipart.NewWriter(&body) for _, file := range files { fw, err := mw.CreateFormFile(file.Fieldname, file.Filename) assert.NoError(t, err) n, err := fw.Write(file.Content) assert.NoError(t, err) assert.Equal(t, len(file.Content), n) } err := mw.Close() assert.NoError(t, err) req, err := http.NewRequest("POST", "/", &body) assert.NoError(t, err) req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+mw.Boundary()) return req } func assertMultipartFileHeader(t *testing.T, fh *multipart.FileHeader, file testFile) { assert.Equal(t, file.Filename, fh.Filename) assert.Equal(t, int64(len(file.Content)), fh.Size) fl, err := fh.Open() assert.NoError(t, err) body, err := ioutil.ReadAll(fl) assert.NoError(t, err) assert.Equal(t, string(file.Content), string(body)) err = fl.Close() assert.NoError(t, err) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./render/any.go
// Copyright 2021 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package render type any = interface{}
// Copyright 2021 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package render type any = interface{}
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/any.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package binding type any = interface{}
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package binding type any = interface{}
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./recovery_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "net" "net/http" "os" "strings" "syscall" "testing" "github.com/stretchr/testify/assert" ) func TestPanicClean(t *testing.T) { buffer := new(bytes.Buffer) router := New() password := "my-super-secret-password" router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery", header{ Key: "Host", Value: "www.google.com", }, header{ Key: "Authorization", Value: fmt.Sprintf("Bearer %s", password), }, header{ Key: "Content-Type", Value: "application/json", }, ) // TEST assert.Equal(t, http.StatusBadRequest, w.Code) // Check the buffer does not have the secret key assert.NotContains(t, buffer.String(), password) } // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") SetMode(TestMode) } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) } func TestSource(t *testing.T) { bs := source(nil, 0) assert.Equal(t, dunno, bs) in := [][]byte{ []byte("Hello world."), []byte("Hi, gin.."), } bs = source(in, 10) assert.Equal(t, dunno, bs) bs = source(in, 1) assert.Equal(t, []byte("Hello world."), bs) } func TestFunction(t *testing.T) { bs := function(1) assert.Equal(t, dunno, bs) } // TestPanicWithBrokenPipe asserts that recovery specifically handles // writing responses to broken pipes func TestPanicWithBrokenPipe(t *testing.T) { const expectCode = 204 expectMsgs := map[syscall.Errno]string{ syscall.EPIPE: "broken pipe", syscall.ECONNRESET: "connection reset by peer", } for errno, expectMsg := range expectMsgs { t.Run(expectMsg, func(t *testing.T) { var buf bytes.Buffer router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Oops. Client connection closed e := &net.OpError{Err: &os.SyscallError{Err: errno}} panic(e) }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, expectCode, w.Code) assert.Contains(t, strings.ToLower(buf.String()), expectMsg) }) } } func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "net" "net/http" "os" "strings" "syscall" "testing" "github.com/stretchr/testify/assert" ) func TestPanicClean(t *testing.T) { buffer := new(bytes.Buffer) router := New() password := "my-super-secret-password" router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery", header{ Key: "Host", Value: "www.google.com", }, header{ Key: "Authorization", Value: fmt.Sprintf("Bearer %s", password), }, header{ Key: "Content-Type", Value: "application/json", }, ) // TEST assert.Equal(t, http.StatusBadRequest, w.Code) // Check the buffer does not have the secret key assert.NotContains(t, buffer.String(), password) } // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") SetMode(TestMode) } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) } func TestSource(t *testing.T) { bs := source(nil, 0) assert.Equal(t, dunno, bs) in := [][]byte{ []byte("Hello world."), []byte("Hi, gin.."), } bs = source(in, 10) assert.Equal(t, dunno, bs) bs = source(in, 1) assert.Equal(t, []byte("Hello world."), bs) } func TestFunction(t *testing.T) { bs := function(1) assert.Equal(t, dunno, bs) } // TestPanicWithBrokenPipe asserts that recovery specifically handles // writing responses to broken pipes func TestPanicWithBrokenPipe(t *testing.T) { const expectCode = 204 expectMsgs := map[syscall.Errno]string{ syscall.EPIPE: "broken pipe", syscall.ECONNRESET: "connection reset by peer", } for errno, expectMsg := range expectMsgs { t.Run(expectMsg, func(t *testing.T) { var buf bytes.Buffer router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Oops. Client connection closed e := &net.OpError{Err: &os.SyscallError{Err: errno}} panic(e) }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, expectCode, w.Code) assert.Contains(t, strings.ToLower(buf.String()), expectMsg) }) } } func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./render/yaml.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "gopkg.in/yaml.v2" ) // YAML contains the given interface object. type YAML struct { Data any } var yamlContentType = []string{"application/x-yaml; charset=utf-8"} // Render (YAML) marshals the given interface object and writes data with custom ContentType. func (r YAML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := yaml.Marshal(r.Data) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (YAML) writes YAML ContentType for response. func (r YAML) WriteContentType(w http.ResponseWriter) { writeContentType(w, yamlContentType) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "net/http" "gopkg.in/yaml.v2" ) // YAML contains the given interface object. type YAML struct { Data any } var yamlContentType = []string{"application/x-yaml; charset=utf-8"} // Render (YAML) marshals the given interface object and writes data with custom ContentType. func (r YAML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := yaml.Marshal(r.Data) if err != nil { return err } _, err = w.Write(bytes) return err } // WriteContentType (YAML) writes YAML ContentType for response. func (r YAML) WriteContentType(w http.ResponseWriter) { writeContentType(w, yamlContentType) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./.git/config
[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] url = https://github.com/gin-gonic/gin.git fetch = +refs/heads/*:refs/remotes/origin/* gh-resolved = base [branch "master"] remote = origin merge = refs/heads/master
[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true [remote "origin"] url = https://github.com/gin-gonic/gin.git fetch = +refs/heads/*:refs/remotes/origin/* gh-resolved = base [branch "master"] remote = origin merge = refs/heads/master
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./render/render.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" // Render interface is to be implemented by JSON, XML, HTML, YAML and so on. type Render interface { // Render writes data with custom ContentType. Render(http.ResponseWriter) error // WriteContentType writes custom ContentType. WriteContentType(w http.ResponseWriter) } var ( _ Render = JSON{} _ Render = IndentedJSON{} _ Render = SecureJSON{} _ Render = JsonpJSON{} _ Render = XML{} _ Render = String{} _ Render = Redirect{} _ Render = Data{} _ Render = HTML{} _ HTMLRender = HTMLDebug{} _ HTMLRender = HTMLProduction{} _ Render = YAML{} _ Render = Reader{} _ Render = AsciiJSON{} _ Render = ProtoBuf{} _ Render = TOML{} ) func writeContentType(w http.ResponseWriter, value []string) { header := w.Header() if val := header["Content-Type"]; len(val) == 0 { header["Content-Type"] = value } }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import "net/http" // Render interface is to be implemented by JSON, XML, HTML, YAML and so on. type Render interface { // Render writes data with custom ContentType. Render(http.ResponseWriter) error // WriteContentType writes custom ContentType. WriteContentType(w http.ResponseWriter) } var ( _ Render = JSON{} _ Render = IndentedJSON{} _ Render = SecureJSON{} _ Render = JsonpJSON{} _ Render = XML{} _ Render = String{} _ Render = Redirect{} _ Render = Data{} _ Render = HTML{} _ HTMLRender = HTMLDebug{} _ HTMLRender = HTMLProduction{} _ Render = YAML{} _ Render = Reader{} _ Render = AsciiJSON{} _ Render = ProtoBuf{} _ Render = TOML{} ) func writeContentType(w http.ResponseWriter, value []string) { header := w.Header() if val := header["Content-Type"]; len(val) == 0 { header["Content-Type"] = value } }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./LICENSE
The MIT License (MIT) Copyright (c) 2014 Manuel Martínez-Almeida Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The MIT License (MIT) Copyright (c) 2014 Manuel Martínez-Almeida Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./binding/form.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "net/http" ) const defaultMemory = 32 << 20 type formBinding struct{} type formPostBinding struct{} type formMultipartBinding struct{} func (formBinding) Name() string { return "form" } func (formBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) { return err } if err := mapForm(obj, req.Form); err != nil { return err } return validate(obj) } func (formPostBinding) Name() string { return "form-urlencoded" } func (formPostBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := mapForm(obj, req.PostForm); err != nil { return err } return validate(obj) } func (formMultipartBinding) Name() string { return "multipart/form-data" } func (formMultipartBinding) Bind(req *http.Request, obj any) error { if err := req.ParseMultipartForm(defaultMemory); err != nil { return err } if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { return err } return validate(obj) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "net/http" ) const defaultMemory = 32 << 20 type formBinding struct{} type formPostBinding struct{} type formMultipartBinding struct{} func (formBinding) Name() string { return "form" } func (formBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) { return err } if err := mapForm(obj, req.Form); err != nil { return err } return validate(obj) } func (formPostBinding) Name() string { return "form-urlencoded" } func (formPostBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } if err := mapForm(obj, req.PostForm); err != nil { return err } return validate(obj) } func (formMultipartBinding) Name() string { return "multipart/form-data" } func (formMultipartBinding) Bind(req *http.Request, obj any) error { if err := req.ParseMultipartForm(defaultMemory); err != nil { return err } if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { return err } return validate(obj) }
-1
gin-gonic/gin
3,361
chore(dep): Changes minimum support go version to go1.16
mstmdev
"2022-10-12T11:28:50Z"
"2022-10-16T01:32:28Z"
6296175f70e21bd1c09efc424a2c14574904720d
fa58bff301a823ce25af800614d3f016b10ae586
chore(dep): Changes minimum support go version to go1.16.
./testdata/certificate/cert.pem
-----BEGIN CERTIFICATE----- MIIC9DCCAdygAwIBAgIQUNSK+OxWHYYFxHVJV0IlpDANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMB4XDTE3MTExNjEyMDA0N1oXDTE4MTExNjEyMDA0 N1owEjEQMA4GA1UEChMHQWNtZSBDbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBAKmyj/YZpD59Bpy4w3qf6VzMw9uUBsWp+IP4kl7z5cmGHYUHn/YopTLH vR23GAB12p6Km5QWzCBuJF4j61PJXHfg3/rjShZ77JcQ3kzxuy1iKDI+DNKN7Klz rdjJ49QD0lczZHeBvvCL7JsJFKFjGy62rnStuW8LaIEdtjXT+GUZTxJh6G7yPYfD MS1IsdMQGOdbGwNa+qogMuQPh0TzHw+C73myKrjY6pREijknMC/rnIMz9dLPt6Kl xXy4br443dpY6dYGIhDuKhROT+vZ05HKasuuQUFhY7v/KoUpEZMB9rfUSzjQ5fak eDUAMniXRcd+DmwvboG2TI6ixmuPK+ECAwEAAaNGMEQwDgYDVR0PAQH/BAQDAgWg MBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA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AAATANBgkqhkiG9w0BAQsFAAOCAQEAMXOLvj7BFsxdbcfRPBd0OFrH/8lI7vPV LRcJ6r5iv0cnNvZXXbIOQLbg4clJAWjoE08nRm1KvNXhKdns0ELEV86YN2S6jThq rIGrBqKtaJLB3M9BtDSiQ6SGPLYrWvmhj3Avi8PbSGy51bpGbqopd16j6LYU7Cp2 TefMRlOAFtHojpCVon1CMpqcNxS0WNlQ3lUBSrw3HB0o12x++roja2ibF54tSHXB KUuadoEzN+mMBwenEBychmAGzdiG4GQHRmhigh85+mtW6UMGiqyCZHs0EgE9FCLL sRrsTI/VOzLz6lluygXkOsXrP+PP0SvmE3eylWjj9e2nj/u/Cy2YKg== -----END CERTIFICATE-----
-1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./debug_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "html/template" "io" "log" "os" "runtime" "sync" "testing" "github.com/stretchr/testify/assert" ) // TODO // func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) { // func debugPrint(format string, values ...interface{}) { func TestIsDebugging(t *testing.T) { SetMode(DebugMode) assert.True(t, IsDebugging()) SetMode(ReleaseMode) assert.False(t, IsDebugging()) SetMode(TestMode) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) debugPrint("DEBUG this!") SetMode(DebugMode) debugPrint("these are %d %s", 2, "error messages") SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] these are 2 error messages\n", re) } func TestDebugPrintError(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintError(nil) debugPrintError(errors.New("this is an error")) SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [ERROR] this is an error\n", re) } func TestDebugPrintRoutes(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintRouteFunc(t *testing.T) { DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintLoadTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl")) debugPrintLoadTemplate(templ) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] Loaded HTML Templates \(2\): \n(\t- \n|\t- hello\.tmpl\n){2}\n`, re) } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGSetHTMLTemplate() SetMode(TestMode) }) 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", re) } func TestDebugPrintWARNINGDefault(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) m, e := getMinVer(runtime.Version()) if e == nil && m < ginSupportMinGoVer { assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.16+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } else { assert.Equal(t, "[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } } func TestDebugPrintWARNINGNew(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGNew() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n", re) } func captureOutput(t *testing.T, f func()) string { reader, writer, err := os.Pipe() if err != nil { panic(err) } defaultWriter := DefaultWriter defaultErrorWriter := DefaultErrorWriter defer func() { DefaultWriter = defaultWriter DefaultErrorWriter = defaultErrorWriter log.SetOutput(os.Stderr) }() DefaultWriter = writer DefaultErrorWriter = writer log.SetOutput(writer) out := make(chan string) wg := new(sync.WaitGroup) wg.Add(1) go func() { var buf bytes.Buffer wg.Done() _, err := io.Copy(&buf, reader) assert.NoError(t, err) out <- buf.String() }() wg.Wait() f() writer.Close() return <-out } func TestGetMinVer(t *testing.T) { var m uint64 var e error _, e = getMinVer("go1") assert.NotNil(t, e) m, e = getMinVer("go1.1") assert.Equal(t, uint64(1), m) assert.Nil(t, e) m, e = getMinVer("go1.1.1") assert.Nil(t, e) assert.Equal(t, uint64(1), m) _, e = getMinVer("go1.1.1.1") assert.NotNil(t, e) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "fmt" "html/template" "io" "log" "os" "runtime" "strings" "sync" "testing" "github.com/stretchr/testify/assert" ) // TODO // func debugRoute(httpMethod, absolutePath string, handlers HandlersChain) { // func debugPrint(format string, values ...interface{}) { func TestIsDebugging(t *testing.T) { SetMode(DebugMode) assert.True(t, IsDebugging()) SetMode(ReleaseMode) assert.False(t, IsDebugging()) SetMode(TestMode) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) debugPrint("DEBUG this!") SetMode(DebugMode) debugPrint("these are %d %s", 2, "error messages") SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] these are 2 error messages\n", re) } func TestDebugPrintError(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintError(nil) debugPrintError(errors.New("this is an error")) SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [ERROR] this is an error\n", re) } func TestDebugPrintRoutes(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintRouteFunc(t *testing.T) { DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute("GET", "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintLoadTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl")) debugPrintLoadTemplate(templ) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] Loaded HTML Templates \(2\): \n(\t- \n|\t- hello\.tmpl\n){2}\n`, re) } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGSetHTMLTemplate() SetMode(TestMode) }) 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", re) } func TestDebugPrintWARNINGDefault(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) m, e := getMinVer(runtime.Version()) if e == nil && m < ginSupportMinGoVer { assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.16+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } else { assert.Equal(t, "[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } } func TestDebugPrintWARNINGNew(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGNew() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n", re) } func captureOutput(t *testing.T, f func()) string { reader, writer, err := os.Pipe() if err != nil { panic(err) } defaultWriter := DefaultWriter defaultErrorWriter := DefaultErrorWriter defer func() { DefaultWriter = defaultWriter DefaultErrorWriter = defaultErrorWriter log.SetOutput(os.Stderr) }() DefaultWriter = writer DefaultErrorWriter = writer log.SetOutput(writer) out := make(chan string) wg := new(sync.WaitGroup) wg.Add(1) go func() { var buf strings.Builder wg.Done() _, err := io.Copy(&buf, reader) assert.NoError(t, err) out <- buf.String() }() wg.Wait() f() writer.Close() return <-out } func TestGetMinVer(t *testing.T) { var m uint64 var e error _, e = getMinVer("go1") assert.NotNil(t, e) m, e = getMinVer("go1.1") assert.Equal(t, uint64(1), m) assert.Nil(t, e) m, e = getMinVer("go1.1.1") assert.Nil(t, e) assert.Equal(t, uint64(1), m) _, e = getMinVer("go1.1.1.1") assert.NotNil(t, e) }
1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./githubapi_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "math/rand" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" ) type route struct { method string path string } // http://developer.github.com/v3/ var githubAPI = []route{ // OAuth Authorizations {http.MethodGet, "/authorizations"}, {http.MethodGet, "/authorizations/:id"}, {http.MethodPost, "/authorizations"}, //{http.MethodPut, "/authorizations/clients/:client_id"}, //{http.MethodPatch, "/authorizations/:id"}, {http.MethodDelete, "/authorizations/:id"}, {http.MethodGet, "/applications/:client_id/tokens/:access_token"}, {http.MethodDelete, "/applications/:client_id/tokens"}, {http.MethodDelete, "/applications/:client_id/tokens/:access_token"}, // Activity {http.MethodGet, "/events"}, {http.MethodGet, "/repos/:owner/:repo/events"}, {http.MethodGet, "/networks/:owner/:repo/events"}, {http.MethodGet, "/orgs/:org/events"}, {http.MethodGet, "/users/:user/received_events"}, {http.MethodGet, "/users/:user/received_events/public"}, {http.MethodGet, "/users/:user/events"}, {http.MethodGet, "/users/:user/events/public"}, {http.MethodGet, "/users/:user/events/orgs/:org"}, {http.MethodGet, "/feeds"}, {http.MethodGet, "/notifications"}, {http.MethodGet, "/repos/:owner/:repo/notifications"}, {http.MethodPut, "/notifications"}, {http.MethodPut, "/repos/:owner/:repo/notifications"}, {http.MethodGet, "/notifications/threads/:id"}, //{http.MethodPatch, "/notifications/threads/:id"}, {http.MethodGet, "/notifications/threads/:id/subscription"}, {http.MethodPut, "/notifications/threads/:id/subscription"}, {http.MethodDelete, "/notifications/threads/:id/subscription"}, {http.MethodGet, "/repos/:owner/:repo/stargazers"}, {http.MethodGet, "/users/:user/starred"}, {http.MethodGet, "/user/starred"}, {http.MethodGet, "/user/starred/:owner/:repo"}, {http.MethodPut, "/user/starred/:owner/:repo"}, {http.MethodDelete, "/user/starred/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/subscribers"}, {http.MethodGet, "/users/:user/subscriptions"}, {http.MethodGet, "/user/subscriptions"}, {http.MethodGet, "/repos/:owner/:repo/subscription"}, {http.MethodPut, "/repos/:owner/:repo/subscription"}, {http.MethodDelete, "/repos/:owner/:repo/subscription"}, {http.MethodGet, "/user/subscriptions/:owner/:repo"}, {http.MethodPut, "/user/subscriptions/:owner/:repo"}, {http.MethodDelete, "/user/subscriptions/:owner/:repo"}, // Gists {http.MethodGet, "/users/:user/gists"}, {http.MethodGet, "/gists"}, //{http.MethodGet, "/gists/public"}, //{http.MethodGet, "/gists/starred"}, {http.MethodGet, "/gists/:id"}, {http.MethodPost, "/gists"}, //{http.MethodPatch, "/gists/:id"}, {http.MethodPut, "/gists/:id/star"}, {http.MethodDelete, "/gists/:id/star"}, {http.MethodGet, "/gists/:id/star"}, {http.MethodPost, "/gists/:id/forks"}, {http.MethodDelete, "/gists/:id"}, // Git Data {http.MethodGet, "/repos/:owner/:repo/git/blobs/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/blobs"}, {http.MethodGet, "/repos/:owner/:repo/git/commits/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/commits"}, //{http.MethodGet, "/repos/:owner/:repo/git/refs/*ref"}, {http.MethodGet, "/repos/:owner/:repo/git/refs"}, {http.MethodPost, "/repos/:owner/:repo/git/refs"}, //{http.MethodPatch, "/repos/:owner/:repo/git/refs/*ref"}, //{http.MethodDelete, "/repos/:owner/:repo/git/refs/*ref"}, {http.MethodGet, "/repos/:owner/:repo/git/tags/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/tags"}, {http.MethodGet, "/repos/:owner/:repo/git/trees/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/trees"}, // Issues {http.MethodGet, "/issues"}, {http.MethodGet, "/user/issues"}, {http.MethodGet, "/orgs/:org/issues"}, {http.MethodGet, "/repos/:owner/:repo/issues"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number"}, {http.MethodPost, "/repos/:owner/:repo/issues"}, //{http.MethodPatch, "/repos/:owner/:repo/issues/:number"}, {http.MethodGet, "/repos/:owner/:repo/assignees"}, {http.MethodGet, "/repos/:owner/:repo/assignees/:assignee"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/comments"}, //{http.MethodGet, "/repos/:owner/:repo/issues/comments"}, //{http.MethodGet, "/repos/:owner/:repo/issues/comments/:id"}, {http.MethodPost, "/repos/:owner/:repo/issues/:number/comments"}, //{http.MethodPatch, "/repos/:owner/:repo/issues/comments/:id"}, //{http.MethodDelete, "/repos/:owner/:repo/issues/comments/:id"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/events"}, //{http.MethodGet, "/repos/:owner/:repo/issues/events"}, //{http.MethodGet, "/repos/:owner/:repo/issues/events/:id"}, {http.MethodGet, "/repos/:owner/:repo/labels"}, {http.MethodGet, "/repos/:owner/:repo/labels/:name"}, {http.MethodPost, "/repos/:owner/:repo/labels"}, //{http.MethodPatch, "/repos/:owner/:repo/labels/:name"}, {http.MethodDelete, "/repos/:owner/:repo/labels/:name"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodPost, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodDelete, "/repos/:owner/:repo/issues/:number/labels/:name"}, {http.MethodPut, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodDelete, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodGet, "/repos/:owner/:repo/milestones/:number/labels"}, {http.MethodGet, "/repos/:owner/:repo/milestones"}, {http.MethodGet, "/repos/:owner/:repo/milestones/:number"}, {http.MethodPost, "/repos/:owner/:repo/milestones"}, //{http.MethodPatch, "/repos/:owner/:repo/milestones/:number"}, {http.MethodDelete, "/repos/:owner/:repo/milestones/:number"}, // Miscellaneous {http.MethodGet, "/emojis"}, {http.MethodGet, "/gitignore/templates"}, {http.MethodGet, "/gitignore/templates/:name"}, {http.MethodPost, "/markdown"}, {http.MethodPost, "/markdown/raw"}, {http.MethodGet, "/meta"}, {http.MethodGet, "/rate_limit"}, // Organizations {http.MethodGet, "/users/:user/orgs"}, {http.MethodGet, "/user/orgs"}, {http.MethodGet, "/orgs/:org"}, //{http.MethodPatch, "/orgs/:org"}, {http.MethodGet, "/orgs/:org/members"}, {http.MethodGet, "/orgs/:org/members/:user"}, {http.MethodDelete, "/orgs/:org/members/:user"}, {http.MethodGet, "/orgs/:org/public_members"}, {http.MethodGet, "/orgs/:org/public_members/:user"}, {http.MethodPut, "/orgs/:org/public_members/:user"}, {http.MethodDelete, "/orgs/:org/public_members/:user"}, {http.MethodGet, "/orgs/:org/teams"}, {http.MethodGet, "/teams/:id"}, {http.MethodPost, "/orgs/:org/teams"}, //{http.MethodPatch, "/teams/:id"}, {http.MethodDelete, "/teams/:id"}, {http.MethodGet, "/teams/:id/members"}, {http.MethodGet, "/teams/:id/members/:user"}, {http.MethodPut, "/teams/:id/members/:user"}, {http.MethodDelete, "/teams/:id/members/:user"}, {http.MethodGet, "/teams/:id/repos"}, {http.MethodGet, "/teams/:id/repos/:owner/:repo"}, {http.MethodPut, "/teams/:id/repos/:owner/:repo"}, {http.MethodDelete, "/teams/:id/repos/:owner/:repo"}, {http.MethodGet, "/user/teams"}, // Pull Requests {http.MethodGet, "/repos/:owner/:repo/pulls"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number"}, {http.MethodPost, "/repos/:owner/:repo/pulls"}, //{http.MethodPatch, "/repos/:owner/:repo/pulls/:number"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/commits"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/files"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/merge"}, {http.MethodPut, "/repos/:owner/:repo/pulls/:number/merge"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/comments"}, //{http.MethodGet, "/repos/:owner/:repo/pulls/comments"}, //{http.MethodGet, "/repos/:owner/:repo/pulls/comments/:number"}, {http.MethodPut, "/repos/:owner/:repo/pulls/:number/comments"}, //{http.MethodPatch, "/repos/:owner/:repo/pulls/comments/:number"}, //{http.MethodDelete, "/repos/:owner/:repo/pulls/comments/:number"}, // Repositories {http.MethodGet, "/user/repos"}, {http.MethodGet, "/users/:user/repos"}, {http.MethodGet, "/orgs/:org/repos"}, {http.MethodGet, "/repositories"}, {http.MethodPost, "/user/repos"}, {http.MethodPost, "/orgs/:org/repos"}, {http.MethodGet, "/repos/:owner/:repo"}, //{http.MethodPatch, "/repos/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/contributors"}, {http.MethodGet, "/repos/:owner/:repo/languages"}, {http.MethodGet, "/repos/:owner/:repo/teams"}, {http.MethodGet, "/repos/:owner/:repo/tags"}, {http.MethodGet, "/repos/:owner/:repo/branches"}, {http.MethodGet, "/repos/:owner/:repo/branches/:branch"}, {http.MethodDelete, "/repos/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/collaborators"}, {http.MethodGet, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodPut, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodDelete, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodGet, "/repos/:owner/:repo/comments"}, {http.MethodGet, "/repos/:owner/:repo/commits/:sha/comments"}, {http.MethodPost, "/repos/:owner/:repo/commits/:sha/comments"}, {http.MethodGet, "/repos/:owner/:repo/comments/:id"}, //{http.MethodPatch, "/repos/:owner/:repo/comments/:id"}, {http.MethodDelete, "/repos/:owner/:repo/comments/:id"}, {http.MethodGet, "/repos/:owner/:repo/commits"}, {http.MethodGet, "/repos/:owner/:repo/commits/:sha"}, {http.MethodGet, "/repos/:owner/:repo/readme"}, //{http.MethodGet, "/repos/:owner/:repo/contents/*path"}, //{http.MethodPut, "/repos/:owner/:repo/contents/*path"}, //{http.MethodDelete, "/repos/:owner/:repo/contents/*path"}, //{http.MethodGet, "/repos/:owner/:repo/:archive_format/:ref"}, {http.MethodGet, "/repos/:owner/:repo/keys"}, {http.MethodGet, "/repos/:owner/:repo/keys/:id"}, {http.MethodPost, "/repos/:owner/:repo/keys"}, //{http.MethodPatch, "/repos/:owner/:repo/keys/:id"}, {http.MethodDelete, "/repos/:owner/:repo/keys/:id"}, {http.MethodGet, "/repos/:owner/:repo/downloads"}, {http.MethodGet, "/repos/:owner/:repo/downloads/:id"}, {http.MethodDelete, "/repos/:owner/:repo/downloads/:id"}, {http.MethodGet, "/repos/:owner/:repo/forks"}, {http.MethodPost, "/repos/:owner/:repo/forks"}, {http.MethodGet, "/repos/:owner/:repo/hooks"}, {http.MethodGet, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/hooks"}, //{http.MethodPatch, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/hooks/:id/tests"}, {http.MethodDelete, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/merges"}, {http.MethodGet, "/repos/:owner/:repo/releases"}, {http.MethodGet, "/repos/:owner/:repo/releases/:id"}, {http.MethodPost, "/repos/:owner/:repo/releases"}, //{http.MethodPatch, "/repos/:owner/:repo/releases/:id"}, {http.MethodDelete, "/repos/:owner/:repo/releases/:id"}, {http.MethodGet, "/repos/:owner/:repo/releases/:id/assets"}, {http.MethodGet, "/repos/:owner/:repo/stats/contributors"}, {http.MethodGet, "/repos/:owner/:repo/stats/commit_activity"}, {http.MethodGet, "/repos/:owner/:repo/stats/code_frequency"}, {http.MethodGet, "/repos/:owner/:repo/stats/participation"}, {http.MethodGet, "/repos/:owner/:repo/stats/punch_card"}, {http.MethodGet, "/repos/:owner/:repo/statuses/:ref"}, {http.MethodPost, "/repos/:owner/:repo/statuses/:ref"}, // Search {http.MethodGet, "/search/repositories"}, {http.MethodGet, "/search/code"}, {http.MethodGet, "/search/issues"}, {http.MethodGet, "/search/users"}, {http.MethodGet, "/legacy/issues/search/:owner/:repository/:state/:keyword"}, {http.MethodGet, "/legacy/repos/search/:keyword"}, {http.MethodGet, "/legacy/user/search/:keyword"}, {http.MethodGet, "/legacy/user/email/:email"}, // Users {http.MethodGet, "/users/:user"}, {http.MethodGet, "/user"}, //{http.MethodPatch, "/user"}, {http.MethodGet, "/users"}, {http.MethodGet, "/user/emails"}, {http.MethodPost, "/user/emails"}, {http.MethodDelete, "/user/emails"}, {http.MethodGet, "/users/:user/followers"}, {http.MethodGet, "/user/followers"}, {http.MethodGet, "/users/:user/following"}, {http.MethodGet, "/user/following"}, {http.MethodGet, "/user/following/:user"}, {http.MethodGet, "/users/:user/following/:target_user"}, {http.MethodPut, "/user/following/:user"}, {http.MethodDelete, "/user/following/:user"}, {http.MethodGet, "/users/:user/keys"}, {http.MethodGet, "/user/keys"}, {http.MethodGet, "/user/keys/:id"}, {http.MethodPost, "/user/keys"}, //{http.MethodPatch, "/user/keys/:id"}, {http.MethodDelete, "/user/keys/:id"}, } func TestShouldBindUri(t *testing.T) { DefaultWriter = os.Stdout router := New() type Person struct { Name string `uri:"name" binding:"required"` ID string `uri:"id" binding:"required"` } router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) { var person Person assert.NoError(t, c.ShouldBindUri(&person)) assert.True(t, person.Name != "") assert.True(t, person.ID != "") c.String(http.StatusOK, "ShouldBindUri test OK") }) path, _ := exampleFromPath("/rest/:name/:id") w := PerformRequest(router, http.MethodGet, path) assert.Equal(t, "ShouldBindUri test OK", w.Body.String()) assert.Equal(t, http.StatusOK, w.Code) } func TestBindUri(t *testing.T) { DefaultWriter = os.Stdout router := New() type Person struct { Name string `uri:"name" binding:"required"` ID string `uri:"id" binding:"required"` } router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) { var person Person assert.NoError(t, c.BindUri(&person)) assert.True(t, person.Name != "") assert.True(t, person.ID != "") c.String(http.StatusOK, "BindUri test OK") }) path, _ := exampleFromPath("/rest/:name/:id") w := PerformRequest(router, http.MethodGet, path) assert.Equal(t, "BindUri test OK", w.Body.String()) assert.Equal(t, http.StatusOK, w.Code) } func TestBindUriError(t *testing.T) { DefaultWriter = os.Stdout router := New() type Member struct { Number string `uri:"num" binding:"required,uuid"` } router.Handle(http.MethodGet, "/new/rest/:num", func(c *Context) { var m Member assert.Error(t, c.BindUri(&m)) }) path1, _ := exampleFromPath("/new/rest/:num") w1 := PerformRequest(router, http.MethodGet, path1) assert.Equal(t, http.StatusBadRequest, w1.Code) } func TestRaceContextCopy(t *testing.T) { DefaultWriter = os.Stdout router := Default() router.GET("/test/copy/race", func(c *Context) { c.Set("1", 0) c.Set("2", 0) // Sending a copy of the Context to two separate routines go readWriteKeys(c.Copy()) go readWriteKeys(c.Copy()) c.String(http.StatusOK, "run OK, no panics") }) w := PerformRequest(router, http.MethodGet, "/test/copy/race") assert.Equal(t, "run OK, no panics", w.Body.String()) } func readWriteKeys(c *Context) { for { c.Set("1", rand.Int()) c.Set("2", c.Value("1")) } } func githubConfigRouter(router *Engine) { for _, route := range githubAPI { router.Handle(route.method, route.path, func(c *Context) { output := make(map[string]string, len(c.Params)+1) output["status"] = "good" for _, param := range c.Params { output[param.Key] = param.Value } c.JSON(http.StatusOK, output) }) } } func TestGithubAPI(t *testing.T) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) for _, route := range githubAPI { path, values := exampleFromPath(route.path) w := PerformRequest(router, route.method, path) // TEST assert.Contains(t, w.Body.String(), "\"status\":\"good\"") for _, value := range values { str := fmt.Sprintf("\"%s\":\"%s\"", value.Key, value.Value) assert.Contains(t, w.Body.String(), str) } } } func exampleFromPath(path string) (string, Params) { output := new(bytes.Buffer) params := make(Params, 0, 6) start := -1 for i, c := range path { if c == ':' { start = i + 1 } if start >= 0 { if c == '/' { value := fmt.Sprint(rand.Intn(100000)) params = append(params, Param{ Key: path[start:i], Value: value, }) output.WriteString(value) output.WriteRune(c) start = -1 } } else { output.WriteRune(c) } } if start >= 0 { value := fmt.Sprint(rand.Intn(100000)) params = append(params, Param{ Key: path[start:], Value: value, }) output.WriteString(value) } return output.String(), params } func BenchmarkGithub(b *testing.B) { router := New() githubConfigRouter(router) runRequest(b, router, http.MethodGet, "/legacy/issues/search/:owner/:repository/:state/:keyword") } func BenchmarkParallelGithub(b *testing.B) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) req, _ := http.NewRequest(http.MethodPost, "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) } func BenchmarkParallelGithubDefault(b *testing.B) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) req, _ := http.NewRequest(http.MethodPost, "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "math/rand" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/stretchr/testify/assert" ) type route struct { method string path string } // http://developer.github.com/v3/ var githubAPI = []route{ // OAuth Authorizations {http.MethodGet, "/authorizations"}, {http.MethodGet, "/authorizations/:id"}, {http.MethodPost, "/authorizations"}, //{http.MethodPut, "/authorizations/clients/:client_id"}, //{http.MethodPatch, "/authorizations/:id"}, {http.MethodDelete, "/authorizations/:id"}, {http.MethodGet, "/applications/:client_id/tokens/:access_token"}, {http.MethodDelete, "/applications/:client_id/tokens"}, {http.MethodDelete, "/applications/:client_id/tokens/:access_token"}, // Activity {http.MethodGet, "/events"}, {http.MethodGet, "/repos/:owner/:repo/events"}, {http.MethodGet, "/networks/:owner/:repo/events"}, {http.MethodGet, "/orgs/:org/events"}, {http.MethodGet, "/users/:user/received_events"}, {http.MethodGet, "/users/:user/received_events/public"}, {http.MethodGet, "/users/:user/events"}, {http.MethodGet, "/users/:user/events/public"}, {http.MethodGet, "/users/:user/events/orgs/:org"}, {http.MethodGet, "/feeds"}, {http.MethodGet, "/notifications"}, {http.MethodGet, "/repos/:owner/:repo/notifications"}, {http.MethodPut, "/notifications"}, {http.MethodPut, "/repos/:owner/:repo/notifications"}, {http.MethodGet, "/notifications/threads/:id"}, //{http.MethodPatch, "/notifications/threads/:id"}, {http.MethodGet, "/notifications/threads/:id/subscription"}, {http.MethodPut, "/notifications/threads/:id/subscription"}, {http.MethodDelete, "/notifications/threads/:id/subscription"}, {http.MethodGet, "/repos/:owner/:repo/stargazers"}, {http.MethodGet, "/users/:user/starred"}, {http.MethodGet, "/user/starred"}, {http.MethodGet, "/user/starred/:owner/:repo"}, {http.MethodPut, "/user/starred/:owner/:repo"}, {http.MethodDelete, "/user/starred/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/subscribers"}, {http.MethodGet, "/users/:user/subscriptions"}, {http.MethodGet, "/user/subscriptions"}, {http.MethodGet, "/repos/:owner/:repo/subscription"}, {http.MethodPut, "/repos/:owner/:repo/subscription"}, {http.MethodDelete, "/repos/:owner/:repo/subscription"}, {http.MethodGet, "/user/subscriptions/:owner/:repo"}, {http.MethodPut, "/user/subscriptions/:owner/:repo"}, {http.MethodDelete, "/user/subscriptions/:owner/:repo"}, // Gists {http.MethodGet, "/users/:user/gists"}, {http.MethodGet, "/gists"}, //{http.MethodGet, "/gists/public"}, //{http.MethodGet, "/gists/starred"}, {http.MethodGet, "/gists/:id"}, {http.MethodPost, "/gists"}, //{http.MethodPatch, "/gists/:id"}, {http.MethodPut, "/gists/:id/star"}, {http.MethodDelete, "/gists/:id/star"}, {http.MethodGet, "/gists/:id/star"}, {http.MethodPost, "/gists/:id/forks"}, {http.MethodDelete, "/gists/:id"}, // Git Data {http.MethodGet, "/repos/:owner/:repo/git/blobs/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/blobs"}, {http.MethodGet, "/repos/:owner/:repo/git/commits/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/commits"}, //{http.MethodGet, "/repos/:owner/:repo/git/refs/*ref"}, {http.MethodGet, "/repos/:owner/:repo/git/refs"}, {http.MethodPost, "/repos/:owner/:repo/git/refs"}, //{http.MethodPatch, "/repos/:owner/:repo/git/refs/*ref"}, //{http.MethodDelete, "/repos/:owner/:repo/git/refs/*ref"}, {http.MethodGet, "/repos/:owner/:repo/git/tags/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/tags"}, {http.MethodGet, "/repos/:owner/:repo/git/trees/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/trees"}, // Issues {http.MethodGet, "/issues"}, {http.MethodGet, "/user/issues"}, {http.MethodGet, "/orgs/:org/issues"}, {http.MethodGet, "/repos/:owner/:repo/issues"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number"}, {http.MethodPost, "/repos/:owner/:repo/issues"}, //{http.MethodPatch, "/repos/:owner/:repo/issues/:number"}, {http.MethodGet, "/repos/:owner/:repo/assignees"}, {http.MethodGet, "/repos/:owner/:repo/assignees/:assignee"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/comments"}, //{http.MethodGet, "/repos/:owner/:repo/issues/comments"}, //{http.MethodGet, "/repos/:owner/:repo/issues/comments/:id"}, {http.MethodPost, "/repos/:owner/:repo/issues/:number/comments"}, //{http.MethodPatch, "/repos/:owner/:repo/issues/comments/:id"}, //{http.MethodDelete, "/repos/:owner/:repo/issues/comments/:id"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/events"}, //{http.MethodGet, "/repos/:owner/:repo/issues/events"}, //{http.MethodGet, "/repos/:owner/:repo/issues/events/:id"}, {http.MethodGet, "/repos/:owner/:repo/labels"}, {http.MethodGet, "/repos/:owner/:repo/labels/:name"}, {http.MethodPost, "/repos/:owner/:repo/labels"}, //{http.MethodPatch, "/repos/:owner/:repo/labels/:name"}, {http.MethodDelete, "/repos/:owner/:repo/labels/:name"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodPost, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodDelete, "/repos/:owner/:repo/issues/:number/labels/:name"}, {http.MethodPut, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodDelete, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodGet, "/repos/:owner/:repo/milestones/:number/labels"}, {http.MethodGet, "/repos/:owner/:repo/milestones"}, {http.MethodGet, "/repos/:owner/:repo/milestones/:number"}, {http.MethodPost, "/repos/:owner/:repo/milestones"}, //{http.MethodPatch, "/repos/:owner/:repo/milestones/:number"}, {http.MethodDelete, "/repos/:owner/:repo/milestones/:number"}, // Miscellaneous {http.MethodGet, "/emojis"}, {http.MethodGet, "/gitignore/templates"}, {http.MethodGet, "/gitignore/templates/:name"}, {http.MethodPost, "/markdown"}, {http.MethodPost, "/markdown/raw"}, {http.MethodGet, "/meta"}, {http.MethodGet, "/rate_limit"}, // Organizations {http.MethodGet, "/users/:user/orgs"}, {http.MethodGet, "/user/orgs"}, {http.MethodGet, "/orgs/:org"}, //{http.MethodPatch, "/orgs/:org"}, {http.MethodGet, "/orgs/:org/members"}, {http.MethodGet, "/orgs/:org/members/:user"}, {http.MethodDelete, "/orgs/:org/members/:user"}, {http.MethodGet, "/orgs/:org/public_members"}, {http.MethodGet, "/orgs/:org/public_members/:user"}, {http.MethodPut, "/orgs/:org/public_members/:user"}, {http.MethodDelete, "/orgs/:org/public_members/:user"}, {http.MethodGet, "/orgs/:org/teams"}, {http.MethodGet, "/teams/:id"}, {http.MethodPost, "/orgs/:org/teams"}, //{http.MethodPatch, "/teams/:id"}, {http.MethodDelete, "/teams/:id"}, {http.MethodGet, "/teams/:id/members"}, {http.MethodGet, "/teams/:id/members/:user"}, {http.MethodPut, "/teams/:id/members/:user"}, {http.MethodDelete, "/teams/:id/members/:user"}, {http.MethodGet, "/teams/:id/repos"}, {http.MethodGet, "/teams/:id/repos/:owner/:repo"}, {http.MethodPut, "/teams/:id/repos/:owner/:repo"}, {http.MethodDelete, "/teams/:id/repos/:owner/:repo"}, {http.MethodGet, "/user/teams"}, // Pull Requests {http.MethodGet, "/repos/:owner/:repo/pulls"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number"}, {http.MethodPost, "/repos/:owner/:repo/pulls"}, //{http.MethodPatch, "/repos/:owner/:repo/pulls/:number"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/commits"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/files"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/merge"}, {http.MethodPut, "/repos/:owner/:repo/pulls/:number/merge"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/comments"}, //{http.MethodGet, "/repos/:owner/:repo/pulls/comments"}, //{http.MethodGet, "/repos/:owner/:repo/pulls/comments/:number"}, {http.MethodPut, "/repos/:owner/:repo/pulls/:number/comments"}, //{http.MethodPatch, "/repos/:owner/:repo/pulls/comments/:number"}, //{http.MethodDelete, "/repos/:owner/:repo/pulls/comments/:number"}, // Repositories {http.MethodGet, "/user/repos"}, {http.MethodGet, "/users/:user/repos"}, {http.MethodGet, "/orgs/:org/repos"}, {http.MethodGet, "/repositories"}, {http.MethodPost, "/user/repos"}, {http.MethodPost, "/orgs/:org/repos"}, {http.MethodGet, "/repos/:owner/:repo"}, //{http.MethodPatch, "/repos/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/contributors"}, {http.MethodGet, "/repos/:owner/:repo/languages"}, {http.MethodGet, "/repos/:owner/:repo/teams"}, {http.MethodGet, "/repos/:owner/:repo/tags"}, {http.MethodGet, "/repos/:owner/:repo/branches"}, {http.MethodGet, "/repos/:owner/:repo/branches/:branch"}, {http.MethodDelete, "/repos/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/collaborators"}, {http.MethodGet, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodPut, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodDelete, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodGet, "/repos/:owner/:repo/comments"}, {http.MethodGet, "/repos/:owner/:repo/commits/:sha/comments"}, {http.MethodPost, "/repos/:owner/:repo/commits/:sha/comments"}, {http.MethodGet, "/repos/:owner/:repo/comments/:id"}, //{http.MethodPatch, "/repos/:owner/:repo/comments/:id"}, {http.MethodDelete, "/repos/:owner/:repo/comments/:id"}, {http.MethodGet, "/repos/:owner/:repo/commits"}, {http.MethodGet, "/repos/:owner/:repo/commits/:sha"}, {http.MethodGet, "/repos/:owner/:repo/readme"}, //{http.MethodGet, "/repos/:owner/:repo/contents/*path"}, //{http.MethodPut, "/repos/:owner/:repo/contents/*path"}, //{http.MethodDelete, "/repos/:owner/:repo/contents/*path"}, //{http.MethodGet, "/repos/:owner/:repo/:archive_format/:ref"}, {http.MethodGet, "/repos/:owner/:repo/keys"}, {http.MethodGet, "/repos/:owner/:repo/keys/:id"}, {http.MethodPost, "/repos/:owner/:repo/keys"}, //{http.MethodPatch, "/repos/:owner/:repo/keys/:id"}, {http.MethodDelete, "/repos/:owner/:repo/keys/:id"}, {http.MethodGet, "/repos/:owner/:repo/downloads"}, {http.MethodGet, "/repos/:owner/:repo/downloads/:id"}, {http.MethodDelete, "/repos/:owner/:repo/downloads/:id"}, {http.MethodGet, "/repos/:owner/:repo/forks"}, {http.MethodPost, "/repos/:owner/:repo/forks"}, {http.MethodGet, "/repos/:owner/:repo/hooks"}, {http.MethodGet, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/hooks"}, //{http.MethodPatch, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/hooks/:id/tests"}, {http.MethodDelete, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/merges"}, {http.MethodGet, "/repos/:owner/:repo/releases"}, {http.MethodGet, "/repos/:owner/:repo/releases/:id"}, {http.MethodPost, "/repos/:owner/:repo/releases"}, //{http.MethodPatch, "/repos/:owner/:repo/releases/:id"}, {http.MethodDelete, "/repos/:owner/:repo/releases/:id"}, {http.MethodGet, "/repos/:owner/:repo/releases/:id/assets"}, {http.MethodGet, "/repos/:owner/:repo/stats/contributors"}, {http.MethodGet, "/repos/:owner/:repo/stats/commit_activity"}, {http.MethodGet, "/repos/:owner/:repo/stats/code_frequency"}, {http.MethodGet, "/repos/:owner/:repo/stats/participation"}, {http.MethodGet, "/repos/:owner/:repo/stats/punch_card"}, {http.MethodGet, "/repos/:owner/:repo/statuses/:ref"}, {http.MethodPost, "/repos/:owner/:repo/statuses/:ref"}, // Search {http.MethodGet, "/search/repositories"}, {http.MethodGet, "/search/code"}, {http.MethodGet, "/search/issues"}, {http.MethodGet, "/search/users"}, {http.MethodGet, "/legacy/issues/search/:owner/:repository/:state/:keyword"}, {http.MethodGet, "/legacy/repos/search/:keyword"}, {http.MethodGet, "/legacy/user/search/:keyword"}, {http.MethodGet, "/legacy/user/email/:email"}, // Users {http.MethodGet, "/users/:user"}, {http.MethodGet, "/user"}, //{http.MethodPatch, "/user"}, {http.MethodGet, "/users"}, {http.MethodGet, "/user/emails"}, {http.MethodPost, "/user/emails"}, {http.MethodDelete, "/user/emails"}, {http.MethodGet, "/users/:user/followers"}, {http.MethodGet, "/user/followers"}, {http.MethodGet, "/users/:user/following"}, {http.MethodGet, "/user/following"}, {http.MethodGet, "/user/following/:user"}, {http.MethodGet, "/users/:user/following/:target_user"}, {http.MethodPut, "/user/following/:user"}, {http.MethodDelete, "/user/following/:user"}, {http.MethodGet, "/users/:user/keys"}, {http.MethodGet, "/user/keys"}, {http.MethodGet, "/user/keys/:id"}, {http.MethodPost, "/user/keys"}, //{http.MethodPatch, "/user/keys/:id"}, {http.MethodDelete, "/user/keys/:id"}, } func TestShouldBindUri(t *testing.T) { DefaultWriter = os.Stdout router := New() type Person struct { Name string `uri:"name" binding:"required"` ID string `uri:"id" binding:"required"` } router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) { var person Person assert.NoError(t, c.ShouldBindUri(&person)) assert.True(t, person.Name != "") assert.True(t, person.ID != "") c.String(http.StatusOK, "ShouldBindUri test OK") }) path, _ := exampleFromPath("/rest/:name/:id") w := PerformRequest(router, http.MethodGet, path) assert.Equal(t, "ShouldBindUri test OK", w.Body.String()) assert.Equal(t, http.StatusOK, w.Code) } func TestBindUri(t *testing.T) { DefaultWriter = os.Stdout router := New() type Person struct { Name string `uri:"name" binding:"required"` ID string `uri:"id" binding:"required"` } router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) { var person Person assert.NoError(t, c.BindUri(&person)) assert.True(t, person.Name != "") assert.True(t, person.ID != "") c.String(http.StatusOK, "BindUri test OK") }) path, _ := exampleFromPath("/rest/:name/:id") w := PerformRequest(router, http.MethodGet, path) assert.Equal(t, "BindUri test OK", w.Body.String()) assert.Equal(t, http.StatusOK, w.Code) } func TestBindUriError(t *testing.T) { DefaultWriter = os.Stdout router := New() type Member struct { Number string `uri:"num" binding:"required,uuid"` } router.Handle(http.MethodGet, "/new/rest/:num", func(c *Context) { var m Member assert.Error(t, c.BindUri(&m)) }) path1, _ := exampleFromPath("/new/rest/:num") w1 := PerformRequest(router, http.MethodGet, path1) assert.Equal(t, http.StatusBadRequest, w1.Code) } func TestRaceContextCopy(t *testing.T) { DefaultWriter = os.Stdout router := Default() router.GET("/test/copy/race", func(c *Context) { c.Set("1", 0) c.Set("2", 0) // Sending a copy of the Context to two separate routines go readWriteKeys(c.Copy()) go readWriteKeys(c.Copy()) c.String(http.StatusOK, "run OK, no panics") }) w := PerformRequest(router, http.MethodGet, "/test/copy/race") assert.Equal(t, "run OK, no panics", w.Body.String()) } func readWriteKeys(c *Context) { for { c.Set("1", rand.Int()) c.Set("2", c.Value("1")) } } func githubConfigRouter(router *Engine) { for _, route := range githubAPI { router.Handle(route.method, route.path, func(c *Context) { output := make(map[string]string, len(c.Params)+1) output["status"] = "good" for _, param := range c.Params { output[param.Key] = param.Value } c.JSON(http.StatusOK, output) }) } } func TestGithubAPI(t *testing.T) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) for _, route := range githubAPI { path, values := exampleFromPath(route.path) w := PerformRequest(router, route.method, path) // TEST assert.Contains(t, w.Body.String(), "\"status\":\"good\"") for _, value := range values { str := fmt.Sprintf("\"%s\":\"%s\"", value.Key, value.Value) assert.Contains(t, w.Body.String(), str) } } } func exampleFromPath(path string) (string, Params) { output := new(strings.Builder) params := make(Params, 0, 6) start := -1 for i, c := range path { if c == ':' { start = i + 1 } if start >= 0 { if c == '/' { value := fmt.Sprint(rand.Intn(100000)) params = append(params, Param{ Key: path[start:i], Value: value, }) output.WriteString(value) output.WriteRune(c) start = -1 } } else { output.WriteRune(c) } } if start >= 0 { value := fmt.Sprint(rand.Intn(100000)) params = append(params, Param{ Key: path[start:], Value: value, }) output.WriteString(value) } return output.String(), params } func BenchmarkGithub(b *testing.B) { router := New() githubConfigRouter(router) runRequest(b, router, http.MethodGet, "/legacy/issues/search/:owner/:repository/:state/:keyword") } func BenchmarkParallelGithub(b *testing.B) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) req, _ := http.NewRequest(http.MethodPost, "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) } func BenchmarkParallelGithubDefault(b *testing.B) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) req, _ := http.NewRequest(http.MethodPost, "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) }
1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./logger_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "errors" "fmt" "net/http" "testing" "time" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestLogger(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer)) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithConfig(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithConfig(LoggerConfig{Output: buffer})) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithFormatter(t *testing.T) { buffer := new(bytes.Buffer) d := DefaultWriter DefaultWriter = buffer defer func() { DefaultWriter = d }() router := New() router.Use(LoggerWithFormatter(func(param LogFormatterParams) string { return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) })) router.GET("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") } func TestLoggerWithConfigFormatting(t *testing.T) { var gotParam LogFormatterParams var gotKeys map[string]any buffer := new(bytes.Buffer) router := New() router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, Formatter: func(param LogFormatterParams) string { // for assert test gotParam = param return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) }, })) router.GET("/example", func(c *Context) { // set dummy ClientIP c.Request.Header.Set("X-Forwarded-For", "20.20.20.20") gotKeys = c.Keys time.Sleep(time.Millisecond) }) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // LogFormatterParams test assert.NotNil(t, gotParam.Request) assert.NotEmpty(t, gotParam.TimeStamp) assert.Equal(t, 200, gotParam.StatusCode) assert.NotEmpty(t, gotParam.Latency) assert.Equal(t, "20.20.20.20", gotParam.ClientIP) assert.Equal(t, "GET", gotParam.Method) assert.Equal(t, "/example?a=100", gotParam.Path) assert.Empty(t, gotParam.ErrorMessage) assert.Equal(t, gotKeys, gotParam.Keys) } func TestDefaultLogFormatter(t *testing.T) { timeStamp := time.Unix(1544173902, 0).UTC() termFalseParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } termTrueParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termTrueLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termFalseLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 5s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 2743h29m3s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseLongDurationParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 5s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 2743h29m3s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueLongDurationParam)) } func TestColorForMethod(t *testing.T) { colorForMethod := func(method string) string { p := LogFormatterParams{ Method: method, } return p.MethodColor() } assert.Equal(t, blue, colorForMethod("GET"), "get should be blue") assert.Equal(t, cyan, colorForMethod("POST"), "post should be cyan") assert.Equal(t, yellow, colorForMethod("PUT"), "put should be yellow") assert.Equal(t, red, colorForMethod("DELETE"), "delete should be red") assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green") assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta") assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white") assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color") } func TestColorForStatus(t *testing.T) { colorForStatus := func(code int) string { p := LogFormatterParams{ StatusCode: code, } return p.StatusCodeColor() } assert.Equal(t, green, colorForStatus(http.StatusOK), "2xx should be green") assert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), "3xx should be white") assert.Equal(t, yellow, colorForStatus(http.StatusNotFound), "4xx should be yellow") assert.Equal(t, red, colorForStatus(2), "other things should be red") } func TestResetColor(t *testing.T) { p := LogFormatterParams{} assert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor()) } func TestIsOutputColor(t *testing.T) { // test with isTerm flag true. p := LogFormatterParams{ isTerm: true, } consoleColorMode = autoColor assert.Equal(t, true, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // test with isTerm flag false. p = LogFormatterParams{ isTerm: false, } consoleColorMode = autoColor assert.Equal(t, false, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // reset console color mode. consoleColorMode = autoColor } func TestErrorLogger(t *testing.T) { router := New() router.Use(ErrorLogger()) router.GET("/error", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck }) router.GET("/abort", func(c *Context) { c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) //nolint: errcheck }) router.GET("/print", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck c.String(http.StatusInternalServerError, "hola!") }) w := PerformRequest(router, "GET", "/error") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String()) w = PerformRequest(router, "GET", "/abort") assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String()) w = PerformRequest(router, "GET", "/print") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String()) } func TestLoggerWithWriterSkippingPaths(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithWriter(buffer, "/skipped")) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestLoggerWithConfigSkippingPaths(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, SkipPaths: []string{"/skipped"}, })) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestDisableConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) DisableConsoleColor() assert.Equal(t, disableColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor } func TestForceConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) ForceConsoleColor() assert.Equal(t, forceColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "errors" "fmt" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestLogger(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithWriter(buffer)) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithConfig(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithConfig(LoggerConfig{Output: buffer})) router.GET("/example", func(c *Context) {}) router.POST("/example", func(c *Context) {}) router.PUT("/example", func(c *Context) {}) router.DELETE("/example", func(c *Context) {}) router.PATCH("/example", func(c *Context) {}) router.HEAD("/example", func(c *Context) {}) router.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // I wrote these first (extending the above) but then realized they are more // like integration tests because they test the whole logging process rather // than individual functions. Im not sure where these should go. buffer.Reset() PerformRequest(router, "POST", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "POST") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PUT", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PUT") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "DELETE", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "DELETE") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "GET", "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithFormatter(t *testing.T) { buffer := new(strings.Builder) d := DefaultWriter DefaultWriter = buffer defer func() { DefaultWriter = d }() router := New() router.Use(LoggerWithFormatter(func(param LogFormatterParams) string { return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) })) router.GET("/example", func(c *Context) {}) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") } func TestLoggerWithConfigFormatting(t *testing.T) { var gotParam LogFormatterParams var gotKeys map[string]any buffer := new(strings.Builder) router := New() router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, Formatter: func(param LogFormatterParams) string { // for assert test gotParam = param return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) }, })) router.GET("/example", func(c *Context) { // set dummy ClientIP c.Request.Header.Set("X-Forwarded-For", "20.20.20.20") gotKeys = c.Keys time.Sleep(time.Millisecond) }) PerformRequest(router, "GET", "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "GET") assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // LogFormatterParams test assert.NotNil(t, gotParam.Request) assert.NotEmpty(t, gotParam.TimeStamp) assert.Equal(t, 200, gotParam.StatusCode) assert.NotEmpty(t, gotParam.Latency) assert.Equal(t, "20.20.20.20", gotParam.ClientIP) assert.Equal(t, "GET", gotParam.Method) assert.Equal(t, "/example?a=100", gotParam.Path) assert.Empty(t, gotParam.ErrorMessage) assert.Equal(t, gotKeys, gotParam.Keys) } func TestDefaultLogFormatter(t *testing.T) { timeStamp := time.Unix(1544173902, 0).UTC() termFalseParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } termTrueParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termTrueLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: true, } termFalseLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: "GET", Path: "/", ErrorMessage: "", isTerm: false, } assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 5s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 2743h29m3s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseLongDurationParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 5s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 2743h29m3s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueLongDurationParam)) } func TestColorForMethod(t *testing.T) { colorForMethod := func(method string) string { p := LogFormatterParams{ Method: method, } return p.MethodColor() } assert.Equal(t, blue, colorForMethod("GET"), "get should be blue") assert.Equal(t, cyan, colorForMethod("POST"), "post should be cyan") assert.Equal(t, yellow, colorForMethod("PUT"), "put should be yellow") assert.Equal(t, red, colorForMethod("DELETE"), "delete should be red") assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green") assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta") assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white") assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color") } func TestColorForStatus(t *testing.T) { colorForStatus := func(code int) string { p := LogFormatterParams{ StatusCode: code, } return p.StatusCodeColor() } assert.Equal(t, green, colorForStatus(http.StatusOK), "2xx should be green") assert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), "3xx should be white") assert.Equal(t, yellow, colorForStatus(http.StatusNotFound), "4xx should be yellow") assert.Equal(t, red, colorForStatus(2), "other things should be red") } func TestResetColor(t *testing.T) { p := LogFormatterParams{} assert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor()) } func TestIsOutputColor(t *testing.T) { // test with isTerm flag true. p := LogFormatterParams{ isTerm: true, } consoleColorMode = autoColor assert.Equal(t, true, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // test with isTerm flag false. p = LogFormatterParams{ isTerm: false, } consoleColorMode = autoColor assert.Equal(t, false, p.IsOutputColor()) ForceConsoleColor() assert.Equal(t, true, p.IsOutputColor()) DisableConsoleColor() assert.Equal(t, false, p.IsOutputColor()) // reset console color mode. consoleColorMode = autoColor } func TestErrorLogger(t *testing.T) { router := New() router.Use(ErrorLogger()) router.GET("/error", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck }) router.GET("/abort", func(c *Context) { c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) //nolint: errcheck }) router.GET("/print", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck c.String(http.StatusInternalServerError, "hola!") }) w := PerformRequest(router, "GET", "/error") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String()) w = PerformRequest(router, "GET", "/abort") assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String()) w = PerformRequest(router, "GET", "/print") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String()) } func TestLoggerWithWriterSkippingPaths(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithWriter(buffer, "/skipped")) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestLoggerWithConfigSkippingPaths(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, SkipPaths: []string{"/skipped"}, })) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, "GET", "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, "GET", "/skipped") assert.Contains(t, buffer.String(), "") } func TestDisableConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) DisableConsoleColor() assert.Equal(t, disableColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor } func TestForceConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) ForceConsoleColor() assert.Equal(t, forceColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor }
1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./recovery_test.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "bytes" "fmt" "net" "net/http" "os" "strings" "syscall" "testing" "github.com/stretchr/testify/assert" ) func TestPanicClean(t *testing.T) { buffer := new(bytes.Buffer) router := New() password := "my-super-secret-password" router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery", header{ Key: "Host", Value: "www.google.com", }, header{ Key: "Authorization", Value: fmt.Sprintf("Bearer %s", password), }, header{ Key: "Content-Type", Value: "application/json", }, ) // TEST assert.Equal(t, http.StatusBadRequest, w.Code) // Check the buffer does not have the secret key assert.NotContains(t, buffer.String(), password) } // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { buffer := new(bytes.Buffer) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") SetMode(TestMode) } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) } func TestSource(t *testing.T) { bs := source(nil, 0) assert.Equal(t, dunno, bs) in := [][]byte{ []byte("Hello world."), []byte("Hi, gin.."), } bs = source(in, 10) assert.Equal(t, dunno, bs) bs = source(in, 1) assert.Equal(t, []byte("Hello world."), bs) } func TestFunction(t *testing.T) { bs := function(1) assert.Equal(t, dunno, bs) } // TestPanicWithBrokenPipe asserts that recovery specifically handles // writing responses to broken pipes func TestPanicWithBrokenPipe(t *testing.T) { const expectCode = 204 expectMsgs := map[syscall.Errno]string{ syscall.EPIPE: "broken pipe", syscall.ECONNRESET: "connection reset by peer", } for errno, expectMsg := range expectMsgs { t.Run(expectMsg, func(t *testing.T) { var buf bytes.Buffer router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Oops. Client connection closed e := &net.OpError{Err: &os.SyscallError{Err: errno}} panic(e) }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, expectCode, w.Code) assert.Contains(t, strings.ToLower(buf.String()), expectMsg) }) } } func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { errBuffer := new(bytes.Buffer) buffer := new(bytes.Buffer) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "net" "net/http" "os" "strings" "syscall" "testing" "github.com/stretchr/testify/assert" ) func TestPanicClean(t *testing.T) { buffer := new(strings.Builder) router := New() password := "my-super-secret-password" router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery", header{ Key: "Host", Value: "www.google.com", }, header{ Key: "Authorization", Value: fmt.Sprintf("Bearer %s", password), }, header{ Key: "Content-Type", Value: "application/json", }, ) // TEST assert.Equal(t, http.StatusBadRequest, w.Code) // Check the buffer does not have the secret key assert.NotContains(t, buffer.String(), password) } // TestPanicInHandler assert that panic has been recovered. func TestPanicInHandler(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") SetMode(TestMode) } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) } func TestSource(t *testing.T) { bs := source(nil, 0) assert.Equal(t, dunno, bs) in := [][]byte{ []byte("Hello world."), []byte("Hi, gin.."), } bs = source(in, 10) assert.Equal(t, dunno, bs) bs = source(in, 1) assert.Equal(t, []byte("Hello world."), bs) } func TestFunction(t *testing.T) { bs := function(1) assert.Equal(t, dunno, bs) } // TestPanicWithBrokenPipe asserts that recovery specifically handles // writing responses to broken pipes func TestPanicWithBrokenPipe(t *testing.T) { const expectCode = 204 expectMsgs := map[syscall.Errno]string{ syscall.EPIPE: "broken pipe", syscall.ECONNRESET: "connection reset by peer", } for errno, expectMsg := range expectMsgs { t.Run(expectMsg, func(t *testing.T) { var buf strings.Builder router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Oops. Client connection closed e := &net.OpError{Err: &os.SyscallError{Err: errno}} panic(e) }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, expectCode, w.Code) assert.Contains(t, strings.ToLower(buf.String()), expectMsg) }) } } func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) router := New() handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestCustomRecovery(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, "GET", "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) }
1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./any.go
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package gin type any = interface{}
// Copyright 2022 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !go1.18 // +build !go1.18 package gin type any = interface{}
-1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./render/html.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "html/template" "net/http" ) // Delims represents a set of Left and Right delimiters for HTML template rendering. type Delims struct { // Left delimiter, defaults to {{. Left string // Right delimiter, defaults to }}. Right string } // HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. type HTMLRender interface { // Instance returns an HTML instance. Instance(string, any) Render } // HTMLProduction contains template reference and its delims. type HTMLProduction struct { Template *template.Template Delims Delims } // HTMLDebug contains template delims and pattern and function with file list. type HTMLDebug struct { Files []string Glob string Delims Delims FuncMap template.FuncMap } // HTML contains template reference and its name with given interface object. type HTML struct { Template *template.Template Name string Data any } var htmlContentType = []string{"text/html; charset=utf-8"} // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ Template: r.Template, Name: name, Data: data, } } // Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. func (r HTMLDebug) Instance(name string, data any) Render { return HTML{ Template: r.loadTemplate(), Name: name, Data: data, } } func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} } if len(r.Files) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) } if r.Glob != "" { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) } panic("the HTML debug render was created without files or glob pattern") } // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) if r.Name == "" { return r.Template.Execute(w, r.Data) } return r.Template.ExecuteTemplate(w, r.Name, r.Data) } // WriteContentType (HTML) writes HTML ContentType. func (r HTML) WriteContentType(w http.ResponseWriter) { writeContentType(w, htmlContentType) }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package render import ( "html/template" "net/http" ) // Delims represents a set of Left and Right delimiters for HTML template rendering. type Delims struct { // Left delimiter, defaults to {{. Left string // Right delimiter, defaults to }}. Right string } // HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. type HTMLRender interface { // Instance returns an HTML instance. Instance(string, any) Render } // HTMLProduction contains template reference and its delims. type HTMLProduction struct { Template *template.Template Delims Delims } // HTMLDebug contains template delims and pattern and function with file list. type HTMLDebug struct { Files []string Glob string Delims Delims FuncMap template.FuncMap } // HTML contains template reference and its name with given interface object. type HTML struct { Template *template.Template Name string Data any } var htmlContentType = []string{"text/html; charset=utf-8"} // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ Template: r.Template, Name: name, Data: data, } } // Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. func (r HTMLDebug) Instance(name string, data any) Render { return HTML{ Template: r.loadTemplate(), Name: name, Data: data, } } func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} } if len(r.Files) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) } if r.Glob != "" { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) } panic("the HTML debug render was created without files or glob pattern") } // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) if r.Name == "" { return r.Template.Execute(w, r.Data) } return r.Template.ExecuteTemplate(w, r.Name, r.Data) } // WriteContentType (HTML) writes HTML ContentType. func (r HTML) WriteContentType(w http.ResponseWriter) { writeContentType(w, htmlContentType) }
-1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./logger.go
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "io" "net/http" "os" "time" "github.com/mattn/go-isatty" ) type consoleColorModeValue int const ( autoColor consoleColorModeValue = iota disableColor forceColor ) const ( green = "\033[97;42m" white = "\033[90;47m" yellow = "\033[90;43m" red = "\033[97;41m" blue = "\033[97;44m" magenta = "\033[97;45m" cyan = "\033[97;46m" reset = "\033[0m" ) var consoleColorMode = autoColor // LoggerConfig defines the config for Logger middleware. type LoggerConfig struct { // Optional. Default value is gin.defaultLogFormatter Formatter LogFormatter // Output is a writer where logs are written. // Optional. Default value is gin.DefaultWriter. Output io.Writer // SkipPaths is an url path array which logs are not written. // Optional. SkipPaths []string } // LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter type LogFormatter func(params LogFormatterParams) string // LogFormatterParams is the structure any formatter will be handed when time to log comes type LogFormatterParams struct { Request *http.Request // TimeStamp shows the time after the server returns a response. TimeStamp time.Time // StatusCode is HTTP response code. StatusCode int // Latency is how much time the server cost to process a certain request. Latency time.Duration // ClientIP equals Context's ClientIP method. ClientIP string // Method is the HTTP method given to the request. Method string // Path is a path the client requests. Path string // ErrorMessage is set if error has occurred in processing the request. ErrorMessage string // isTerm shows whether gin's output descriptor refers to a terminal. isTerm bool // BodySize is the size of the Response Body BodySize int // Keys are the keys set on the request's context. Keys map[string]any } // StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal. func (p *LogFormatterParams) StatusCodeColor() string { code := p.StatusCode switch { case code >= http.StatusOK && code < http.StatusMultipleChoices: return green case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: return white case code >= http.StatusBadRequest && code < http.StatusInternalServerError: return yellow default: return red } } // MethodColor is the ANSI color for appropriately logging http method to a terminal. func (p *LogFormatterParams) MethodColor() string { method := p.Method switch method { case http.MethodGet: return blue case http.MethodPost: return cyan case http.MethodPut: return yellow case http.MethodDelete: return red case http.MethodPatch: return green case http.MethodHead: return magenta case http.MethodOptions: return white default: return reset } } // ResetColor resets all escape attributes. func (p *LogFormatterParams) ResetColor() string { return reset } // IsOutputColor indicates whether can colors be outputted to the log. func (p *LogFormatterParams) IsOutputColor() bool { return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm) } // defaultLogFormatter is the default log format function Logger middleware uses. var defaultLogFormatter = func(param LogFormatterParams) string { var statusColor, methodColor, resetColor string if param.IsOutputColor() { statusColor = param.StatusCodeColor() methodColor = param.MethodColor() resetColor = param.ResetColor() } if param.Latency > time.Minute { param.Latency = param.Latency.Truncate(time.Second) } return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), statusColor, param.StatusCode, resetColor, param.Latency, param.ClientIP, methodColor, param.Method, resetColor, param.Path, param.ErrorMessage, ) } // DisableConsoleColor disables color output in the console. func DisableConsoleColor() { consoleColorMode = disableColor } // ForceConsoleColor force color output in the console. func ForceConsoleColor() { consoleColorMode = forceColor } // ErrorLogger returns a HandlerFunc for any error type. func ErrorLogger() HandlerFunc { return ErrorLoggerT(ErrorTypeAny) } // ErrorLoggerT returns a HandlerFunc for a given error type. func ErrorLoggerT(typ ErrorType) HandlerFunc { return func(c *Context) { c.Next() errors := c.Errors.ByType(typ) if len(errors) > 0 { c.JSON(-1, errors) } } } // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. // By default, gin.DefaultWriter = os.Stdout. func Logger() HandlerFunc { return LoggerWithConfig(LoggerConfig{}) } // LoggerWithFormatter instance a Logger middleware with the specified log format function. func LoggerWithFormatter(f LogFormatter) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Formatter: f, }) } // LoggerWithWriter instance a Logger middleware with the specified writer buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Output: out, SkipPaths: notlogged, }) } // LoggerWithConfig instance a Logger middleware with config. func LoggerWithConfig(conf LoggerConfig) HandlerFunc { formatter := conf.Formatter if formatter == nil { formatter = defaultLogFormatter } out := conf.Output if out == nil { out = DefaultWriter } notlogged := conf.SkipPaths isTerm := true if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) { isTerm = false } var skip map[string]struct{} if length := len(notlogged); length > 0 { skip = make(map[string]struct{}, length) for _, path := range notlogged { skip[path] = struct{}{} } } return func(c *Context) { // Start timer start := time.Now() path := c.Request.URL.Path raw := c.Request.URL.RawQuery // Process request c.Next() // Log only when path is not being skipped if _, ok := skip[path]; !ok { param := LogFormatterParams{ Request: c.Request, isTerm: isTerm, Keys: c.Keys, } // Stop timer param.TimeStamp = time.Now() param.Latency = param.TimeStamp.Sub(start) param.ClientIP = c.ClientIP() param.Method = c.Request.Method param.StatusCode = c.Writer.Status() param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String() param.BodySize = c.Writer.Size() if raw != "" { path = path + "?" + raw } param.Path = path fmt.Fprint(out, formatter(param)) } } }
// Copyright 2014 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package gin import ( "fmt" "io" "net/http" "os" "time" "github.com/mattn/go-isatty" ) type consoleColorModeValue int const ( autoColor consoleColorModeValue = iota disableColor forceColor ) const ( green = "\033[97;42m" white = "\033[90;47m" yellow = "\033[90;43m" red = "\033[97;41m" blue = "\033[97;44m" magenta = "\033[97;45m" cyan = "\033[97;46m" reset = "\033[0m" ) var consoleColorMode = autoColor // LoggerConfig defines the config for Logger middleware. type LoggerConfig struct { // Optional. Default value is gin.defaultLogFormatter Formatter LogFormatter // Output is a writer where logs are written. // Optional. Default value is gin.DefaultWriter. Output io.Writer // SkipPaths is an url path array which logs are not written. // Optional. SkipPaths []string } // LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter type LogFormatter func(params LogFormatterParams) string // LogFormatterParams is the structure any formatter will be handed when time to log comes type LogFormatterParams struct { Request *http.Request // TimeStamp shows the time after the server returns a response. TimeStamp time.Time // StatusCode is HTTP response code. StatusCode int // Latency is how much time the server cost to process a certain request. Latency time.Duration // ClientIP equals Context's ClientIP method. ClientIP string // Method is the HTTP method given to the request. Method string // Path is a path the client requests. Path string // ErrorMessage is set if error has occurred in processing the request. ErrorMessage string // isTerm shows whether gin's output descriptor refers to a terminal. isTerm bool // BodySize is the size of the Response Body BodySize int // Keys are the keys set on the request's context. Keys map[string]any } // StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal. func (p *LogFormatterParams) StatusCodeColor() string { code := p.StatusCode switch { case code >= http.StatusOK && code < http.StatusMultipleChoices: return green case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: return white case code >= http.StatusBadRequest && code < http.StatusInternalServerError: return yellow default: return red } } // MethodColor is the ANSI color for appropriately logging http method to a terminal. func (p *LogFormatterParams) MethodColor() string { method := p.Method switch method { case http.MethodGet: return blue case http.MethodPost: return cyan case http.MethodPut: return yellow case http.MethodDelete: return red case http.MethodPatch: return green case http.MethodHead: return magenta case http.MethodOptions: return white default: return reset } } // ResetColor resets all escape attributes. func (p *LogFormatterParams) ResetColor() string { return reset } // IsOutputColor indicates whether can colors be outputted to the log. func (p *LogFormatterParams) IsOutputColor() bool { return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm) } // defaultLogFormatter is the default log format function Logger middleware uses. var defaultLogFormatter = func(param LogFormatterParams) string { var statusColor, methodColor, resetColor string if param.IsOutputColor() { statusColor = param.StatusCodeColor() methodColor = param.MethodColor() resetColor = param.ResetColor() } if param.Latency > time.Minute { param.Latency = param.Latency.Truncate(time.Second) } return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), statusColor, param.StatusCode, resetColor, param.Latency, param.ClientIP, methodColor, param.Method, resetColor, param.Path, param.ErrorMessage, ) } // DisableConsoleColor disables color output in the console. func DisableConsoleColor() { consoleColorMode = disableColor } // ForceConsoleColor force color output in the console. func ForceConsoleColor() { consoleColorMode = forceColor } // ErrorLogger returns a HandlerFunc for any error type. func ErrorLogger() HandlerFunc { return ErrorLoggerT(ErrorTypeAny) } // ErrorLoggerT returns a HandlerFunc for a given error type. func ErrorLoggerT(typ ErrorType) HandlerFunc { return func(c *Context) { c.Next() errors := c.Errors.ByType(typ) if len(errors) > 0 { c.JSON(-1, errors) } } } // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. // By default, gin.DefaultWriter = os.Stdout. func Logger() HandlerFunc { return LoggerWithConfig(LoggerConfig{}) } // LoggerWithFormatter instance a Logger middleware with the specified log format function. func LoggerWithFormatter(f LogFormatter) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Formatter: f, }) } // LoggerWithWriter instance a Logger middleware with the specified writer buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Output: out, SkipPaths: notlogged, }) } // LoggerWithConfig instance a Logger middleware with config. func LoggerWithConfig(conf LoggerConfig) HandlerFunc { formatter := conf.Formatter if formatter == nil { formatter = defaultLogFormatter } out := conf.Output if out == nil { out = DefaultWriter } notlogged := conf.SkipPaths isTerm := true if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) { isTerm = false } var skip map[string]struct{} if length := len(notlogged); length > 0 { skip = make(map[string]struct{}, length) for _, path := range notlogged { skip[path] = struct{}{} } } return func(c *Context) { // Start timer start := time.Now() path := c.Request.URL.Path raw := c.Request.URL.RawQuery // Process request c.Next() // Log only when path is not being skipped if _, ok := skip[path]; !ok { param := LogFormatterParams{ Request: c.Request, isTerm: isTerm, Keys: c.Keys, } // Stop timer param.TimeStamp = time.Now() param.Latency = param.TimeStamp.Sub(start) param.ClientIP = c.ClientIP() param.Method = c.Request.Method param.StatusCode = c.Writer.Status() param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String() param.BodySize = c.Writer.Size() if raw != "" { path = path + "?" + raw } param.Path = path fmt.Fprint(out, formatter(param)) } } }
-1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./binding/query.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import "net/http" type queryBinding struct{} func (queryBinding) Name() string { return "query" } func (queryBinding) Bind(req *http.Request, obj any) error { values := req.URL.Query() if err := mapForm(obj, values); err != nil { return err } return validate(obj) }
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import "net/http" type queryBinding struct{} func (queryBinding) Name() string { return "query" } func (queryBinding) Bind(req *http.Request, obj any) error { values := req.URL.Query() if err := mapForm(obj, values); err != nil { return err } return validate(obj) }
-1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./binding/multipart_form_mapping.go
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "mime/multipart" "net/http" "reflect" ) type multipartRequest http.Request var _ setter = (*multipartRequest)(nil) var ( // ErrMultiFileHeader multipart.FileHeader invalid ErrMultiFileHeader = errors.New("unsupported field type for multipart.FileHeader") // ErrMultiFileHeaderLenInvalid array for []*multipart.FileHeader len invalid ErrMultiFileHeaderLenInvalid = errors.New("unsupported len of array for []*multipart.FileHeader") ) // TrySet tries to set a value by the multipart request with the binding a form file func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (bool, error) { if files := r.MultipartForm.File[key]; len(files) != 0 { return setByMultipartFormFile(value, field, files) } return setByForm(value, field, r.MultipartForm.Value, key, opt) } func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) { switch value.Kind() { case reflect.Ptr: switch value.Interface().(type) { case *multipart.FileHeader: value.Set(reflect.ValueOf(files[0])) return true, nil } case reflect.Struct: switch value.Interface().(type) { case multipart.FileHeader: value.Set(reflect.ValueOf(*files[0])) return true, nil } case reflect.Slice: slice := reflect.MakeSlice(value.Type(), len(files), len(files)) isSet, err = setArrayOfMultipartFormFiles(slice, field, files) if err != nil || !isSet { return isSet, err } value.Set(slice) return true, nil case reflect.Array: return setArrayOfMultipartFormFiles(value, field, files) } return false, ErrMultiFileHeader } func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) { if value.Len() != len(files) { return false, ErrMultiFileHeaderLenInvalid } for i := range files { set, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1]) if err != nil || !set { return set, err } } return true, nil }
// Copyright 2019 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "errors" "mime/multipart" "net/http" "reflect" ) type multipartRequest http.Request var _ setter = (*multipartRequest)(nil) var ( // ErrMultiFileHeader multipart.FileHeader invalid ErrMultiFileHeader = errors.New("unsupported field type for multipart.FileHeader") // ErrMultiFileHeaderLenInvalid array for []*multipart.FileHeader len invalid ErrMultiFileHeaderLenInvalid = errors.New("unsupported len of array for []*multipart.FileHeader") ) // TrySet tries to set a value by the multipart request with the binding a form file func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (bool, error) { if files := r.MultipartForm.File[key]; len(files) != 0 { return setByMultipartFormFile(value, field, files) } return setByForm(value, field, r.MultipartForm.Value, key, opt) } func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) { switch value.Kind() { case reflect.Ptr: switch value.Interface().(type) { case *multipart.FileHeader: value.Set(reflect.ValueOf(files[0])) return true, nil } case reflect.Struct: switch value.Interface().(type) { case multipart.FileHeader: value.Set(reflect.ValueOf(*files[0])) return true, nil } case reflect.Slice: slice := reflect.MakeSlice(value.Type(), len(files), len(files)) isSet, err = setArrayOfMultipartFormFiles(slice, field, files) if err != nil || !isSet { return isSet, err } value.Set(slice) return true, nil case reflect.Array: return setArrayOfMultipartFormFiles(value, field, files) } return false, ErrMultiFileHeader } func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) { if value.Len() != len(files) { return false, ErrMultiFileHeaderLenInvalid } for i := range files { set, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1]) if err != nil || !set { return set, err } } return true, nil }
-1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./binding/binding_msgpack_test.go
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package binding import ( "bytes" "testing" "github.com/stretchr/testify/assert" "github.com/ugorji/go/codec" ) func TestBindingMsgPack(t *testing.T) { test := FooStruct{ Foo: "bar", } h := new(codec.MsgpackHandle) assert.NotNil(t, h) buf := bytes.NewBuffer([]byte{}) assert.NotNil(t, buf) err := codec.NewEncoder(buf, h).Encode(test) assert.NoError(t, err) data := buf.Bytes() testMsgPackBodyBinding(t, MsgPack, "msgpack", "/", "/", string(data), string(data[1:])) } func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) { assert.Equal(t, name, b.Name()) obj := FooStruct{} req := requestWithBody("POST", path, body) req.Header.Add("Content-Type", MIMEMSGPACK) err := b.Bind(req, &obj) assert.NoError(t, err) assert.Equal(t, "bar", obj.Foo) obj = FooStruct{} req = requestWithBody("POST", badPath, badBody) req.Header.Add("Content-Type", MIMEMSGPACK) err = MsgPack.Bind(req, &obj) assert.Error(t, err) } func TestBindingDefaultMsgPack(t *testing.T) { assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK)) assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2)) }
// Copyright 2020 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package binding import ( "bytes" "testing" "github.com/stretchr/testify/assert" "github.com/ugorji/go/codec" ) func TestBindingMsgPack(t *testing.T) { test := FooStruct{ Foo: "bar", } h := new(codec.MsgpackHandle) assert.NotNil(t, h) buf := bytes.NewBuffer([]byte{}) assert.NotNil(t, buf) err := codec.NewEncoder(buf, h).Encode(test) assert.NoError(t, err) data := buf.Bytes() testMsgPackBodyBinding(t, MsgPack, "msgpack", "/", "/", string(data), string(data[1:])) } func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) { assert.Equal(t, name, b.Name()) obj := FooStruct{} req := requestWithBody("POST", path, body) req.Header.Add("Content-Type", MIMEMSGPACK) err := b.Bind(req, &obj) assert.NoError(t, err) assert.Equal(t, "bar", obj.Foo) obj = FooStruct{} req = requestWithBody("POST", badPath, badBody) req.Header.Add("Content-Type", MIMEMSGPACK) err = MsgPack.Bind(req, &obj) assert.Error(t, err) } func TestBindingDefaultMsgPack(t *testing.T) { assert.Equal(t, MsgPack, Default("POST", MIMEMSGPACK)) assert.Equal(t, MsgPack, Default("PUT", MIMEMSGPACK2)) }
-1
gin-gonic/gin
3,347
Replace bytes.Buffer with strings.Builder where appropriate
To build strings more efficiently, use strings.Builder instead.
hopehook
"2022-10-03T05:49:17Z"
"2023-01-20T01:51:42Z"
8cd11c82e447f74d63e3da6037cb0463440d8e16
b2d4185eec36ce5e0cf21be7cb246fb8be9fd6db
Replace bytes.Buffer with strings.Builder where appropriate. To build strings more efficiently, use strings.Builder instead.
./render/msgpack.go
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package render import ( "net/http" "github.com/ugorji/go/codec" ) // Check interface implemented here to support go build tag nomsgpack. // See: https://github.com/gin-gonic/gin/pull/1852/ var ( _ Render = MsgPack{} ) // MsgPack contains the given interface object. type MsgPack struct { Data any } var msgpackContentType = []string{"application/msgpack; charset=utf-8"} // WriteContentType (MsgPack) writes MsgPack ContentType. func (r MsgPack) WriteContentType(w http.ResponseWriter) { writeContentType(w, msgpackContentType) } // Render (MsgPack) encodes the given interface object and writes data with custom ContentType. func (r MsgPack) Render(w http.ResponseWriter) error { return WriteMsgPack(w, r.Data) } // WriteMsgPack writes MsgPack ContentType and encodes the given interface object. func WriteMsgPack(w http.ResponseWriter, obj any) error { writeContentType(w, msgpackContentType) var mh codec.MsgpackHandle return codec.NewEncoder(w, &mh).Encode(obj) }
// Copyright 2017 Manu Martinez-Almeida. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. //go:build !nomsgpack // +build !nomsgpack package render import ( "net/http" "github.com/ugorji/go/codec" ) // Check interface implemented here to support go build tag nomsgpack. // See: https://github.com/gin-gonic/gin/pull/1852/ var ( _ Render = MsgPack{} ) // MsgPack contains the given interface object. type MsgPack struct { Data any } var msgpackContentType = []string{"application/msgpack; charset=utf-8"} // WriteContentType (MsgPack) writes MsgPack ContentType. func (r MsgPack) WriteContentType(w http.ResponseWriter) { writeContentType(w, msgpackContentType) } // Render (MsgPack) encodes the given interface object and writes data with custom ContentType. func (r MsgPack) Render(w http.ResponseWriter) error { return WriteMsgPack(w, r.Data) } // WriteMsgPack writes MsgPack ContentType and encodes the given interface object. func WriteMsgPack(w http.ResponseWriter, obj any) error { writeContentType(w, msgpackContentType) var mh codec.MsgpackHandle return codec.NewEncoder(w, &mh).Encode(obj) }
-1