另客网go项目公用的代码库

0doc.go 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. /*
  4. Package codec provides a
  5. High Performance, Feature-Rich Idiomatic Go 1.4+ codec/encoding library
  6. for binc, msgpack, cbor, json.
  7. Supported Serialization formats are:
  8. - msgpack: https://github.com/msgpack/msgpack
  9. - binc: http://github.com/ugorji/binc
  10. - cbor: http://cbor.io http://tools.ietf.org/html/rfc7049
  11. - json: http://json.org http://tools.ietf.org/html/rfc7159
  12. - simple:
  13. To install:
  14. go get github.com/ugorji/go/codec
  15. This package will carefully use 'unsafe' for performance reasons in specific places.
  16. You can build without unsafe use by passing the safe or appengine tag
  17. i.e. 'go install -tags=safe ...'. Note that unsafe is only supported for the last 3
  18. go sdk versions e.g. current go release is go 1.9, so we support unsafe use only from
  19. go 1.7+ . This is because supporting unsafe requires knowledge of implementation details.
  20. For detailed usage information, read the primer at http://ugorji.net/blog/go-codec-primer .
  21. The idiomatic Go support is as seen in other encoding packages in
  22. the standard library (ie json, xml, gob, etc).
  23. Rich Feature Set includes:
  24. - Simple but extremely powerful and feature-rich API
  25. - Support for go1.4 and above, while selectively using newer APIs for later releases
  26. - Excellent code coverage ( > 90% )
  27. - Very High Performance.
  28. Our extensive benchmarks show us outperforming Gob, Json, Bson, etc by 2-4X.
  29. - Careful selected use of 'unsafe' for targeted performance gains.
  30. 100% mode exists where 'unsafe' is not used at all.
  31. - Lock-free (sans mutex) concurrency for scaling to 100's of cores
  32. - In-place updates during decode, with option to zero value in maps and slices prior to decode
  33. - Coerce types where appropriate
  34. e.g. decode an int in the stream into a float, decode numbers from formatted strings, etc
  35. - Corner Cases:
  36. Overflows, nil maps/slices, nil values in streams are handled correctly
  37. - Standard field renaming via tags
  38. - Support for omitting empty fields during an encoding
  39. - Encoding from any value and decoding into pointer to any value
  40. (struct, slice, map, primitives, pointers, interface{}, etc)
  41. - Extensions to support efficient encoding/decoding of any named types
  42. - Support encoding.(Binary|Text)(M|Unm)arshaler interfaces
  43. - Support IsZero() bool to determine if a value is a zero value.
  44. Analogous to time.Time.IsZero() bool.
  45. - Decoding without a schema (into a interface{}).
  46. Includes Options to configure what specific map or slice type to use
  47. when decoding an encoded list or map into a nil interface{}
  48. - Mapping a non-interface type to an interface, so we can decode appropriately
  49. into any interface type with a correctly configured non-interface value.
  50. - Encode a struct as an array, and decode struct from an array in the data stream
  51. - Option to encode struct keys as numbers (instead of strings)
  52. (to support structured streams with fields encoded as numeric codes)
  53. - Comprehensive support for anonymous fields
  54. - Fast (no-reflection) encoding/decoding of common maps and slices
  55. - Code-generation for faster performance.
  56. - Support binary (e.g. messagepack, cbor) and text (e.g. json) formats
  57. - Support indefinite-length formats to enable true streaming
  58. (for formats which support it e.g. json, cbor)
  59. - Support canonical encoding, where a value is ALWAYS encoded as same sequence of bytes.
  60. This mostly applies to maps, where iteration order is non-deterministic.
  61. - NIL in data stream decoded as zero value
  62. - Never silently skip data when decoding.
  63. User decides whether to return an error or silently skip data when keys or indexes
  64. in the data stream do not map to fields in the struct.
  65. - Detect and error when encoding a cyclic reference (instead of stack overflow shutdown)
  66. - Encode/Decode from/to chan types (for iterative streaming support)
  67. - Drop-in replacement for encoding/json. `json:` key in struct tag supported.
  68. - Provides a RPC Server and Client Codec for net/rpc communication protocol.
  69. - Handle unique idiosyncrasies of codecs e.g.
  70. - For messagepack, configure how ambiguities in handling raw bytes are resolved
  71. - For messagepack, provide rpc server/client codec to support
  72. msgpack-rpc protocol defined at:
  73. https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
  74. Extension Support
  75. Users can register a function to handle the encoding or decoding of
  76. their custom types.
  77. There are no restrictions on what the custom type can be. Some examples:
  78. type BisSet []int
  79. type BitSet64 uint64
  80. type UUID string
  81. type MyStructWithUnexportedFields struct { a int; b bool; c []int; }
  82. type GifImage struct { ... }
  83. As an illustration, MyStructWithUnexportedFields would normally be
  84. encoded as an empty map because it has no exported fields, while UUID
  85. would be encoded as a string. However, with extension support, you can
  86. encode any of these however you like.
  87. Custom Encoding and Decoding
  88. This package maintains symmetry in the encoding and decoding halfs.
  89. We determine how to encode or decode by walking this decision tree
  90. - is type a codec.Selfer?
  91. - is there an extension registered for the type?
  92. - is format binary, and is type a encoding.BinaryMarshaler and BinaryUnmarshaler?
  93. - is format specifically json, and is type a encoding/json.Marshaler and Unmarshaler?
  94. - is format text-based, and type an encoding.TextMarshaler?
  95. - else we use a pair of functions based on the "kind" of the type e.g. map, slice, int64, etc
  96. This symmetry is important to reduce chances of issues happening because the
  97. encoding and decoding sides are out of sync e.g. decoded via very specific
  98. encoding.TextUnmarshaler but encoded via kind-specific generalized mode.
  99. Consequently, if a type only defines one-half of the symmetry
  100. (e.g. it implements UnmarshalJSON() but not MarshalJSON() ),
  101. then that type doesn't satisfy the check and we will continue walking down the
  102. decision tree.
  103. RPC
  104. RPC Client and Server Codecs are implemented, so the codecs can be used
  105. with the standard net/rpc package.
  106. Usage
  107. The Handle is SAFE for concurrent READ, but NOT SAFE for concurrent modification.
  108. The Encoder and Decoder are NOT safe for concurrent use.
  109. Consequently, the usage model is basically:
  110. - Create and initialize the Handle before any use.
  111. Once created, DO NOT modify it.
  112. - Multiple Encoders or Decoders can now use the Handle concurrently.
  113. They only read information off the Handle (never write).
  114. - However, each Encoder or Decoder MUST not be used concurrently
  115. - To re-use an Encoder/Decoder, call Reset(...) on it first.
  116. This allows you use state maintained on the Encoder/Decoder.
  117. Sample usage model:
  118. // create and configure Handle
  119. var (
  120. bh codec.BincHandle
  121. mh codec.MsgpackHandle
  122. ch codec.CborHandle
  123. )
  124. mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
  125. // configure extensions
  126. // e.g. for msgpack, define functions and enable Time support for tag 1
  127. // mh.SetExt(reflect.TypeOf(time.Time{}), 1, myExt)
  128. // create and use decoder/encoder
  129. var (
  130. r io.Reader
  131. w io.Writer
  132. b []byte
  133. h = &bh // or mh to use msgpack
  134. )
  135. dec = codec.NewDecoder(r, h)
  136. dec = codec.NewDecoderBytes(b, h)
  137. err = dec.Decode(&v)
  138. enc = codec.NewEncoder(w, h)
  139. enc = codec.NewEncoderBytes(&b, h)
  140. err = enc.Encode(v)
  141. //RPC Server
  142. go func() {
  143. for {
  144. conn, err := listener.Accept()
  145. rpcCodec := codec.GoRpc.ServerCodec(conn, h)
  146. //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h)
  147. rpc.ServeCodec(rpcCodec)
  148. }
  149. }()
  150. //RPC Communication (client side)
  151. conn, err = net.Dial("tcp", "localhost:5555")
  152. rpcCodec := codec.GoRpc.ClientCodec(conn, h)
  153. //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h)
  154. client := rpc.NewClientWithCodec(rpcCodec)
  155. Running Tests
  156. To run tests, use the following:
  157. go test
  158. To run the full suite of tests, use the following:
  159. go test -tags alltests -run Suite
  160. You can run the tag 'safe' to run tests or build in safe mode. e.g.
  161. go test -tags safe -run Json
  162. go test -tags "alltests safe" -run Suite
  163. Running Benchmarks
  164. Please see http://github.com/ugorji/go-codec-bench .
  165. Caveats
  166. Struct fields matching the following are ignored during encoding and decoding
  167. - struct tag value set to -
  168. - func, complex numbers, unsafe pointers
  169. - unexported and not embedded
  170. - unexported and embedded and not struct kind
  171. - unexported and embedded pointers (from go1.10)
  172. Every other field in a struct will be encoded/decoded.
  173. Embedded fields are encoded as if they exist in the top-level struct,
  174. with some caveats. See Encode documentation.
  175. */
  176. package codec