golang 生产graphql时使用本地包
在 Go 中使用本地包来生成 GraphQL 是很方便的。您只需要在您的项目中引用这些本地包,然后使用它们来生成您的 GraphQL。
以下是一个简单的示例:
首先,您需要安装 github.com/graphql-go/graphql 包。您可以使用以下命令在终端中安装该包:
go get github.com/graphql-go/graphql
然后,您可以创建一个名为 schema.go 的文件,其中包含您的 GraphQL 模式。在此文件中,您可以使用 github.com/graphql-go/graphql 包中的类型和函数来定义您的模式。
例如,以下是一个简单的模式,其中包含一个查询类型和一个名称为 hello 的字段:
package main
import (
"github.com/graphql-go/graphql"
)
var queryType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
},
},
)
var schema, _ = graphql.NewSchema(
graphql.SchemaConfig{
Query: queryType,
},
)
在 main.go 文件中,您可以使用 schema.go 文件中定义的模式来生成您的 GraphQL:
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/graphql-go/graphql"
)
func main() {
http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: r.URL.Query().Get("query"),
})
json.NewEncoder(w).Encode(result)
})
fmt.Println("Listening on :8080")
http.ListenAndServe(":8080", nil)
}
现在,您可以运行您的 Go 应用程序,并使用以下命令在终端中查询您的 GraphQL:
curl 'http://localhost:8080/graphql?query={hello}'
您应该会看到以下响应:
{"data":{"hello":"world"}}
这就是使用本地包在 Go 中生成 GraphQL 的基本方法。您可以使用其他本地包和函数来扩展您的模式和解析器。
原文地址: https://www.cveoy.top/t/topic/bqeC 著作权归作者所有。请勿转载和采集!