In my Go application I have such route:
router.HandleFunc("/api/users_groups_relationship/{user_id:[0-9]+}", controllers.CreateUsersGroupsRelationship).Methods("POST")
I make POST request. In body of that request I send such JSON which looks like this:
{
"groups": [1, 2, 3]
}
As you can see groups
key has array of ids as value. User can be in several groups. I am trying to insert multiple values to PostgreSQL database.
How to get the value of a specific key in request body?
Is there any other best way to insert multiple values in database by Go?
My code:
var CreateUsersGroupsRelationship = func(responseWriter http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
userID := vars["user_id"]
fmt.Println(userID)
var groups []int
groups = request.Body("groups") // ???
for i := 1; i < len(groups); i++ {
fmt.Println(groups[i])
_, _ := database.DBSQL.Exec("INSERT INTO users_groups (user_id, group_id) VALUES ($1, $2);", userID, groups[i])
}
utils.ResponseWithSuccess(responseWriter, http.StatusOK, "All new records successfully created.")
}