Skip to main content

GraphQL Example

Github StackBlitz

This project demonstrates how to set up a GraphQL server in a Go application using the Fiber framework.

Prerequisites

Ensure you have the following installed:

Setup

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/graphql
  2. Install dependencies:

    go get
  3. Initialize gqlgen:

    go run github.com/99designs/gqlgen init

Running the Application

  1. Start the application:

    go run main.go
  2. Access the GraphQL playground at http://localhost:3000/graphql.

Example

Here is an example main.go file for the Fiber application with GraphQL:

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"))
}

References