- 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
The c.Writer.WriteString or c.Writer.Write will set default http code(200). Then call c.Status will be noneffective.Why is it designed this way?
How to reproduce
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
g := gin.Default()
r.GET("/", func(c *gin.Context) {
c.Writer.WriteString("hello world")
c.Status(400) // noneffective
})
r.GET("/", func(c *gin.Context) {
c.Status(400) // noneffective
c.Writer.WriteString("hello world")
})
g.Run(":9000")
}
Expectations
$ curl http://localhost:9000
400 http code
Actual result
$ curl -i http://localhost:9000
200 http code
Environment
- go version:
- gin version (or commit ref): latest
- operating system:
Comment From: aryan-more
When using c.Writer.WriteString in Gin, it's necessary to call c.Writer.WriteHeader explicitly before writing the response body. If the status code is not explicitly set using c.Writer.WriteHeader, Gin will automatically set the status code to 200 (OK).
r.GET("/", func(c *gin.Context) {
c.Writer.WriteHeader(http.StatusBadRequest)
c.Writer.WriteString("hello world")
})
Comment From: bestgopher
When using c.Writer.WriteString in Gin, it's necessary to call c.Writer.WriteHeader explicitly before writing the response body. If the status code is not explicitly set using c.Writer.WriteHeader, Gin will automatically set the status code to 200 (OK).
r.GET("/", func(c *gin.Context) { c.Writer.WriteHeader(http.StatusBadRequest) c.Writer.WriteString("hello world") })
I somewhat disagree with the idea that using WriteString implies a status code of 200.
Comment From: aryan-more
After doing some research on HTTP via Wikipedia, I discovered that the first line of an HTTP response is the status line. This is why it is necessary to send the status code first.
https://en.wikipedia.org/wiki/HTTP#Response_status_codes
Comment From: bestgopher
@aryan-more Thanks for the answer. The stdlib has the same behavior.