-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
46 lines (41 loc) · 1.07 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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/joho/godotenv"
"github.com/kiyutink/sowhenthen/mongo"
mongoDB "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
const timeout = time.Second * 30
func newMongoClient(url string) (*mongoDB.Client, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
client, err := mongoDB.Connect(ctx, options.Client().ApplyURI(url))
if err != nil {
return client, err
}
err = client.Ping(ctx, readpref.Primary())
return client, err
}
func main() {
err := godotenv.Load()
if err != nil && !errors.Is(err, os.ErrNotExist) {
panic(err)
}
mongoClient, err := newMongoClient(os.Getenv("MONGO_URL"))
defer mongoClient.Disconnect(context.Background())
if err != nil {
panic(err)
}
srv := NewServer(mongo.NewStorage(mongoClient))
srv.routes()
fmt.Println("server listening on port", os.Getenv("PORT"))
err = http.ListenAndServe(":"+os.Getenv("PORT"), srv)
fmt.Println(err)
}