GraphQL Go Playground 使用教程
1. 项目的目录结构及介绍
graphql-go/playground/
├── README.md
├── examples
│ ├── basic
│ │ ├── main.go
│ │ └── schema.graphql
│ └── advanced
│ ├── main.go
│ └── schema.graphql
├── graphql
│ ├── executor.go
│ ├── schema.go
│ └── types.go
├── playground
│ ├── assets
│ │ ├── index.html
│ │ └── style.css
│ ├── handler.go
│ └── middleware.go
└── go.mod
README.md
: 项目说明文档。examples/
: 包含基本和高级示例。basic/
: 基本示例,包含main.go
和schema.graphql
。advanced/
: 高级示例,包含main.go
和schema.graphql
。
graphql/
: GraphQL 核心实现。executor.go
: 执行器实现。schema.go
: 模式定义。types.go
: 类型定义。
playground/
: GraphQL Playground 实现。assets/
: 静态资源文件。index.html
: Playground 主页面。style.css
: 样式文件。
handler.go
: 处理请求的处理器。middleware.go
: 中间件实现。
go.mod
: Go 模块定义文件。
2. 项目的启动文件介绍
在 examples/basic/
和 examples/advanced/
目录下,main.go
是项目的启动文件。以下是 examples/basic/main.go
的示例代码:
package main
import (
"log"
"net/http"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
)
func main() {
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: MyQuery,
Mutation: MyMutation,
})
if err != nil {
log.Fatalf("failed to create new schema, error: %v", err)
}
h := handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: true,
})
http.Handle("/graphql", h)
log.Println("Server is running on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
main
函数是程序的入口点。graphql.NewSchema
用于创建 GraphQL 模式。handler.New
创建一个 GraphQL 处理器。http.Handle
将处理器绑定到/graphql
路径。http.ListenAndServe
启动 HTTP 服务器。
3. 项目的配置文件介绍
在 examples/basic/
和 examples/advanced/
目录下,schema.graphql
是项目的配置文件。以下是 examples/basic/schema.graphql
的示例内容:
type Query {
hello: String
}
type Mutation {
setHello(msg: String): String
}
Query
定义了查询操作。Mutation
定义了变更操作。hello
是一个简单的查询字段。setHello
是一个简单的变更字段。
以上是 GraphQL Go Playground 项目的目录结构、启动文件和配置文件的介绍。希望这份文档能帮助你更好地理解和使用该项目。