github.com/99designs/gqlgen@v0.17.45/graphql/float.go (about) 1 package graphql 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "io" 8 "math" 9 "strconv" 10 ) 11 12 func MarshalFloat(f float64) Marshaler { 13 return WriterFunc(func(w io.Writer) { 14 io.WriteString(w, fmt.Sprintf("%g", f)) 15 }) 16 } 17 18 func UnmarshalFloat(v interface{}) (float64, error) { 19 switch v := v.(type) { 20 case string: 21 return strconv.ParseFloat(v, 64) 22 case int: 23 return float64(v), nil 24 case int64: 25 return float64(v), nil 26 case float64: 27 return v, nil 28 case json.Number: 29 return strconv.ParseFloat(string(v), 64) 30 default: 31 return 0, fmt.Errorf("%T is not an float", v) 32 } 33 } 34 35 func MarshalFloatContext(f float64) ContextMarshaler { 36 return ContextWriterFunc(func(ctx context.Context, w io.Writer) error { 37 if math.IsInf(f, 0) || math.IsNaN(f) { 38 return fmt.Errorf("cannot marshal infinite no NaN float values") 39 } 40 io.WriteString(w, fmt.Sprintf("%g", f)) 41 return nil 42 }) 43 } 44 45 func UnmarshalFloatContext(ctx context.Context, v interface{}) (float64, error) { 46 return UnmarshalFloat(v) 47 }