Skip to content

Commit 1a14d48

Browse files
go mongodb connect
1 parent 6d2e80d commit 1a14d48

File tree

9 files changed

+145
-214
lines changed

9 files changed

+145
-214
lines changed

.env.dev

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
S3_BUCKET=YOURS3BUCKET
22
SECRET_KEY=YOURSECRETKEYGOESHERE
33
PORT=3001
4-
DBNAME=test
4+
DBNAME=test
5+
MONGOURL=mongodb://localhost:27017/test

configs/mongoconnection.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package configs
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"time"
8+
9+
"go.mongodb.org/mongo-driver/mongo"
10+
"go.mongodb.org/mongo-driver/mongo/options"
11+
)
12+
13+
func ConnectDB() *mongo.Client {
14+
client, err := mongo.NewClient(options.Client().ApplyURI(EnvMongoURI()))
15+
if err != nil {
16+
log.Fatal(err)
17+
}
18+
19+
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
20+
err = client.Connect(ctx)
21+
if err != nil {
22+
log.Fatal(err)
23+
}
24+
25+
//ping the database
26+
err = client.Ping(ctx, nil)
27+
if err != nil {
28+
log.Fatal(err)
29+
}
30+
31+
fmt.Println("Connected to MongoDB 1")
32+
33+
return client
34+
}
35+
36+
// Client instance
37+
var DB *mongo.Client = ConnectDB()
38+
39+
// getting database collections
40+
func GetCollection(client *mongo.Client, collectionName string) *mongo.Collection {
41+
collection := client.Database("golangAPI").Collection(collectionName)
42+
43+
return collection
44+
}

configs/mongoenv.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package configs
2+
3+
import (
4+
"log"
5+
"os"
6+
7+
"github.com/joho/godotenv"
8+
)
9+
10+
func EnvMongoURI() string {
11+
err := godotenv.Load(".env.dev")
12+
if err != nil {
13+
log.Fatal("Error loading .env file")
14+
}
15+
return os.Getenv("MONGOURL")
16+
}

controllers/users.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package markscontrollers
2+
3+
import (
4+
"context"
5+
"net/http"
6+
"time"
7+
8+
"github.com/gin-gonic/gin"
9+
"github.com/vinodnextcoder/golang-mongo-server/configs"
10+
"github.com/vinodnextcoder/golang-mongo-server/models"
11+
"github.com/vinodnextcoder/golang-mongo-server/responses"
12+
"go.mongodb.org/mongo-driver/bson/primitive"
13+
"go.mongodb.org/mongo-driver/mongo"
14+
)
15+
16+
var userCollection *mongo.Collection = configs.GetCollection(configs.DB, "users")
17+
18+
func CreateUser() gin.HandlerFunc {
19+
return func(c *gin.Context) {
20+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
21+
var user models.User
22+
defer cancel()
23+
24+
//validate the request body
25+
if err := c.BindJSON(&user); err != nil {
26+
c.JSON(http.StatusBadRequest, responses.UserResponse{Status: http.StatusBadRequest, Message: "error", Data: map[string]interface{}{"data": err.Error()}})
27+
return
28+
}
29+
30+
//use the validator library to validate required fields
31+
// if validationErr := validate.Struct(&user); validationErr != nil {
32+
// c.JSON(http.StatusBadRequest, responses.UserResponse{Status: http.StatusBadRequest, Message: "error", Data: map[string]interface{}{"data": validationErr.Error()}})
33+
// return
34+
// }
35+
36+
newUser := models.User{
37+
Id: primitive.NewObjectID(),
38+
Name: user.Name,
39+
Location: user.Location,
40+
Title: user.Title,
41+
}
42+
43+
result, err := userCollection.InsertOne(ctx, newUser)
44+
if err != nil {
45+
c.JSON(http.StatusInternalServerError, responses.UserResponse{Status: http.StatusInternalServerError, Message: "error", Data: map[string]interface{}{"data": err.Error()}})
46+
return
47+
}
48+
49+
c.JSON(http.StatusCreated, responses.UserResponse{Status: http.StatusCreated, Message: "success", Data: map[string]interface{}{"data": result}})
50+
}
51+
}

