Why there is an error at package main?

Hi Team,

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

Why I am getting the error at package main.

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"
	//"log"
	"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, _ := context.WithTimeout(context.Background(), 10*time.Second)
	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:8000", 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("thepolyglotdeveloper").Collection("people")
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	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("thepolyglotdeveloper").Collection("people")
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	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("thepolyglotdeveloper").Collection("people")
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	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)
}

Hi @shubhra, please share your current go.mod file.

The message you get in VSCode is a bit weird, as it mentions a workspace, although you have no go.work file. I guess this is a VSCode issue rather than an issue with Go. In any case, VSCode seems to be confused by the module name.

1 Like

Could you be specific about the error?

@bluefire There were two errors:

  1. My VSCODE was not accepting the code as is, it requires go.work file. Since, I am new to golang, I took a course to learn how to create go.work file.
  2. The problem is I am not able to write a CURL API, to insert the data into MongoDB via RESTAPI call.
    The RESTAPI, which I have used, is not creating the new database (thepolyglotdeveloper) , not creating the collection (people) and not inserting the data into the mongoDB.

I have used the below CURL commands:

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

But, due to not having go.work file, the VSCODE was not letting me insert data into database via GOLANG RESTAPI. Do you see that I have create right or wrong CURL API for inserting data into MongoDB?

@bluefire The below are the general steps I noted, to create go.work space file in VSCODE.
Sharing it for community benefits.

// How to create a workspace for go modules in Golang//
Create a folder in D directory ( named toolkit-project): D:\goprojects\tookit-project
Go to VSCODE and click on File menu —> save workspace as : toolkit.code-workspace
Create a new folder inside of ( toolkit-project folder) and named it as “toolkit”.
Create another folder inside of ( toolkit-project folder) and named it as “app”.
Go to VSCODE and add “toolkit” and “app” folders using the File menu —> add folders to workspace option.

PS D:\goprojects\tookit-project\toolkit>
PS D:\goprojects\tookit-project\toolkit> go mod init github.com/sgarg2023/golangprojectpractice/toolkit
go: creating new go.mod: module github.com/sgarg2023/golangprojectpractice/toolkit
PS D:\goprojects\tookit-project\toolkit>
PS D:\goprojects\tookit-project\toolkit> cd …/app
PS D:\goprojects\tookit-project\app>
PS D:\goprojects\tookit-project\app>
PS D:\goprojects\tookit-project\app> go mod init myapp
go: creating new go.mod: module myapp
PS D:\goprojects\tookit-project\app>

Go to the main folder: toolkit-project

PS D:\goprojects\tookit-project> ls

Directory: D:\goprojects\tookit-project

Mode LastWriteTime Length Name


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:\goprojects\tookit-project>
PS D:\goprojects\tookit-project> go work init toolkit app
PS D:\goprojects\tookit-project>
PS D:\goprojects\tookit-project> ls

Directory: D:\goprojects\tookit-project

Mode LastWriteTime Length Name


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:\goprojects\tookit-project>
PS D:\goprojects\tookit-project> cat go.work
go 1.20

use (
./app
./toolkit
)
PS D:\goprojects\tookit-project>

@bluefire I have used postman too for sending the JSON ( firstname and lastname) via POST query but that is not inserting the data into mongoDB database.

It is also very simple to create a go.mod file to develop Go language using LiteIDE.
Why not try using LiteIDE rather than VSCODE?

@shubhra Be careful, the name “workspace” has two meanings here:

  1. A VSCode workspace, where VSCode saves workspace settings. The file extension is .code-workspace. The existence of aVSCode workspace file has no influence on the Go project. You can always manage the Go project completely outside VSCode, on the command line, using the Go commands.
  2. A Go workspace, which you probably do not need here at all. The Go workspace file name is go.work. You only need it for overriding dependencies locally.

I’d put the VSCode workspace file problem aside for now.

CORRECTION: Upon closer look, I guess you do need a go.work file, because you use two separate modules locally.

Please try this and let me know if it helps:

  1. cd into the app folder
  2. Run go work init . to create a new Go workspace for your app.
  3. Run go work use ../toolkit-project to include the other Go module into the Go workspace.

With this setup, the Go command knows where to find the imports locally.

1 Like

@shubhra wait, does this mean that you are able to compile and run your app?

@christophberger didn’t tried running the app yet. Will do it tonight. But, atleast leant both workspace things, via a udemy.com course
Able to create go.work and vscode code workspace, both.

1 Like