Tutorial & Training/Go
#01. go-graphql 시작하기
TL&D
2020. 12. 16. 00:15
728x90
본문은 시리즈로 작성되는 내용입니다.
Go Version은 1.15.6으로 진행되었습니다.
go get github.com/graphql-go/graphql
go get github.com/graphql-go/handler
먼저 graphql-go/graphql, graphql-go/handler를 install 합니다.
설치가 다 되었다면, 대충 main.go 파일을 만들어서 코드를 작성합니다.
// main.go
package main
import (
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
"net/http"
)
func main() {
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
}
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
schema, _ := graphql.NewSchema(schemaConfig)
h := handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: false,
Playground: true,
})
http.Handle("/graphql", h)
http.ListenAndServe(":8888", nil)
}
두 패키지의 공식문서를 결합한다면 위 와 같은 코드가 됩니다.
graphql-go/graphql 에서 GraphQL에 필요로 하는 fields를 작성하여 Resolver를 구현한 내용입니다.
rootQuery를 통해 쿼리를 설정 후 스키마에 등록하여 handler를 통해 서빙할 수 있습니다.
Playground: true 옵션을 통해 플레이그라운드를 확인할 수 있는데
playground에서 쿼리를 직접 실행해보면
hello World!
정말 간단합니다!
728x90