-
Notifications
You must be signed in to change notification settings - Fork 26
/
http_consensus_maps.go
93 lines (73 loc) · 1.67 KB
/
http_consensus_maps.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
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
package util
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"sort"
"strings"
)
var ErrNilHttpConsensusMaps = errors.New("nil_httpconsensusmaps")
type HttpConsensusMaps struct {
ConsensusThresh int
MaxConsensus int
WinMap map[string]json.RawMessage
WinMapConsensus map[string]int
WinError string
WinInfo string
}
func NewHttpConsensusMaps(consensusThresh int) *HttpConsensusMaps {
return &HttpConsensusMaps{
ConsensusThresh: consensusThresh,
WinMapConsensus: make(map[string]int),
}
}
func (c *HttpConsensusMaps) GetValue(name string) (json.RawMessage, bool) {
if c == nil || c.WinMap == nil {
return nil, false
}
v, ok := c.WinMap[name]
return v, ok
}
func (c *HttpConsensusMaps) Add(statusCode int, respBody string) error {
if c == nil {
return ErrNilHttpConsensusMaps
}
if statusCode != http.StatusOK {
c.WinError = respBody
return nil
}
m, hash, err := c.buildMap(respBody)
if err != nil {
return err
}
c.WinMapConsensus[hash]++
if c.WinMapConsensus[hash] > c.MaxConsensus {
c.MaxConsensus = c.WinMapConsensus[hash]
c.WinMap = m
c.WinInfo = respBody
}
return nil
}
func (c *HttpConsensusMaps) buildMap(respBody string) (map[string]json.RawMessage, string, error) {
var m map[string]json.RawMessage
err := json.Unmarshal([]byte(respBody), &m)
if err != nil {
return nil, "", err
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
sb := strings.Builder{}
for _, k := range keys {
sb.Write(m[k])
sb.WriteString(":")
}
h := sha1.New()
h.Write([]byte(sb.String()))
hash := h.Sum(nil)
return m, hex.EncodeToString(hash), nil
}