github.com/99designs/gqlgen@v0.17.45/graphql/int.go (about) 1 package graphql 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "strconv" 8 ) 9 10 func MarshalInt(i int) Marshaler { 11 return WriterFunc(func(w io.Writer) { 12 io.WriteString(w, strconv.Itoa(i)) 13 }) 14 } 15 16 func UnmarshalInt(v interface{}) (int, error) { 17 switch v := v.(type) { 18 case string: 19 return strconv.Atoi(v) 20 case int: 21 return v, nil 22 case int64: 23 return int(v), nil 24 case json.Number: 25 return strconv.Atoi(string(v)) 26 default: 27 return 0, fmt.Errorf("%T is not an int", v) 28 } 29 } 30 31 func MarshalInt64(i int64) Marshaler { 32 return WriterFunc(func(w io.Writer) { 33 io.WriteString(w, strconv.FormatInt(i, 10)) 34 }) 35 } 36 37 func UnmarshalInt64(v interface{}) (int64, error) { 38 switch v := v.(type) { 39 case string: 40 return strconv.ParseInt(v, 10, 64) 41 case int: 42 return int64(v), nil 43 case int64: 44 return v, nil 45 case json.Number: 46 return strconv.ParseInt(string(v), 10, 64) 47 default: 48 return 0, fmt.Errorf("%T is not an int", v) 49 } 50 } 51 52 func MarshalInt32(i int32) Marshaler { 53 return WriterFunc(func(w io.Writer) { 54 io.WriteString(w, strconv.FormatInt(int64(i), 10)) 55 }) 56 } 57 58 func UnmarshalInt32(v interface{}) (int32, error) { 59 switch v := v.(type) { 60 case string: 61 iv, err := strconv.ParseInt(v, 10, 32) 62 if err != nil { 63 return 0, err 64 } 65 return int32(iv), nil 66 case int: 67 return int32(v), nil 68 case int64: 69 return int32(v), nil 70 case json.Number: 71 iv, err := strconv.ParseInt(string(v), 10, 32) 72 if err != nil { 73 return 0, err 74 } 75 return int32(iv), nil 76 default: 77 return 0, fmt.Errorf("%T is not an int", v) 78 } 79 }