Debian Codegraph @

encoders/builtin/json_enc.go

raw
1 // Copyright 2012-2023 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package builtin
15
16 import (
17 "encoding/json"
18 "strings"
19 )
20
21 // JsonEncoder is a JSON Encoder implementation for EncodedConn.
22 // This encoder will use the builtin encoding/json to Marshal
23 // and Unmarshal most types, including structs.
24 //
25 // Deprecated: Encoded connections are no longer supported.
26 type JsonEncoder struct {
27 // Empty
28 }
29
30 // Encode
31 //
32 // Deprecated: Encoded connections are no longer supported.
33 func (je *JsonEncoder) Encode(subject string, v any) ([]byte, error) {
34 b, err := json.Marshal(v)
35 if err != nil {
36 return nil, err
37 }
38 return b, nil
39 }
40
41 // Decode
42 //
43 // Deprecated: Encoded connections are no longer supported.
44 func (je *JsonEncoder) Decode(subject string, data []byte, vPtr any) (err error) {
45 switch arg := vPtr.(type) {
46 case *string:
47 // If they want a string and it is a JSON string, strip quotes
48 // This allows someone to send a struct but receive as a plain string
49 // This cast should be efficient for Go 1.3 and beyond.
50 str := string(data)
51 if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) {
52 *arg = str[1 : len(str)-1]
53 } else {
54 *arg = str
55 }
56 case *[]byte:
57 *arg = data
58 default:
59 err = json.Unmarshal(data, arg)
60 }
61 return
62 }