-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (50 loc) · 1.49 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
package main
import (
"context"
"flag"
"github.com/gofiber/fiber/v2"
"github.com/omar-p/hotel-reservation/api"
"github.com/omar-p/hotel-reservation/db"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"os"
)
var (
dbUri = os.Getenv("DB_URI")
dbName = os.Getenv("DB_NAME")
)
var config = fiber.Config{
ErrorHandler: func(ctx *fiber.Ctx, err error) error {
return ctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": err.Error(),
})
},
}
func main() {
listenAddr := flag.String("listenAdder", ":8080", "port that the server will listen on")
flag.Parse()
ctx := context.Background()
// Use the SetServerAPIOptions() method to set the Stable API version to 1
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().ApplyURI(dbUri).SetServerAPIOptions(serverAPI)
// Create a new client and connect to the server
client, err := mongo.Connect(ctx, opts)
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
// handlers initialization
userHandler := api.NewUserHandler(db.NewMongoUserStore(client, dbName))
app := fiber.New(config)
apiV1 := app.Group("/api/v1")
apiV1.Get("/users", userHandler.HandleGetUsers)
apiV1.Get("/users/:id", userHandler.HandleGetUser)
apiV1.Post("/users", userHandler.HandlePostUser)
apiV1.Put("/users/:id", userHandler.HandlePutUser)
apiV1.Delete("/users/:id", userHandler.HandleDeleteUser)
app.Listen(*listenAddr)
}