github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/go/encoding/json/encode.go (about) 1 // Copyright 2010 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package json implements encoding and decoding of JSON as defined in 6 // RFC 7159. The mapping between JSON and Go values is described 7 // in the documentation for the Marshal and Unmarshal functions. 8 // 9 // See "JSON and Go" for an introduction to this package: 10 // https://golang.org/doc/articles/json_and_go.html 11 package json 12 13 import ( 14 "bytes" 15 "encoding" 16 "encoding/base64" 17 "fmt" 18 "math" 19 "reflect" 20 "sort" 21 "strconv" 22 "strings" 23 "sync" 24 "unicode" 25 "unicode/utf8" 26 ) 27 28 // Marshal returns the JSON encoding of v. 29 // 30 // Marshal traverses the value v recursively. 31 // If an encountered value implements the Marshaler interface 32 // and is not a nil pointer, Marshal calls its MarshalJSON method 33 // to produce JSON. If no MarshalJSON method is present but the 34 // value implements encoding.TextMarshaler instead, Marshal calls 35 // its MarshalText method and encodes the result as a JSON string. 36 // The nil pointer exception is not strictly necessary 37 // but mimics a similar, necessary exception in the behavior of 38 // UnmarshalJSON. 39 // 40 // Otherwise, Marshal uses the following type-dependent default encodings: 41 // 42 // Boolean values encode as JSON booleans. 43 // 44 // Floating point, integer, and Number values encode as JSON numbers. 45 // 46 // String values encode as JSON strings coerced to valid UTF-8, 47 // replacing invalid bytes with the Unicode replacement rune. 48 // So that the JSON will be safe to embed inside HTML <script> tags, 49 // the string is encoded using HTMLEscape, 50 // which replaces "<", ">", "&", U+2028, and U+2029 are escaped 51 // to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". 52 // This replacement can be disabled when using an Encoder, 53 // by calling SetEscapeHTML(false). 54 // 55 // Array and slice values encode as JSON arrays, except that 56 // []byte encodes as a base64-encoded string, and a nil slice 57 // encodes as the null JSON value. 58 // 59 // Struct values encode as JSON objects. 60 // Each exported struct field becomes a member of the object, using the 61 // field name as the object key, unless the field is omitted for one of the 62 // reasons given below. 63 // 64 // The encoding of each struct field can be customized by the format string 65 // stored under the "json" key in the struct field's tag. 66 // The format string gives the name of the field, possibly followed by a 67 // comma-separated list of options. The name may be empty in order to 68 // specify options without overriding the default field name. 69 // 70 // The "omitempty" option specifies that the field should be omitted 71 // from the encoding if the field has an empty value, defined as 72 // false, 0, a nil pointer, a nil interface value, and any empty array, 73 // slice, map, or string. 74 // 75 // As a special case, if the field tag is "-", the field is always omitted. 76 // Note that a field with name "-" can still be generated using the tag "-,". 77 // 78 // Examples of struct field tags and their meanings: 79 // 80 // // Field appears in JSON as key "myName". 81 // Field int `json:"myName"` 82 // 83 // // Field appears in JSON as key "myName" and 84 // // the field is omitted from the object if its value is empty, 85 // // as defined above. 86 // Field int `json:"myName,omitempty"` 87 // 88 // // Field appears in JSON as key "Field" (the default), but 89 // // the field is skipped if empty. 90 // // Note the leading comma. 91 // Field int `json:",omitempty"` 92 // 93 // // Field is ignored by this package. 94 // Field int `json:"-"` 95 // 96 // // Field appears in JSON as key "-". 97 // Field int `json:"-,"` 98 // 99 // The "string" option signals that a field is stored as JSON inside a 100 // JSON-encoded string. It applies only to fields of string, floating point, 101 // integer, or boolean types. This extra level of encoding is sometimes used 102 // when communicating with JavaScript programs: 103 // 104 // Int64String int64 `json:",string"` 105 // 106 // The key name will be used if it's a non-empty string consisting of 107 // only Unicode letters, digits, and ASCII punctuation except quotation 108 // marks, backslash, and comma. 109 // 110 // Anonymous struct fields are usually marshaled as if their inner exported fields 111 // were fields in the outer struct, subject to the usual Go visibility rules amended 112 // as described in the next paragraph. 113 // An anonymous struct field with a name given in its JSON tag is treated as 114 // having that name, rather than being anonymous. 115 // An anonymous struct field of interface type is treated the same as having 116 // that type as its name, rather than being anonymous. 117 // 118 // The Go visibility rules for struct fields are amended for JSON when 119 // deciding which field to marshal or unmarshal. If there are 120 // multiple fields at the same level, and that level is the least 121 // nested (and would therefore be the nesting level selected by the 122 // usual Go rules), the following extra rules apply: 123 // 124 // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, 125 // even if there are multiple untagged fields that would otherwise conflict. 126 // 127 // 2) If there is exactly one field (tagged or not according to the first rule), that is selected. 128 // 129 // 3) Otherwise there are multiple fields, and all are ignored; no error occurs. 130 // 131 // Handling of anonymous struct fields is new in Go 1.1. 132 // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of 133 // an anonymous struct field in both current and earlier versions, give the field 134 // a JSON tag of "-". 135 // 136 // Map values encode as JSON objects. The map's key type must either be a 137 // string, an integer type, or implement encoding.TextMarshaler. The map keys 138 // are sorted and used as JSON object keys by applying the following rules, 139 // subject to the UTF-8 coercion described for string values above: 140 // - keys of any string type are used directly 141 // - encoding.TextMarshalers are marshaled 142 // - integer keys are converted to strings 143 // 144 // Pointer values encode as the value pointed to. 145 // A nil pointer encodes as the null JSON value. 146 // 147 // Interface values encode as the value contained in the interface. 148 // A nil interface value encodes as the null JSON value. 149 // 150 // Channel, complex, and function values cannot be encoded in JSON. 151 // Attempting to encode such a value causes Marshal to return 152 // an UnsupportedTypeError. 153 // 154 // JSON cannot represent cyclic data structures and Marshal does not 155 // handle them. Passing cyclic structures to Marshal will result in 156 // an error. 157 // 158 func Marshal(v interface{}) ([]byte, error) { 159 e := newEncodeState() 160 161 err := e.marshal(v, encOpts{escapeHTML: true}) 162 if err != nil { 163 return nil, err 164 } 165 buf := append([]byte(nil), e.Bytes()...) 166 167 encodeStatePool.Put(e) 168 169 return buf, nil 170 } 171 172 // MarshalIndent is like Marshal but applies Indent to format the output. 173 // Each JSON element in the output will begin on a new line beginning with prefix 174 // followed by one or more copies of indent according to the indentation nesting. 175 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { 176 b, err := Marshal(v) 177 if err != nil { 178 return nil, err 179 } 180 var buf bytes.Buffer 181 err = Indent(&buf, b, prefix, indent) 182 if err != nil { 183 return nil, err 184 } 185 return buf.Bytes(), nil 186 } 187 188 // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 189 // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 190 // so that the JSON will be safe to embed inside HTML <script> tags. 191 // For historical reasons, web browsers don't honor standard HTML 192 // escaping within <script> tags, so an alternative JSON encoding must 193 // be used. 194 func HTMLEscape(dst *bytes.Buffer, src []byte) { 195 // The characters can only appear in string literals, 196 // so just scan the string one byte at a time. 197 start := 0 198 for i, c := range src { 199 if c == '<' || c == '>' || c == '&' { 200 if start < i { 201 dst.Write(src[start:i]) 202 } 203 dst.WriteString(`\u00`) 204 dst.WriteByte(hex[c>>4]) 205 dst.WriteByte(hex[c&0xF]) 206 start = i + 1 207 } 208 // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9). 209 if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 { 210 if start < i { 211 dst.Write(src[start:i]) 212 } 213 dst.WriteString(`\u202`) 214 dst.WriteByte(hex[src[i+2]&0xF]) 215 start = i + 3 216 } 217 } 218 if start < len(src) { 219 dst.Write(src[start:]) 220 } 221 } 222 223 // Marshaler is the interface implemented by types that 224 // can marshal themselves into valid JSON. 225 type Marshaler interface { 226 MarshalJSON() ([]byte, error) 227 } 228 229 // An UnsupportedTypeError is returned by Marshal when attempting 230 // to encode an unsupported value type. 231 type UnsupportedTypeError struct { 232 Type reflect.Type 233 } 234 235 func (e *UnsupportedTypeError) Error() string { 236 return "json: unsupported type: " + e.Type.String() 237 } 238 239 type UnsupportedValueError struct { 240 Value reflect.Value 241 Str string 242 } 243 244 func (e *UnsupportedValueError) Error() string { 245 return "json: unsupported value: " + e.Str 246 } 247 248 // Before Go 1.2, an InvalidUTF8Error was returned by Marshal when 249 // attempting to encode a string value with invalid UTF-8 sequences. 250 // As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by 251 // replacing invalid bytes with the Unicode replacement rune U+FFFD. 252 // 253 // Deprecated: No longer used; kept for compatibility. 254 type InvalidUTF8Error struct { 255 S string // the whole string value that caused the error 256 } 257 258 func (e *InvalidUTF8Error) Error() string { 259 return "json: invalid UTF-8 in string: " + strconv.Quote(e.S) 260 } 261 262 // A MarshalerError represents an error from calling a MarshalJSON or MarshalText method. 263 type MarshalerError struct { 264 Type reflect.Type 265 Err error 266 sourceFunc string 267 } 268 269 func (e *MarshalerError) Error() string { 270 srcFunc := e.sourceFunc 271 if srcFunc == "" { 272 srcFunc = "MarshalJSON" 273 } 274 return "json: error calling " + srcFunc + 275 " for type " + e.Type.String() + 276 ": " + e.Err.Error() 277 } 278 279 // Unwrap returns the underlying error. 280 func (e *MarshalerError) Unwrap() error { return e.Err } 281 282 var hex = "0123456789abcdef" 283 284 // An encodeState encodes JSON into a bytes.Buffer. 285 type encodeState struct { 286 bytes.Buffer // accumulated output 287 scratch [64]byte 288 289 // Keep track of what pointers we've seen in the current recursive call 290 // path, to avoid cycles that could lead to a stack overflow. Only do 291 // the relatively expensive map operations if ptrLevel is larger than 292 // startDetectingCyclesAfter, so that we skip the work if we're within a 293 // reasonable amount of nested pointers deep. 294 ptrLevel uint 295 ptrSeen map[interface{}]struct{} 296 } 297 298 const startDetectingCyclesAfter = 1000 299 300 var encodeStatePool sync.Pool 301 302 func newEncodeState() *encodeState { 303 if v := encodeStatePool.Get(); v != nil { 304 e := v.(*encodeState) 305 e.Reset() 306 if len(e.ptrSeen) > 0 { 307 panic("ptrEncoder.encode should have emptied ptrSeen via defers") 308 } 309 e.ptrLevel = 0 310 return e 311 } 312 return &encodeState{ptrSeen: make(map[interface{}]struct{})} 313 } 314 315 // jsonError is an error wrapper type for internal use only. 316 // Panics with errors are wrapped in jsonError so that the top-level recover 317 // can distinguish intentional panics from this package. 318 type jsonError struct{ error } 319 320 func (e *encodeState) marshal(v interface{}, opts encOpts) (err error) { 321 defer func() { 322 if r := recover(); r != nil { 323 if je, ok := r.(jsonError); ok { 324 err = je.error 325 } else { 326 panic(r) 327 } 328 } 329 }() 330 e.reflectValue(reflect.ValueOf(v), opts) 331 return nil 332 } 333 334 // error aborts the encoding by panicking with err wrapped in jsonError. 335 func (e *encodeState) error(err error) { 336 panic(jsonError{err}) 337 } 338 339 func isEmptyValue(v reflect.Value) bool { 340 switch v.Kind() { 341 case reflect.Array, reflect.Map, reflect.Slice, reflect.String: 342 return v.Len() == 0 343 case reflect.Bool: 344 return !v.Bool() 345 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 346 return v.Int() == 0 347 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 348 return v.Uint() == 0 349 case reflect.Float32, reflect.Float64: 350 return v.Float() == 0 351 case reflect.Interface, reflect.Ptr: 352 return v.IsNil() 353 } 354 return false 355 } 356 357 func (e *encodeState) reflectValue(v reflect.Value, opts encOpts) { 358 valueEncoder(v)(e, v, opts) 359 } 360 361 type encOpts struct { 362 // quoted causes primitive fields to be encoded inside JSON strings. 363 quoted bool 364 // escapeHTML causes '<', '>', and '&' to be escaped in JSON strings. 365 escapeHTML bool 366 } 367 368 type encoderFunc func(e *encodeState, v reflect.Value, opts encOpts) 369 370 var encoderCache sync.Map // map[reflect.Type]encoderFunc 371 372 func valueEncoder(v reflect.Value) encoderFunc { 373 if !v.IsValid() { 374 return invalidValueEncoder 375 } 376 return typeEncoder(v.Type()) 377 } 378 379 func typeEncoder(t reflect.Type) encoderFunc { 380 if fi, ok := encoderCache.Load(t); ok { 381 return fi.(encoderFunc) 382 } 383 384 // To deal with recursive types, populate the map with an 385 // indirect func before we build it. This type waits on the 386 // real func (f) to be ready and then calls it. This indirect 387 // func is only used for recursive types. 388 var ( 389 wg sync.WaitGroup 390 f encoderFunc 391 ) 392 wg.Add(1) 393 fi, loaded := encoderCache.LoadOrStore(t, encoderFunc(func(e *encodeState, v reflect.Value, opts encOpts) { 394 wg.Wait() 395 f(e, v, opts) 396 })) 397 if loaded { 398 return fi.(encoderFunc) 399 } 400 401 // Compute the real encoder and replace the indirect func with it. 402 f = newTypeEncoder(t, true) 403 wg.Done() 404 encoderCache.Store(t, f) 405 return f 406 } 407 408 var ( 409 marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() 410 textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() 411 ) 412 413 // newTypeEncoder constructs an encoderFunc for a type. 414 // The returned encoder only checks CanAddr when allowAddr is true. 415 func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc { 416 // If we have a non-pointer value whose type implements 417 // Marshaler with a value receiver, then we're better off taking 418 // the address of the value - otherwise we end up with an 419 // allocation as we cast the value to an interface. 420 if t.Kind() != reflect.Ptr && allowAddr && reflect.PtrTo(t).Implements(marshalerType) { 421 return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false)) 422 } 423 if t.Implements(marshalerType) { 424 return marshalerEncoder 425 } 426 if t.Kind() != reflect.Ptr && allowAddr && reflect.PtrTo(t).Implements(textMarshalerType) { 427 return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false)) 428 } 429 if t.Implements(textMarshalerType) { 430 return textMarshalerEncoder 431 } 432 433 switch t.Kind() { 434 case reflect.Bool: 435 return boolEncoder 436 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 437 return intEncoder 438 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 439 return uintEncoder 440 case reflect.Float32: 441 return float32Encoder 442 case reflect.Float64: 443 return float64Encoder 444 case reflect.String: 445 return stringEncoder 446 case reflect.Interface: 447 return interfaceEncoder 448 case reflect.Struct: 449 return newStructEncoder(t) 450 case reflect.Map: 451 return newMapEncoder(t) 452 case reflect.Slice: 453 return newSliceEncoder(t) 454 case reflect.Array: 455 return newArrayEncoder(t) 456 case reflect.Ptr: 457 return newPtrEncoder(t) 458 default: 459 return unsupportedTypeEncoder 460 } 461 } 462 463 func invalidValueEncoder(e *encodeState, v reflect.Value, _ encOpts) { 464 e.WriteString("null") 465 } 466 467 func marshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { 468 if v.Kind() == reflect.Ptr && v.IsNil() { 469 e.WriteString("null") 470 return 471 } 472 m, ok := v.Interface().(Marshaler) 473 if !ok { 474 e.WriteString("null") 475 return 476 } 477 b, err := m.MarshalJSON() 478 if err == nil { 479 // copy JSON into buffer, checking validity. 480 err = compact(&e.Buffer, b, opts.escapeHTML) 481 } 482 if err != nil { 483 e.error(&MarshalerError{v.Type(), err, "MarshalJSON"}) 484 } 485 } 486 487 func addrMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { 488 va := v.Addr() 489 if va.IsNil() { 490 e.WriteString("null") 491 return 492 } 493 m := va.Interface().(Marshaler) 494 b, err := m.MarshalJSON() 495 if err == nil { 496 // copy JSON into buffer, checking validity. 497 err = compact(&e.Buffer, b, opts.escapeHTML) 498 } 499 if err != nil { 500 e.error(&MarshalerError{v.Type(), err, "MarshalJSON"}) 501 } 502 } 503 504 func textMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { 505 if v.Kind() == reflect.Ptr && v.IsNil() { 506 e.WriteString("null") 507 return 508 } 509 m, ok := v.Interface().(encoding.TextMarshaler) 510 if !ok { 511 e.WriteString("null") 512 return 513 } 514 b, err := m.MarshalText() 515 if err != nil { 516 e.error(&MarshalerError{v.Type(), err, "MarshalText"}) 517 } 518 e.stringBytes(b, opts.escapeHTML) 519 } 520 521 func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { 522 va := v.Addr() 523 if va.IsNil() { 524 e.WriteString("null") 525 return 526 } 527 m := va.Interface().(encoding.TextMarshaler) 528 b, err := m.MarshalText() 529 if err != nil { 530 e.error(&MarshalerError{v.Type(), err, "MarshalText"}) 531 } 532 e.stringBytes(b, opts.escapeHTML) 533 } 534 535 func boolEncoder(e *encodeState, v reflect.Value, opts encOpts) { 536 if opts.quoted { 537 e.WriteByte('"') 538 } 539 if v.Bool() { 540 e.WriteString("true") 541 } else { 542 e.WriteString("false") 543 } 544 if opts.quoted { 545 e.WriteByte('"') 546 } 547 } 548 549 func intEncoder(e *encodeState, v reflect.Value, opts encOpts) { 550 b := strconv.AppendInt(e.scratch[:0], v.Int(), 10) 551 if opts.quoted { 552 e.WriteByte('"') 553 } 554 e.Write(b) 555 if opts.quoted { 556 e.WriteByte('"') 557 } 558 } 559 560 func uintEncoder(e *encodeState, v reflect.Value, opts encOpts) { 561 b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10) 562 if opts.quoted { 563 e.WriteByte('"') 564 } 565 e.Write(b) 566 if opts.quoted { 567 e.WriteByte('"') 568 } 569 } 570 571 type floatEncoder int // number of bits 572 573 func (bits floatEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { 574 f := v.Float() 575 if math.IsInf(f, 0) || math.IsNaN(f) { 576 e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))}) 577 } 578 579 // Convert as if by ES6 number to string conversion. 580 // This matches most other JSON generators. 581 // See golang.org/issue/6384 and golang.org/issue/14135. 582 // Like fmt %g, but the exponent cutoffs are different 583 // and exponents themselves are not padded to two digits. 584 b := e.scratch[:0] 585 abs := math.Abs(f) 586 fmt := byte('f') 587 // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. 588 if abs != 0 { 589 if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { 590 fmt = 'e' 591 } 592 } 593 b = strconv.AppendFloat(b, f, fmt, -1, int(bits)) 594 if fmt == 'e' { 595 // clean up e-09 to e-9 596 n := len(b) 597 if n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' { 598 b[n-2] = b[n-1] 599 b = b[:n-1] 600 } 601 } 602 603 if opts.quoted { 604 e.WriteByte('"') 605 } 606 e.Write(b) 607 if opts.quoted { 608 e.WriteByte('"') 609 } 610 } 611 612 var ( 613 float32Encoder = (floatEncoder(32)).encode 614 float64Encoder = (floatEncoder(64)).encode 615 ) 616 617 func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) { 618 if v.Type() == numberType { 619 numStr := v.String() 620 // In Go1.5 the empty string encodes to "0", while this is not a valid number literal 621 // we keep compatibility so check validity after this. 622 if numStr == "" { 623 numStr = "0" // Number's zero-val 624 } 625 if !isValidNumber(numStr) { 626 e.error(fmt.Errorf("json: invalid number literal %q", numStr)) 627 } 628 if opts.quoted { 629 e.WriteByte('"') 630 } 631 e.WriteString(numStr) 632 if opts.quoted { 633 e.WriteByte('"') 634 } 635 return 636 } 637 if opts.quoted { 638 b := make([]byte, 0, v.Len()+2) 639 b = append(b, '"') 640 b = append(b, []byte(v.String())...) 641 b = append(b, '"') 642 e.stringBytes(b, opts.escapeHTML) 643 } else { 644 e.string(v.String(), opts.escapeHTML) 645 } 646 } 647 648 // isValidNumber reports whether s is a valid JSON number literal. 649 func isValidNumber(s string) bool { 650 // This function implements the JSON numbers grammar. 651 // See https://tools.ietf.org/html/rfc7159#section-6 652 // and https://json.org/number.gif 653 654 if s == "" { 655 return false 656 } 657 658 // Optional - 659 if s[0] == '-' { 660 s = s[1:] 661 if s == "" { 662 return false 663 } 664 } 665 666 // Digits 667 switch { 668 default: 669 return false 670 671 case s[0] == '0': 672 s = s[1:] 673 674 case '1' <= s[0] && s[0] <= '9': 675 s = s[1:] 676 for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { 677 s = s[1:] 678 } 679 } 680 681 // . followed by 1 or more digits. 682 if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { 683 s = s[2:] 684 for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { 685 s = s[1:] 686 } 687 } 688 689 // e or E followed by an optional - or + and 690 // 1 or more digits. 691 if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { 692 s = s[1:] 693 if s[0] == '+' || s[0] == '-' { 694 s = s[1:] 695 if s == "" { 696 return false 697 } 698 } 699 for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { 700 s = s[1:] 701 } 702 } 703 704 // Make sure we are at the end. 705 return s == "" 706 } 707 708 func interfaceEncoder(e *encodeState, v reflect.Value, opts encOpts) { 709 if v.IsNil() { 710 e.WriteString("null") 711 return 712 } 713 e.reflectValue(v.Elem(), opts) 714 } 715 716 func unsupportedTypeEncoder(e *encodeState, v reflect.Value, _ encOpts) { 717 e.error(&UnsupportedTypeError{v.Type()}) 718 } 719 720 type structEncoder struct { 721 fields structFields 722 } 723 724 type structFields struct { 725 list []field 726 nameIndex map[string]int 727 } 728 729 func (se structEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { 730 next := byte('{') 731 FieldLoop: 732 for i := range se.fields.list { 733 f := &se.fields.list[i] 734 735 // Find the nested struct field by following f.index. 736 fv := v 737 for _, i := range f.index { 738 if fv.Kind() == reflect.Ptr { 739 if fv.IsNil() { 740 continue FieldLoop 741 } 742 fv = fv.Elem() 743 } 744 fv = fv.Field(i) 745 } 746 747 if f.omitEmpty && isEmptyValue(fv) { 748 continue 749 } 750 e.WriteByte(next) 751 next = ',' 752 if opts.escapeHTML { 753 e.WriteString(f.nameEscHTML) 754 } else { 755 e.WriteString(f.nameNonEsc) 756 } 757 opts.quoted = f.quoted 758 f.encoder(e, fv, opts) 759 } 760 if next == '{' { 761 e.WriteString("{}") 762 } else { 763 e.WriteByte('}') 764 } 765 } 766 767 func newStructEncoder(t reflect.Type) encoderFunc { 768 se := structEncoder{fields: cachedTypeFields(t)} 769 return se.encode 770 } 771 772 type mapEncoder struct { 773 elemEnc encoderFunc 774 } 775 776 func (me mapEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { 777 if v.IsNil() { 778 e.WriteString("null") 779 return 780 } 781 e.WriteByte('{') 782 783 // Extract and sort the keys. 784 keys := v.MapKeys() 785 sv := make([]reflectWithString, len(keys)) 786 for i, v := range keys { 787 sv[i].v = v 788 if err := sv[i].resolve(); err != nil { 789 e.error(fmt.Errorf("json: encoding error for type %q: %q", v.Type().String(), err.Error())) 790 } 791 } 792 sort.Slice(sv, func(i, j int) bool { return sv[i].s < sv[j].s }) 793 794 for i, kv := range sv { 795 if i > 0 { 796 e.WriteByte(',') 797 } 798 e.string(kv.s, opts.escapeHTML) 799 e.WriteByte(':') 800 me.elemEnc(e, v.MapIndex(kv.v), opts) 801 } 802 e.WriteByte('}') 803 } 804 805 func newMapEncoder(t reflect.Type) encoderFunc { 806 switch t.Key().Kind() { 807 case reflect.String, 808 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 809 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 810 default: 811 if !t.Key().Implements(textMarshalerType) { 812 return unsupportedTypeEncoder 813 } 814 } 815 me := mapEncoder{typeEncoder(t.Elem())} 816 return me.encode 817 } 818 819 func encodeByteSlice(e *encodeState, v reflect.Value, _ encOpts) { 820 if v.IsNil() { 821 e.WriteString("null") 822 return 823 } 824 s := v.Bytes() 825 e.WriteByte('"') 826 encodedLen := base64.StdEncoding.EncodedLen(len(s)) 827 if encodedLen <= len(e.scratch) { 828 // If the encoded bytes fit in e.scratch, avoid an extra 829 // allocation and use the cheaper Encoding.Encode. 830 dst := e.scratch[:encodedLen] 831 base64.StdEncoding.Encode(dst, s) 832 e.Write(dst) 833 } else if encodedLen <= 1024 { 834 // The encoded bytes are short enough to allocate for, and 835 // Encoding.Encode is still cheaper. 836 dst := make([]byte, encodedLen) 837 base64.StdEncoding.Encode(dst, s) 838 e.Write(dst) 839 } else { 840 // The encoded bytes are too long to cheaply allocate, and 841 // Encoding.Encode is no longer noticeably cheaper. 842 enc := base64.NewEncoder(base64.StdEncoding, e) 843 enc.Write(s) 844 enc.Close() 845 } 846 e.WriteByte('"') 847 } 848 849 // sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil. 850 type sliceEncoder struct { 851 arrayEnc encoderFunc 852 } 853 854 func (se sliceEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { 855 if v.IsNil() { 856 e.WriteString("null") 857 return 858 } 859 se.arrayEnc(e, v, opts) 860 } 861 862 func newSliceEncoder(t reflect.Type) encoderFunc { 863 // Byte slices get special treatment; arrays don't. 864 if t.Elem().Kind() == reflect.Uint8 { 865 p := reflect.PtrTo(t.Elem()) 866 if !p.Implements(marshalerType) && !p.Implements(textMarshalerType) { 867 return encodeByteSlice 868 } 869 } 870 enc := sliceEncoder{newArrayEncoder(t)} 871 return enc.encode 872 } 873 874 type arrayEncoder struct { 875 elemEnc encoderFunc 876 } 877 878 func (ae arrayEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { 879 e.WriteByte('[') 880 n := v.Len() 881 for i := 0; i < n; i++ { 882 if i > 0 { 883 e.WriteByte(',') 884 } 885 ae.elemEnc(e, v.Index(i), opts) 886 } 887 e.WriteByte(']') 888 } 889 890 func newArrayEncoder(t reflect.Type) encoderFunc { 891 enc := arrayEncoder{typeEncoder(t.Elem())} 892 return enc.encode 893 } 894 895 type ptrEncoder struct { 896 elemEnc encoderFunc 897 } 898 899 func (pe ptrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { 900 if v.IsNil() { 901 e.WriteString("null") 902 return 903 } 904 if e.ptrLevel++; e.ptrLevel > startDetectingCyclesAfter { 905 // We're a large number of nested ptrEncoder.encode calls deep; 906 // start checking if we've run into a pointer cycle. 907 ptr := v.Interface() 908 if _, ok := e.ptrSeen[ptr]; ok { 909 e.error(&UnsupportedValueError{v, fmt.Sprintf("encountered a cycle via %s", v.Type())}) 910 } 911 e.ptrSeen[ptr] = struct{}{} 912 defer delete(e.ptrSeen, ptr) 913 } 914 pe.elemEnc(e, v.Elem(), opts) 915 e.ptrLevel-- 916 } 917 918 func newPtrEncoder(t reflect.Type) encoderFunc { 919 enc := ptrEncoder{typeEncoder(t.Elem())} 920 return enc.encode 921 } 922 923 type condAddrEncoder struct { 924 canAddrEnc, elseEnc encoderFunc 925 } 926 927 func (ce condAddrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { 928 if v.CanAddr() { 929 ce.canAddrEnc(e, v, opts) 930 } else { 931 ce.elseEnc(e, v, opts) 932 } 933 } 934 935 // newCondAddrEncoder returns an encoder that checks whether its value 936 // CanAddr and delegates to canAddrEnc if so, else to elseEnc. 937 func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc { 938 enc := condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc} 939 return enc.encode 940 } 941 942 func isValidTag(s string) bool { 943 if s == "" { 944 return false 945 } 946 for _, c := range s { 947 switch { 948 case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): 949 // Backslash and quote chars are reserved, but 950 // otherwise any punctuation chars are allowed 951 // in a tag name. 952 case !unicode.IsLetter(c) && !unicode.IsDigit(c): 953 return false 954 } 955 } 956 return true 957 } 958 959 func typeByIndex(t reflect.Type, index []int) reflect.Type { 960 for _, i := range index { 961 if t.Kind() == reflect.Ptr { 962 t = t.Elem() 963 } 964 t = t.Field(i).Type 965 } 966 return t 967 } 968 969 type reflectWithString struct { 970 v reflect.Value 971 s string 972 } 973 974 func (w *reflectWithString) resolve() error { 975 if w.v.Kind() == reflect.String { 976 w.s = w.v.String() 977 return nil 978 } 979 if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok { 980 if w.v.Kind() == reflect.Ptr && w.v.IsNil() { 981 return nil 982 } 983 buf, err := tm.MarshalText() 984 w.s = string(buf) 985 return err 986 } 987 switch w.v.Kind() { 988 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 989 w.s = strconv.FormatInt(w.v.Int(), 10) 990 return nil 991 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 992 w.s = strconv.FormatUint(w.v.Uint(), 10) 993 return nil 994 } 995 panic("unexpected map key type") 996 } 997 998 // NOTE: keep in sync with stringBytes below. 999 func (e *encodeState) string(s string, escapeHTML bool) { 1000 e.WriteByte('"') 1001 start := 0 1002 for i := 0; i < len(s); { 1003 if b := s[i]; b < utf8.RuneSelf { 1004 if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) { 1005 i++ 1006 continue 1007 } 1008 if start < i { 1009 e.WriteString(s[start:i]) 1010 } 1011 e.WriteByte('\\') 1012 switch b { 1013 case '\\', '"': 1014 e.WriteByte(b) 1015 case '\n': 1016 e.WriteByte('n') 1017 case '\r': 1018 e.WriteByte('r') 1019 case '\t': 1020 e.WriteByte('t') 1021 default: 1022 // This encodes bytes < 0x20 except for \t, \n and \r. 1023 // If escapeHTML is set, it also escapes <, >, and & 1024 // because they can lead to security holes when 1025 // user-controlled strings are rendered into JSON 1026 // and served to some browsers. 1027 e.WriteString(`u00`) 1028 e.WriteByte(hex[b>>4]) 1029 e.WriteByte(hex[b&0xF]) 1030 } 1031 i++ 1032 start = i 1033 continue 1034 } 1035 c, size := utf8.DecodeRuneInString(s[i:]) 1036 if c == utf8.RuneError && size == 1 { 1037 if start < i { 1038 e.WriteString(s[start:i]) 1039 } 1040 e.WriteString(`\ufffd`) 1041 i += size 1042 start = i 1043 continue 1044 } 1045 // U+2028 is LINE SEPARATOR. 1046 // U+2029 is PARAGRAPH SEPARATOR. 1047 // They are both technically valid characters in JSON strings, 1048 // but don't work in JSONP, which has to be evaluated as JavaScript, 1049 // and can lead to security holes there. It is valid JSON to 1050 // escape them, so we do so unconditionally. 1051 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. 1052 if c == '\u2028' || c == '\u2029' { 1053 if start < i { 1054 e.WriteString(s[start:i]) 1055 } 1056 e.WriteString(`\u202`) 1057 e.WriteByte(hex[c&0xF]) 1058 i += size 1059 start = i 1060 continue 1061 } 1062 i += size 1063 } 1064 if start < len(s) { 1065 e.WriteString(s[start:]) 1066 } 1067 e.WriteByte('"') 1068 } 1069 1070 // NOTE: keep in sync with string above. 1071 func (e *encodeState) stringBytes(s []byte, escapeHTML bool) { 1072 e.WriteByte('"') 1073 start := 0 1074 for i := 0; i < len(s); { 1075 if b := s[i]; b < utf8.RuneSelf { 1076 if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) { 1077 i++ 1078 continue 1079 } 1080 if start < i { 1081 e.Write(s[start:i]) 1082 } 1083 e.WriteByte('\\') 1084 switch b { 1085 case '\\', '"': 1086 e.WriteByte(b) 1087 case '\n': 1088 e.WriteByte('n') 1089 case '\r': 1090 e.WriteByte('r') 1091 case '\t': 1092 e.WriteByte('t') 1093 default: 1094 // This encodes bytes < 0x20 except for \t, \n and \r. 1095 // If escapeHTML is set, it also escapes <, >, and & 1096 // because they can lead to security holes when 1097 // user-controlled strings are rendered into JSON 1098 // and served to some browsers. 1099 e.WriteString(`u00`) 1100 e.WriteByte(hex[b>>4]) 1101 e.WriteByte(hex[b&0xF]) 1102 } 1103 i++ 1104 start = i 1105 continue 1106 } 1107 c, size := utf8.DecodeRune(s[i:]) 1108 if c == utf8.RuneError && size == 1 { 1109 if start < i { 1110 e.Write(s[start:i]) 1111 } 1112 e.WriteString(`\ufffd`) 1113 i += size 1114 start = i 1115 continue 1116 } 1117 // U+2028 is LINE SEPARATOR. 1118 // U+2029 is PARAGRAPH SEPARATOR. 1119 // They are both technically valid characters in JSON strings, 1120 // but don't work in JSONP, which has to be evaluated as JavaScript, 1121 // and can lead to security holes there. It is valid JSON to 1122 // escape them, so we do so unconditionally. 1123 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. 1124 if c == '\u2028' || c == '\u2029' { 1125 if start < i { 1126 e.Write(s[start:i]) 1127 } 1128 e.WriteString(`\u202`) 1129 e.WriteByte(hex[c&0xF]) 1130 i += size 1131 start = i 1132 continue 1133 } 1134 i += size 1135 } 1136 if start < len(s) { 1137 e.Write(s[start:]) 1138 } 1139 e.WriteByte('"') 1140 } 1141 1142 // A field represents a single field found in a struct. 1143 type field struct { 1144 name string 1145 nameBytes []byte // []byte(name) 1146 equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent 1147 1148 nameNonEsc string // `"` + name + `":` 1149 nameEscHTML string // `"` + HTMLEscape(name) + `":` 1150 1151 tag bool 1152 index []int 1153 typ reflect.Type 1154 omitEmpty bool 1155 quoted bool 1156 1157 encoder encoderFunc 1158 } 1159 1160 // byIndex sorts field by index sequence. 1161 type byIndex []field 1162 1163 func (x byIndex) Len() int { return len(x) } 1164 1165 func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } 1166 1167 func (x byIndex) Less(i, j int) bool { 1168 for k, xik := range x[i].index { 1169 if k >= len(x[j].index) { 1170 return false 1171 } 1172 if xik != x[j].index[k] { 1173 return xik < x[j].index[k] 1174 } 1175 } 1176 return len(x[i].index) < len(x[j].index) 1177 } 1178 1179 // typeFields returns a list of fields that JSON should recognize for the given type. 1180 // The algorithm is breadth-first search over the set of structs to include - the top struct 1181 // and then any reachable anonymous structs. 1182 func typeFields(t reflect.Type) structFields { 1183 // Anonymous fields to explore at the current level and the next. 1184 current := []field{} 1185 next := []field{{typ: t}} 1186 1187 // Count of queued names for current level and the next. 1188 var count, nextCount map[reflect.Type]int 1189 1190 // Types already visited at an earlier level. 1191 visited := map[reflect.Type]bool{} 1192 1193 // Fields found. 1194 var fields []field 1195 1196 // Buffer to run HTMLEscape on field names. 1197 var nameEscBuf bytes.Buffer 1198 1199 for len(next) > 0 { 1200 current, next = next, current[:0] 1201 count, nextCount = nextCount, map[reflect.Type]int{} 1202 1203 for _, f := range current { 1204 if visited[f.typ] { 1205 continue 1206 } 1207 visited[f.typ] = true 1208 1209 // Scan f.typ for fields to include. 1210 for i := 0; i < f.typ.NumField(); i++ { 1211 sf := f.typ.Field(i) 1212 isUnexported := sf.PkgPath != "" 1213 if sf.Anonymous { 1214 t := sf.Type 1215 if t.Kind() == reflect.Ptr { 1216 t = t.Elem() 1217 } 1218 if isUnexported && t.Kind() != reflect.Struct { 1219 // Ignore embedded fields of unexported non-struct types. 1220 continue 1221 } 1222 // Do not ignore embedded fields of unexported struct types 1223 // since they may have exported fields. 1224 } else if isUnexported { 1225 // Ignore unexported non-embedded fields. 1226 continue 1227 } 1228 tag := sf.Tag.Get("json") 1229 if tag == "-" { 1230 continue 1231 } 1232 name, opts := parseTag(tag) 1233 if !isValidTag(name) { 1234 name = "" 1235 } 1236 index := make([]int, len(f.index)+1) 1237 copy(index, f.index) 1238 index[len(f.index)] = i 1239 1240 ft := sf.Type 1241 if ft.Name() == "" && ft.Kind() == reflect.Ptr { 1242 // Follow pointer. 1243 ft = ft.Elem() 1244 } 1245 1246 // Only strings, floats, integers, and booleans can be quoted. 1247 quoted := false 1248 if opts.Contains("string") { 1249 switch ft.Kind() { 1250 case reflect.Bool, 1251 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 1252 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, 1253 reflect.Float32, reflect.Float64, 1254 reflect.String: 1255 quoted = true 1256 } 1257 } 1258 1259 // Record found field and index sequence. 1260 if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { 1261 tagged := name != "" 1262 if name == "" { 1263 name = sf.Name 1264 } 1265 field := field{ 1266 name: name, 1267 tag: tagged, 1268 index: index, 1269 typ: ft, 1270 omitEmpty: opts.Contains("omitempty"), 1271 quoted: quoted, 1272 } 1273 field.nameBytes = []byte(field.name) 1274 field.equalFold = foldFunc(field.nameBytes) 1275 1276 // Build nameEscHTML and nameNonEsc ahead of time. 1277 nameEscBuf.Reset() 1278 nameEscBuf.WriteString(`"`) 1279 HTMLEscape(&nameEscBuf, field.nameBytes) 1280 nameEscBuf.WriteString(`":`) 1281 field.nameEscHTML = nameEscBuf.String() 1282 field.nameNonEsc = `"` + field.name + `":` 1283 1284 fields = append(fields, field) 1285 if count[f.typ] > 1 { 1286 // If there were multiple instances, add a second, 1287 // so that the annihilation code will see a duplicate. 1288 // It only cares about the distinction between 1 or 2, 1289 // so don't bother generating any more copies. 1290 fields = append(fields, fields[len(fields)-1]) 1291 } 1292 continue 1293 } 1294 1295 // Record new anonymous struct to explore in next round. 1296 nextCount[ft]++ 1297 if nextCount[ft] == 1 { 1298 next = append(next, field{name: ft.Name(), index: index, typ: ft}) 1299 } 1300 } 1301 } 1302 } 1303 1304 sort.Slice(fields, func(i, j int) bool { 1305 x := fields 1306 // sort field by name, breaking ties with depth, then 1307 // breaking ties with "name came from json tag", then 1308 // breaking ties with index sequence. 1309 if x[i].name != x[j].name { 1310 return x[i].name < x[j].name 1311 } 1312 if len(x[i].index) != len(x[j].index) { 1313 return len(x[i].index) < len(x[j].index) 1314 } 1315 if x[i].tag != x[j].tag { 1316 return x[i].tag 1317 } 1318 return byIndex(x).Less(i, j) 1319 }) 1320 1321 // Delete all fields that are hidden by the Go rules for embedded fields, 1322 // except that fields with JSON tags are promoted. 1323 1324 // The fields are sorted in primary order of name, secondary order 1325 // of field index length. Loop over names; for each name, delete 1326 // hidden fields by choosing the one dominant field that survives. 1327 out := fields[:0] 1328 for advance, i := 0, 0; i < len(fields); i += advance { 1329 // One iteration per name. 1330 // Find the sequence of fields with the name of this first field. 1331 fi := fields[i] 1332 name := fi.name 1333 for advance = 1; i+advance < len(fields); advance++ { 1334 fj := fields[i+advance] 1335 if fj.name != name { 1336 break 1337 } 1338 } 1339 if advance == 1 { // Only one field with this name 1340 out = append(out, fi) 1341 continue 1342 } 1343 dominant, ok := dominantField(fields[i : i+advance]) 1344 if ok { 1345 out = append(out, dominant) 1346 } 1347 } 1348 1349 fields = out 1350 sort.Sort(byIndex(fields)) 1351 1352 for i := range fields { 1353 f := &fields[i] 1354 f.encoder = typeEncoder(typeByIndex(t, f.index)) 1355 } 1356 nameIndex := make(map[string]int, len(fields)) 1357 for i, field := range fields { 1358 nameIndex[field.name] = i 1359 } 1360 return structFields{fields, nameIndex} 1361 } 1362 1363 // dominantField looks through the fields, all of which are known to 1364 // have the same name, to find the single field that dominates the 1365 // others using Go's embedding rules, modified by the presence of 1366 // JSON tags. If there are multiple top-level fields, the boolean 1367 // will be false: This condition is an error in Go and we skip all 1368 // the fields. 1369 func dominantField(fields []field) (field, bool) { 1370 // The fields are sorted in increasing index-length order, then by presence of tag. 1371 // That means that the first field is the dominant one. We need only check 1372 // for error cases: two fields at top level, either both tagged or neither tagged. 1373 if len(fields) > 1 && len(fields[0].index) == len(fields[1].index) && fields[0].tag == fields[1].tag { 1374 return field{}, false 1375 } 1376 return fields[0], true 1377 } 1378 1379 var fieldCache sync.Map // map[reflect.Type]structFields 1380 1381 // cachedTypeFields is like typeFields but uses a cache to avoid repeated work. 1382 func cachedTypeFields(t reflect.Type) structFields { 1383 if f, ok := fieldCache.Load(t); ok { 1384 return f.(structFields) 1385 } 1386 f, _ := fieldCache.LoadOrStore(t, typeFields(t)) 1387 return f.(structFields) 1388 }