반업주부의 일상 배움사
[Golang] Gin + gqlgen [GraphQL] 본문
반응형
새로운 폴더 만들고 시작할께요.
1. 설치
$ go mod init banjubu
$ go get github.com/gin-gonic/gin
$ go get github.com/99designs/gqlgen
$ printf '// +build tools\npackage tools\nimport _ "github.com/99designs/gqlgen"' | gofmt > tools.go
$ go run github.com/99designs/gqlgen init
$ rm -rf server.go
2. main.go
package main
import (
"banjubu/graph"
"banjubu/graph/generated"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/gin-gonic/gin"
)
func graphqlHandler() gin.HandlerFunc {
h := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}
func playgroundHandler() gin.HandlerFunc {
h := playground.Handler("GraphQL", "/query")
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}
func main() {
r := gin.Default()
r.POST("/query", graphqlHandler())
r.GET("/", playgroundHandler())
r.Run(":3000")
}
3. graph/resolver.go
package graph
import "banjubu/graph/model"
// This file will not be regenerated automatically.
//
// It serves as dependency injection for your app, add any dependencies you require here.
type Resolver struct {
id int
todos []*model.Todo
}
4. graph/schema.resolvers.go
package graph
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
import (
"banjubu/graph/generated"
"banjubu/graph/model"
"context"
"fmt"
)
func (r *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (*model.Todo, error) {
r.id++
todo := &model.Todo{
Text: input.Text,
ID: fmt.Sprintf("T%d", r.id),
User: &model.User{ID: input.UserID, Name: "user " + input.UserID},
}
r.todos = append(r.todos, todo)
return todo, nil
}
func (r *queryResolver) Todos(ctx context.Context) ([]*model.Todo, error) {
return r.todos, nil
}
// Mutation returns generated.MutationResolver implementation.
func (r *Resolver) Mutation() generated.MutationResolver { return &mutationResolver{r} }
// Query returns generated.QueryResolver implementation.
func (r *Resolver) Query() generated.QueryResolver { return &queryResolver{r} }
type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }
5. 확인 - http://localhost:3000 접속
6. Todo 추가
mutation {
createTodo(input:{
text: "first todo"
userId: "user1"
}) {
id
text
done
user {
id
name
}
}
}
7. Todo 리스트 확인
{
todos {
id
text
done
user {
id
name
}
}
}
8. 스키마 변경 > 제너레이팅
$ go run github.com/99designs/gqlgen generate --verbose
영어, 중국어 공부중이신가요?
홈스쿨 교재. 한 권으로 가족 모두 할 수 있어요!
반응형
LIST
'IT 인터넷 > Golang' 카테고리의 다른 글
[Copper] 설치 (0) | 2022.09.15 |
---|---|
[Copper] 카퍼 소개 (0) | 2022.09.15 |
[Golang] 단숨에 GraphQL 적용하기 [gqlgen] (0) | 2022.05.19 |
[Golang] Supervisor로 데몬 실행하기 (0) | 2022.05.18 |
[Golang] AWS CloudFront > 무효화 (CreateInvalidation) (0) | 2022.05.18 |
Comments