gqlgen golang 的graphql server
具體代碼參考https://github.com/rongfengliang/gqlgen-demo
特點
安裝
go get -u github.com/vektah/gqlgen
建立schema
schema.graphql
type Todo {id: ID!text: String!done: Boolean!user: User!}type User {id: ID!name: String!}type Query {todos: [Todo!]!}input NewTodo {text: String!userId: String!}type Mutation {createTodo(input: NewTodo!): Todo!}
建立model
package model// User user infotype User struct { ID string Name string}
package model// Todo todo inotype Todo struct { ID string Text string Done bool UserID string}
產生graphql 運行時代碼
schema: schema.graphqlexec: filename: graph/generated.gomodel: filename: model/generated.gomodels: Todo: model: github.com/rongfengliang/gqlgen-app/model.Todo User: model: github.com/rongfengliang/gqlgen-app/model.User
gqlgen
- 編寫 resolver
graph/graph.go
package graphimport ( "context" "fmt" "math/rand" model "github.com/rongfengliang/gqlgen-app/model")type App struct { todos []model.Todo}func (a *App) Mutation() MutationResolver { return &mutationResolver{a}}func (a *App) Query() QueryResolver { return &queryResolver{a}}func (a *App) Todo() TodoResolver { return &todoResolver{a}}type queryResolver struct{ *App }func (a *queryResolver) Todos(ctx context.Context) ([]model.Todo, error) { return a.todos, nil}type mutationResolver struct{ *App }func (a *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (model.Todo, error) { todo := model.Todo{ Text: input.Text, ID: fmt.Sprintf("T%d", rand.Int()), UserID: input.UserId, } a.todos = append(a.todos, todo) return todo, nil}type todoResolver struct{ *App }func (a *todoResolver) User(ctx context.Context, it *model.Todo) (model.User, error) { return model.User{ID: it.UserID, Name: "user " + it.UserID}, nil}
入口代碼編寫
package mainimport ( "fmt" "log" "net/http" "github.com/rongfengliang/gqlgen-app/graph" "github.com/vektah/gqlgen/handler")func main() { http.Handle("/", handler.Playground("Todo", "/query")) http.Handle("/query", handler.GraphQL(graph.NewExecutableSchema(&graph.App{}))) fmt.Println("Listening on :8080") log.Fatal(http.ListenAndServe(":8080", nil))}
運行
go run main.go
效果
整合dep
dep init
參考資料
https://gqlgen.com/getting-started/
https://github.com/vektah/gqlgen
https://github.com/rongfengliang/gqlgen-demo