• 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

Comment From: nisarg-ssai

  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"}