-
Notifications
You must be signed in to change notification settings - Fork 672
/
codec.go
65 lines (54 loc) · 1.68 KB
/
codec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package json
import (
"errors"
"fmt"
"net/http"
"strings"
"unicode"
"unicode/utf8"
"github.com/gorilla/rpc/v2"
"github.com/gorilla/rpc/v2/json2"
)
const (
// Null is the string representation of a null value
Null = "null"
)
var (
errUppercaseMethod = errors.New("method must start with a non-uppercase letter")
errInvalidArg = errors.New("couldn't unmarshal an argument. Ensure arguments are valid and properly formatted. See documentation for example calls")
)
// NewCodec returns a new json codec that will convert the first character of
// the method to uppercase
func NewCodec() rpc.Codec {
return lowercase{json2.NewCodec()}
}
type lowercase struct{ *json2.Codec }
func (lc lowercase) NewRequest(r *http.Request) rpc.CodecRequest {
return &request{lc.Codec.NewRequest(r).(*json2.CodecRequest)}
}
type request struct{ *json2.CodecRequest }
func (r *request) Method() (string, error) {
method, err := r.CodecRequest.Method()
methodSections := strings.SplitN(method, ".", 2)
if len(methodSections) != 2 || err != nil {
return method, err
}
class, function := methodSections[0], methodSections[1]
firstRune, runeLen := utf8.DecodeRuneInString(function)
if firstRune == utf8.RuneError {
return method, nil
}
if unicode.IsUpper(firstRune) {
return method, errUppercaseMethod
}
uppercaseRune := string(unicode.ToUpper(firstRune))
return fmt.Sprintf("%s.%s%s", class, uppercaseRune, function[runeLen:]), nil
}
func (r *request) ReadRequest(args interface{}) error {
if err := r.CodecRequest.ReadRequest(args); err != nil {
return errInvalidArg
}
return nil
}