用golang写一个GraphQL 服务器的示例
时间: 2023-12-02 12:02:19 浏览: 74
playground:使用graphql-go和graphql-relay-go编写的Golang GraphQL服务器示例
好的,这里是一个简单的示例,使用Golang编写GraphQL服务器:
首先,需要安装必要的依赖:
```
go get github.com/graphql-go/graphql
go get github.com/graphql-go/handler
```
然后,创建一个GraphQL的schema,定义查询和类型:
```go
package main
import (
"github.com/graphql-go/graphql"
)
type Book struct {
Title string
Author string
}
var books []Book
var bookType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{
Type: graphql.String,
},
"author": &graphql.Field{
Type: graphql.String,
},
},
},
)
var queryType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{
Type: graphql.NewList(bookType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return books, nil
},
},
},
},
)
var schema, _ = graphql.NewSchema(
graphql.SchemaConfig{
Query: queryType,
},
)
```
在上述代码中,我们定义了一个`Book`类型和一个`Query`类型。`Query`类型有一个查询字段`books`,它返回一个`Book`类型的列表。`books`字段的解析器函数返回了一个`books`数组。
接下来,在`main`函数中,我们创建一个HTTP处理器,并将其绑定到`/graphql`路径:
```go
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
)
func main() {
books = []Book{
Book{"Book 1", "Author 1"},
Book{"Book 2", "Author 2"},
}
http.Handle("/graphql", handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: true,
}))
fmt.Println("Server is running on port 8080...")
http.ListenAndServe(":8080", nil)
}
```
在`main`函数中,我们初始化了`books`数组,并创建了一个GraphQL处理器。我们将GraphQL处理器绑定到`/graphql`路径,并启动HTTP服务器。
现在,我们可以使用GraphiQL界面测试我们的GraphQL服务器了。在浏览器中打开`http://localhost:8080/graphql`,即可进入GraphiQL界面,输入以下查询语句:
```graphql
query {
books {
title
author
}
}
```
点击运行按钮,即可得到以下响应:
```json
{
"data": {
"books": [
{
"title": "Book 1",
"author": "Author 1"
},
{
"title": "Book 2",
"author": "Author 2"
}
]
}
}
```
这是一个简单的GraphQL服务器示例,你可以根据自己的需求进行调整和扩展。
阅读全文