-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
61 lines (52 loc) · 1.57 KB
/
server.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
package main
import (
"fmt"
"github.com/phyrwork/benevolent-dictator/pkg/api/auth"
"github.com/phyrwork/benevolent-dictator/pkg/api/database"
"gorm.io/gorm"
"log"
"net/http"
"os"
"time"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/phyrwork/benevolent-dictator/pkg/api/graph"
"github.com/phyrwork/benevolent-dictator/pkg/api/graph/generated"
)
const defaultPort = "8080"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
dsn := fmt.Sprintf(
"host=%s user=dictator password=%s dbname=dictator sslmode=disable",
os.Getenv("DB_SERVICE_HOST"),
os.Getenv("DB_SERVICE_PASSWORD"))
log.Printf("database dsn=%s", dsn)
var err error
var db *gorm.DB
for db == nil {
db, err = database.Open(dsn)
if db != nil {
break
}
log.Printf("database open error: %v", err)
time.Sleep(time.Second * 3)
}
log.Printf("database open ok")
if err = database.Migrate(db); err != nil {
log.Fatalf("database migrate error: %v", err)
}
log.Printf("database migration ok")
resolver := &graph.Resolver{
DB: db,
}
srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: resolver}))
mux := http.NewServeMux()
mux.Handle("/query", auth.Handle(srv))
mux.Handle("/playground", playground.Handler("GraphQL playground", "/query"))
mux.Handle("/", http.FileServer(http.Dir("dist"))) // TODO: What to do about development environment?
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, mux))
}