I know there are a lots of people that has run into the same issue but still here I am. I'm pretty sure my code is correct and still the resulting struct is empty. Function :
func PostAdminHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "application/json")
var admin admin.Admin
json.NewDecoder(r.Body).Decode(&admin)
fmt.Println(admin)
_, err := PostAdmin(admin)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Console print :
{ ObjectID("000000000000000000000000")}
Structure :
package entity
import "go.mongodb.org/mongo-driver/bson/primitive"
type Admin struct {
FirstName string
LastName string
Email string
Password string
Role string
Campus primitive.ObjectID
}
Route :
adminRoute.HandleFunc("/admin", admin.PostAdminHandler).Methods("POST")
Json data I'm sending through Insomnia :
{
"FirstName": "Jeanne",
"LastName": "Darc",
"Email": "[email protected]",
"Password": "JeanneDarc2022",
"Role": "admin",
"Campus": "60d5a25ff4d722d3b77d1929",
}
Error i'm getting from decoder :
invalid character '}' looking for beginning of object key string
This RFC:
https://datatracker.ietf.org/doc/html/rfc7159
specifies the JSON object format as:
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name
from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
object = begin-object [ member *( value-separator member ) ]
end-object
member = string name-separator value
So, no trailing commas.
Remove the last comma in the input.