-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathutil.go
More file actions
103 lines (84 loc) · 2.21 KB
/
Copy pathutil.go
File metadata and controls
103 lines (84 loc) · 2.21 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"fmt"
"net/url"
"strings"
"encoding/json"
)
type BoolHolder struct {
Value bool
}
func (b *BoolHolder) MarshalBinary() ([]byte, error) {
return json.Marshal(b)
}
func (b *BoolHolder) UnmarshalBinaryData(data []byte) (newdata []byte, err error) {
err = json.Unmarshal(data, b)
return
}
func (b *BoolHolder) UnmarshalBinary(data []byte) (err error) {
_, err = b.UnmarshalBinaryData(data)
return
}
func MarshalStringToBytes(str string, maxlength int) ([]byte, error) {
if len(str) > maxlength {
return nil, fmt.Errorf("Length of string is too long, found length is %d, max length is %d",
len(str), maxlength)
}
data := []byte(str)
for i := 0; i < len(data); i++ {
if data[i] == 0x00 {
// Naughty, Naughty, Naughty
data[i] = 0x01
}
}
data = append(data, 0x00)
return data, nil
}
func UnmarshalStringFromBytes(data []byte, maxlength int) (resp string, err error) {
resp, _, err = UnmarshalStringFromBytesData(data, maxlength)
return
}
func UnmarshalStringFromBytesData(data []byte, maxlength int) (resp string, newData []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("A panic has occurred while unmarshaling: %s", r)
return
}
}()
newData = data
end := -1
if len(data)-1 < maxlength {
maxlength = len(data) - 1
}
for i := 0; i <= maxlength; i++ {
if newData[i] == 0x00 {
// found null terminator
end = i
break
}
}
if end == -1 {
err = fmt.Errorf("Could not find a 0x00 byte before max length + 1")
return
}
resp = string(newData[:end])
newData = newData[end+1:]
return
}
// SanitizeFactomdLocation sanitizes user input for the factdom endpoint
// Accepts any string and attempts to parse scheme, host, port, and path
// returns a well-formated URL of scheme://host[:port][/path], removing
// any trailing slash
func SanitizeFactomdLocation(input string) (string, error) {
if strings.Index(input, "://") == -1 {
input = "http://" + input
}
parsed, err := url.Parse(input)
if err != nil {
return "", err
}
if len(parsed.Path) > 0 && parsed.Path[len(parsed.Path)-1:] == "/" {
parsed.Path = parsed.Path[0 : len(parsed.Path)-1]
}
return fmt.Sprintf("%s://%s%s", parsed.Scheme, parsed.Host, parsed.Path), nil
}