Skip to content

Instantly share code, notes, and snippets.

@LuD1161
Created February 20, 2020 16:43
Show Gist options
  • Save LuD1161/72a4247d735962464bc75c7740a75bac to your computer and use it in GitHub Desktop.
Save LuD1161/72a4247d735962464bc75c7740a75bac to your computer and use it in GitHub Desktop.
Standard Output Format for all API endpoint
package main
import "github.com/gin-gonic/gin"
// Response : BaseResponse
// To get const output format for all endpoint
type Response struct {
Meta interface{} `json:"meta"`
Error interface{} `json:"error"`
Data interface{} `json:"data"`
}
type user struct {
Fname string `json:"fname"`
Lname string `json:"lname"`
}
func main() {
r := gin.Default()
user1 := []user{
user{
Fname: "fname1",
Lname: "lname1",
},
user{
Fname: "fname2",
Lname: "lname2",
},
}
var br Response
br.Data = user1
br.Meta = "This is the meta tag"
// br.Error = nil // not defining this to get all types, Data -> struct; Meta -> const string; Error -> nil
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, br)
})
/*
{
"meta": "This is the meta tag",
"error": null,
"data": [
{
"fname": "fname1",
"lname": "lname1"
},
{
"fname": "fname2",
"lname": "lname2"
}
]
}
*/
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment