Gin.H in the gin framework returns a json response

problem description

when a string is empty, I don"t want to return it. If I don"t want to use if, what better way to handle it? Ask the Great God for advice

related codes

if url != "" {
    g.JSON(status, gin.H{"result": result, "message": msg, "redirect_url":url})
} else {
    g.JSON(status, gin.H{"result": result, "message": msg})
}


Go
Jun.27,2022

The essence of

gin.H should be a map.
if you don't want to compare with if, you can customize a struct and tag the attribute, for example:

type Result struct {
    Result string         `json:"result"`
    Message string        `json:"message"`
    RedirectUrl string    `json:"redirect_url,omitempty"`
}
The

omitempty tag lets the json serializer ignore null values.

Menu