Skip to content
Santekno.com | Tech Tutorials and Trends
EN
📖 0%
07 Jul 2025 · 4 min read ·Article 7 / 125
Go

7 Installing the graphql-go Library and Additional Dependencies

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

7 Installing the graphql-go Library and Additional Dependencies

By: [Your Name], Backend Engineer

GraphQL has become one of the new standards for designing modern APIs. One of the more popular libraries for implementing GraphQL in Go (Golang) is graphql-go . If you’re just getting started, this article will guide you step by step through installing the graphql-go library along with the additional dependencies commonly used in real-world projects. I’ll also include code examples, a simulation, and flow diagrams to make the integration process clearer.


1. Prepare Your Go Environment

Make sure you already have Go installed. At least version 1.16. Check it with:

bash
1go version

If it isn’t installed yet, you can grab it from https://golang.org/dl/ .


2. Initialize a New Project

We’ll use Go modules to manage dependencies. Create a new project folder and initialize the module:

bash
1mkdir graphql-tutorial
2cd graphql-tutorial
3go mod init github.com/yourusername/graphql-tutorial

3. Installing the Core Library: graphql-go

graphql-go is the main GraphQL engine in Go. Install it with:

bash
1go get github.com/graph-gophers/graphql-go
2go get github.com/graph-gophers/graphql-go/relay

This adds the graphql-go library to your go.mod.

Quick Overview of the Components:

LibraryMain Function
github.com/graph-gophers/graphql-goParser and executor for GraphQL schema queries
github.com/graph-gophers/graphql-go/relayHTTP handler for the GraphQL endpoint

4. Routing Support: chi

You could technically use http.ServeMux. However, in real-world applications, a router package like chi is often used.

bash
1go get github.com/go-chi/chi/v5

Routing Integration Example:

go
 1import (
 2    "net/http"
 3    "github.com/go-chi/chi/v5"
 4)
 5
 6func main() {
 7    r := chi.NewRouter()
 8    r.Post("/query", relayHandler) // we'll define relayHandler later
 9    http.ListenAndServe(":8080", r)
10}

5. JSON Dependency: graphql-go-tools / Encoding

The graphql-go library does not encode/decode JSON responses automatically. We’ll use Go’s built-in encoding (encoding/json), though a companion library is also commonly used, for example graphql-go-tools .

bash
1go get github.com/wundergraph/graphql-go-tools

But to get started, encoding/json is enough.


6. Dependency Injection & Middleware

To keep the code modular and testable, it’s recommended to use dependency injection, for example google/wire , and middleware such as alice .

bash
1go get github.com/justinas/alice
2go get github.com/google/wire

7. Logging: zerolog

Logging is essential. One modern logging library is zerolog .

bash
1go get github.com/rs/zerolog/log

Simulation: Setting Up a Simple GraphQL Endpoint

Simple Project Structure:

MERMAID
graph TD
    A[main.go] --> B[chi router]
    B --> C[GraphQL Schema]
    C --> D[Resolver]
    D -->|handle| E[relay.Handler]

Example Schema and Resolver:

File: schema.graphql

graphql
1type Query {
2    hello: String!
3}

File: main.go

go
 1package main
 2
 3import (
 4    "context"
 5    "embed"
 6    "net/http"
 7    "github.com/go-chi/chi/v5"
 8    "github.com/graph-gophers/graphql-go"
 9    "github.com/graph-gophers/graphql-go/relay"
10    "github.com/rs/zerolog/log"
11)
12
13//go:embed schema.graphql
14var sdl embed.FS
15
16type resolver struct{}
17
18func (r *resolver) Hello() string {
19    log.Info().Msg("handling hello query")
20    return "Hello, graphql-go!"
21}
22
23func main() {
24    schemaStr, _ := sdl.ReadFile("schema.graphql")
25    schema := graphql.MustParseSchema(string(schemaStr), &resolver{})
26
27    r := chi.NewRouter()
28    // Logging middleware
29    r.Use(func(next http.Handler) http.Handler {
30        return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
31            log.Info().Msgf("Request: %s %s", req.Method, req.URL.Path)
32            next.ServeHTTP(w, req)
33        })
34    })
35
36    r.Post("/query", (&relay.Handler{Schema: schema}).ServeHTTP)
37    log.Info().Msg("GraphQL server started at :8080")
38    http.ListenAndServe(":8080", r)
39}

Try the Query via cURL:

bash
1curl -X POST -d '{"query": "{ hello }"}' -H "Content-Type: application/json" localhost:8080/query

Output:

json
1{"data":{"hello":"Hello, graphql-go!"}}


Dependency Summary Table

NoLibraryDescriptionExample Usage
1graphql-goMain GraphQL engineSchema design & query processing
2graphql-go/relayGraphQL HTTP handlerThe /query endpoint
3go-chi/chiLightweight, modular routerEndpoint routing
4encoding/jsonJSON encoding/decodingParsing the response
5zerologModern, lightweight loggingLogging queries/requests/errors
6justinas/aliceMiddleware chainingAuth/logging wrapper
7google/wireDependency injectionModularizing resolvers

End-to-End Flow Diagram

MERMAID
sequenceDiagram
    participant C as Client
    participant S as Web Server
    participant G as GraphQL Handler
    
    C->>S: POST /query { query }
    S->>G: Parse and Validate Query
    G->>G: Execute Resolver Function
    G->>S: GraphQL Response JSON
    S->>C: Response (data/error)

Conclusion

Installing and setting up a GraphQL library in Go requires understanding its components, because the architecture is highly modular. With the right combination of graphql-go, chi, and zerolog, you can run a production-grade GraphQL server that is also easy to maintain and scale. From here, development can be enhanced with integrations for authentication, batching, and custom directives.

Don’t hesitate to experiment with other dependencies as your project requires. I hope this article gives you a solid foundation for building reliable GraphQL APIs in Go.


References

Happy Coding! 🚀

Related Articles

💬 Comments