forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (65 loc) · 1.84 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
package main
// go get -u go.mongodb.org/mongo-driver
// go get -u github.com/joho/godotenv
import (
"context"
"flag"
"fmt"
"log"
"os"
// APIs
storeapi "myapp/api/store"
//
"myapp/env"
"myapp/store"
"github.com/kataras/iris/v12"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const version = "0.0.1"
func init() {
envFileName := ".env"
flagset := flag.CommandLine
flagset.StringVar(&envFileName, "env", envFileName, "the env file which web app will use to extract its environment variables")
flagset.Parse(os.Args[1:])
env.Load(envFileName)
}
func main() {
clientOptions := options.Client().SetHosts([]string{env.DSN})
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(context.TODO())
db := client.Database("store")
var (
// Collections.
moviesCollection = db.Collection("movies")
// Services.
movieService = store.NewMovieService(moviesCollection)
)
app := iris.New()
app.Use(func(ctx iris.Context) {
ctx.Header("Server", "Iris MongoDB/"+version)
ctx.Next()
})
storeAPI := app.Party("/api/store")
{
movieHandler := storeapi.NewMovieHandler(movieService)
storeAPI.Get("/movies", movieHandler.GetAll)
storeAPI.Post("/movies", movieHandler.Add)
storeAPI.Get("/movies/{id}", movieHandler.Get)
storeAPI.Put("/movies/{id}", movieHandler.Update)
storeAPI.Delete("/movies/{id}", movieHandler.Delete)
}
// GET: http://localhost:8080/api/store/movies
// POST: http://localhost:8080/api/store/movies
// GET: http://localhost:8080/api/store/movies/{id}
// PUT: http://localhost:8080/api/store/movies/{id}
// DELETE: http://localhost:8080/api/store/movies/{id}
app.Listen(fmt.Sprintf(":%s", env.Port), iris.WithOptimizations)
}