Documentation
¶
Overview ¶
Example ¶
Example demonstrates how to parse a GraphQL schema and execute a query against it.
package main import ( "context" "encoding/json" "fmt" "os" "github.com/graph-gophers/graphql-go" ) type exampleResolver struct{} func (*exampleResolver) Greet(ctx context.Context, args struct{ Name string }) string { return fmt.Sprintf("Hello, %s!", args.Name) } // Example demonstrates how to parse a GraphQL schema and execute a query against it. func main() { s := ` schema { query: Query } type Query { greet(name: String!): String! } ` opts := []graphql.SchemaOpt{ // schema options go here } schema := graphql.MustParseSchema(s, &exampleResolver{}, opts...) query := ` query { greet(name: "GraphQL") } ` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) } }
Output: { "data": { "greet": "Hello, GraphQL!" } }
Example (CustomErrors) ¶
Example_customErrors demonstrates the use of custom errors and error extensions.
package main import ( "context" "encoding/json" "fmt" "os" "github.com/graph-gophers/graphql-go" ) type product struct { ID graphql.ID Name string } type custErrResolver struct { products map[graphql.ID]*product } func (r *custErrResolver) Product(ctx context.Context, args struct{ ID graphql.ID }) (*productResolver, error) { if p := r.products[args.ID]; p != nil { return &productResolver{p: p}, nil } traceID := "your-trace-id-here" // get trace ID from ctx return nil, &productNotFoundError{Code: "NotFound", Message: "Product not found", TraceID: traceID} } type productResolver struct { p *product } func (r *productResolver) ID() graphql.ID { return r.p.ID } func (r *productResolver) Name() string { return r.p.Name } type productNotFoundError struct { Code string `json:"code"` Message string `json:"message"` TraceID string `json:"traceId"` } func (e productNotFoundError) Error() string { return fmt.Sprintf("error [%s]: %s.", e.Code, e.Message) } // Extensions provides additional error context according to the spec https://spec.graphql.org/October2021/#sel-GAPHRPZCAACCBx6b. func (e productNotFoundError) Extensions() map[string]interface{} { return map[string]interface{}{ "code": e.Code, "message": e.Message, "traceId": e.TraceID, } } // Example_customErrors demonstrates the use of custom errors and error extensions. func main() { var products = []*product{ {ID: "1000", Name: "Product1"}, {ID: "1001", Name: "Product2"}, } resolver := &custErrResolver{ products: map[graphql.ID]*product{}, } for _, p := range products { resolver.products[p.ID] = p } s := ` schema { query: Query } type Query { product(id: ID!): Product! } type Product { id: ID! name: String! } ` schema := graphql.MustParseSchema(s, resolver) query := ` query { product(id: "1007") { id name } } ` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) } }
Output: { "errors": [ { "message": "error [NotFound]: Product not found.", "path": [ "product" ], "extensions": { "code": "NotFound", "message": "Product not found", "traceId": "your-trace-id-here" } } ], "data": null }
Example (CustomScalarMap) ¶
package main import ( "context" "encoding/json" "fmt" "os" "github.com/graph-gophers/graphql-go" ) type Map map[string]interface{} func (Map) ImplementsGraphQLType(name string) bool { return name == "Map" } func (m *Map) UnmarshalGraphQL(input interface{}) error { val, ok := input.(map[string]interface{}) if !ok { return fmt.Errorf("wrong type") } *m = val return nil } type Args struct { Name string Data Map } type mutation struct{} func (*mutation) Hello(args Args) string { fmt.Println(args) return "Args accepted!" } func main() { s := ` scalar Map type Query {} type Mutation { hello( name: String! data: Map! ): String! } ` schema := graphql.MustParseSchema(s, &mutation{}) query := ` mutation { hello(name: "GraphQL", data: { num: 5, code: "example" }) } ` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) } }
Output: {GraphQL map[code:example num:5]} { "data": { "hello": "Args accepted!" } }
Example (InputArray) ¶
Example_inputArray shows a simple GraphQL schema which defines a custom input type. Then it executes a query against it passing array arguments.
package main import ( "context" "encoding/json" "os" "github.com/graph-gophers/graphql-go" ) type query struct{} type IntTuple struct { A int32 B int32 } func (*query) Reversed(args struct{ Values []string }) []string { result := make([]string, len(args.Values)) for i, value := range args.Values { for _, v := range value { result[i] = string(v) + result[i] } } return result } func (*query) Sums(args struct{ Values []IntTuple }) []int32 { result := make([]int32, len(args.Values)) for i, value := range args.Values { result[i] = value.A + value.B } return result } // Example_inputArray shows a simple GraphQL schema which defines a custom input type. // Then it executes a query against it passing array arguments. func main() { s := ` input IntTuple { a: Int! b: Int! } type Query { reversed(values: [String!]!): [String!]! sums(values: [IntTuple!]!): [Int!]! } ` schema := graphql.MustParseSchema(s, &query{}) query := ` query{ reversed(values:["hello", "hi"]) sums(values:[{a:2,b:3},{a:-10,b:-1}]) } ` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) } }
Output: { "data": { "reversed": [ "olleh", "ih" ], "sums": [ 5, -11 ] } }
Example (ResolverFieldTag) ¶
ExampleFieldTag demonstrates the use of the graphql field tag.
type resolver struct { Hello string HelloUnderscore string `graphql:"_hello"` HelloLower string `graphql:"hello"` HelloTitle string `graphql:"Hello"` HelloUpper string `graphql:"HELLO"` } sdl := ` type Query { _hello: String! hello: String! Hello: String! HELLO: String! }` r := &resolver{ Hello: "This field is not used during query execution!", HelloLower: "Hello, graphql!", HelloTitle: "Hello, GraphQL!", HelloUnderscore: "Hello, _!", HelloUpper: "Hello, GRAPHQL!", } query := ` { _hello hello Hello HELLO } ` schema := graphql.MustParseSchema(sdl, r, graphql.UseFieldResolvers()) res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) }
Output: { "data": { "_hello": "Hello, _!", "hello": "Hello, graphql!", "Hello": "Hello, GraphQL!", "HELLO": "Hello, GRAPHQL!" } }
Index ¶
- type ID
- type NullBool
- type NullFloat
- type NullID
- type NullInt
- type NullString
- type NullTime
- type Response
- type Schema
- func (s *Schema) AST() *ast.Schema
- func (s *Schema) ASTSchema() *ast.Schemadeprecated
- func (s *Schema) Exec(ctx context.Context, queryString string, operationName string, ...) *Response
- func (s *Schema) Inspect() *introspection.Schema
- func (s *Schema) Subscribe(ctx context.Context, queryString string, operationName string, ...) (<-chan interface{}, error)
- func (s *Schema) ToJSON() ([]byte, error)
- func (s *Schema) Validate(queryString string) []*errors.QueryError
- func (s *Schema) ValidateWithVariables(queryString string, variables map[string]interface{}) []*errors.QueryError
- type SchemaOpt
- func DisableIntrospection() SchemaOptdeprecated
- func Logger(logger log.Logger) SchemaOpt
- func MaxDepth(n int) SchemaOpt
- func MaxParallelism(n int) SchemaOpt
- func MaxQueryLength(n int) SchemaOpt
- func PanicHandler(panicHandler errors.PanicHandler) SchemaOpt
- func RestrictIntrospection(fn func(ctx context.Context) bool) SchemaOpt
- func SubscribeResolverTimeout(timeout time.Duration) SchemaOpt
- func Tracer(t tracer.Tracer) SchemaOpt
- func UseFieldResolvers() SchemaOpt
- func UseStringDescriptions() SchemaOpt
- func ValidationTracer(tracer tracer.LegacyValidationTracer) SchemaOpt
- type Time
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ID ¶
type ID string
ID represents GraphQL's "ID" scalar type. A custom type may be used instead.
Example ¶
schemaString := ` schema { query: Query } type Query { post: Post! } type Post { id: ID! title: String! } ` resolver := &Resolver{ post: &Post{ id: graphql.ID("5"), title: "title", }, } schema := graphql.MustParseSchema(schemaString, resolver) query := ` query { post { id title } } ` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) }
Output: { "data": { "post": { "id": "5", "title": "title" } } }
func (ID) ImplementsGraphQLType ¶
func (ID) MarshalJSON ¶
func (*ID) UnmarshalGraphQL ¶
type NullBool ¶
NullBool is a boolean that can be null. Use it in input structs to differentiate a value explicitly set to null from an omitted value. When the value is defined (either null or a value) Set is true.
Example ¶
ExampleNullBool demonstrates how to use nullable Bool type when it is necessary to differentiate between nil and not set.
package main import ( "context" "encoding/json" "fmt" "os" "github.com/graph-gophers/graphql-go" ) type mutnb struct{} func (*mutnb) Toggle(args struct{ Enabled graphql.NullBool }) string { if !args.Enabled.Set { return "input value was not provided" } else if args.Enabled.Value == nil { return "enabled is 'null'" } return fmt.Sprintf("enabled '%v'", *args.Enabled.Value) } // ExampleNullBool demonstrates how to use nullable Bool type when it is necessary to differentiate between nil and not set. func main() { const s = ` schema { query: Query mutation: Mutation } type Query{} type Mutation{ toggle(enabled: Boolean): String! } ` schema := graphql.MustParseSchema(s, &mutnb{}) const query = `mutation{ toggle1: toggle() toggle2: toggle(enabled: null) toggle3: toggle(enabled: true) }` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) } }
Output: { "data": { "toggle1": "input value was not provided", "toggle2": "enabled is 'null'", "toggle3": "enabled 'true'" } }
func (NullBool) ImplementsGraphQLType ¶
func (*NullBool) UnmarshalGraphQL ¶
type NullFloat ¶
NullFloat is a float that can be null. Use it in input structs to differentiate a value explicitly set to null from an omitted value. When the value is defined (either null or a value) Set is true.
func (NullFloat) ImplementsGraphQLType ¶
func (*NullFloat) UnmarshalGraphQL ¶
type NullID ¶ added in v1.6.0
NullID is an ID that can be null. Use it in input structs to differentiate a value explicitly set to null from an omitted value. When the value is defined (either null or a value) Set is true.
func (NullID) ImplementsGraphQLType ¶ added in v1.6.0
func (*NullID) UnmarshalGraphQL ¶ added in v1.6.0
type NullInt ¶
NullInt is an int that can be null. Use it in input structs to differentiate a value explicitly set to null from an omitted value. When the value is defined (either null or a value) Set is true.
func (NullInt) ImplementsGraphQLType ¶
func (*NullInt) UnmarshalGraphQL ¶
type NullString ¶
NullString is a string that can be null. Use it in input structs to differentiate a value explicitly set to null from an omitted value. When the value is defined (either null or a value) Set is true.
func (NullString) ImplementsGraphQLType ¶
func (NullString) ImplementsGraphQLType(name string) bool
func (*NullString) Nullable ¶
func (s *NullString) Nullable()
func (*NullString) UnmarshalGraphQL ¶
func (s *NullString) UnmarshalGraphQL(input interface{}) error
type NullTime ¶
NullTime is a time value that can be null. Use it in input structs to differentiate a value explicitly set to null from an omitted value. When the value is defined (either null or a value) Set is true.
func (NullTime) ImplementsGraphQLType ¶
func (*NullTime) UnmarshalGraphQL ¶
type Response ¶
type Response struct { Errors []*errors.QueryError `json:"errors,omitempty"` Data json.RawMessage `json:"data,omitempty"` Extensions map[string]interface{} `json:"extensions,omitempty"` }
Response represents a typical response of a GraphQL server. It may be encoded to JSON directly or it may be further processed to a custom response type, for example to include custom error data. Errors are intentionally serialized first based on the advice in the spec.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema represents a GraphQL schema with an optional resolver.
func MustParseSchema ¶
MustParseSchema calls ParseSchema and panics on error.
func ParseSchema ¶
ParseSchema parses a GraphQL schema and attaches the given root resolver. It returns an error if the Go type signature of the resolvers does not match the schema. If nil is passed as the resolver, then the schema can not be executed, but it may be inspected (e.g. with Schema.ToJSON or Schema.AST).
func (*Schema) AST ¶ added in v1.6.0
AST returns the abstract syntax tree of the GraphQL schema definition. It in turn can be used by other tools such as validators or generators.
Example ¶
schema := graphql.MustParseSchema(starwars.Schema, nil) ast := schema.AST() for _, e := range ast.Enums { fmt.Printf("Enum %q has the following options:\n", e.Name) for _, o := range e.EnumValuesDefinition { fmt.Printf(" - %s\n", o.EnumValue) } }
Output: Enum "Episode" has the following options: - NEWHOPE - EMPIRE - JEDI Enum "LengthUnit" has the following options: - METER - FOOT
Example (GenerateEnum) ¶
s := ` type Query { currentSeason: Season! } """ Season represents a season of the year. """ enum Season { SPRING SUMMER AUTUMN WINTER } ` gocode := ` {{ $enum := . }} // {{ $enum.Desc }} type {{ $enum.Name }} int const ( {{ range $i, $e := $enum.EnumValuesDefinition }}{{ if ne $i 0 }}{{ printf "\n\t" }}{{ end }} {{- $e.EnumValue | toVar }}{{ if eq $i 0 }} {{ $enum.Name }} = iota{{ end }} {{- end }} ) var {{ $enum.Name | toLower }}Items = [...]string{ {{- range $i, $e := $enum.EnumValuesDefinition }}{{ if ne $i 0 }}{{ printf ", " }}{{ end }} {{- $e.EnumValue | quote }} {{- end -}} } func (s {{ $enum.Name }}) String() string { return {{ $enum.Name | toLower }}Items[s] } func (s *{{ $enum.Name }}) Deserialize(str string) { var found bool for i, v := range {{ $enum.Name | toLower }}Items { if v == str { found = true (*s) = {{ $enum.Name }}(i) } } if !found { panic("invalid value for enum {{ $enum.Name }}: " + str) } } func ({{ $enum.Name }}) ImplementsGraphQLType(name string) bool { return name == {{ $enum.Name | quote }} } func (s *{{ $enum.Name }}) UnmarshalGraphQL(input interface{}) error { var err error switch input := input.(type) { case string: s.Deserialize(input) default: err = fmt.Errorf("wrong type for {{ $enum.Name }}: %T", input) } return err } ` funcs := template.FuncMap{ "quote": func(s string) string { return `"` + s + `"` }, "toLower": strings.ToLower, "toVar": func(s string) string { if len(s) == 0 { return s } return strings.ToUpper(s[:1]) + strings.ToLower(s[1:]) }, } tpl, err := template.New("enum").Funcs(funcs).Parse(gocode) if err != nil { panic(err) } opts := []graphql.SchemaOpt{ graphql.UseStringDescriptions(), } schema := graphql.MustParseSchema(s, nil, opts...) ast := schema.AST() seasons := ast.Enums[0] err = tpl.Execute(os.Stdout, seasons) if err != nil { panic(err) }
Output: // Season represents a season of the year. type Season int const ( Spring Season = iota Summer Autumn Winter ) var seasonItems = [...]string{"SPRING", "SUMMER", "AUTUMN", "WINTER"} func (s Season) String() string { return seasonItems[s] } func (s *Season) Deserialize(str string) { var found bool for i, v := range seasonItems { if v == str { found = true (*s) = Season(i) } } if !found { panic("invalid value for enum Season: " + str) } } func (Season) ImplementsGraphQLType(name string) bool { return name == "Season" } func (s *Season) UnmarshalGraphQL(input interface{}) error { var err error switch input := input.(type) { case string: s.Deserialize(input) default: err = fmt.Errorf("wrong type for Season: %T", input) } return err }
func (*Schema) ASTSchema
deprecated
added in
v1.1.0
ASTSchema returns the abstract syntax tree of the GraphQL schema definition.
Deprecated: use Schema.AST instead.
func (*Schema) Exec ¶
func (s *Schema) Exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}) *Response
Exec executes the given query with the schema's resolver. It panics if the schema was created without a resolver. If the context get cancelled, no further resolvers will be called and a the context error will be returned as soon as possible (not immediately).
func (*Schema) Inspect ¶
func (s *Schema) Inspect() *introspection.Schema
Inspect allows inspection of the given schema.
func (*Schema) Subscribe ¶
func (s *Schema) Subscribe(ctx context.Context, queryString string, operationName string, variables map[string]interface{}) (<-chan interface{}, error)
Subscribe returns a response channel for the given subscription with the schema's resolver. It returns an error if the schema was created without a resolver. If the context gets cancelled, the response channel will be closed and no further resolvers will be called. The context error will be returned as soon as possible (not immediately).
func (*Schema) Validate ¶
func (s *Schema) Validate(queryString string) []*errors.QueryError
Validate validates the given query with the schema.
func (*Schema) ValidateWithVariables ¶
func (s *Schema) ValidateWithVariables(queryString string, variables map[string]interface{}) []*errors.QueryError
ValidateWithVariables validates the given query with the schema and the input variables.
type SchemaOpt ¶
type SchemaOpt func(*Schema)
SchemaOpt is an option to pass to ParseSchema or MustParseSchema.
func DisableIntrospection
deprecated
func DisableIntrospection() SchemaOpt
DisableIntrospection disables introspection queries. This function is left for backwards compatibility reasons and is just a shorthand for:
filter := func(context.Context) bool { return false } graphql.RestrictIntrospection(filter)
Deprecated: use RestrictIntrospection filter instead. Do not use it together with RestrictIntrospection, otherwise the option added last takes precedence.
func Logger ¶
Logger is used to log panics during query execution. It defaults to log.DefaultLogger.
func MaxDepth ¶
MaxDepth specifies the maximum field nesting depth in a query. The default is 0 which disables max depth checking.
Example ¶
schema := graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{}, graphql.MaxDepth(3)) // this query has a depth of 4 query := ` query { hero(episode:EMPIRE) { # level 1 name # level 2 friends { name # level 3 friends { id # level 4 - this would exceed the max depth } } } }` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) }
Output: { "errors": [ { "message": "Field \"id\" has depth 4 that exceeds max depth 3", "locations": [ { "line": 8, "column": 12 } ] } ] }
func MaxParallelism ¶
MaxParallelism specifies the maximum number of resolvers per request allowed to run in parallel. The default is 10.
func MaxQueryLength ¶ added in v1.6.0
MaxQueryLength specifies the maximum allowed query length in bytes. The default is 0 which disables max length checking.
Example ¶
schema := graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{}, graphql.MaxQueryLength(50)) // this query has a length of 53 query := `{ hero(episode:EMPIRE) { id name } }` res := schema.Exec(context.Background(), query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) }
Output: { "errors": [ { "message": "query length 53 exceeds the maximum allowed query length of 50 bytes" } ] }
func PanicHandler ¶ added in v1.3.0
func PanicHandler(panicHandler errors.PanicHandler) SchemaOpt
PanicHandler is used to customize the panic errors during query execution. It defaults to errors.DefaultPanicHandler.
func RestrictIntrospection ¶ added in v1.6.0
RestrictIntrospection accepts a filter func. If this function returns false the introspection is disabled, otherwise it is enabled. If this option is not provided the introspection is enabled by default. This option is useful for allowing introspection only to admin users, for example:
filter := func(ctx context.Context) bool { u, ok := user.FromContext(ctx) return ok && u.IsAdmin() }
Do not use it together with DisableIntrospection, otherwise the option added last takes precedence.
Example ¶
allowKey := struct{}{} // only allow introspection if the function below returns true filter := func(ctx context.Context) bool { allow, found := ctx.Value(allowKey).(bool) return found && allow } schema := graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{}, graphql.RestrictIntrospection(filter)) query := `{ __type(name: "Episode") { enumValues { name } } }` cases := []struct { name string ctx context.Context }{ { name: "Empty context", ctx: context.Background(), }, { name: "Introspection forbidden", ctx: context.WithValue(context.Background(), allowKey, false), }, { name: "Introspection allowed", ctx: context.WithValue(context.Background(), allowKey, true), }, } for _, c := range cases { fmt.Println(c.name, "result:") res := schema.Exec(c.ctx, query, "", nil) enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") err := enc.Encode(res) if err != nil { panic(err) } }
Output: Empty context result: { "data": {} } Introspection forbidden result: { "data": {} } Introspection allowed result: { "data": { "__type": { "enumValues": [ { "name": "NEWHOPE" }, { "name": "EMPIRE" }, { "name": "JEDI" } ] } } }
func SubscribeResolverTimeout ¶
SubscribeResolverTimeout is an option to control the amount of time we allow for a single subscribe message resolver to complete it's job before it times out and returns an error to the subscriber.
func Tracer ¶
Tracer is used to trace queries and fields. It defaults to noop.Tracer.
func UseFieldResolvers ¶
func UseFieldResolvers() SchemaOpt
UseFieldResolvers specifies whether to use struct fields as resolvers.
func UseStringDescriptions ¶
func UseStringDescriptions() SchemaOpt
UseStringDescriptions enables the usage of double quoted and triple quoted strings as descriptions as per the June 2018 spec. When this is not enabled, comments are parsed as descriptions instead.
Example ¶
s := ` schema { query: Query } type Query { post(id: Int!): Post } """ Post represents a blog post. """ type Post { "Unique identifier of the post." id: ID! # The title field has no description. title: String! """ Tags of the post. """ # tags can be empty tags: [String!]! } ` opts := []graphql.SchemaOpt{ graphql.UseStringDescriptions(), } schema := graphql.MustParseSchema(s, nil, opts...) ast := schema.AST() post := ast.Objects[1] fmt.Printf("Field descriptions of the %q type:\n", post.TypeName()) for _, f := range post.Fields { fmt.Printf(" field: %q, description: %q\n", f.Name, f.Desc) }
Output: Field descriptions of the "Post" type: field: "id", description: "Unique identifier of the post." field: "title", description: "" field: "tags", description: "Tags of the post."
func ValidationTracer ¶
func ValidationTracer(tracer tracer.LegacyValidationTracer) SchemaOpt
ValidationTracer is used to trace validation errors. It defaults to tracer.LegacyNoopValidationTracer. Deprecated: context is needed to support tracing correctly. Use a tracer which implements tracer.ValidationTracer.
type Time ¶
Time is a custom GraphQL type to represent an instant in time. It has to be added to a schema via "scalar Time" since it is not a predeclared GraphQL type like "ID".
Example ¶
package main import ( "context" "encoding/json" "os" "time" "github.com/graph-gophers/graphql-go" ) type tquery struct{} func (*tquery) CurrentTime() graphql.Time { return graphql.Time{Time: time.Date(2023, 2, 6, 12, 3, 22, 0, time.UTC)} } func main() { const s = ` scalar Time type Query { currentTime: Time! } ` schema := graphql.MustParseSchema(s, &tquery{}) const query = "{ currentTime }" res := schema.Exec(context.Background(), query, "", nil) err := json.NewEncoder(os.Stdout).Encode(res) if err != nil { panic(err) } }
Output: {"data":{"currentTime":"2023-02-06T12:03:22Z"}}
func (Time) ImplementsGraphQLType ¶
ImplementsGraphQLType maps this custom Go type to the graphql scalar type in the schema.
func (Time) MarshalJSON ¶
MarshalJSON is a custom marshaler for Time
This function will be called whenever you query for fields that use the Time type
func (*Time) UnmarshalGraphQL ¶
UnmarshalGraphQL is a custom unmarshaler for Time
This function will be called whenever you use the time scalar as an input
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package ast represents all types from the [GraphQL specification] in code.
|
Package ast represents all types from the [GraphQL specification] in code. |
example
|
|
caching/cache
Package cache implements caching of GraphQL requests by allowing resolvers to provide hints about their cacheability, which can be used by the transport handlers (e.g.
|
Package cache implements caching of GraphQL requests by allowing resolvers to provide hints about their cacheability, which can be used by the transport handlers (e.g. |
enum
Package main demonstrates a simple web app that uses type-safe enums in a GraphQL resolver.
|
Package main demonstrates a simple web app that uses type-safe enums in a GraphQL resolver. |
starwars
Package starwars provides a example schema and resolver based on Star Wars characters.
|
Package starwars provides a example schema and resolver based on Star Wars characters. |
internal
|
|
The trace package provides tracing functionality.
|
The trace package provides tracing functionality. |
noop
Package noop defines a no-op tracer implementation.
|
Package noop defines a no-op tracer implementation. |
opentracing
The opentracing package provides tracing functionality using OpenTracing.
|
The opentracing package provides tracing functionality using OpenTracing. |
otel
The otel package provides tracing functionality using OpenTelemetry.
|
The otel package provides tracing functionality using OpenTelemetry. |
tracer
The tracer package provides tracing functionality.
|
The tracer package provides tracing functionality. |
Package types represents all types from the GraphQL specification in code.
|
Package types represents all types from the GraphQL specification in code. |