-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
53 lines (42 loc) · 952 Bytes
/
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
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}
func setupDatabase() (ClientIface, func(), error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://mongo:27017"))
if err != nil {
return nil, nil, err
}
cleanup := func() {
if err := client.Disconnect(ctx); err != nil {
panic(err)
}
}
return &mongoClient{cl: client}, cleanup, nil
}
func run() error {
r := mux.NewRouter()
db, dbCleanup, err := setupDatabase()
if err != nil {
return fmt.Errorf("setup database error: %w", err)
}
defer dbCleanup()
server := newServer(db, r)
http.ListenAndServe(":8080", server)
return nil
}