Giter Club home page Giter Club logo

go-graphql-starter's Introduction

Go Graphql Starter

GitHub license

This project aims to use graph-gophers/graphql-go to build a starter web application. This project has already been used as backend application in production.

In case you need to get called from another frontend side, CORS may needed to be enabled in this application as this project mainly focuses on backend logic at this stage.

This project would be continuously under development for enhancement. Pull request is welcome.

RoadMap:

  • Integrated with sqlx
  • Integrated with graphql-go
  • Use go-bindata to generate Go code from .graphql file
  • Use psql
  • Integrated with dataloader
  • Add authentication & authorization
  • Add unit test cases
  • Support subscription
  • Support web-socket notification and messaging

Structure

go-graphql-starer
│   README.md
│   server.go           --- the entry file
│   Config.toml         --- the configuration file for setting server parameter
│   Dockerfile
│   Gopkg.lock          --- generated file from dependency management tool, dep
│   Gopkg.toml          --- generated file from dependency management tool, dep
│   graphiql.html       --- the html for graphiql which is used for testing query & mutation
└───context             --- application context like db configuration
└───data                --- storing the sql data patch for different version
│   └───1.0             --- storing sql data patch for version 1.0
│      └───...          --- sql files
└───handler             --- the handler used for chaining http request like authentication, logging etc.
└───loader              --- implementation of dataloader for caching and batching the graphql query
└───model               --- the folder putting struct file
└───resolver            --- implementation of graphql resolvers
└───schema              --- definition of graphql schemas
│   │   schema.go       --- used for generate go code from static graphql files inside 'type' folder
│   │   schema.graphql  --- graphql root schema
│   └───type            --- folder for storing graphql schema in *.graphql format
│       └───...         --- graphql schema files in *.graphql format
└───service             --- services for users, authorization etc.
└───util                --- utilities

Requirement:

  1. Postgres database
  2. Golang

Remark: If you want to use other databases, please feel free to change the driver in context/db.go

Usage(Without docker):

  1. Run the sql scripts under data/1.0 folder inside Postgres database console

  2. Install go-bindata

    go get -u github.com/jteeuwen/go-bindata/...
    
  3. Setup GOPATH (Optional if already set)

    For example: MacOS

    export GOPATH=/Users/${username}/go
    export PATH=$PATH:$GOPATH/bin
    
  4. Run the following command at root directory to generate Go code from .graphql file

    go-bindata -ignore=\.go -pkg=schema -o=schema/bindata.go schema/...
    

    OR

    go generate ./schema
    

    There would be bindata.go generated under schema folder

  5. Start the server (Ensure your postgres database is live and its setting in Config.toml is correct)

    go build server.go
    

Usage(With docker):

  1. Run the sql scripts under data/1.0 folder inside Postgres database console

  2. Build docker image

    docker build -t go-graphql-starter .
    
  3. Run docker image (Ensure your database setting in Config.toml is correct)

    docker run go-graphql-starter
    

Usage(With docker-compose):

  1. Create a folder /psqldata on your OS system and set it for file sharing in docker

  2. Create and starter services by docker-compose

    docker-compose up
    

Graphql Example:

Test in graphiql by the following endpoint

localhost:3000

Basically there are two graphql queries and one mutation

Query:
  1. Get a user by email
  2. Get user list by cursor pagination
Mutation:

To query a list of users, you need to be authenticated. Authentication is not required for other operations. In order to authenticate, here are the steps to follow:

  1. Create a user
mutation {
  createUser (email: "[email protected]", password: "123456") {
    id
  }
}
  1. Log in by submitting your email and password through a Basic Authorization Header.

