github.com/opiuman/genqlient@v1.0.0/generate/marshal_helper.go.tmpl (about) 1 {{/* This is somewhat parallel to unmarshal_helper.go.tmpl, but, as usual, in 2 reverse. Note the helper accepts a pointer-to-interface, for 3 consistency with unmarshaling and with the API we expect of custom 4 marshalers. */}} 5 6 func __marshal{{.GoName}}(v *{{.GoName}}) ([]byte, error) { 7 {{/* Determine the GraphQL typename, which the unmarshaler will need should 8 it be called on our output. */}} 9 var typename string 10 switch v := (*v).(type) { 11 {{range .Implementations -}} 12 case *{{.GoName}}: 13 typename = "{{.GraphQLName}}" 14 15 {{/* Now actually do the marshal, with the concrete type. (Go only 16 marshals embeds the way we want if they're structs.) Except that 17 won't work right if the implementation-type has its own 18 MarshalJSON method (maybe it in turn has an interface-typed 19 field), so we call the helper __premarshalJSON directly (see 20 marshal.go.tmpl). */}} 21 {{if .NeedsMarshaling -}} 22 premarshaled, err := v.__premarshalJSON() 23 if err != nil { 24 return nil, err 25 } 26 result := struct { 27 TypeName string `json:"__typename"` 28 *__premarshal{{.GoName}} 29 }{typename, premarshaled} 30 {{else -}} 31 result := struct { 32 TypeName string `json:"__typename"` 33 *{{.GoName}} 34 }{typename, v} 35 {{end -}} 36 return json.Marshal(result) 37 {{end -}} 38 case nil: 39 return []byte("null"), nil 40 default: 41 return nil, {{ref "fmt.Errorf"}}( 42 `unexpected concrete type for {{.GoName}}: "%T"`, v) 43 } 44 }