Closed dream-kzx closed 4 months ago
Thanks for your contribution. I have one suggestion: http code 204 does not have http body. How about this?
if resp.StatusCode != http.StatusNoContent {
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.New("read ping resp failed, error: " + err.Error())
}
+ resp.body.close()
return errors.New("ping error resp, code: " + resp.Status + "body: " + string(body))
}
204 also needs to close
Thanks for your contribution. I have one suggestion: http code 204 does not have http body. How about this?
if resp.StatusCode != http.StatusNoContent { body, err := io.ReadAll(resp.Body) if err != nil { return errors.New("read ping resp failed, error: " + err.Error()) } + resp.body.close() return errors.New("ping error resp, code: " + resp.Status + "body: " + string(body)) }
Simple code to verify and the conclusion is that the body needs to be closed:
package main
import (
"encoding/json"
"io"
"net"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
var client = &http.Client{
Timeout: time.Second * 3,
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: time.Second * 3,
}).DialContext,
},
}
func startHttpServer() {
r := gin.Default()
gin.SetMode(gin.ReleaseMode)
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusNoContent, "")
})
err := r.Run(":30388")
if err != nil {
panic(err)
}
}
func doRequest() {
request, err := http.NewRequest("GET", "http://localhost:30388/ping", nil)
if err != nil {
panic(err)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
if response.Body != nil {
panic("response body should be nil")
}
defer response.Body.Close()
readAll, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
var m = make(map[string]interface{})
err = json.Unmarshal(readAll, &m)
if err != nil {
panic(err)
}
}
func main() {
go startHttpServer()
time.Sleep(time.Second)
doRequest()
}
Fix #92