chore: upgrade golangci-lint and fix golangci-lint error (#3278)

This commit is contained in:
thinkerou 2022-08-15 21:38:20 +08:00 committed by GitHub
parent 1b5ba251cf
commit b04917c53e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 74 additions and 60 deletions

View File

@ -21,7 +21,7 @@ jobs:
- name: Setup golangci-lint - name: Setup golangci-lint
uses: golangci/golangci-lint-action@v3.2.0 uses: golangci/golangci-lint-action@v3.2.0
with: with:
version: v1.45.0 version: v1.48.0
args: --verbose args: --verbose
test: test:
needs: lint needs: lint

View File

@ -153,9 +153,10 @@ func (c *Context) Handler() HandlerFunc {
// FullPath returns a matched route full path. For not found routes // FullPath returns a matched route full path. For not found routes
// returns an empty string. // returns an empty string.
// router.GET("/user/:id", func(c *gin.Context) { //
// c.FullPath() == "/user/:id" // true // router.GET("/user/:id", func(c *gin.Context) {
// }) // c.FullPath() == "/user/:id" // true
// })
func (c *Context) FullPath() string { func (c *Context) FullPath() string {
return c.fullPath return c.fullPath
} }
@ -382,10 +383,11 @@ func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)
// Param returns the value of the URL param. // Param returns the value of the URL param.
// It is a shortcut for c.Params.ByName(key) // It is a shortcut for c.Params.ByName(key)
// router.GET("/user/:id", func(c *gin.Context) { //
// // a GET request to /user/john // router.GET("/user/:id", func(c *gin.Context) {
// id := c.Param("id") // id == "john" // // a GET request to /user/john
// }) // id := c.Param("id") // id == "john"
// })
func (c *Context) Param(key string) string { func (c *Context) Param(key string) string {
return c.Params.ByName(key) return c.Params.ByName(key)
} }
@ -402,11 +404,12 @@ func (c *Context) AddParam(key, value string) {
// Query returns the keyed url query value if it exists, // Query returns the keyed url query value if it exists,
// otherwise it returns an empty string `("")`. // otherwise it returns an empty string `("")`.
// It is shortcut for `c.Request.URL.Query().Get(key)` // It is shortcut for `c.Request.URL.Query().Get(key)`
// GET /path?id=1234&name=Manu&value= //
// c.Query("id") == "1234" // GET /path?id=1234&name=Manu&value=
// c.Query("name") == "Manu" // c.Query("id") == "1234"
// c.Query("value") == "" // c.Query("name") == "Manu"
// c.Query("wtf") == "" // c.Query("value") == ""
// c.Query("wtf") == ""
func (c *Context) Query(key string) (value string) { func (c *Context) Query(key string) (value string) {
value, _ = c.GetQuery(key) value, _ = c.GetQuery(key)
return return
@ -415,10 +418,11 @@ func (c *Context) Query(key string) (value string) {
// DefaultQuery returns the keyed url query value if it exists, // DefaultQuery returns the keyed url query value if it exists,
// otherwise it returns the specified defaultValue string. // otherwise it returns the specified defaultValue string.
// See: Query() and GetQuery() for further information. // See: Query() and GetQuery() for further information.
// GET /?name=Manu&lastname= //
// c.DefaultQuery("name", "unknown") == "Manu" // GET /?name=Manu&lastname=
// c.DefaultQuery("id", "none") == "none" // c.DefaultQuery("name", "unknown") == "Manu"
// c.DefaultQuery("lastname", "none") == "" // c.DefaultQuery("id", "none") == "none"
// c.DefaultQuery("lastname", "none") == ""
func (c *Context) DefaultQuery(key, defaultValue string) string { func (c *Context) DefaultQuery(key, defaultValue string) string {
if value, ok := c.GetQuery(key); ok { if value, ok := c.GetQuery(key); ok {
return value return value
@ -430,10 +434,11 @@ func (c *Context) DefaultQuery(key, defaultValue string) string {
// if it exists `(value, true)` (even when the value is an empty string), // if it exists `(value, true)` (even when the value is an empty string),
// otherwise it returns `("", false)`. // otherwise it returns `("", false)`.
// It is shortcut for `c.Request.URL.Query().Get(key)` // It is shortcut for `c.Request.URL.Query().Get(key)`
// GET /?name=Manu&lastname= //
// ("Manu", true) == c.GetQuery("name") // GET /?name=Manu&lastname=
// ("", false) == c.GetQuery("id") // ("Manu", true) == c.GetQuery("name")
// ("", true) == c.GetQuery("lastname") // ("", false) == c.GetQuery("id")
// ("", true) == c.GetQuery("lastname")
func (c *Context) GetQuery(key string) (string, bool) { func (c *Context) GetQuery(key string) (string, bool) {
if values, ok := c.GetQueryArray(key); ok { if values, ok := c.GetQueryArray(key); ok {
return values[0], ok return values[0], ok
@ -500,9 +505,10 @@ func (c *Context) DefaultPostForm(key, defaultValue string) string {
// form or multipart form when it exists `(value, true)` (even when the value is an empty string), // form or multipart form when it exists `(value, true)` (even when the value is an empty string),
// otherwise it returns ("", false). // otherwise it returns ("", false).
// For example, during a PATCH request to update the user's email: // For example, during a PATCH request to update the user's email:
// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" //
// email= --> ("", true) := GetPostForm("email") // set email to "" // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
// --> ("", false) := GetPostForm("email") // do nothing with email // email= --> ("", true) := GetPostForm("email") // set email to ""
// --> ("", false) := GetPostForm("email") // do nothing with email
func (c *Context) GetPostForm(key string) (string, bool) { func (c *Context) GetPostForm(key string) (string, bool) {
if values, ok := c.GetPostFormArray(key); ok { if values, ok := c.GetPostFormArray(key); ok {
return values[0], ok return values[0], ok
@ -607,8 +613,10 @@ func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
// Bind checks the Method and Content-Type to select a binding engine automatically, // Bind checks the Method and Content-Type to select a binding engine automatically,
// Depending on the "Content-Type" header different bindings are used, for example: // Depending on the "Content-Type" header different bindings are used, for example:
// "application/json" --> JSON binding //
// "application/xml" --> XML binding // "application/json" --> JSON binding
// "application/xml" --> XML binding
//
// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
// It decodes the json payload into the struct specified as a pointer. // It decodes the json payload into the struct specified as a pointer.
// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid. // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
@ -651,7 +659,7 @@ func (c *Context) BindHeader(obj any) error {
// It will abort the request with HTTP 400 if any error occurs. // It will abort the request with HTTP 400 if any error occurs.
func (c *Context) BindUri(obj any) error { func (c *Context) BindUri(obj any) error {
if err := c.ShouldBindUri(obj); err != nil { if err := c.ShouldBindUri(obj); err != nil {
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck
return err return err
} }
return nil return nil
@ -662,7 +670,7 @@ func (c *Context) BindUri(obj any) error {
// See the binding package. // See the binding package.
func (c *Context) MustBindWith(obj any, b binding.Binding) error { func (c *Context) MustBindWith(obj any, b binding.Binding) error {
if err := c.ShouldBindWith(obj, b); err != nil { if err := c.ShouldBindWith(obj, b); err != nil {
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck
return err return err
} }
return nil return nil
@ -670,8 +678,10 @@ func (c *Context) MustBindWith(obj any, b binding.Binding) error {
// ShouldBind checks the Method and Content-Type to select a binding engine automatically, // ShouldBind checks the Method and Content-Type to select a binding engine automatically,
// Depending on the "Content-Type" header different bindings are used, for example: // Depending on the "Content-Type" header different bindings are used, for example:
// "application/json" --> JSON binding //
// "application/xml" --> XML binding // "application/json" --> JSON binding
// "application/xml" --> XML binding
//
// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
// It decodes the json payload into the struct specified as a pointer. // It decodes the json payload into the struct specified as a pointer.
// Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid. // Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid.
@ -1112,7 +1122,7 @@ func (c *Context) Negotiate(code int, config Negotiate) {
c.TOML(code, data) c.TOML(code, data)
default: default:
c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) //nolint: errcheck
} }
} }

View File

@ -152,7 +152,7 @@ func TestContextReset(t *testing.T) {
c.index = 2 c.index = 2
c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()} c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
c.Params = Params{Param{}} c.Params = Params{Param{}}
c.Error(errors.New("test")) // nolint: errcheck c.Error(errors.New("test")) //nolint: errcheck
c.Set("foo", "bar") c.Set("foo", "bar")
c.reset() c.reset()
@ -1376,12 +1376,12 @@ func TestContextError(t *testing.T) {
assert.Empty(t, c.Errors) assert.Empty(t, c.Errors)
firstErr := errors.New("first error") firstErr := errors.New("first error")
c.Error(firstErr) // nolint: errcheck c.Error(firstErr) //nolint: errcheck
assert.Len(t, c.Errors, 1) assert.Len(t, c.Errors, 1)
assert.Equal(t, "Error #01: first error\n", c.Errors.String()) assert.Equal(t, "Error #01: first error\n", c.Errors.String())
secondErr := errors.New("second error") secondErr := errors.New("second error")
c.Error(&Error{ // nolint: errcheck c.Error(&Error{ //nolint: errcheck
Err: secondErr, Err: secondErr,
Meta: "some data 2", Meta: "some data 2",
Type: ErrorTypePublic, Type: ErrorTypePublic,
@ -1403,13 +1403,13 @@ func TestContextError(t *testing.T) {
t.Error("didn't panic") t.Error("didn't panic")
} }
}() }()
c.Error(nil) // nolint: errcheck c.Error(nil) //nolint: errcheck
} }
func TestContextTypedError(t *testing.T) { func TestContextTypedError(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder()) c, _ := CreateTestContext(httptest.NewRecorder())
c.Error(errors.New("externo 0")).SetType(ErrorTypePublic) // nolint: errcheck c.Error(errors.New("externo 0")).SetType(ErrorTypePublic) //nolint: errcheck
c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate) // nolint: errcheck c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate) //nolint: errcheck
for _, err := range c.Errors.ByType(ErrorTypePublic) { for _, err := range c.Errors.ByType(ErrorTypePublic) {
assert.Equal(t, ErrorTypePublic, err.Type) assert.Equal(t, ErrorTypePublic, err.Type)
@ -1424,7 +1424,7 @@ func TestContextAbortWithError(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
c, _ := CreateTestContext(w) c, _ := CreateTestContext(w)
c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input") // nolint: errcheck c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input") //nolint: errcheck
assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Equal(t, abortIndex, c.index) assert.Equal(t, abortIndex, c.index)

View File

@ -124,10 +124,11 @@ func (a errorMsgs) Last() *Error {
// Errors returns an array with all the error messages. // Errors returns an array with all the error messages.
// Example: // Example:
// c.Error(errors.New("first")) //
// c.Error(errors.New("second")) // c.Error(errors.New("first"))
// c.Error(errors.New("third")) // c.Error(errors.New("second"))
// c.Errors.Errors() // == []string{"first", "second", "third"} // c.Error(errors.New("third"))
// c.Errors.Errors() // == []string{"first", "second", "third"}
func (a errorMsgs) Errors() []string { func (a errorMsgs) Errors() []string {
if len(a) == 0 { if len(a) == 0 {
return nil return nil

View File

@ -35,7 +35,7 @@ func TestError(t *testing.T) {
jsonBytes, _ := json.Marshal(err) jsonBytes, _ := json.Marshal(err)
assert.Equal(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes)) assert.Equal(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))
err.SetMeta(H{ // nolint: errcheck err.SetMeta(H{ //nolint: errcheck
"status": "200", "status": "200",
"data": "some data", "data": "some data",
}) })
@ -45,7 +45,7 @@ func TestError(t *testing.T) {
"data": "some data", "data": "some data",
}, err.JSON()) }, err.JSON())
err.SetMeta(H{ // nolint: errcheck err.SetMeta(H{ //nolint: errcheck
"error": "custom error", "error": "custom error",
"status": "200", "status": "200",
"data": "some data", "data": "some data",
@ -60,7 +60,7 @@ func TestError(t *testing.T) {
status string status string
data string data string
} }
err.SetMeta(customError{status: "200", data: "other data"}) // nolint: errcheck err.SetMeta(customError{status: "200", data: "other data"}) //nolint: errcheck
assert.Equal(t, customError{status: "200", data: "other data"}, err.JSON()) assert.Equal(t, customError{status: "200", data: "other data"}, err.JSON())
} }

View File

@ -108,7 +108,8 @@ func StaticFile(relativePath, filepath string) gin.IRoutes {
// of the Router's NotFound handler. // of the Router's NotFound handler.
// To use the operating system's file system implementation, // To use the operating system's file system implementation,
// use : // use :
// router.Static("/static", "/var/www") //
// router.Static("/static", "/var/www")
func Static(relativePath, root string) gin.IRoutes { func Static(relativePath, root string) gin.IRoutes {
return engine().Static(relativePath, root) return engine().Static(relativePath, root)
} }

View File

@ -358,13 +358,13 @@ func TestErrorLogger(t *testing.T) {
router := New() router := New()
router.Use(ErrorLogger()) router.Use(ErrorLogger())
router.GET("/error", func(c *Context) { router.GET("/error", func(c *Context) {
c.Error(errors.New("this is an error")) // nolint: errcheck c.Error(errors.New("this is an error")) //nolint: errcheck
}) })
router.GET("/abort", func(c *Context) { router.GET("/abort", func(c *Context) {
c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) // nolint: errcheck c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) //nolint: errcheck
}) })
router.GET("/print", func(c *Context) { router.GET("/print", func(c *Context) {
c.Error(errors.New("this is an error")) // nolint: errcheck c.Error(errors.New("this is an error")) //nolint: errcheck
c.String(http.StatusInternalServerError, "hola!") c.String(http.StatusInternalServerError, "hola!")
}) })

View File

@ -211,7 +211,7 @@ func TestMiddlewareFailHandlersChain(t *testing.T) {
router := New() router := New()
router.Use(func(context *Context) { router.Use(func(context *Context) {
signature += "A" signature += "A"
context.AbortWithError(http.StatusInternalServerError, errors.New("foo")) // nolint: errcheck context.AbortWithError(http.StatusInternalServerError, errors.New("foo")) //nolint: errcheck
}) })
router.Use(func(context *Context) { router.Use(func(context *Context) {
signature += "B" signature += "B"

View File

@ -35,8 +35,9 @@ const (
// Note that both Logger and Recovery provides custom ways to configure their // Note that both Logger and Recovery provides custom ways to configure their
// output io.Writer. // output io.Writer.
// To support coloring in Windows use: // To support coloring in Windows use:
// import "github.com/mattn/go-colorable" //
// gin.DefaultWriter = colorable.NewColorableStdout() // import "github.com/mattn/go-colorable"
// gin.DefaultWriter = colorable.NewColorableStdout()
var DefaultWriter io.Writer = os.Stdout var DefaultWriter io.Writer = os.Stdout
// DefaultErrorWriter is the default io.Writer used by Gin to debug errors // DefaultErrorWriter is the default io.Writer used by Gin to debug errors

12
path.go
View File

@ -10,12 +10,12 @@ package gin
// //
// The following rules are applied iteratively until no further processing can // The following rules are applied iteratively until no further processing can
// be done: // be done:
// 1. Replace multiple slashes with a single slash. // 1. Replace multiple slashes with a single slash.
// 2. Eliminate each . path name element (the current directory). // 2. Eliminate each . path name element (the current directory).
// 3. Eliminate each inner .. path name element (the parent directory) // 3. Eliminate each inner .. path name element (the parent directory)
// along with the non-.. element that precedes it. // along with the non-.. element that precedes it.
// 4. Eliminate .. elements that begin a rooted path: // 4. Eliminate .. elements that begin a rooted path:
// that is, replace "/.." by "/" at the beginning of a path. // that is, replace "/.." by "/" at the beginning of a path.
// //
// If the result of this process is an empty string, "/" is returned. // If the result of this process is an empty string, "/" is returned.
func cleanPath(p string) string { func cleanPath(p string) string {

View File

@ -91,7 +91,7 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
} }
if brokenPipe { if brokenPipe {
// If the connection is dead, we can't write a status to it. // If the connection is dead, we can't write a status to it.
c.Error(err.(error)) // nolint: errcheck c.Error(err.(error)) //nolint: errcheck
c.Abort() c.Abort()
} else { } else {
handle(c, err) handle(c, err)

View File

@ -182,7 +182,8 @@ func (group *RouterGroup) staticFileHandler(relativePath string, handler Handler
// of the Router's NotFound handler. // of the Router's NotFound handler.
// To use the operating system's file system implementation, // To use the operating system's file system implementation,
// use : // use :
// router.Static("/static", "/var/www") //
// router.Static("/static", "/var/www")
func (group *RouterGroup) Static(relativePath, root string) IRoutes { func (group *RouterGroup) Static(relativePath, root string) IRoutes {
return group.StaticFS(relativePath, Dir(root, false)) return group.StaticFS(relativePath, Dir(root, false))
} }