How do I access the original functions of a customized type in Go?
I do not believe this is not specific to gqlgen
, but my use-case heavily involves their framework. I'm trying to build a custom scalar for dates in gqlgen
following their setup here: https://gqlgen.com/reference/scalars/
I'm having difficulty with the MarshalGQL
function. Here is the code I have so far:
package scalars
import (
"fmt"
"io"
"time"
)
type Date time.Time
// UnmarshalGQL implements the graphql.Unmarshaler interface
func (date *Date) UnmarshalGQL(value interface{}) error {
dateAsString, ok := value.(string)
if !ok {
return fmt.Errorf("date must be a string")
}
parsedTime, err := time.Parse(time.RFC3339, dateAsString)
if err != nil {
return fmt.Errorf("failed to convert given date value (%s) to Time struct", dateAsString)
}
*date = Date(parsedTime)
return nil
}
// MarshalGQL implements the graphql.Marshaler interface
func (date Date) MarshalGQL(w io.Writer) {
// This line causes a compiler error
w.Write(date.Format(time.RFC3339))
}
My issue is this line: w.Write(date.Format(time.RFC3339))
It's giving me this compiler error:
date.Format undefined (type Date has no field or method Format) compiler (MissingFieldOrMethod)
I understand why it's saying this. The Date
type only has two functions as far as the compiler knows, UnmarshalGQL
and MarshalGQL
, both of which are declared in this file. I want to get to the time.Time
type's functions though so that I can format the date being returned. How do I go about doing this?