Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix errcheck warnings #1739

Merged
merged 1 commit into from
Jan 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions binding/binding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -516,28 +516,28 @@ func createFormPostRequestFail() *http.Request {
return req
}

func createFormMultipartRequest() *http.Request {
func createFormMultipartRequest(t *testing.T) *http.Request {
boundary := "--testboundary"
body := new(bytes.Buffer)
mw := multipart.NewWriter(body)
defer mw.Close()

mw.SetBoundary(boundary)
mw.WriteField("foo", "bar")
mw.WriteField("bar", "foo")
assert.NoError(t, mw.SetBoundary(boundary))
assert.NoError(t, mw.WriteField("foo", "bar"))
assert.NoError(t, mw.WriteField("bar", "foo"))
req, _ := http.NewRequest("POST", "/?foo=getfoo&bar=getbar", body)
req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
return req
}

func createFormMultipartRequestFail() *http.Request {
func createFormMultipartRequestFail(t *testing.T) *http.Request {
boundary := "--testboundary"
body := new(bytes.Buffer)
mw := multipart.NewWriter(body)
defer mw.Close()

mw.SetBoundary(boundary)
mw.WriteField("map_foo", "bar")
assert.NoError(t, mw.SetBoundary(boundary))
assert.NoError(t, mw.WriteField("map_foo", "bar"))
req, _ := http.NewRequest("POST", "/?map_foo=getfoo", body)
req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
return req
Expand All @@ -546,7 +546,7 @@ func createFormMultipartRequestFail() *http.Request {
func TestBindingFormPost(t *testing.T) {
req := createFormPostRequest()
var obj FooBarStruct
FormPost.Bind(req, &obj)
assert.NoError(t, FormPost.Bind(req, &obj))

assert.Equal(t, "form-urlencoded", FormPost.Name())
assert.Equal(t, "bar", obj.Foo)
Expand All @@ -556,7 +556,7 @@ func TestBindingFormPost(t *testing.T) {
func TestBindingDefaultValueFormPost(t *testing.T) {
req := createDefaultFormPostRequest()
var obj FooDefaultBarStruct
FormPost.Bind(req, &obj)
assert.NoError(t, FormPost.Bind(req, &obj))

assert.Equal(t, "bar", obj.Foo)
assert.Equal(t, "hello", obj.Bar)
Expand All @@ -570,17 +570,17 @@ func TestBindingFormPostFail(t *testing.T) {
}

func TestBindingFormMultipart(t *testing.T) {
req := createFormMultipartRequest()
req := createFormMultipartRequest(t)
var obj FooBarStruct
FormMultipart.Bind(req, &obj)
assert.NoError(t, FormMultipart.Bind(req, &obj))

assert.Equal(t, "multipart/form-data", FormMultipart.Name())
assert.Equal(t, "bar", obj.Foo)
assert.Equal(t, "foo", obj.Bar)
}

func TestBindingFormMultipartFail(t *testing.T) {
req := createFormMultipartRequestFail()
req := createFormMultipartRequestFail(t)
var obj FooStructForMapType
err := FormMultipart.Bind(req, &obj)
assert.Error(t, err)
Expand Down
6 changes: 5 additions & 1 deletion binding/form.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ func (formBinding) Bind(req *http.Request, obj interface{}) error {
if err := req.ParseForm(); err != nil {
return err
}
req.ParseMultipartForm(defaultMemory)
if err := req.ParseMultipartForm(defaultMemory); err != nil {
if err != http.ErrNotMultipart {
return err
}
}
if err := mapForm(obj, req.Form); err != nil {
return err
}
Expand Down
22 changes: 15 additions & 7 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,11 @@ func (c *Context) PostFormArray(key string) []string {
// a boolean value whether at least one value exists for the given key.
func (c *Context) GetPostFormArray(key string) ([]string, bool) {
req := c.Request
req.ParseMultipartForm(c.engine.MaxMultipartMemory)
if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
if err != http.ErrNotMultipart {
debugPrint("error on parse multipart form array: %v", err)
}
}
if values := req.PostForm[key]; len(values) > 0 {
return values, true
}
Expand All @@ -437,7 +441,11 @@ func (c *Context) PostFormMap(key string) map[string]string {
// whether at least one value exists for the given key.
func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {
req := c.Request
req.ParseMultipartForm(c.engine.MaxMultipartMemory)
if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
if err != http.ErrNotMultipart {
debugPrint("error on parse multipart form map: %v", err)
}
}
dicts, exist := c.get(req.PostForm, key)

if !exist && req.MultipartForm != nil && req.MultipartForm.File != nil {
Expand Down Expand Up @@ -493,8 +501,8 @@ func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
}
defer out.Close()

io.Copy(out, src)
return nil
_, err = io.Copy(out, src)
return err
}

// Bind checks the Content-Type to select a binding engine automatically,
Expand Down Expand Up @@ -534,7 +542,7 @@ func (c *Context) BindYAML(obj interface{}) error {
// It will abort the request with HTTP 400 if any error occurs.
func (c *Context) BindUri(obj interface{}) error {
if err := c.ShouldBindUri(obj); err != nil {
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind)
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
return err
}
return nil
Expand All @@ -545,7 +553,7 @@ func (c *Context) BindUri(obj interface{}) error {
// See the binding package.
func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {
if err := c.ShouldBindWith(obj, b); err != nil {
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind)
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
return err
}
return nil
Expand Down Expand Up @@ -913,7 +921,7 @@ func (c *Context) Negotiate(code int, config Negotiate) {
c.XML(code, data)

default:
c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck
}
}

Expand Down
36 changes: 21 additions & 15 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ func TestContextFormFile(t *testing.T) {
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "test")
if assert.NoError(t, err) {
w.Write([]byte("test"))
_, err = w.Write([]byte("test"))
assert.NoError(t, err)
}
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
Expand Down Expand Up @@ -100,10 +101,11 @@ func TestContextFormFileFailed(t *testing.T) {
func TestContextMultipartForm(t *testing.T) {
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
mw.WriteField("foo", "bar")
assert.NoError(t, mw.WriteField("foo", "bar"))
w, err := mw.CreateFormFile("file", "test")
if assert.NoError(t, err) {
w.Write([]byte("test"))
_, err = w.Write([]byte("test"))
assert.NoError(t, err)
}
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
Expand Down Expand Up @@ -137,7 +139,8 @@ func TestSaveUploadedCreateFailed(t *testing.T) {
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "test")
if assert.NoError(t, err) {
w.Write([]byte("test"))
_, err = w.Write([]byte("test"))
assert.NoError(t, err)
}
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
Expand All @@ -159,7 +162,7 @@ func TestContextReset(t *testing.T) {
c.index = 2
c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
c.Params = Params{Param{}}
c.Error(errors.New("test"))
c.Error(errors.New("test")) // nolint: errcheck
c.Set("foo", "bar")
c.reset()

Expand Down Expand Up @@ -798,7 +801,7 @@ func TestContextRenderHTML2(t *testing.T) {
assert.Len(t, router.trees, 1)

templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
re := captureOutput(func() {
re := captureOutput(t, func() {
SetMode(DebugMode)
router.SetHTMLTemplate(templ)
SetMode(TestMode)
Expand Down Expand Up @@ -1211,7 +1214,8 @@ func TestContextAbortWithStatusJSON(t *testing.T) {
assert.Equal(t, "application/json; charset=utf-8", contentType)

buf := new(bytes.Buffer)
buf.ReadFrom(w.Body)
_, err := buf.ReadFrom(w.Body)
assert.NoError(t, err)
jsonStringBody := buf.String()
assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody)
}
Expand All @@ -1220,11 +1224,11 @@ func TestContextError(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
assert.Empty(t, c.Errors)

c.Error(errors.New("first error"))
c.Error(errors.New("first error")) // nolint: errcheck
assert.Len(t, c.Errors, 1)
assert.Equal(t, "Error #01: first error\n", c.Errors.String())

c.Error(&Error{
c.Error(&Error{ // nolint: errcheck
Err: errors.New("second error"),
Meta: "some data 2",
Type: ErrorTypePublic,
Expand All @@ -1246,13 +1250,13 @@ func TestContextError(t *testing.T) {
t.Error("didn't panic")
}
}()
c.Error(nil)
c.Error(nil) // nolint: errcheck
}

func TestContextTypedError(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
c.Error(errors.New("externo 0")).SetType(ErrorTypePublic) // nolint: errcheck
c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate) // nolint: errcheck

for _, err := range c.Errors.ByType(ErrorTypePublic) {
assert.Equal(t, ErrorTypePublic, err.Type)
Expand All @@ -1267,7 +1271,7 @@ func TestContextAbortWithError(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)

c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input")
c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input") // nolint: errcheck

assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Equal(t, abortIndex, c.index)
Expand Down Expand Up @@ -1713,7 +1717,8 @@ func TestContextStream(t *testing.T) {
stopStream = false
}()

w.Write([]byte("test"))
_, err := w.Write([]byte("test"))
assert.NoError(t, err)

return stopStream
})
Expand All @@ -1730,7 +1735,8 @@ func TestContextStreamWithClientGone(t *testing.T) {
w.closeClient()
}()

writer.Write([]byte("test"))
_, err := writer.Write([]byte("test"))
assert.NoError(t, err)

return true
})
Expand Down
19 changes: 10 additions & 9 deletions debug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func TestIsDebugging(t *testing.T) {
}

func TestDebugPrint(t *testing.T) {
re := captureOutput(func() {
re := captureOutput(t, func() {
SetMode(DebugMode)
SetMode(ReleaseMode)
debugPrint("DEBUG this!")
Expand All @@ -46,7 +46,7 @@ func TestDebugPrint(t *testing.T) {
}

func TestDebugPrintError(t *testing.T) {
re := captureOutput(func() {
re := captureOutput(t, func() {
SetMode(DebugMode)
debugPrintError(nil)
debugPrintError(errors.New("this is an error"))
Expand All @@ -56,7 +56,7 @@ func TestDebugPrintError(t *testing.T) {
}

func TestDebugPrintRoutes(t *testing.T) {
re := captureOutput(func() {
re := captureOutput(t, func() {
SetMode(DebugMode)
debugPrintRoute("GET", "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest})
SetMode(TestMode)
Expand All @@ -65,7 +65,7 @@ func TestDebugPrintRoutes(t *testing.T) {
}

func TestDebugPrintLoadTemplate(t *testing.T) {
re := captureOutput(func() {
re := captureOutput(t, func() {
SetMode(DebugMode)
templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl"))
debugPrintLoadTemplate(templ)
Expand All @@ -75,7 +75,7 @@ func TestDebugPrintLoadTemplate(t *testing.T) {
}

func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) {
re := captureOutput(func() {
re := captureOutput(t, func() {
SetMode(DebugMode)
debugPrintWARNINGSetHTMLTemplate()
SetMode(TestMode)
Expand All @@ -84,7 +84,7 @@ func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) {
}

func TestDebugPrintWARNINGDefault(t *testing.T) {
re := captureOutput(func() {
re := captureOutput(t, func() {
SetMode(DebugMode)
debugPrintWARNINGDefault()
SetMode(TestMode)
Expand All @@ -98,15 +98,15 @@ func TestDebugPrintWARNINGDefault(t *testing.T) {
}

func TestDebugPrintWARNINGNew(t *testing.T) {
re := captureOutput(func() {
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(f func()) string {
func captureOutput(t *testing.T, f func()) string {
reader, writer, err := os.Pipe()
if err != nil {
panic(err)
Expand All @@ -127,7 +127,8 @@ func captureOutput(f func()) string {
go func() {
var buf bytes.Buffer
wg.Done()
io.Copy(&buf, reader)
_, err := io.Copy(&buf, reader)
assert.NoError(t, err)
out <- buf.String()
}()
wg.Wait()
Expand Down
6 changes: 3 additions & 3 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestError(t *testing.T) {
jsonBytes, _ := json.Marshal(err)
assert.Equal(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))

err.SetMeta(H{
err.SetMeta(H{ // nolint: errcheck
"status": "200",
"data": "some data",
})
Expand All @@ -44,7 +44,7 @@ func TestError(t *testing.T) {
"data": "some data",
}, err.JSON())

err.SetMeta(H{
err.SetMeta(H{ // nolint: errcheck
"error": "custom error",
"status": "200",
"data": "some data",
Expand All @@ -59,7 +59,7 @@ func TestError(t *testing.T) {
status string
data string
}
err.SetMeta(customError{status: "200", data: "other data"})
err.SetMeta(customError{status: "200", data: "other data"}) // nolint: errcheck
assert.Equal(t, customError{status: "200", data: "other data"}, err.JSON())
}

Expand Down
5 changes: 4 additions & 1 deletion gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,10 @@ func serveError(c *Context, code int, defaultMessage []byte) {
}
if c.writermem.Status() == code {
c.writermem.Header()["Content-Type"] = mimePlain
c.Writer.Write(defaultMessage)
_, err := c.Writer.Write(defaultMessage)
if err != nil {
debugPrint("cannot write message to writer during serve error: %v", err)
}
return
}
c.writermem.WriteHeaderNow()
Expand Down
Loading