Sunday, June 22, 2025
HomeGolangFailing to insert information - Golang REST API with MongoDB on VSCODE...

Failing to insert information – Golang REST API with MongoDB on VSCODE – Code Evaluation


Hello Crew,

I’m making an attempt to run Golang REST API with MongoDB on VSCODE. However, my information just isn’t getting inserted into DB.
I’m new to Golang and RESTAPI and MongoDB. Might you please assist me with the beneath code and let me know why it’s not inserting information into MongoDB.

package deal foremost

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/choices"

	"web/http"

	"time"
)

var consumer *mongo.Shopper

sort Particular 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 foremost() {

	fmt.Println("Beginning the appliance...")

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

	consumer, _ = mongo.Join(ctx, clientOptions)

	router := mux.NewRouter()

	router.HandleFunc("/individual", CreatePersonEndpoint).Strategies("POST")

	router.HandleFunc("/individuals", GetPeopleEndpoint).Strategies("GET")

	router.HandleFunc("/individual/{id}", GetPersonEndpoint).Strategies("GET")

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

}

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

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

	var individual Particular person

	_ = json.NewDecoder(request.Physique).Decode(&individual)

	assortment := consumer.Database("books").Assortment("individual")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	end result, _ := assortment.InsertOne(ctx, individual)

	json.NewEncoder(response).Encode(end result)

}

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

	params := mux.Vars(request)

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

	var individual Particular person

	assortment := consumer.Database("books").Assortment("authors")

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

	if err != nil {

		response.WriteHeader(http.StatusInternalServerError)

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

		return

	}

	json.NewEncoder(response).Encode(individual)

}

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

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

	var individuals []Particular person

	assortment := consumer.Database("books").Assortment("individual")

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

	if err != nil {

		response.WriteHeader(http.StatusInternalServerError)

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

		return

	}

	defer cursor.Shut(ctx)

	for cursor.Subsequent(ctx) {

		var individual Particular person

		cursor.Decode(&individual)

		individuals = append(individuals, individual)

	}

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

}

PS D:goprojectsgorilla_mux_mongodb> go run foremost.go
Beginning the appliance…

.

@christophberger Do you see any errors whereas calling RESTAPI? There's ‘books’ DB and inside it I'm making an attempt to create a ‘individual’ assortment. By some means information just isn't getting inserted.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments