I am trying to do a POST request using postman to Mux Router. But each time I try to do the POST request, PostMan always tells me "ERROR: socket hang up".
Then in Go I also receive the following error:
http: panic serving [::1]:64995: runtime error: invalid memory address or nil pointer dereference
Code:
type Person struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Firstname string `json:"firstname,omitempty" bson:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty" bson:"lastname,omitempty"`
}
var client *mongo.Client // create mongo client
func CreatePersonEndpoint(w http.ResponseWriter, r *http.Request){
w.Header().Add("Content-Type", "application/json")
var person Person
json.NewDecoder(r.Body).Decode(&person)
collection := client.Database("People").Collection("people")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
result, _:= collection.InsertOne(ctx, person)
json.NewEncoder(w).Encode(result)
}
func main(){
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://username:password[@cluster0.51awc.mongodb.net/test"))
client.Connect(ctx)
client.Ping(ctx, readpref.Primary())
databases, _ := client.ListDatabaseNames(ctx, bson.M{})
fmt.Println(databases)
r := mux.NewRouter()
r.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")
http.ListenAndServe(":8000", r)
}
Here are the available Databases I have created in MongoDB: [Hotels People admin local]
Under the "People" Database I created a "people" collection.