-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
69 lines (58 loc) · 1.89 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
package main
import (
"fmt"
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/render"
"github.com/graphql-go/graphql"
"github.com/theShivaa/go-gql-crud/gql"
"github.com/theShivaa/go-gql-crud/postgres"
"github.com/theShivaa/go-gql-crud/server"
)
func main() {
// Initialize our api and return a pointer to our router for http.ListenAndServe
// and a pointer to our db to defer its closing when main() is finished
router, db := initializeAPI()
defer db.Close()
// Listen on port 4000 and if there's an error log it and exit
log.Fatal(http.ListenAndServe(":4000", router))
}
func initializeAPI() (*chi.Mux, *postgres.Db) {
// Create a new router
router := chi.NewRouter()
// Create a new connection to our pg database
db, err := postgres.New(
postgres.ConnString("localhost", 5432, "shiv", "go_graphql_db"),
)
if err != nil {
log.Fatal(err)
}
// Create a new graphql schema, passing in the the root query
sc, err := graphql.NewSchema(
graphql.SchemaConfig{
Query: gql.RootQueries(db),
Mutation: gql.RootMutations(db),
},
)
if err != nil {
fmt.Println("Error creating schema: ", err)
}
// Create a server struct that holds a pointer to our database as well
// as the address of our graphql schema
s := server.Server{
GqlSchema: &sc,
}
// Add some middleware to our router
router.Use(
render.SetContentType(render.ContentTypeJSON), // set content-type headers as application/json
middleware.Logger, // log api request calls
// middleware.DefaultCompress, // compress results, mostly gzipping assets and json
middleware.StripSlashes, // match paths with a trailing slash, strip it, and continue routing through the mux
middleware.Recoverer, // recover from panics without crashing server
)
// Create the graphql route with a Server method to handle it
router.Post("/graphql", s.GraphQL())
return router, db
}