-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
60 lines (49 loc) · 1.55 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
package main
import (
"log"
"net/http"
"os"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/go-chi/chi"
"github.com/joho/godotenv"
"github.com/wangyangjun/receipt-uploader/graph"
"github.com/wangyangjun/receipt-uploader/graph/generated"
"github.com/wangyangjun/receipt-uploader/graph/service/auth"
)
const defaultPort = "8080"
const defaultJwtKey = "this-is-not-safe"
const defaultPwdKey = "this-is-not-safe"
func preenv() {
if _, err := os.Stat(".env"); os.IsNotExist(err) {
log.Println("No environment file found will use default values instead!")
} else {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
}
// set default env variables if not present
if os.Getenv("PORT") == "" {
os.Setenv("PORT", defaultPort)
}
if os.Getenv("JWT_KEY") == "" {
os.Setenv("JWT_KEY", defaultJwtKey)
}
if os.Getenv("PORT") == "" {
os.Setenv("PORT", defaultPwdKey)
}
}
func main() {
preenv()
port := os.Getenv("PORT")
router := chi.NewRouter()
router.Use(auth.AuthMiddleware())
srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))
router.Handle("/", playground.Handler("GraphQL playground", "/query"))
router.Handle("/query", srv)
fs := http.FileServer(http.Dir("./images"))
router.Handle("/image/{userId}/*", auth.ImageAuthMiddleware(http.StripPrefix("/image/", fs)))
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, router))
}