Sunday, June 22, 2025
HomeGolangWhy there may be an error at package deal primary? - Code...

Why there may be an error at package deal primary? – Code Evaluate


Hello Staff,

What are the steps to create a mod file in go.

Why I get the error at package deal primary.

package deal primary

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"
	//"log"
	"web/http"
	"time"
)

var consumer *mongo.Consumer

kind 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 primary() {
	fmt.Println("Beginning the applying...")
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	clientOptions := choices.Consumer().ApplyURI("mongodb://localhost:27017")
	consumer, _ = mongo.Join(ctx, clientOptions)
	router := mux.NewRouter()
	router.HandleFunc("/particular person", CreatePersonEndpoint).Strategies("POST")
	router.HandleFunc("/folks", GetPeopleEndpoint).Strategies("GET")
	router.HandleFunc("/particular person/{id}", GetPersonEndpoint).Strategies("GET")
	http.ListenAndServe("localhost:8000", router)
}

func CreatePersonEndpoint(response http.ResponseWriter, request *http.Request) {
	response.Header().Set("content-type", "software/json")
	var particular person Particular person
	_ = json.NewDecoder(request.Physique).Decode(&particular person)
	assortment := consumer.Database("thepolyglotdeveloper").Assortment("folks")
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	outcome, _ := assortment.InsertOne(ctx, particular person)
	json.NewEncoder(response).Encode(outcome)
}

func GetPersonEndpoint(response http.ResponseWriter, request *http.Request) {
	response.Header().Set("content-type", "software/json")
	params := mux.Vars(request)
	id, _ := primitive.ObjectIDFromHex(params["id"])
	var particular person Particular person
	assortment := consumer.Database("thepolyglotdeveloper").Assortment("folks")
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	err := assortment.FindOne(ctx, Particular person{ID: id}).Decode(&particular person)
	if err != nil {
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))
		return
	}
	json.NewEncoder(response).Encode(particular person)
}

func GetPeopleEndpoint(response http.ResponseWriter, request *http.Request) {
	response.Header().Set("content-type", "software/json")
	var folks []Particular person
	assortment := consumer.Database("thepolyglotdeveloper").Assortment("folks")
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	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 particular person Particular person
		cursor.Decode(&particular person)
		folks = append(folks, particular person)
	}
	if err := cursor.Err(); err != nil {
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(`{ "message": "` + err.Error() + `" }`))
		return
	}
	json.NewEncoder(response).Encode(folks)
}

Hello @shubhra, please share your present go.mod file.

The message you get in VSCode is a bit bizarre, because it mentions a workspace, though you haven’t any go.work file. I suppose this can be a VSCode situation moderately than a difficulty with Go. In any case, VSCode appears to be confused by the module title.

1 Like

Might you be particular in regards to the error?

@bluefire There have been two errors:

  1. My VSCODE was not accepting the code as is, it requires go.work file. Since, I’m new to golang, I took a course to discover ways to create go.work file.
  2. The issue is I’m not capable of write a CURL API, to insert the info into MongoDB by way of RESTAPI name.
    The RESTAPI, which I’ve used, is just not creating the brand new database (thepolyglotdeveloper) , not creating the gathering (folks) and never inserting the info into the mongoDB.

I’ve used the under CURL instructions:

  1. curl http://localhost:8000/particular person {“Firstname” : “Shubhra” “Lastname” : “Garg”}
  2. curl -X POST http://localhost:8000/v1/particular person -H ‘cache-control: no-cache’ -H ‘content-type: software/json’ -d ‘{ “Firstname” : “Shubhra”, “Lastname” : “Garg”}’

However, resulting from not having go.work file, the VSCODE was not letting me insert knowledge into database by way of GOLANG RESTAPI. Do you see that I’ve create proper or flawed CURL API for inserting knowledge into MongoDB?

@bluefire The under are the final steps I famous, to create go.work area file in VSCODE.
Sharing it for neighborhood advantages.

// Tips on how to create a workspace for go modules in Golang//
Create a folder in D listing ( named toolkit-project): D:goprojectstookit-project
Go to VSCODE and click on on File menu —> save workspace as : toolkit.code-workspace
Create a brand new folder inside ( toolkit-project folder) and named it as “toolkit”.
Create one other folder inside ( toolkit-project folder) and named it as “app”.
Go to VSCODE and add “toolkit” and “app” folders utilizing the File menu —> add folders to workspace choice.

PS D:goprojectstookit-projecttoolkit>
PS D:goprojectstookit-projecttoolkit> go mod init github.com/sgarg2023/golangprojectpractice/toolkit
go: creating new go.mod: module github.com/sgarg2023/golangprojectpractice/toolkit
PS D:goprojectstookit-projecttoolkit>
PS D:goprojectstookit-projecttoolkit> cd …/app
PS D:goprojectstookit-projectapp>
PS D:goprojectstookit-projectapp>
PS D:goprojectstookit-projectapp> go mod init myapp
go: creating new go.mod: module myapp
PS D:goprojectstookit-projectapp>

Go to the principle folder: toolkit-project

PS D:goprojectstookit-project> ls

Listing: D:goprojectstookit-project

Mode LastWriteTime Size Identify


d—– 6/14/2023 11:09 PM app
d—– 6/14/2023 11:08 PM toolkit
-a—- 6/14/2023 10:59 PM 75 toolkit.code-workspace

PS D:goprojectstookit-project>
PS D:goprojectstookit-project> go work init toolkit app
PS D:goprojectstookit-project>
PS D:goprojectstookit-project> ls

Listing: D:goprojectstookit-project

Mode LastWriteTime Size Identify


d—– 6/14/2023 11:09 PM app
d—– 6/14/2023 11:08 PM toolkit
-a—- 6/14/2023 11:11 PM 35 go.work
-a—- 6/14/2023 10:59 PM 75 toolkit.code-workspace

PS D:goprojectstookit-project>
PS D:goprojectstookit-project> cat go.work
go 1.20

use (
./app
./toolkit
)
PS D:goprojectstookit-project>

@bluefire I’ve used postman too for sending the JSON ( firstname and lastname) by way of POST question however that’s not inserting the info into mongoDB database.

Additionally it is quite simple to create a go.mod file to develop Go language utilizing LiteIDE.
Why not attempt utilizing LiteIDE moderately than VSCODE?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments