github.com/bowd/gqlgen@v0.7.2/docs/content/reference/scalars.md (about) 1 --- 2 linkTitle: Custom Scalars 3 title: Using custom graphql types in golang 4 description: Defining custom GraphQL scalar types using gqlgen 5 menu: { main: { parent: 'reference' } } 6 --- 7 8 There are two different ways to implement scalars in gqlgen, depending on your need. 9 10 11 ## With user defined types 12 For user defined types you can implement the graphql.Marshal and graphql.Unmarshal interfaces and they will be called. 13 14 ```go 15 package mypkg 16 17 import ( 18 "fmt" 19 "io" 20 "strings" 21 ) 22 23 type YesNo bool 24 25 // UnmarshalGQL implements the graphql.Marshaler interface 26 func (y *YesNo) UnmarshalGQL(v interface{}) error { 27 yes, ok := v.(string) 28 if !ok { 29 return fmt.Errorf("points must be strings") 30 } 31 32 if yes == "yes" { 33 *y = true 34 } else { 35 *y = false 36 } 37 return nil 38 } 39 40 // MarshalGQL implements the graphql.Marshaler interface 41 func (y YesNo) MarshalGQL(w io.Writer) { 42 if y { 43 w.Write([]byte(`"yes"`)) 44 } else { 45 w.Write([]byte(`"no"`)) 46 } 47 } 48 ``` 49 50 and then in .gqlgen.yml point to the name without the Marshal|Unmarshal in front: 51 ```yaml 52 models: 53 YesNo: 54 model: github.com/me/mypkg.YesNo 55 ``` 56 57 58 ## Custom scalars for types you don't control 59 60 Sometimes you cant add methods to a type because its in another repo, part of the standard 61 library (eg string or time.Time). To do this we can build an external marshaler: 62 63 ```go 64 package mypkg 65 66 import ( 67 "fmt" 68 "io" 69 "strings" 70 71 "github.com/99designs/gqlgen/graphql" 72 ) 73 74 75 func MarshalMyCustomBooleanScalar(b bool) graphql.Marshaler { 76 return graphql.WriterFunc(func(w io.Writer) { 77 if b { 78 w.Write([]byte("true")) 79 } else { 80 w.Write([]byte("false")) 81 } 82 }) 83 } 84 85 func UnmarshalMyCustomBooleanScalar(v interface{}) (bool, error) { 86 switch v := v.(type) { 87 case string: 88 return "true" == strings.ToLower(v), nil 89 case int: 90 return v != 0, nil 91 case bool: 92 return v, nil 93 default: 94 return false, fmt.Errorf("%T is not a bool", v) 95 } 96 } 97 ``` 98 99 and then in .gqlgen.yml point to the name without the Marshal|Unmarshal in front: 100 ```yaml 101 models: 102 MyCustomBooleanScalar: 103 model: github.com/me/mypkg.MyCustomBooleanScalar 104 ``` 105 106 see the [example/scalars](https://github.com/99designs/gqlgen/tree/master/example/scalars) package for more examples.