...

Source file src/github.com/99designs/gqlgen/graphql/string.go

Documentation: github.com/99designs/gqlgen/graphql

     1  package graphql
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"strconv"
     8  )
     9  
    10  const encodeHex = "0123456789ABCDEF"
    11  
    12  func MarshalString(s string) Marshaler {
    13  	return WriterFunc(func(w io.Writer) {
    14  		writeQuotedString(w, s)
    15  	})
    16  }
    17  
    18  func writeQuotedString(w io.Writer, s string) {
    19  	start := 0
    20  	io.WriteString(w, `"`)
    21  
    22  	for i, c := range s {
    23  		if c < 0x20 || c == '\\' || c == '"' {
    24  			io.WriteString(w, s[start:i])
    25  
    26  			switch c {
    27  			case '\t':
    28  				io.WriteString(w, `\t`)
    29  			case '\r':
    30  				io.WriteString(w, `\r`)
    31  			case '\n':
    32  				io.WriteString(w, `\n`)
    33  			case '\\':
    34  				io.WriteString(w, `\\`)
    35  			case '"':
    36  				io.WriteString(w, `\"`)
    37  			default:
    38  				io.WriteString(w, `\u00`)
    39  				w.Write([]byte{encodeHex[c>>4], encodeHex[c&0xf]})
    40  			}
    41  
    42  			start = i + 1
    43  		}
    44  	}
    45  
    46  	io.WriteString(w, s[start:])
    47  	io.WriteString(w, `"`)
    48  }
    49  
    50  func UnmarshalString(v interface{}) (string, error) {
    51  	switch v := v.(type) {
    52  	case string:
    53  		return v, nil
    54  	case int:
    55  		return strconv.Itoa(v), nil
    56  	case int64:
    57  		return strconv.FormatInt(v, 10), nil
    58  	case float64:
    59  		return strconv.FormatFloat(v, 'f', -1, 64), nil
    60  	case json.Number:
    61  		return string(v), nil
    62  	case bool:
    63  		if v {
    64  			return "true", nil
    65  		} else {
    66  			return "false", nil
    67  		}
    68  	case nil:
    69  		return "null", nil
    70  	default:
    71  		return "", fmt.Errorf("%T is not a string", v)
    72  	}
    73  }
    74  

View as plain text