1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Wizard
  • 462
  • 1
  • 6
  • 14
  • 2
    First, always check errors! In `main()` you use short variable.declaration and create a new `client` local variable. Use assignment to assign to the package level `client` variable. – icza Jun 28 '21 at 06:32
  • You’re not handling the database connection error. You’re most likely not connecting, the client is not being set, and you’re getting a nil pointer dereference because the MongoDB client was never initialized. – Clark McCauley Jun 28 '21 at 06:32

1 Answers1

3

You're creating a new client variable in your main function with the := operator. Use = to assign to your global client variable.

Bryan Austin
  • 487
  • 3
  • 13