-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.go
78 lines (62 loc) · 1.7 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"database/sql"
"log"
"net/http"
"os"
"fmt"
"github.com/joho/godotenv"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
"github.com/uptrace/bun/extra/bundebug"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/Learn-go-language/task_tracker_api_with_graphql_and_bun/graph"
)
const defaultPort = "8080"
var DB *bun.DB
func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
// Make a connection with the database
err := connectToDatabase()
if err != nil {
log.Fatalf("Unable to connect to the database: %s", err.Error())
}
fmt.Println("Successfully connected to the database")
resolver := &graph.Resolver{
DB: DB,
}
es := graph.NewExecutableSchema(graph.Config{Resolvers: resolver})
srv := handler.NewDefaultServer(es)
http.Handle("/", playground.Handler("GraphQL playground", "/query"))
http.Handle("/query", srv)
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func connectToDatabase() error {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
dsn := fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=%s",
os.Getenv("DB_USER"),
os.Getenv("DB_PASSWORD"),
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_NAME"),
os.Getenv("DB_SSL_MODE"),
)
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
// defer sqldb.Close()
DB = bun.NewDB(sqldb, pgdialect.New())
DB.AddQueryHook(bundebug.NewQueryHook(
bundebug.WithVerbose(true),
bundebug.FromEnv("BUNDEBUG"),
))
return DB.Ping()
}