go-graphql
정보
이 스킬은 개발자가 gqlgen을 사용한 스키마 우선 생성 방식으로 Go에서 GraphQL 서버를 구축하는 데 도움을 줍니다. 리졸버 구현, 데이터로더를 통한 N+1 문제 해결, 복잡도 제한 및 인가 기능 추가를 다룹니다. Go에서 GraphQL API를 구현하거나 쿼리 성능을 최적화할 때 활용하세요.
빠른 설치
Claude Code
추천npx skills add eduardo-sl/go-agent-skills -a claude-code/plugin add https://github.com/eduardo-sl/go-agent-skillsgit clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-graphqlClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Go GraphQL
GraphQL moves query planning to the client. That is the feature and the danger: one innocuous query can become ten thousand database round trips, and one over-permissive field can leak another tenant's data. Both are solved at the server, not in the schema review.
1. Schema-First with gqlgen
The .graphql schema is the source of truth. gqlgen generates models,
resolver stubs, and the execution layer from it.
go get -tool github.com/99designs/gqlgen
go tool gqlgen init # once
go tool gqlgen generate # after every schema change
# gqlgen.yml — bind generated types to your own models
models:
User:
model: github.com/myorg/app/internal/domain.User
ID:
model:
- github.com/99designs/gqlgen/graphql.ID
- github.com/99designs/gqlgen/graphql.Int64
Bind domain types explicitly. Left to itself gqlgen generates a parallel set of anaemic structs, and every resolver becomes a mapping function.
Commit generated code, and fail CI when it is stale:
go tool gqlgen generate && git diff --exit-code
Never edit generated.go or models_gen.go. resolver.go and the
*.resolvers.go files are yours.
2. Resolvers Stay Thin
A resolver translates a GraphQL request into a service call. It contains no business logic and no SQL.
func (r *queryResolver) User(ctx context.Context, id string) (*domain.User, error) {
u, err := r.users.Find(ctx, id)
if errors.Is(err, domain.ErrNotFound) {
return nil, nil // nullable field: absent, not an error
}
if err != nil {
return nil, fmt.Errorf("find user %s: %w", id, err)
}
return u, nil
}
Inject dependencies through the Resolver struct, never through package
globals:
type Resolver struct {
users UserService
orders OrderService
loader *Loaders
}
Always propagate ctx. It carries the request deadline, the authenticated
principal, and the per-request dataloaders.
3. The N+1 Problem — the one that matters
A field resolver on a list type runs once per element.
// ❌ 1 query for the orders, then N queries for the users
func (r *orderResolver) Customer(ctx context.Context, obj *domain.Order) (*domain.User, error) {
return r.users.Find(ctx, obj.CustomerID)
}
Batch with a dataloader. It collects the keys requested within a short window and issues one query.
import "github.com/vikstrous/dataloadgen"
type Loaders struct {
UserByID *dataloadgen.Loader[string, *domain.User]
}
func NewLoaders(s UserService) *Loaders {
return &Loaders{
UserByID: dataloadgen.NewLoader(func(ctx context.Context, ids []string) ([]*domain.User, []error) {
return s.FindMany(ctx, ids) // ONE query for all ids
}, dataloadgen.WithWait(time.Millisecond)),
}
}
// ✅ 1 query for the orders, 1 for all customers
func (r *orderResolver) Customer(ctx context.Context, obj *domain.Order) (*domain.User, error) {
return loadersFrom(ctx).UserByID.Load(ctx, obj.CustomerID)
}
Loaders are per request, installed by middleware. A process-wide loader caches across users and leaks data between them.
func withLoaders(svc UserService, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), loadersKey{}, NewLoaders(svc))
next.ServeHTTP(w, r.WithContext(ctx))
})
}
The batch function must return results in the order of the keys it was given, with a nil entry and an error per missing key. Returning a shorter slice silently misaligns every result.
4. Bound Every Query
A public GraphQL endpoint without limits is a denial-of-service endpoint.
srv := handler.New(generated.NewExecutableSchema(cfg))
srv.AddTransport(transport.POST{})
srv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
srv.Use(extension.FixedComplexityLimit(300))
srv.Use(extension.AutomaticPersistedQuery{Cache: lru.New[string](100)})
- Complexity limit — assign a cost per field, higher for list fields with
a large
first. Start at a number your slowest legitimate query fits under, then measure. - Depth — recursive types (
user { orders { customer { orders ... } } }) must be bounded. gqlgen has no built-in depth limit; enforce it in an operation middleware. - Pagination is mandatory on every list field. A field returning an unbounded list is a schema bug.
- Introspection is only enabled if you install
extension.Introspection. Do not install it in production, or gate it behind an authenticated role. - Persisted queries let a public client send a hash instead of a document, so the server executes only queries you shipped.
Set srv.AroundOperations to enforce a per-operation timeout, and always run
behind an http.Server with ReadTimeout and WriteTimeout set.
5. Errors
GraphQL returns 200 with an errors array. Never leak internals into it.
srv.SetErrorPresenter(func(ctx context.Context, e error) *gqlerror.Error {
err := graphql.DefaultErrorPresenter(ctx, e)
var domainErr *domain.ValidationError
if errors.As(e, &domainErr) {
err.Message = domainErr.Message
err.Extensions = map[string]any{"code": "VALIDATION_FAILED"}
return err
}
slog.ErrorContext(ctx, "graphql resolver failed", "error", e)
err.Message = "internal server error" // stable, safe
err.Extensions = map[string]any{"code": "INTERNAL"}
return err
})
Use srv.SetRecoverFunc to convert a resolver panic into an error instead of
killing the connection, and log it with the stack.
Remember the nullability rule: an error on a non-null field nulls out its nearest nullable ancestor. Make a field non-null only when it can never legitimately be absent.
6. Authorization Belongs on the Field
Object-level checks are not enough — a client can reach an object through several paths.
directive @hasRole(role: Role!) on FIELD_DEFINITION
type User {
id: ID!
email: String! @hasRole(role: ADMIN)
}
cfg.Directives.HasRole = func(ctx context.Context, obj any, next graphql.Resolver, role model.Role) (any, error) {
if !auth.FromContext(ctx).HasRole(role) {
return nil, gqlerror.Errorf("access denied")
}
return next(ctx)
}
Authenticate in HTTP middleware, before the GraphQL handler. Authorize in the directive or the resolver, using the principal from the context — never from a query argument.
7. Testing
func TestUserQuery(t *testing.T) {
c := client.New(handler.NewDefaultServer(generated.NewExecutableSchema(cfg)))
var resp struct {
User struct{ ID, Email string }
}
c.MustPost(`{ user(id: "u-1") { id email } }`, &resp)
require.Equal(t, "u-1", resp.User.ID)
}
Assert the query count for any resolver with a dataloader — that is the only way an N+1 regression fails a build rather than a dashboard:
require.Equal(t, 2, db.QueryCount(), "expected batched loads, got N+1")
Verification Checklist
- Schema is the source of truth; generated files are committed and CI-checked
- Generated types bind to domain models via
gqlgen.yml - Resolvers contain no business logic and always propagate
ctx - Every list-field resolver that fetches by ID goes through a dataloader
- Dataloaders are constructed per request, never shared across requests
- Batch functions return one result per key, in key order
- A complexity limit and a depth bound are configured and tested
- Every list field is paginated
- Introspection is disabled or role-gated in production
- An error presenter strips internal errors; a recover func is installed
- Authorization is enforced per field, from the context principal
- A test asserts the query count for at least one batched field
GitHub 저장소
자주 묻는 질문
go-graphql Skill이란 무엇인가요?
go-graphql은(는) eduardo-sl이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 go-graphql 관련 작업을 수행할 수 있게 합니다.
go-graphql은(는) 어떻게 설치하나요?
이 페이지의 설치 명령을 사용하세요. go-graphql을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.
go-graphql은(는) 어떤 카테고리에 속하나요?
go-graphql은(는) 메타 카테고리에 속합니다.
go-graphql은(는) 무료로 사용할 수 있나요?
네. go-graphql은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.
연관 스킬
이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.
이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.
이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.
SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.