main.go

Lines changed: 5 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,16 @@
11
package main
22

33
import (
4-
"fmt"
54
"log"
65
"net/http"
76
"os"
87

9-
// "context"
10-
// "time"
11-
"github.com/vinodnextcoder/golang-mongo-server/mongoconnect"
12-
13-
// "go.mongodb.org/mongo-driver/mongo"
14-
// "go.mongodb.org/mongo-driver/mongo/options"
15-
// "go.mongodb.org/mongo-driver/mongo/readpref"
16-
178
"github.com/gin-gonic/gin"
189
"github.com/joho/godotenv"
1910
swaggerFiles "github.com/swaggo/files"
2011
ginSwagger "github.com/swaggo/gin-swagger"
2112
_ "github.com/vinodnextcoder/golang-mongo-server/docs"
13+
"github.com/vinodnextcoder/golang-mongo-server/routes"
2214
)
2315

2416
// @title Swagger Example API
@@ -41,56 +33,16 @@ func main() {
4133
if err != nil {
4234
log.Fatal("Error loading .env file")
4335
}
44-
45-
// Get Client, Context, CancelFunc and
46-
// err from connect method.
47-
client, ctx, cancel, err := mongoconnect.Connect("mongodb://localhost:27017/test")
48-
if err != nil {
49-
panic(err)
50-
}
51-
52-
// Release resource when the main
53-
// function is returned.
54-
// defer mongoconnect.Close(client, ctx, cancel)
55-
56-
// // Ping mongoDB with Ping method
57-
// // mongoconnect.Ping(client, ctx)
58-
59-
// // Create a object of type interface to store
60-
// // the bson values, that we are inserting into database.
61-
// var document interface{}
62-
63-
// document = bson.D{
64-
// {"rollNo", 175},
65-
// {"maths", 80},
66-
// {"science", 90},
67-
// {"computer", 95},
68-
// }
69-
70-
// dbname := os.Getenv("DBNAME")
71-
// // insertOne accepts client , context, database
72-
// // name collection name and an interface that
73-
// // will be inserted into the collection.
74-
// // insertOne returns an error and a result of
75-
// // insert in a single document into the collection.
76-
// insertOneResult, err := mongoconnect.Insertdata(client, ctx, dbname, "marks", document)
77-
78-
// handle the error
79-
if err != nil {
80-
panic(err)
81-
}
82-
83-
// print the insertion id of the document,
84-
// if it is inserted.
85-
fmt.Println("Result of InsertOne", client, ctx, cancel)
86-
// fmt.Println(insertOneResult.InsertedID)
36+
//run database
37+
// configs.ConnectDB()
8738

8839
port := os.Getenv("PORT")
8940

9041
router := gin.Default()
9142

9243
router.GET("/", helloCall)
93-
router.POST("/add", mongoconnect.PostMarks)
44+
routes.UserRoute(router)
45+
9446
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
9547

9648
router.Run("0.0.0.0:" + port)

models/user_model.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package models
2+
3+
import "go.mongodb.org/mongo-driver/bson/primitive"
4+
5+
type User struct {
6+
Id primitive.ObjectID `json:"id,omitempty"`
7+
Name string `json:"name,omitempty" validate:"required"`
8+
Location string `json:"location,omitempty" validate:"required"`
9+
Title string `json:"title,omitempty" validate:"required"`
10+
}

mongoconnect/config.go

Lines changed: 0 additions & 160 deletions
This file was deleted.

responses/user_response.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package responses
2+
3+
type UserResponse struct {
4+
Status int `json:"status"`
5+
Message string `json:"message"`
6+
Data map[string]interface{} `json:"data"`
7+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy