Failing to insert data - Golang REST API with MongoDB on VSCODE

Hi Team,

I am trying to run Golang REST API with MongoDB on VSCODE. But, my data is not getting inserted into DB.
I am new to Golang and RESTAPI and MongoDB. Could you please help me with the below code and let me know why it is not inserting data into MongoDB.

package main

import (
	"context"

	"encoding/json"

	"fmt"

	"github.com/gorilla/mux"

	"go.mongodb.org/mongo-driver/bson"

	"go.mongodb.org/mongo-driver/bson/primitive"

	"go.mongodb.org/mongo-driver/mongo"

	"go.mongodb.org/mongo-driver/mongo/options"

	"net/http"

	"time"
)

var client *mongo.Client

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"`
}

//func CreatePersonEndpoint(response http.ResponseWriter, request *http.Request) {}

//func GetPeopleEndpoint(response http.ResponseWriter, request *http.Request) {}

//func GetPersonEndpoint(response http.ResponseWriter, request *http.Request) {}

func main() {

	fmt.Println("Starting the application...")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

	client, _ = mongo.Connect(ctx, clientOptions)

	router := mux.NewRouter()

	router.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")

	router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")

	router.HandleFunc("/person/{id}", GetPersonEndpoint).Methods("GET")

	http.ListenAndServe("localhost:8080", router)

}

func CreatePersonEndpoint(response http.ResponseWriter,
	request *http.Request) {

	response.Header().Set("content-type", "application/json")

	var person Person

	_ = json.NewDecoder(request.Body).Decode(&person)

	collection := client.Database("books").Collection("person")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	result, _ := collection.InsertOne(ctx, person)

	json.NewEncoder(response).Encode(result)

}

func GetPersonEndpoint(response http.ResponseWriter,
	request *http.Request) {
	response.Header().Set("content-type", "application/json")

	params := mux.Vars(request)

	id, _ := primitive.ObjectIDFromHex(params["id"])

	var person Person

	collection := client.Database("books").Collection("authors")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	err := collection.FindOne(ctx, Person{ID: id}).Decode(&person)

	if err != nil {

		response.WriteHeader(http.StatusInternalServerError)

		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))

		return

	}

	json.NewEncoder(response).Encode(person)

}

func GetPeopleEndpoint(response http.ResponseWriter, request *http.Request) {

	response.Header().Set("content-type", "application/json")

	var people []Person

	collection := client.Database("books").Collection("person")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	cursor, err := collection.Find(ctx, bson.M{})

	if err != nil {

		response.WriteHeader(http.StatusInternalServerError)

		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))

		return

	}

	defer cursor.Close(ctx)

	for cursor.Next(ctx) {

		var person Person

		cursor.Decode(&person)

		people = append(people, person)

	}

	if err := cursor.Err(); err != nil {
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))
		return
	}
	json.NewEncoder(response).Encode(people)

}

PS D:\goprojects\gorilla_mux_mongodb> go run main.go
Starting the application…

.

@christophberger Do you see any errors while calling RESTAPI? There is ‘books’ DB and inside it I am trying to create a ‘person’ collection. Somehow data is not getting inserted.