gqlgen Plugin Example
This example demonstrates how to use gqlscanner as a gqlgen plugin.
Setup
- Install dependencies:
go get github.com/99designs/gqlgen
go get github.com/pablor21/gqlscanner/plugin
- Create a
tools.go file to ensure the plugin is included:
//go:build tools
// +build tools
package tools
import (
_ "github.com/99designs/gqlgen"
_ "github.com/pablor21/gqlscanner/plugin"
)
- Run
go mod tidy:
go mod tidy
Configuration
The gqlgen.yml file is configured to use the gqlscanner plugin:
plugins:
gqlscanner:
packages:
- ./graph/models
This tells gqlscanner to scan the ./graph/models directory for Go structs with gql annotations.
Usage
Generate GraphQL code with gqlgen:
go run github.com/99designs/gqlgen generate
This will:
- gqlscanner plugin runs first: Generates GraphQL schemas from Go structs in
graph/models/
- gqlgen continues: Generates resolvers and types based on the schemas
Models
The graph/models/ directory contains example Go structs:
product.go - Product and Category types
These use the same annotation format as the CLI example.
Plugin vs CLI
| Feature |
CLI |
Plugin |
| Usage |
Standalone tool |
Integrated with gqlgen |
| When to run |
Manually or in build scripts |
Automatically during gqlgen generate |
| Configuration |
gqlscanner.yml or flags |
gqlgen.yml plugins section |
| Best for |
Independent schema generation |
Full gqlgen workflow |
Workflow
- Define Go structs with gql annotations in
graph/models/
- Run
gqlgen generate
- gqlscanner generates schemas to
graph/schema/
- gqlgen generates resolvers and types
- Implement resolver logic
Example Output
After running gqlgen generate, you'll have:
graph/
├── generated.go # gqlgen generated code
├── model/
│ └── models_gen.go # Generated GraphQL models
├── models/
│ └── product.go # Your Go structs (source)
├── schema/
│ └── schema.graphql # Generated by gqlscanner
└── *.resolvers.go # Generated resolver stubs
Advanced Configuration
You can customize gqlscanner behavior in gqlgen.yml:
plugins:
gqlscanner:
packages:
- ./graph/models
# Additional config can be added here
# (currently packages is the main config option)
For more control over schema generation, use the CLI tool separately and reference the generated schemas in gqlgen.yml.