-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (78 loc) · 1.93 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
MONGO_URI = "mongodb://%s:%s@mongo:%v/golangmongo?authSource=admin"
)
type Item struct {
Name string `json:"name"`
Price float64 `json:"price"`
}
var collection *mongo.Collection
func main() {
r := gin.Default()
conn := fmt.Sprintf(MONGO_URI, "root", "rootpassword", 8081)
// Access the client
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(conn))
// Capture the errors
if err != nil {
log.Fatalf("Could not connect to MongoDB: %v", err)
}
defer func() {
if err = client.Disconnect(context.Background()); err != nil {
log.Fatalf("could not connect to MongoDB: %v", err)
}
}()
db := client.Database("golangmongo")
collection = db.Collection("items")
r.GET("/items", getItems)
r.POST("/items", createItem)
// Start the server
port := os.Getenv("PORT")
if port == "" {
port = "8800"
}
err = r.Run(":" + port)
if err != nil {
log.Fatal(err)
}
}
func getItems(c *gin.Context) {
var items []Item
cursor, err := collection.Find(context.Background(), nil)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
var item Item
if err := cursor.Decode(&item); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
items = append(items, item)
}
c.JSON(http.StatusOK, items)
}
func createItem(c *gin.Context) {
var item Item
if err := c.ShouldBindJSON(&item); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
_, err := collection.InsertOne(context.Background(), item)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, item)
}