跳到主要内容

GraphQL 示例

Github StackBlitz

本项目演示了如何使用 Fiber 框架在 Go 应用程序中设置 GraphQL 服务器。

先决条件

确保您已安装以下内容

设置

  1. 克隆仓库

    git clone https://github.com/gofiber/recipes.git
    cd recipes/graphql
  2. 安装依赖

    go get
  3. 初始化 gqlgen

    go run github.com/99designs/gqlgen init

运行应用程序

  1. 启动应用程序

    go run main.go
  2. 访问 GraphQL playground,地址为 http://localhost:3000/graphql

示例

以下是使用 GraphQL 的 Fiber 应用程序的 main.go 文件示例

package main

import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
)

func main() {
app := fiber.New()

srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &resolver{}}))

app.All("/graphql", func(c *fiber.Ctx) error {
srv.ServeHTTP(c.Context().ResponseWriter(), c.Context().Request)
return nil
})

app.Get("/", func(c *fiber.Ctx) error {
playground.Handler("GraphQL playground", "/graphql").ServeHTTP(c.Context().ResponseWriter(), c.Context().Request)
return nil
})

log.Fatal(app.Listen(":3000"))
}

参考资料