Here's an example on how to achieve this:

   a. Download [Insomnia](https://insomnia.rest/) OR Other RESTful endpoint testing tools e.g. Postman

   b. Create a new POST request, paste `localhost:3000/login` in the URL bar and go to the Header tab

   c. Generate your basic Authorization on [blitter.se](https://www.blitter.se/utils/basic-authentication-header-generator/)

   d. In Insomnia, first column, type Authorization, second column enter the Basic you just copied `Basic dGVzdGVyQHRlc3Rlci5jb206a3Rta3Rt`

   e. Click send, you should get a jwt token back.

You can change the Authorization of request header in graphiql.html and restart the server to see the effect of authentication using token

Test:

  • Run Unit Tests
    go test
    

Reference

-graph-gophers/graphql-go

-tonyghita/graphql-go-example

go-graphql-starter's People

Contributors

aquiseb avatar boonep avatar jmancherje avatar oscaryuen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-graphql-starter's Issues

Improvements for the future :)

Hey @OscarYuen thanks again for your work 😄

Just to warn you that since "go" is releasing a new package manager (ex-"vgo") currently in the go1.11beta2 CLI release, it favors downloading latest releases over latest commits when you specify no version for the package.

I had a lot of issue with github.com/jteeuwen/go-bindata since the latest release was published in 2014 while there is more recent commits. So when I was trying to generate my schema the "MustAsset" function was missing:

schema\schema.go:11:8: undefined: MustAsset

To simply solve that I advise users to switch to a brand new repository that is supposed to aggregate all forks of go-bindata:
https://github.com/go-bindata/go-bindata

That works well for me 😃

PS: The coming package manager (go modules) is really cool 👍

About roadmap

Hi @OscarYuen!

I saw you've these goals on the roadmap:

  • Support subscription
  • Support web-socket notification and messaging

Could you tell me if you are currently working on that please 😃 ?

I'm just discovering GraphQL in Golang instead of JS and it would be great to use streams 👍

Thank you

A typo in the configuration file in the parameter jwt-expire-in

Hi,

I am using your repository for the purpose of exploring GraphQL with Go and I noticed a typo in the file configuration, in the jet-expire-in.

For the correct signature of the jwt, you need to remove the letter s.

[auth]
jwt-secret = "[you_secret_here]"    # you secret here
jwt-expire-in = "3600"              # 1 hour in seconds

If you do not make changes, then after reading the configuration file, the value of this parameter will take the value with the letter and the output after conversion to Unix() you will get a completely different value than 1 hour.

You can check it: try to logging the parameter after read configuration file.

go build server.go error

$ go generate ./schema
$ go build server.go

github.com/OscarYuen/go-graphql-starter/loader

loader/user.go:17:21: cannot use userLoader literal.loadBatch (type func("golang.org/x/net/context".Context, dataloader.Keys) []*dataloader.Result) as type dataloader.BatchFunc in return argument

Please advise fix

graphql: panic occurred: runtime error: invalid memory address or nil pointer dereference

Hi,

I just got that error while trying the step described on the readme (using an auth token). I'm really new to the go world so I probably have done some thing stupid but just in case here is the error and the query and auth parameters that created it.

query

{
  users{
    totalCount
  }
}

user

email: "[email protected]", password: "test"

token used
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVkX2F0IjoiMjAxOC0wNC0zMFQxMzo1MToyOS45NzczOTlaIiwiZXhwIjo4OTgzOTU4OTk2LCJpZCI6IlltSnFiR1k0T1RWcWJXOXdabXQyWW1WbWREQT0iLCJpc3MiOiJnby1ncmFwaHFsLXN0YXJ0ZXIifQ.bTE8-DnSYA1BRMgc1QdtyJilxZpQDbfbSqPwxVVTQMo',

error

2018/04/30 14:08:36 graphql: panic occurred: runtime error: invalid memory address or nil pointer dereference
goroutine 13 [running]:
github.com/graph-gophers/graphql-go/log.(*DefaultLogger).LogPanic(0xc26c78, 0x9aa2c0, 0xc4200abb00, 0x8b6180, 0xbf7e40)
        /home/newtrax/workspace/experiments/go/src/github.com/graph-gophers/graphql-go/log/log.go:21 +0x77
github.com/graph-gophers/graphql-go/internal/exec.execFieldSelection.func2.1(0xc4200c4180, 0x9aa2c0, 0xc4200abb00, 0xc420066ef8, 0xc42000c220)
        /home/newtrax/workspace/experiments/go/src/github.com/graph-gophers/graphql-go/internal/exec/exec.go:161 +0x87
panic(0x8b6180, 0xbf7e40)
        /usr/lib/go-1.10/src/runtime/panic.go:505 +0x229
github.com/OscarYuen/go-graphql-starter/resolver.(*Resolver).Users(0xc26c78, 0x9aa2c0, 0xc4200abb90, 0x0, 0x0, 0x0, 0x0, 0x0)
        /home/newtrax/workspace/experiments/go/src/github.com/OscarYuen/go-graphql-starter/resolver/user_query.go:36 +0xff
reflect.Value.call(0x8c31c0, 0xc26c78, 0xa13, 0x9412cc, 0x4, 0xc4200abc20, 0x2, 0x2, 0x3, 0xc4200abc20, ...)
        /usr/lib/go-1.10/src/reflect/value.go:447 +0x969
reflect.Value.Call(0x8c31c0, 0xc26c78, 0xa13, 0xc4200abc20, 0x2, 0x2, 0xa13, 0x2, 0xc420093200)
        /usr/lib/go-1.10/src/reflect/value.go:308 +0xa4
github.com/graph-gophers/graphql-go/internal/exec.execFieldSelection.func2(0xc4200c4180, 0x9aa2c0, 0xc4200abb00, 0xc42000c220, 0xc420036a00, 0xc420066f40, 0x9aa2c0, 0xc4200abb90, 0x0)
        /home/newtrax/workspace/experiments/go/src/github.com/graph-gophers/graphql-go/internal/exec/exec.go:183 +0x372
github.com/graph-gophers/graphql-go/internal/exec.execFieldSelection(0x9aa2c0, 0xc4200abb00, 0xc4200c4180, 0xc420036a00, 0xc42000c220, 0x1)
        /home/newtrax/workspace/experiments/go/src/github.com/graph-gophers/graphql-go/internal/exec/exec.go:193 +0x1aa
github.com/graph-gophers/graphql-go/internal/exec.(*Request).execSelections.func1(0xc4200bca90, 0xc4200c4180, 0x9aa2c0, 0xc4200abb00, 0x0, 0xc420036a00)
        /home/newtrax/workspace/experiments/go/src/github.com/graph-gophers/graphql-go/internal/exec/exec.go:74 +0x16c
created by github.com/graph-gophers/graphql-go/internal/exec.(*Request).execSelections
        /home/newtrax/workspace/experiments/go/src/github.com/graph-gophers/graphql-go/internal/exec/exec.go:70 +0x476

hasNextPage Logic

Hi OscarYuen,
on your user_connection_resolver.go on func PageInfo you have function like this:
func (r *usersConnectionResolver) PageInfo() *pageInfoResolver { return &pageInfoResolver{ startCursor: service.EncodeCursor(r.from), endCursor: service.EncodeCursor(r.to), hasNextPage: false, } }
It seems hasNextPage is always false. how is the logic to provide real hasNextPage value?
Thanks.

Basic & Bearer Authentication

I have used the suggestive blitter.se. The generated basic gives me an error of not being long enough.

2018/12/29 15:43:25 crypto/bcrypt: hashedSecret too short to be a bcrypted password

The Bearer example in the graphql.html file is obviously tailored for an example you had used.

I would suggest a clearer explanation of how you generated the Basic Authorization key. Is this possible in the near future?

undefined: AssetNames and MustAsset

Hi, I'm very interested in taking a look at this project and maybe contribute. But I'm getting the following error... Could you please enlighten me on what's going on?
Thanks in advance

$ go build server.go
# github.com/OscarYuen/go-graphql-starter/schema
../github.com/OscarYuen/go-graphql-starter/schema/schema.go:9:23: undefined: AssetNames
../github.com/OscarYuen/go-graphql-starter/schema/schema.go:10:8: undefined: MustAsset

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.