gqlgen?Go 語(yǔ)言實(shí)現(xiàn)的基于 graphql 的服務(wù)器庫(kù)
gqlgen 是一個(gè)使用 Go 語(yǔ)言實(shí)現(xiàn)的用于快速創(chuàng)建嚴(yán)格類型的 graphql 服務(wù)器的庫(kù)。
dep ensure -add github.com/vektah/gqlgen
示例代碼
定義 schema
schema {
query: Query
mutation: 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 yourapp
type Todo struct {
ID string
Text string
Done bool
UserID int
}
type User struct {
ID string
Name string
}
告訴生成器如何在 types.json 中的兩者之間進(jìn)行映射
{
"Todo": "github.com/you/yourapp.Todo",
"User": "github.com/you/yourapp.User"}
然后從其中生成運(yùn)行時(shí)
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)
}
實(shí)現(xiàn)此接口,然后通過(guò)將其傳遞到生成的代碼中來(lái)創(chuàng)建服務(wù)器
func main() {
http.Handle("/query", graphql.Handler(gen.NewResolver(yourResolvers{})))
log.Fatal(http.ListenAndServe(":8080", nil))
}評(píng)論
圖片
表情
