GraphQL
Rue includes a built-in GraphQL handler with an interactive Playground UI.
Basic Setup
go
r := rue.Default()
schema := &rue.GraphQLSchema{
Query: &rue.ObjectType{
Name: "Query",
Fields: map[string]*rue.Field{
"hello": {
Type: rue.StringType,
Resolve: func(ctx *rue.ResolveContext) (any, error) {
return "Hello, GraphQL!", nil
},
},
},
},
}
handler := rue.NewGraphQLHandler(schema)
r.POST("/graphql", handler.Handle)
r.GET("/graphql", handler.Playground) // Interactive UI
r.Run(":8080")
Defining Types
go
// Define a User type
userType := &rue.ObjectType{
Name: "User",
Fields: map[string]*rue.Field{
"id": {Type: rue.StringType},
"name": {Type: rue.StringType},
"email": {Type: rue.StringType},
"age": {Type: rue.IntType},
},
}
// Use in schema
schema := &rue.GraphQLSchema{
Query: &rue.ObjectType{
Name: "Query",
Fields: map[string]*rue.Field{
"user": {
Type: userType,
Args: map[string]*rue.Argument{
"id": {Type: rue.StringType},
},
Resolve: func(ctx *rue.ResolveContext) (any, error) {
id := ctx.Args["id"].(string)
return getUser(id), nil
},
},
"users": {
Type: &rue.ListType{OfType: userType},
Resolve: func(ctx *rue.ResolveContext) (any, error) {
return getAllUsers(), nil
},
},
},
},
}
Mutations
go
schema := &rue.GraphQLSchema{
Query: queryType,
Mutation: &rue.ObjectType{
Name: "Mutation",
Fields: map[string]*rue.Field{
"createUser": {
Type: userType,
Args: map[string]*rue.Argument{
"name": {Type: rue.StringType},
"email": {Type: rue.StringType},
},
Resolve: func(ctx *rue.ResolveContext) (any, error) {
name := ctx.Args["name"].(string)
email := ctx.Args["email"].(string)
return createUser(name, email), nil
},
},
"deleteUser": {
Type: rue.BoolType,
Args: map[string]*rue.Argument{
"id": {Type: rue.StringType},
},
Resolve: func(ctx *rue.ResolveContext) (any, error) {
id := ctx.Args["id"].(string)
return deleteUser(id), nil
},
},
},
},
}
GraphQL Playground
Access the interactive Playground at GET /graphql:
- Write and execute queries
- Explore schema documentation
- View query history
- Set HTTP headers
Available Types
| Type | Description |
|---|---|
rue.StringType | String scalar |
rue.IntType | Integer scalar |
rue.FloatType | Float scalar |
rue.BoolType | Boolean scalar |
&rue.ListType{OfType: T} | List of type T |
&rue.ObjectType{} | Custom object type |