应用 apollo server 将 graphql 集成到 golang 框架中:组装 apollo server 和 gqlgen 依赖项。应用 gqlgen cli形成 graphql 方式。定义和完成 graphql 解析器。应用 apollo server 建立 graphql 服务器。运作应用软件,并用 graphql playground浏览 graphql api。
怎么使用 Apollo Server 将 GraphQL 集成到 Golang 框架中
GraphQL 是一种查询语言,容许客户端以申明性方法要求和处理数据。可以将 GraphQL 集成到 Golang 应用程序中,您可以创建给予灵便且强悍的查询和突变功能的 API。
应用 Apollo Server
Apollo Server 是一个流行的 GraphQL 服务器架构,它提供了一组工具来帮助你迅速快速地搭建 GraphQL API。本教程将向您展现怎么使用 Apollo Server 将 GraphQL 集成到 Golang 应用程序中。
实战案例 :建立一个简单的 GraphQL API
最先,使我们建立一个简单的 Golang 应用软件,它将使用 Apollo Server 公布一个 GraphQL API。
组装依赖项
gogetgithub.com/99designs/gqlgen
gogetgithub.com/vektah/gqlparser/v2
生成 GraphQL 方式
应用 gqlgen CLI生成一个基本的 GraphQL 方式:
gqlgeninit
这将在您的项目中建立一个名为 schema.graphql 文件,其中包括你的 GraphQL 模式的定义。
定义 GraphQL 方式
在 schema.graphql 中,定义一个包括单独查看解析器的 GraphQL 种类,该解析器将返回一个字符串:
typeQuery{
hello:String
}
完成 GraphQL 解析器
在 resolver.go 文档中,为查看解析器撰写完成了函数:
packageresolvers
import(
"context"
)
//QueryResolverisaresolverfortheQuerytype.
typeQueryResolverstruct{}
//Helloresolvesthehellofield.
func(rQueryResolver)Hello(ctxcontext.Context)string{
return"Hello,world!"
}
建立 GraphQL 服务器
在 main.go 文档中,建立应用 Apollo Server 的 GraphQL 服务器:
packagemain
import(
"log"
"net/http"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
resolvers"github.com/username/project/graph/resolvers"
)
funcmain(){
//建立 GraphQL 服务器
srv := handler.NewDefaultServer(
resolvers.NewExecutableSchema(resolvers.New()),
)
playgroundHandler := playground.Handler("GraphQL Playground", "/query")
// 路由器,将查询和 Playground 导入到 HTTP 路由器中
http.Handle("/", playgroundHandler)
http.Handle("/query", srv)
// 运行 HTTP 服务器
log.Printf("server listening on port %s", "8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
运作应用软件
使用下列指令运作应用软件:
gorunmain.go
如今,您可以使用 GraphQL Playground(http://localhost:8080/)对 GraphQL API查询和突变。
以上就是Golang架构如何跟GraphQL集成?的详细内容,大量请关注其他类似文章!