GraphQL Example
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
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git
cd recipes/graphql -
Install dependencies:
go get
-
Initialize gqlgen:
go run github.com/99designs/gqlgen init
Running the Application
-
Start the application:
go run main.go
-
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"))
}