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

Can't get status as expected from context.Status() #3886

Open
livingston0318 opened this issue Mar 13, 2024 · 1 comment
Open

Can't get status as expected from context.Status() #3886

livingston0318 opened this issue Mar 13, 2024 · 1 comment

Comments

@livingston0318
Copy link

  • 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

I use context.Context.Json to set status code and response message, but I found the code is only set to code in context.Writer, but when I get status by using context.Status(), it only returns status from context.Writer.ResponseWriter's status

How to reproduce

package main

import (
	"github.com/gin-gonic/gin"
)

func main() {
	g := gin.Default()
	g.GET("/hello/:name", func(c *gin.Context) {
		c.Json(500, "Hello %s", c.Param("name"))
		fmt.Println(c.Status())
	})
	g.Run(":9000")
}

Expectations

$ curl http://localhost:9000/hello/world
500

Actual result

$ curl -i http://localhost:9000/hello/world
200

Environment

  • go version: 1.20.9
  • gin version (or commit ref): 1.19.1
  • operating system:mac OS
@nisarg-ssai
Copy link

  1. c.JSON only takes a number and an object
// JSON serializes the given struct as JSON into the response body.
// It also sets the Content-Type as "application/json".
func (c *Context) JSON(code int, obj any) {
	c.Render(code, render.JSON{Data: obj})
}
  1. c.Status() is only used to set the status and it does not return anything
// Status sets the HTTP response code.
func (c *Context) Status(code int) {
	c.Writer.WriteHeader(code)
}

it is working as expected

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	g := gin.Default()
	g.GET("/hello/:name", func(c *gin.Context) {
		responseString := fmt.Sprintf("Hello %s", c.Param("name"))
		c.JSON(200, gin.H{"name": responseString})
	})
	g.Run(":9000")
}
$ curl -i http://localhost:9000/hello/yo
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Wed, 13 Mar 2024 08:57:58 GMT
Content-Length: 19
{"name":"Hello yo"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants