I am creating a API in golang which will simply display all data from a map in json format. endpoint: /keys
type UserController struct{}
// NewUserController function
func NewUserController() *UserController {
return &UserController{}
}
// Data struct
type Data struct {
Datakey int `json:"key"`
Datavalue string `json:"value"`
}
var datamap = make(map[int]string)
func (uc UserController) getallkeys(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
type Users []Data
var uj Users
for k, v := range datamap {
uj = Users{
Data{
Datakey: k,
Datavalue: v,
},
}
}
result, _ := json.Marshal(uj)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", result)
}
For eg: The response should be something like
[
{
"key":somekey,
"value":"somevalue"
},
{
"key":somekey,
"value":"somevalue"
}
]
I am not clear how to implement this. The above code is displaying just the last data from the map. This is incorrect but I am not sure how to proceed. It would be great if someone could help me with this.
Thanks.