1. 项目地址:
    https://github.com/graphql-go/graphql

  2. 用法:

    1. main.go
       package main
       import (
           "encoding/json"
           "fmt"
           "github.com/graphql-go/graphql"
           "html/template"
           "math/rand"
           "net/http"
           "time"
       )
       type User struct {
           ID   int
           Name string
       }
       // 测试数据
       var UserList = []User{
           {
               1,
               "old user",
           },
       }
       var queryType = graphql.NewObject(graphql.ObjectConfig{
           Name:        "user",
           Description: "用户字段",
           Fields: graphql.Fields{
               "id": &graphql.Field{
                   Type:        graphql.ID,
                   Description: "ID",
               },
               "name": &graphql.Field{
                   Type:        graphql.String,
                   Description: "名字",
               },
           },
       })
       func main() {
           query := graphql.NewObject(graphql.ObjectConfig{
               Name:        graphql.DirectiveLocationQuery,
               Description: "读操作",
               Fields: graphql.Fields{
                   "getUserList": &graphql.Field{
                       Type:        graphql.NewList(queryType),
                       Description: "获取用户列表",
                       Args: graphql.FieldConfigArgument{
                           "page": &graphql.ArgumentConfig{
                               Type:         graphql.Int,
                               DefaultValue: 1,
                           },
                           "query": &graphql.ArgumentConfig{
                               Type: graphql.String,
                           },
                       },
                       Resolve: func(params graphql.ResolveParams) (interface{}, error) {
                           fmt.Printf("args: %v \n", params.Args)
                           return UserList, nil
                       },
                   },
               }})
           mutation := graphql.NewObject(graphql.ObjectConfig{
               Name:        graphql.DirectiveLocationMutation,
               Description: "写操作",
               Fields: graphql.Fields{
                   "createUser": &graphql.Field{
                       Type:        queryType,
                       Description: "创建用户",
                       Args: graphql.FieldConfigArgument{
                           "name": &graphql.ArgumentConfig{
                               Type: graphql.String,
                           },
                       },
                       Resolve: func(params graphql.ResolveParams) (interface{}, error) {
                           name := params.Args["name"]
                           rand.Seed(time.Now().UnixNano())
                           id := rand.Intn(10000)
                           user := User{
                               ID:   id,
                               Name: name.(string),
                           }
                           UserList = append(UserList, user)
                           return UserList[len(UserList)-1], nil
                       },
                   },
               },
           })
           schema, err := graphql.NewSchema(graphql.SchemaConfig{
               Query:    query,
               Mutation: mutation,
           })
           if err != nil {
               panic("创建 schema 失败:" + err.Error())
           }
           http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
               w.Header().Add("Content-Type", "text/html; charset=utf-8")
               w.WriteHeader(http.StatusOK)
               t, err := template.ParseFiles("index.html")
               if err != nil {
                   fmt.Println("模板解析失败:" + err.Error())
                   return
               }
               if err := t.Execute(w, nil); err != nil {
                   fmt.Println("模板执行失败:" + err.Error())
               }
           })
           http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
               if err := r.ParseForm(); err != nil {
                   fmt.Println("参数解析失败:" + err.Error())
               }
               sql := r.Form["sql"]
               w.Header().Add("Content-Type", "application/json; charset=utf-8")
               w.WriteHeader(http.StatusOK)
               params := graphql.Params{Schema: schema, RequestString: sql[0]}
               res := graphql.Do(params)
               if len(res.Errors) > 0 {
                   fmt.Println("请求失败:", res.Errors)
               }
               jsonByte, err := json.Marshal(res)
               if err != nil {
                   fmt.Println("json编码失败:" + err.Error())
               }
               if _, err := fmt.Fprintln(w, string(jsonByte)); err != nil {
                   fmt.Println("输出失败:" + err.Error())
               }
           })
           fmt.Println("访问地址:http://localhost:8080")
           if err := http.ListenAndServe("localhost:8080", nil); err != nil {
               fmt.Println("服务启动失败:" + err.Error())
           }
       }
    2. index.html
       <!doctype html>
       <html lang="en">
       <head>
           <meta charset="UTF-8">
           <meta name="viewport"
                 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
           <meta http-equiv="X-UA-Compatible" content="ie=edge">
           <title>graphql测试</title>
           <style>
               .title {
                   font-size: 1.2rem;
               }
               textarea {
                   width: 500px;
                   height: 200px;
                   resize: none;
               }
           </style>
           <script src="http://file.job520.net/other/jquery/jquery-1.12.4.min.js"></script>
       </head>
       <body>
       <div>
           <label for="input" class="title">input:</label>
       </div>
       <textarea id="input"></textarea>
       <div>
           <button id="requestRead">读请求</button>
           <button id="requestWrite">写请求</button>
       </div>
       <div>
           <label for="output" class="title">output:</label>
       </div>
       <textarea id="output" disabled></textarea>
       <script>
           var read = "query{\n  getUserList(query:\"old user\"){\n    id\n    name\n  }\n}"
           var write = "mutation{\n  createUser(name:\"new user\"){\n    id\n    name\n  }\n}"
           function sendRequest() {
               $.post(
                   "http://localhost:8080/graphql",
                   {
                       sql: $("#input").val()
                   },
                   function (res) {
                       var str = JSON.stringify(res)
                       $("#output").val(str)
                   }
               )
           }
           $("#requestRead").click(function () {
               $("#input").val(read)
               sendRequest()
           })
           $("#requestWrite").click(function () {
               $("#input").val(write)
               sendRequest()
           })
       </script>
       </body>
       </html>
文档更新时间: 2024-04-20 10:57   作者:lee