Creating an Opinionated Go GQL Server — Part 1

Project setup and initial steps

Christian Melgarejo
Published in
3 min readJul 15, 2019

--

Let’s make an opinionated GraphQL server using the Gin-gonic web framework, Goth for OAuth2 connections, GORM as DB ORM, and GQLGen for building GraphQL servers.

This project assumes you have at least basic Go knowledge, Go 1.12+ installed, and VSCode (preferred) or similar IDE.

Project Setup

We’ll follow the Go standard project layout for this service. Take a look at the specification. It is opinionated and serves as a good base, though we might stray a little bit from its guidelines.

Start by creating a directory anywhere we want to:

Let’s create the whole project layout with:

internal/gql-server will hold all the related files for the gql server.

cmd/gql-server will house the main.go file for the server, the entry point that will glue it all together.

Since we’re using Go 1.12+, you can use any directory you want outside the $GOPATH/src path. We want to use go modules to initialize our project. We have to run:

Coding our web server

Now we can start adding packages to our project! Let’s start by getting our web framework: gin-gonic

From gin-gonic.com:

What is Gin? Gin is a web framework written in Golang. It features a martini-like API with much better performance, up to 40 times faster. If you need performance and good productivity, you will love Gin.

Let’s start creating the web server.

Create a main.go file in cmd/gql-server :

And paste this placeholder code:

If you go run cmd/gql-server/main.go this code, it will bring up a Gin server listening to locahost:7777 and get an OK printed out in the browser. It works!

Now, let's refactor this code using our already present directory structure, script, internal and pkg folders:

How about it? One line and we have our server running out of the pkg folder.

Now we can build up the server with a script:

And before running, make sure you chmod +x it:

Now we can start building our server, like so:

16M standalone server, not bad I think, and this could be the size of its docker image!

Ok, now on to trying out what has been built:

That’s some serious speed, 39 µ( micro) seconds.

We can further improve our server code and make configurations load from a .env file. Let's create some utils for our server:

The code is pretty much self-explanatory. If an ENV var does not exist, the program will panic. We need these to run. Now, changing

- pkg/server/main.go to this:

And we see how it’s starting to take form as a well-laid-out project!

We can still make a couple of things, like running the server locally by using this script:

This will set up ENV vars, and go run the server.

You can also add a .gitignore file. Run git init, set up the origin to your own repository, and git push it :)

--

--