-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
79 lines (65 loc) · 1.57 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
package main
import (
"fmt"
"log"
"os"
"test_articles/api"
"test_articles/api/resolvers"
"test_articles/middleware"
"github.com/joho/godotenv"
"github.com/gin-gonic/gin"
graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
func loadEnv() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func connectToDB() *gorm.DB {
connectionString := fmt.Sprintf(
"host=%s port=%s user=%s dbname=%s sslmode=disable password=%s",
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_USER"),
os.Getenv("DB_NAME"),
os.Getenv("DB_PASSWORD"),
)
db, err := gorm.Open("postgres", connectionString)
if err != nil {
panic(err)
}
return db
}
func loadSchema() string {
s, err := api.GetSchema("./api/schema.graphql")
if err != nil {
panic(err)
}
return s
}
func graphQLHandler(r *relay.Handler) gin.HandlerFunc {
return func(c *gin.Context) {
r.ServeHTTP(c.Writer, c.Request)
}
}
func main() {
loadEnv()
var db *gorm.DB
db = connectToDB()
defer db.Close()
db.LogMode(!(os.Getenv("PRODUCTION") != "" && os.Getenv("PRODUCTION") == "TRUE")) //For debugging
// Preparing schema
rootResolver := resolvers.RootResolver{}
schema := graphql.MustParseSchema(loadSchema(), &rootResolver)
r := gin.New()
r.Use(middleware.AddDatabase(db))
r.Use(middleware.AddDGinContext())
r.Use(middleware.AddUser())
r.POST("/graphql", graphQLHandler(&relay.Handler{Schema: schema}))
r.Static("/", "./static/graphiql")
r.Run(":3001")
}