gqlgen golang graphql server 基本试用

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

  • User (model/user.go)
package model

// User user info
type User struct {
    ID string
    Name string
}
  • Todo (model/todo.go)
package model

// Todo todo ino
type Todo struct {
    ID string
    Text string
    Done bool
    UserID string
}

生成graphql 运行时代码

  • 配置模型关联

    gqlgen.yml

schema: schema.graphql
exec:
  filename: graph/generated.go
model:
  filename: model/generated.go

models:
  Todo:
    model: github.com/rongfengliang/gqlgen-app/model.Todo
  User:
    model: github.com/rongfengliang/gqlgen-app/model.User
  • 生成bingings
gqlgen

  • 编写 resolver

    graph/graph.go

package graph

import (
    "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
}

入口代码编写

  • main.go
package main

import (
    "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

posted on 2018-07-25 11:02  荣锋亮  阅读(1586)  评论(0编辑  收藏  举报

导航