gqlgen是一个使用Go语言实现的用于快速创建严格类型的graphql服务器的库。
dep ensure -add github.com/vektah/gqlgen示例代码
定义schema
schema {query: Querymutation: Mutation}type Query {todos: [Todo!]!}type Mutation {createTodo(text: String!): Todo!}type Todo {id: ID!text: String!done: Boolean!user: User!}type User { id: ID! name: String!}
定义模型
package yourapptype Todo struct {ID stringText stringDone boolUserID int}type User struct { ID string Name string}
告诉生成器如何在types.json中的两者之间进行映射
{ "Todo": "github.com/you/yourapp.Todo", "User": "github.com/you/yourapp.User"}
然后从其中生成运行时
gqlgen -out generated.go在生成的文件的顶部将是与完成所需的图的解析器的接口
package yourapptype Resolvers interface {Mutation_createTodo(ctx context.Context, text string) (Todo, error)Query_todos(ctx context.Context) ([]Todo, error)Todo_user(ctx context.Context, it *Todo) (User, error)}
实现此接口,然后通过将其传递到生成的代码中来创建服务器
func main() {http.Handle("/query", graphql.Handler(gen.NewResolver(yourResolvers{})))log.Fatal(http.ListenAndServe(":8080", nil))}
评论