implement config file

This commit is contained in:
Matthieu Lamalle 2019-07-25 14:29:02 +02:00
parent 9ddca46ea7
commit e12876b3ed
7 changed files with 49 additions and 17 deletions

View File

@ -44,7 +44,6 @@ query GetAllUsers {
```
## Mutation
Toute requếte visant à modifier une donnée est appellée une 'Mutation'
@ -69,7 +68,6 @@ mutation CreateUser($firstname: String!, $lastname: String!) {
}
}
```
## Postgres
@ -99,5 +97,9 @@ firstname TEXT,
lastname TEXT
);
> CREATE TABLE roles (
id SERIAL PRIMARY KEY,
name TEXT
);
```

25
config/config.go Normal file
View File

@ -0,0 +1,25 @@
package config
import (
"log"
"github.com/tkanos/gonfig"
)
type Configuration struct {
DB_HOST string
DB_PORT string
DB_USER string
DB_PASSWORD string
DB_NAME string
JWT_SECRET string
}
func GetConfig() Configuration {
configuration := Configuration{}
err := gonfig.GetConf("config/config.json", &configuration)
if err != nil {
log.Fatalf("Failed to load configuration file, error: %v", err)
}
return configuration
}

8
config/config.json Normal file
View File

@ -0,0 +1,8 @@
{
"DB_HOST":"localhost",
"DB_PORT":"5432",
"DB_USER":"graphql",
"DB_PASSWORD":"graphql",
"DB_NAME":"graphql",
"JWT_SECRET":"cadoles"
}

BIN
graphql

Binary file not shown.

12
main.go
View File

@ -1,15 +1,17 @@
package main
import (
"cadoles/graphql/mutations"
"cadoles/graphql/postgres"
"cadoles/graphql/queries"
"log"
"net/http"
"cadoles/graphql/mutations"
"cadoles/graphql/postgres"
"cadoles/graphql/queries"
"cadoles/graphql/security"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
"github.com/mnmtanish/go-graphiql"
graphiql "github.com/mnmtanish/go-graphiql"
)
func main() {
@ -39,7 +41,7 @@ func main() {
postgres.DBConnect()
defer postgres.DBClose()
http.Handle("/graphql", httpHandler)
http.Handle("/graphql", security.Handle(httpHandler))
http.HandleFunc("/", graphiql.ServeGraphiQL)
log.Print("ready: listening...\n")

View File

@ -1,20 +1,13 @@
package postgres
import (
"cadoles/graphql/config"
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
const (
DB_HOST = "localhost"
DB_PORT = "5432"
DB_USER = "graphql"
DB_PASSWORD = "graphql"
DB_NAME = "graphql"
)
var (
DB *sql.DB
)
@ -26,8 +19,9 @@ func checkErr(err error, DB *sql.DB) {
}
func DBConnect() {
conf := config.GetConfig()
dbinfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME)
conf.DB_HOST, conf.DB_PORT, conf.DB_USER, conf.DB_PASSWORD, conf.DB_NAME)
var err error
DB, err = sql.Open("postgres", dbinfo)
checkErr(err, DB)

View File

@ -7,6 +7,7 @@ import (
// GetRootFields returns all the available queries.
func GetRootFields() graphql.Fields {
return graphql.Fields{
"users": GetUserQuery(),
"user": GetUserQuery(),
}
}