graphql---go http请求使用

来源:互联网 发布:数据库文件类型 编辑:程序博客网 时间:2024/05/24 02:44

1. Graphql是什么?

GraphQL是Facebook 在2012年开发的,2015年开源,2016年下半年Facebook宣布可以在生产环境使用,而其内部早就已经广泛应用了,用于替代 REST API。facebook的解决方案和简单:用一个“聪明”的节点来进行复杂的查询,将数据按照客户端的要求传回去,后端根据GraphQL机制提供一个具有强大功能的接口,用以满足前端数据的个性化需求,既保证了多样性,又控制了接口数量。

GraphQL并不是一门程序语言或者框架,它是描述你的请求数据的一种规范,是协议而非存储,GraphQL本身并不直接提供后端存储的能力,它不绑定任何的数据库或者存储引擎,它可以利用已有的代码和技术来进行数据源管理。

一个GraphQL查询是一个被发往服务端的字符串,该查询在服务端被解释和执行后返回JSON数据给客户端。


2. Graphql和Rest Api的对比
RESTful:服务端决定有哪些数据获取方式,客户端只能挑选使用,如果数据过于冗余也只能默默接收再对数据进行处理;而数据不能满足需求则需要请求更多的接口。
GraphQL:给客户端自主选择数据内容的能力,客户端完全自主决定获取信息的内容,服务端负责精确的返回目标数据。提供一种更严格、可扩展、可维护的数据查询方式。


3. Graphql在go语言中使用

1.定义 graphql 用户类型userType; Fields为user参数

/*定义 graphql 用户类型userType; Fields为user参数 */var userType = graphql.NewObject(   graphql.ObjectConfig{      Name: "User",      Fields: graphql.Fields{         "id": &graphql.Field{            Type: graphql.String,         },         "name": &graphql.Field{            Type: graphql.String,         },      },   },)

2.定义graphql 查询类型 Resolve 通过Id 获取用户信息

/*定义graphql 查询类型 Resolve  通过Id 获取用户信息 */var queryType = graphql.NewObject(   graphql.ObjectConfig{      Name: "Query",      Fields: graphql.Fields{         "user": &graphql.Field{            Type: userType,            Args: graphql.FieldConfigArgument{               "id": &graphql.ArgumentConfig{                  Type: graphql.String,               },            },            Resolve: func(p graphql.ResolveParams) (interface{}, error) {               idQuery, isOK := p.Args["id"].(string)               if isOK {                  return data[idQuery], nil               }               return nil, nil            },         },      },   })


3.定义 graphql schemad对象

var schema, _ = graphql.NewSchema(   graphql.SchemaConfig{      Query: queryType,   },)


4.执行查询方法

func executeQuery(query string, schema graphql.Schema) *graphql.Result {   result := graphql.Do(graphql.Params{      Schema:        schema,      RequestString: query,   })   if len(result.Errors) > 0 {      fmt.Printf("wrong result, unexpected errors: %v", result.Errors)   }   return result}

5.main 函数执行:

import (   "encoding/json"   "fmt"   "io/ioutil"   "net/http"   "github.com/graphql-go/graphql")
type user struct { ID string `json:"id"` Name string `json:"name"`}var data map[string]user

func main() {   data = make(map[string]user)   data["1"] = user{      ID:   "1",      Name: "wt",   }   data["2"] = user{      ID:   "2",      Name: "go",   }   http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {      result := executeQuery(r.URL.Query().Get("query"), schema)      json.NewEncoder(w).Encode(result)   })   http.ListenAndServe(":8080", nil)}


4. 结果输出,总结

游览器输入:http://127.0.0.1:8080/graphql?query={user(id:"1"){id,name}}

输出结果:{"data":{"user":{"id":"1","name":"wt"}}}


使用 graphql  再也不需要对接口的文档进行维护了。

go语言库地址:https://github.com/graphql-go/graphql



原创粉丝点击