Browse Source

add log hooks

whao 5 years ago
parent
commit
20997d1909
100 changed files with 22166 additions and 1 deletions
  1. 6
    0
      log/go.mod
  2. 20
    0
      log/go.sum
  3. 141
    0
      log/hooks/client.go
  4. 102
    0
      log/hooks/notification.go
  5. 14
    1
      log/logger.go
  6. 26
    0
      log/vendor/github.com/gin-contrib/sse/.travis.yml
  7. 21
    0
      log/vendor/github.com/gin-contrib/sse/LICENSE
  8. 58
    0
      log/vendor/github.com/gin-contrib/sse/README.md
  9. 116
    0
      log/vendor/github.com/gin-contrib/sse/sse-decoder.go
  10. 110
    0
      log/vendor/github.com/gin-contrib/sse/sse-encoder.go
  11. 24
    0
      log/vendor/github.com/gin-contrib/sse/writer.go
  12. 5
    0
      log/vendor/github.com/gin-gonic/gin/.gitignore
  13. 35
    0
      log/vendor/github.com/gin-gonic/gin/.travis.yml
  14. 231
    0
      log/vendor/github.com/gin-gonic/gin/AUTHORS.md
  15. 604
    0
      log/vendor/github.com/gin-gonic/gin/BENCHMARKS.md
  16. 213
    0
      log/vendor/github.com/gin-gonic/gin/CHANGELOG.md
  17. 46
    0
      log/vendor/github.com/gin-gonic/gin/CODE_OF_CONDUCT.md
  18. 13
    0
      log/vendor/github.com/gin-gonic/gin/CONTRIBUTING.md
  19. 21
    0
      log/vendor/github.com/gin-gonic/gin/LICENSE
  20. 62
    0
      log/vendor/github.com/gin-gonic/gin/Makefile
  21. 1820
    0
      log/vendor/github.com/gin-gonic/gin/README.md
  22. 96
    0
      log/vendor/github.com/gin-gonic/gin/auth.go
  23. 99
    0
      log/vendor/github.com/gin-gonic/gin/binding/binding.go
  24. 51
    0
      log/vendor/github.com/gin-gonic/gin/binding/default_validator.go
  25. 56
    0
      log/vendor/github.com/gin-gonic/gin/binding/form.go
  26. 209
    0
      log/vendor/github.com/gin-gonic/gin/binding/form_mapping.go
  27. 43
    0
      log/vendor/github.com/gin-gonic/gin/binding/json.go
  28. 35
    0
      log/vendor/github.com/gin-gonic/gin/binding/msgpack.go
  29. 36
    0
      log/vendor/github.com/gin-gonic/gin/binding/protobuf.go
  30. 21
    0
      log/vendor/github.com/gin-gonic/gin/binding/query.go
  31. 33
    0
      log/vendor/github.com/gin-gonic/gin/binding/xml.go
  32. 5
    0
      log/vendor/github.com/gin-gonic/gin/codecov.yml
  33. 933
    0
      log/vendor/github.com/gin-gonic/gin/context.go
  34. 11
    0
      log/vendor/github.com/gin-gonic/gin/context_appengine.go
  35. 13
    0
      log/vendor/github.com/gin-gonic/gin/coverage.sh
  36. 80
    0
      log/vendor/github.com/gin-gonic/gin/debug.go
  37. 21
    0
      log/vendor/github.com/gin-gonic/gin/deprecated.go
  38. 6
    0
      log/vendor/github.com/gin-gonic/gin/doc.go
  39. 157
    0
      log/vendor/github.com/gin-gonic/gin/errors.go
  40. 45
    0
      log/vendor/github.com/gin-gonic/gin/fs.go
  41. 443
    0
      log/vendor/github.com/gin-gonic/gin/gin.go
  42. 15
    0
      log/vendor/github.com/gin-gonic/gin/json/json.go
  43. 16
    0
      log/vendor/github.com/gin-gonic/gin/json/jsoniter.go
  44. 152
    0
      log/vendor/github.com/gin-gonic/gin/logger.go
  45. 72
    0
      log/vendor/github.com/gin-gonic/gin/mode.go
  46. 123
    0
      log/vendor/github.com/gin-gonic/gin/path.go
  47. 116
    0
      log/vendor/github.com/gin-gonic/gin/recovery.go
  48. 23
    0
      log/vendor/github.com/gin-gonic/gin/render/data.go
  49. 80
    0
      log/vendor/github.com/gin-gonic/gin/render/html.go
  50. 146
    0
      log/vendor/github.com/gin-gonic/gin/render/json.go
  51. 31
    0
      log/vendor/github.com/gin-gonic/gin/render/msgpack.go
  52. 36
    0
      log/vendor/github.com/gin-gonic/gin/render/reader.go
  53. 28
    0
      log/vendor/github.com/gin-gonic/gin/render/redirect.go
  54. 37
    0
      log/vendor/github.com/gin-gonic/gin/render/render.go
  55. 36
    0
      log/vendor/github.com/gin-gonic/gin/render/text.go
  56. 25
    0
      log/vendor/github.com/gin-gonic/gin/render/xml.go
  57. 33
    0
      log/vendor/github.com/gin-gonic/gin/render/yaml.go
  58. 115
    0
      log/vendor/github.com/gin-gonic/gin/response_writer.go
  59. 12
    0
      log/vendor/github.com/gin-gonic/gin/response_writer_1.7.go
  60. 25
    0
      log/vendor/github.com/gin-gonic/gin/response_writer_1.8.go
  61. 213
    0
      log/vendor/github.com/gin-gonic/gin/routergroup.go
  62. 16
    0
      log/vendor/github.com/gin-gonic/gin/test_helpers.go
  63. 620
    0
      log/vendor/github.com/gin-gonic/gin/tree.go
  64. 151
    0
      log/vendor/github.com/gin-gonic/gin/utils.go
  65. 1
    0
      log/vendor/github.com/gin-gonic/gin/wercker.yml
  66. 3
    0
      log/vendor/github.com/golang/protobuf/AUTHORS
  67. 3
    0
      log/vendor/github.com/golang/protobuf/CONTRIBUTORS
  68. 28
    0
      log/vendor/github.com/golang/protobuf/LICENSE
  69. 253
    0
      log/vendor/github.com/golang/protobuf/proto/clone.go
  70. 427
    0
      log/vendor/github.com/golang/protobuf/proto/decode.go
  71. 63
    0
      log/vendor/github.com/golang/protobuf/proto/deprecated.go
  72. 350
    0
      log/vendor/github.com/golang/protobuf/proto/discard.go
  73. 203
    0
      log/vendor/github.com/golang/protobuf/proto/encode.go
  74. 301
    0
      log/vendor/github.com/golang/protobuf/proto/equal.go
  75. 607
    0
      log/vendor/github.com/golang/protobuf/proto/extensions.go
  76. 965
    0
      log/vendor/github.com/golang/protobuf/proto/lib.go
  77. 181
    0
      log/vendor/github.com/golang/protobuf/proto/message_set.go
  78. 360
    0
      log/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
  79. 313
    0
      log/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
  80. 545
    0
      log/vendor/github.com/golang/protobuf/proto/properties.go
  81. 2776
    0
      log/vendor/github.com/golang/protobuf/proto/table_marshal.go
  82. 654
    0
      log/vendor/github.com/golang/protobuf/proto/table_merge.go
  83. 2053
    0
      log/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
  84. 843
    0
      log/vendor/github.com/golang/protobuf/proto/text.go
  85. 880
    0
      log/vendor/github.com/golang/protobuf/proto/text_parser.go
  86. 25
    0
      log/vendor/github.com/gorilla/websocket/.gitignore
  87. 19
    0
      log/vendor/github.com/gorilla/websocket/.travis.yml
  88. 8
    0
      log/vendor/github.com/gorilla/websocket/AUTHORS
  89. 22
    0
      log/vendor/github.com/gorilla/websocket/LICENSE
  90. 64
    0
      log/vendor/github.com/gorilla/websocket/README.md
  91. 392
    0
      log/vendor/github.com/gorilla/websocket/client.go
  92. 16
    0
      log/vendor/github.com/gorilla/websocket/client_clone.go
  93. 38
    0
      log/vendor/github.com/gorilla/websocket/client_clone_legacy.go
  94. 148
    0
      log/vendor/github.com/gorilla/websocket/compression.go
  95. 1149
    0
      log/vendor/github.com/gorilla/websocket/conn.go
  96. 18
    0
      log/vendor/github.com/gorilla/websocket/conn_read.go
  97. 21
    0
      log/vendor/github.com/gorilla/websocket/conn_read_legacy.go
  98. 180
    0
      log/vendor/github.com/gorilla/websocket/doc.go
  99. 55
    0
      log/vendor/github.com/gorilla/websocket/json.go
  100. 0
    0
      log/vendor/github.com/gorilla/websocket/mask.go

+ 6
- 0
log/go.mod View File

@@ -6,9 +6,15 @@ require (
6 6
 	github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3 // indirect
7 7
 	github.com/gin-gonic/gin v1.3.0
8 8
 	github.com/golang/protobuf v1.3.0 // indirect
9
+	github.com/json-iterator/go v1.1.5 // indirect
9 10
 	github.com/mattn/go-isatty v0.0.6 // indirect
11
+	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
12
+	github.com/modern-go/reflect2 v1.0.1 // indirect
10 13
 	github.com/sirupsen/logrus v1.3.0
11 14
 	github.com/ugorji/go/codec v0.0.0-20190204201341-e444a5086c43 // indirect
15
+	github.com/wpajqz/go-sdk v0.0.0-20180819022515-c5611acbd333
16
+	gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect
17
+	gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect
12 18
 	gopkg.in/go-playground/validator.v8 v8.18.2 // indirect
13 19
 	gopkg.in/yaml.v2 v2.2.2 // indirect
14 20
 )

+ 20
- 0
log/go.sum View File

@@ -1,13 +1,24 @@
1
+git.links123.net/links123.com/pkg v0.0.0-20190305161421-f7760ca72e73 h1:louYKnJtqtbqG353upoVwSNZxFPlIEKzFi+KoKtXW+I=
1 2
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2 3
 github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3 h1:t8FVkw33L+wilf2QiWkw0UV77qRpcH/JHPKGpKa2E8g=
3 4
 github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s=
4 5
 github.com/gin-gonic/gin v1.3.0 h1:kCmZyPklC0gVdL728E6Aj20uYBJV93nj/TkwBTKhFbs=
5 6
 github.com/gin-gonic/gin v1.3.0/go.mod h1:7cKuhb5qV2ggCFctp2fJQ+ErvciLZrIeoOSOm6mUr7Y=
7
+github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
6 8
 github.com/golang/protobuf v1.3.0 h1:kbxbvI4Un1LUWKxufD+BiE6AEExYYgkQLQmLFqA1LFk=
7 9
 github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0=
10
+github.com/gorilla/websocket v1.2.0 h1:VJtLvh6VQym50czpZzx07z/kw9EgAxI3x1ZB8taTMQQ=
11
+github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
12
+github.com/json-iterator/go v1.1.5 h1:gL2yXlmiIo4+t+y32d4WGwOjKGYcGOuyrg46vadswDE=
13
+github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
14
+github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
8 15
 github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
9 16
 github.com/mattn/go-isatty v0.0.6 h1:SrwhHcpV4nWrMGdNcC2kXpMfcBVYGDuTArqyhocJgvA=
10 17
 github.com/mattn/go-isatty v0.0.6/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
18
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
19
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
20
+github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
21
+github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
11 22
 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
12 23
 github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME=
13 24
 github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
@@ -17,6 +28,11 @@ github.com/ugorji/go v1.1.2 h1:JON3E2/GPW2iDNGoSAusl1KDf5TRQ8k8q7Tp097pZGs=
17 28
 github.com/ugorji/go v1.1.2/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ=
18 29
 github.com/ugorji/go/codec v0.0.0-20190204201341-e444a5086c43 h1:BasDe+IErOQKrMVXab7UayvSlIpiyGwRvuX3EKYY7UA=
19 30
 github.com/ugorji/go/codec v0.0.0-20190204201341-e444a5086c43/go.mod h1:iT03XoTwV7xq/+UGwKO3UbC1nNNlopQiY61beSdrtOA=
31
+github.com/wpajqz/go-sdk v0.0.0-20180819022515-c5611acbd333 h1:uIekph2ww/ZvE3w3kC36LdwIjfGj3enaf1SNWEh04oQ=
32
+github.com/wpajqz/go-sdk v0.0.0-20180819022515-c5611acbd333/go.mod h1:8Z5OwaDGrREAqXYMHp9WVhDIkZdeJFfNbUyjYQGRg8U=
33
+github.com/wpajqz/linker v0.0.0-20180818151004-5d64412a1130 h1:Ag6S5CgRpXz7sB8oRT98hWrPBvBGTM2Dv5dPD7wFdgc=
34
+github.com/wpajqz/linker v0.0.0-20180818151004-5d64412a1130/go.mod h1:1LpNSex7lqvQi8t5uj9LBLKsvxfm3HK2j6o5Ht3BGmQ=
35
+golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 h1:u+LnwYTOOW7Ukr/fppxEb1Nwz0AtPflrblfvUudpo+I=
20 36
 golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
21 37
 golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
22 38
 golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -24,7 +40,11 @@ golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5h
24 40
 golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
25 41
 golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
26 42
 google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
43
+gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo=
44
+gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U=
27 45
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
46
+gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNjB2u4i700xBkIT4e0=
47
+gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo=
28 48
 gopkg.in/go-playground/validator.v8 v8.18.2 h1:lFB4DoMU6B626w8ny76MV7VX6W2VHct2GVOI3xgiMrQ=
29 49
 gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y=
30 50
 gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=

+ 141
- 0
log/hooks/client.go View File

@@ -0,0 +1,141 @@
1
+package hooks
2
+
3
+import (
4
+	"context"
5
+	"encoding/json"
6
+	"errors"
7
+	"sync"
8
+	"time"
9
+
10
+	"github.com/sirupsen/logrus"
11
+	"github.com/wpajqz/go-sdk/export"
12
+)
13
+
14
+const (
15
+	timeout       = 5 * time.Second
16
+	retryInterval = 100 * time.Microsecond
17
+)
18
+
19
+const (
20
+	notifyPath = "/v1/notify"
21
+)
22
+
23
+var (
24
+	defaultClient *Client
25
+	once          = &sync.Once{}
26
+)
27
+
28
+type Client struct{ tcpClient *export.Client }
29
+
30
+func (c *Client) Notify(req *NotifyRequest) (*NotifyResponse, error) {
31
+	if err := req.Check(); err != nil {
32
+		return nil, err
33
+	}
34
+	param, err := json.Marshal(req)
35
+	if err != nil {
36
+		return nil, err
37
+	}
38
+
39
+	var resp NotifyResponse
40
+
41
+	err = c.tcpClient.SyncSend(notifyPath, param, &RequestStatusCallback{
42
+		Success: func(header, body []byte) {
43
+			err = json.Unmarshal(body, &resp)
44
+		},
45
+		Error: func(code int, message string) {
46
+			err = errors.New(message)
47
+		},
48
+	})
49
+	if err != nil {
50
+		return nil, err
51
+	}
52
+
53
+	return &resp, err
54
+}
55
+
56
+func NewClient(server string, port int) *Client {
57
+	once.Do(func() {
58
+		defaultClient = &Client{tcpClient: export.NewClient(server, port, &ReadyStateCallback{})}
59
+
60
+		ctx, cancel := context.WithTimeout(context.Background(), timeout)
61
+		defer cancel()
62
+
63
+		for {
64
+			select {
65
+			case <-time.After(retryInterval):
66
+				if defaultClient.tcpClient.GetReadyState() == export.OPEN {
67
+					return
68
+				}
69
+			case <-ctx.Done():
70
+				panic("connect link timeout ...")
71
+			}
72
+		}
73
+	})
74
+
75
+	return defaultClient
76
+}
77
+
78
+func GetClient() *Client {
79
+	return defaultClient
80
+}
81
+
82
+type (
83
+	NotifyRequest struct {
84
+		Project     string   `json:"project"`
85
+		Maintainers []string `json:"maintainers"`
86
+		Message     string   `json:"message"`
87
+		Time        string   `json:"time"`
88
+	}
89
+	NotifyResponse struct {
90
+	}
91
+)
92
+
93
+func (ar *NotifyRequest) Check() error {
94
+	return nil
95
+}
96
+
97
+type (
98
+	ReadyStateCallback    struct{}
99
+	RequestStatusCallback struct {
100
+		Start   func()
101
+		End     func()
102
+		Success func(header, body []byte)
103
+		Error   func(code int, message string)
104
+	}
105
+)
106
+
107
+func (readyStateCallback *ReadyStateCallback) OnOpen() {
108
+	logrus.Info("open link socket connection")
109
+}
110
+
111
+func (readyStateCallback *ReadyStateCallback) OnClose() {
112
+	logrus.Info("close link socket connection")
113
+}
114
+
115
+func (readyStateCallback *ReadyStateCallback) OnError(err string) {
116
+	logrus.Infof("error:%s", err)
117
+}
118
+
119
+func (r RequestStatusCallback) OnStart() {
120
+	if r.Start != nil {
121
+		r.Start()
122
+	}
123
+}
124
+
125
+func (r RequestStatusCallback) OnSuccess(header, body []byte) {
126
+	if r.Success != nil {
127
+		r.Success(header, body)
128
+	}
129
+}
130
+
131
+func (r RequestStatusCallback) OnError(code int, message string) {
132
+	if r.Error != nil {
133
+		r.Error(code, message)
134
+	}
135
+}
136
+
137
+func (r RequestStatusCallback) OnEnd() {
138
+	if r.End != nil {
139
+		r.End()
140
+	}
141
+}

+ 102
- 0
log/hooks/notification.go View File

@@ -0,0 +1,102 @@
1
+package hooks
2
+
3
+import (
4
+	"fmt"
5
+
6
+	"github.com/sirupsen/logrus"
7
+)
8
+
9
+var linkClient *Client
10
+
11
+type NotificationHook struct {
12
+	Project     *Project
13
+	Maintainers []*Maintainer
14
+	NS          *NotificationService
15
+}
16
+
17
+type Project struct {
18
+	Name   string
19
+	Domain string
20
+}
21
+
22
+type Maintainer struct {
23
+	Name  string
24
+	Email string
25
+}
26
+
27
+type NotificationService struct {
28
+	Addr string
29
+	Port int
30
+}
31
+
32
+func DefaultMaintainers() []*Maintainer {
33
+	return []*Maintainer{
34
+		{
35
+			Name:  "Paul",
36
+			Email: "paul@links123.com",
37
+		},
38
+		{
39
+			Name:  "Adam",
40
+			Email: "adam@links123.com",
41
+		},
42
+		{
43
+			Name:  "Whao",
44
+			Email: "whao@links123.com",
45
+		},
46
+		{
47
+			Name:  "Slate",
48
+			Email: "slate@links123.com",
49
+		},
50
+	}
51
+}
52
+
53
+func DefaultNotificationService() *NotificationService {
54
+	return &NotificationService{
55
+		Addr: "127.0.0.1",
56
+		Port: 8085,
57
+	}
58
+}
59
+
60
+func (nh *NotificationHook) Fire(entry *logrus.Entry) error {
61
+	return notify(nh, entry)
62
+}
63
+
64
+func (nh *NotificationHook) Levels() []logrus.Level {
65
+	return []logrus.Level{
66
+		logrus.ErrorLevel,
67
+		logrus.FatalLevel,
68
+		logrus.PanicLevel,
69
+	}
70
+}
71
+
72
+func NewNotificationHook(project *Project, maintainers []*Maintainer, ns *NotificationService) (*NotificationHook, error) {
73
+	if project == nil {
74
+		return nil, fmt.Errorf("project is required")
75
+	}
76
+	if maintainers == nil {
77
+		return nil, fmt.Errorf("maintainers muest not be blank")
78
+	}
79
+	if ns == nil {
80
+		return nil, fmt.Errorf("notification service is required")
81
+	}
82
+
83
+	if linkClient == nil {
84
+		linkClient = NewClient(ns.Addr, ns.Port)
85
+	}
86
+
87
+	return &NotificationHook{Project: project, Maintainers: maintainers, NS: ns}, nil
88
+}
89
+
90
+func notify(nh *NotificationHook, entry *logrus.Entry) error {
91
+	var emails []string
92
+	for _, m := range nh.Maintainers {
93
+		emails = append(emails, m.Email)
94
+	}
95
+	_, err := defaultClient.Notify(&NotifyRequest{
96
+		Project:     nh.Project.Name,
97
+		Maintainers: emails,
98
+		Message:     entry.Message,
99
+		Time:        entry.Time.Format("2006-02-01 15:04:05"),
100
+	})
101
+	return err
102
+}

+ 14
- 1
log/logger.go View File

@@ -1,13 +1,24 @@
1 1
 package log
2 2
 
3 3
 import (
4
+	"git.links123.net/links123.com/pkg/log/hooks"
4 5
 	"github.com/gin-gonic/gin"
5 6
 	"github.com/sirupsen/logrus"
6 7
 )
7 8
 
8 9
 var logger *logrus.Logger
9 10
 
10
-func init() {
11
+func NewDefaultLogger(project *hooks.Project) error {
12
+	return NewLogger(project, hooks.DefaultMaintainers(), hooks.DefaultNotificationService())
13
+}
14
+
15
+func NewLogger(project *hooks.Project, maintainers []*hooks.Maintainer, ns *hooks.NotificationService) error {
16
+	notificationHook, err := hooks.NewNotificationHook(project, maintainers, ns)
17
+	if err != nil {
18
+		return err
19
+	}
20
+
21
+	logrus.AddHook(notificationHook)
11 22
 	logger = logrus.New()
12 23
 
13 24
 	switch gin.Mode() {
@@ -18,4 +29,6 @@ func init() {
18 29
 	default:
19 30
 		panic("unsupported running mode")
20 31
 	}
32
+
33
+	return nil
21 34
 }

+ 26
- 0
log/vendor/github.com/gin-contrib/sse/.travis.yml View File

@@ -0,0 +1,26 @@
1
+language: go
2
+sudo: false
3
+go:
4
+  - 1.8.x
5
+  - 1.9.x
6
+  - 1.10.x
7
+  - 1.11.x
8
+  - 1.12.x
9
+  - master
10
+
11
+git:
12
+  depth: 10
13
+
14
+matrix:
15
+  fast_finish: true
16
+  include:
17
+  - go: 1.11.x
18
+    env: GO111MODULE=on
19
+  - go: 1.12.x
20
+    env: GO111MODULE=on
21
+
22
+script:
23
+  - go test -v -covermode=count -coverprofile=coverage.out
24
+
25
+after_success:
26
+  - bash <(curl -s https://codecov.io/bash)

+ 21
- 0
log/vendor/github.com/gin-contrib/sse/LICENSE View File

@@ -0,0 +1,21 @@
1
+The MIT License (MIT)
2
+
3
+Copyright (c) 2014 Manuel Martínez-Almeida
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in
13
+all copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+THE SOFTWARE.

+ 58
- 0
log/vendor/github.com/gin-contrib/sse/README.md View File

@@ -0,0 +1,58 @@
1
+# Server-Sent Events
2
+
3
+[![GoDoc](https://godoc.org/github.com/gin-contrib/sse?status.svg)](https://godoc.org/github.com/gin-contrib/sse)
4
+[![Build Status](https://travis-ci.org/gin-contrib/sse.svg)](https://travis-ci.org/gin-contrib/sse)
5
+[![codecov](https://codecov.io/gh/gin-contrib/sse/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-contrib/sse)
6
+[![Go Report Card](https://goreportcard.com/badge/github.com/gin-contrib/sse)](https://goreportcard.com/report/github.com/gin-contrib/sse)
7
+
8
+Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is [standardized as part of HTML5[1] by the W3C](http://www.w3.org/TR/2009/WD-eventsource-20091029/).
9
+
10
+- [Read this great SSE introduction by the HTML5Rocks guys](http://www.html5rocks.com/en/tutorials/eventsource/basics/)
11
+- [Browser support](http://caniuse.com/#feat=eventsource)
12
+
13
+## Sample code
14
+
15
+```go
16
+import "github.com/gin-contrib/sse"
17
+
18
+func httpHandler(w http.ResponseWriter, req *http.Request) {
19
+	// data can be a primitive like a string, an integer or a float
20
+	sse.Encode(w, sse.Event{
21
+		Event: "message",
22
+		Data:  "some data\nmore data",
23
+	})
24
+
25
+	// also a complex type, like a map, a struct or a slice
26
+	sse.Encode(w, sse.Event{
27
+		Id:    "124",
28
+		Event: "message",
29
+		Data: map[string]interface{}{
30
+			"user":    "manu",
31
+			"date":    time.Now().Unix(),
32
+			"content": "hi!",
33
+		},
34
+	})
35
+}
36
+```
37
+```
38
+event: message
39
+data: some data\\nmore data
40
+
41
+id: 124
42
+event: message
43
+data: {"content":"hi!","date":1431540810,"user":"manu"}
44
+ 
45
+```
46
+
47
+## Content-Type
48
+
49
+```go
50
+fmt.Println(sse.ContentType)
51
+```
52
+```
53
+text/event-stream
54
+```
55
+
56
+## Decoding support
57
+
58
+There is a client-side implementation of SSE coming soon.

+ 116
- 0
log/vendor/github.com/gin-contrib/sse/sse-decoder.go View File

@@ -0,0 +1,116 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package sse
6
+
7
+import (
8
+	"bytes"
9
+	"io"
10
+	"io/ioutil"
11
+)
12
+
13
+type decoder struct {
14
+	events []Event
15
+}
16
+
17
+func Decode(r io.Reader) ([]Event, error) {
18
+	var dec decoder
19
+	return dec.decode(r)
20
+}
21
+
22
+func (d *decoder) dispatchEvent(event Event, data string) {
23
+	dataLength := len(data)
24
+	if dataLength > 0 {
25
+		//If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
26
+		data = data[:dataLength-1]
27
+		dataLength--
28
+	}
29
+	if dataLength == 0 && event.Event == "" {
30
+		return
31
+	}
32
+	if event.Event == "" {
33
+		event.Event = "message"
34
+	}
35
+	event.Data = data
36
+	d.events = append(d.events, event)
37
+}
38
+
39
+func (d *decoder) decode(r io.Reader) ([]Event, error) {
40
+	buf, err := ioutil.ReadAll(r)
41
+	if err != nil {
42
+		return nil, err
43
+	}
44
+
45
+	var currentEvent Event
46
+	var dataBuffer *bytes.Buffer = new(bytes.Buffer)
47
+	// TODO (and unit tests)
48
+	// Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair,
49
+	// a single U+000A LINE FEED (LF) character,
50
+	// or a single U+000D CARRIAGE RETURN (CR) character.
51
+	lines := bytes.Split(buf, []byte{'\n'})
52
+	for _, line := range lines {
53
+		if len(line) == 0 {
54
+			// If the line is empty (a blank line). Dispatch the event.
55
+			d.dispatchEvent(currentEvent, dataBuffer.String())
56
+
57
+			// reset current event and data buffer
58
+			currentEvent = Event{}
59
+			dataBuffer.Reset()
60
+			continue
61
+		}
62
+		if line[0] == byte(':') {
63
+			// If the line starts with a U+003A COLON character (:), ignore the line.
64
+			continue
65
+		}
66
+
67
+		var field, value []byte
68
+		colonIndex := bytes.IndexRune(line, ':')
69
+		if colonIndex != -1 {
70
+			// If the line contains a U+003A COLON character character (:)
71
+			// Collect the characters on the line before the first U+003A COLON character (:),
72
+			// and let field be that string.
73
+			field = line[:colonIndex]
74
+			// Collect the characters on the line after the first U+003A COLON character (:),
75
+			// and let value be that string.
76
+			value = line[colonIndex+1:]
77
+			// If value starts with a single U+0020 SPACE character, remove it from value.
78
+			if len(value) > 0 && value[0] == ' ' {
79
+				value = value[1:]
80
+			}
81
+		} else {
82
+			// Otherwise, the string is not empty but does not contain a U+003A COLON character character (:)
83
+			// Use the whole line as the field name, and the empty string as the field value.
84
+			field = line
85
+			value = []byte{}
86
+		}
87
+		// The steps to process the field given a field name and a field value depend on the field name,
88
+		// as given in the following list. Field names must be compared literally,
89
+		// with no case folding performed.
90
+		switch string(field) {
91
+		case "event":
92
+			// Set the event name buffer to field value.
93
+			currentEvent.Event = string(value)
94
+		case "id":
95
+			// Set the event stream's last event ID to the field value.
96
+			currentEvent.Id = string(value)
97
+		case "retry":
98
+			// If the field value consists of only characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
99
+			// then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer.
100
+			// Otherwise, ignore the field.
101
+			currentEvent.Id = string(value)
102
+		case "data":
103
+			// Append the field value to the data buffer,
104
+			dataBuffer.Write(value)
105
+			// then append a single U+000A LINE FEED (LF) character to the data buffer.
106
+			dataBuffer.WriteString("\n")
107
+		default:
108
+			//Otherwise. The field is ignored.
109
+			continue
110
+		}
111
+	}
112
+	// Once the end of the file is reached, the user agent must dispatch the event one final time.
113
+	d.dispatchEvent(currentEvent, dataBuffer.String())
114
+
115
+	return d.events, nil
116
+}

+ 110
- 0
log/vendor/github.com/gin-contrib/sse/sse-encoder.go View File

@@ -0,0 +1,110 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package sse
6
+
7
+import (
8
+	"encoding/json"
9
+	"fmt"
10
+	"io"
11
+	"net/http"
12
+	"reflect"
13
+	"strconv"
14
+	"strings"
15
+)
16
+
17
+// Server-Sent Events
18
+// W3C Working Draft 29 October 2009
19
+// http://www.w3.org/TR/2009/WD-eventsource-20091029/
20
+
21
+const ContentType = "text/event-stream"
22
+
23
+var contentType = []string{ContentType}
24
+var noCache = []string{"no-cache"}
25
+
26
+var fieldReplacer = strings.NewReplacer(
27
+	"\n", "\\n",
28
+	"\r", "\\r")
29
+
30
+var dataReplacer = strings.NewReplacer(
31
+	"\n", "\ndata:",
32
+	"\r", "\\r")
33
+
34
+type Event struct {
35
+	Event string
36
+	Id    string
37
+	Retry uint
38
+	Data  interface{}
39
+}
40
+
41
+func Encode(writer io.Writer, event Event) error {
42
+	w := checkWriter(writer)
43
+	writeId(w, event.Id)
44
+	writeEvent(w, event.Event)
45
+	writeRetry(w, event.Retry)
46
+	return writeData(w, event.Data)
47
+}
48
+
49
+func writeId(w stringWriter, id string) {
50
+	if len(id) > 0 {
51
+		w.WriteString("id:")
52
+		fieldReplacer.WriteString(w, id)
53
+		w.WriteString("\n")
54
+	}
55
+}
56
+
57
+func writeEvent(w stringWriter, event string) {
58
+	if len(event) > 0 {
59
+		w.WriteString("event:")
60
+		fieldReplacer.WriteString(w, event)
61
+		w.WriteString("\n")
62
+	}
63
+}
64
+
65
+func writeRetry(w stringWriter, retry uint) {
66
+	if retry > 0 {
67
+		w.WriteString("retry:")
68
+		w.WriteString(strconv.FormatUint(uint64(retry), 10))
69
+		w.WriteString("\n")
70
+	}
71
+}
72
+
73
+func writeData(w stringWriter, data interface{}) error {
74
+	w.WriteString("data:")
75
+	switch kindOfData(data) {
76
+	case reflect.Struct, reflect.Slice, reflect.Map:
77
+		err := json.NewEncoder(w).Encode(data)
78
+		if err != nil {
79
+			return err
80
+		}
81
+		w.WriteString("\n")
82
+	default:
83
+		dataReplacer.WriteString(w, fmt.Sprint(data))
84
+		w.WriteString("\n\n")
85
+	}
86
+	return nil
87
+}
88
+
89
+func (r Event) Render(w http.ResponseWriter) error {
90
+	r.WriteContentType(w)
91
+	return Encode(w, r)
92
+}
93
+
94
+func (r Event) WriteContentType(w http.ResponseWriter) {
95
+	header := w.Header()
96
+	header["Content-Type"] = contentType
97
+
98
+	if _, exist := header["Cache-Control"]; !exist {
99
+		header["Cache-Control"] = noCache
100
+	}
101
+}
102
+
103
+func kindOfData(data interface{}) reflect.Kind {
104
+	value := reflect.ValueOf(data)
105
+	valueType := value.Kind()
106
+	if valueType == reflect.Ptr {
107
+		valueType = value.Elem().Kind()
108
+	}
109
+	return valueType
110
+}

+ 24
- 0
log/vendor/github.com/gin-contrib/sse/writer.go View File

@@ -0,0 +1,24 @@
1
+package sse
2
+
3
+import "io"
4
+
5
+type stringWriter interface {
6
+	io.Writer
7
+	WriteString(string) (int, error)
8
+}
9
+
10
+type stringWrapper struct {
11
+	io.Writer
12
+}
13
+
14
+func (w stringWrapper) WriteString(str string) (int, error) {
15
+	return w.Writer.Write([]byte(str))
16
+}
17
+
18
+func checkWriter(writer io.Writer) stringWriter {
19
+	if w, ok := writer.(stringWriter); ok {
20
+		return w
21
+	} else {
22
+		return stringWrapper{writer}
23
+	}
24
+}

+ 5
- 0
log/vendor/github.com/gin-gonic/gin/.gitignore View File

@@ -0,0 +1,5 @@
1
+vendor/*
2
+!vendor/vendor.json
3
+coverage.out
4
+count.out
5
+test

+ 35
- 0
log/vendor/github.com/gin-gonic/gin/.travis.yml View File

@@ -0,0 +1,35 @@
1
+language: go
2
+sudo: false
3
+go:
4
+  - 1.6.x
5
+  - 1.7.x
6
+  - 1.8.x
7
+  - 1.9.x
8
+  - 1.10.x
9
+  - master
10
+
11
+git:
12
+  depth: 10
13
+
14
+install:
15
+  - make install
16
+
17
+go_import_path: github.com/gin-gonic/gin
18
+
19
+script:
20
+  - make vet
21
+  - make fmt-check
22
+  - make embedmd
23
+  - make misspell-check
24
+  - make test
25
+
26
+after_success:
27
+  - bash <(curl -s https://codecov.io/bash)
28
+
29
+notifications:
30
+  webhooks:
31
+    urls:
32
+      - https://webhooks.gitter.im/e/7f95bf605c4d356372f4
33
+    on_success: change  # options: [always|never|change] default: always
34
+    on_failure: always  # options: [always|never|change] default: always
35
+    on_start: false     # default: false

+ 231
- 0
log/vendor/github.com/gin-gonic/gin/AUTHORS.md View File

@@ -0,0 +1,231 @@
1
+List of all the awesome people working to make Gin the best Web Framework in Go.
2
+
3
+## gin 1.x series authors
4
+
5
+**Gin Core Team:** Bo-Yi Wu (@appleboy), 田欧 (@thinkerou), Javier Provecho (@javierprovecho)
6
+
7
+## gin 0.x series authors
8
+
9
+**Maintainers:** Manu Martinez-Almeida (@manucorporat), Javier Provecho (@javierprovecho)
10
+
11
+People and companies, who have contributed, in alphabetical order.
12
+
13
+**@858806258 (杰哥)**
14
+- Fix typo in example
15
+
16
+
17
+**@achedeuzot (Klemen Sever)**
18
+- Fix newline debug printing
19
+
20
+
21
+**@adammck (Adam Mckaig)**
22
+- Add MIT license
23
+
24
+
25
+**@AlexanderChen1989 (Alexander)**
26
+- Typos in README
27
+
28
+
29
+**@alexanderdidenko (Aleksandr Didenko)**
30
+- Add support multipart/form-data
31
+
32
+
33
+**@alexandernyquist (Alexander Nyquist)**
34
+- Using template.Must to fix multiple return issue
35
+- ★ Added support for OPTIONS verb
36
+- ★ Setting response headers before calling WriteHeader
37
+- Improved documentation for model binding
38
+- ★ Added Content.Redirect()
39
+- ★ Added tons of Unit tests
40
+
41
+
42
+**@austinheap (Austin Heap)**
43
+- Added travis CI integration
44
+
45
+
46
+**@andredublin (Andre Dublin)**
47
+- Fix typo in comment
48
+
49
+
50
+**@bredov (Ludwig Valda Vasquez)**
51
+- Fix html templating in debug mode
52
+
53
+
54
+**@bluele (Jun Kimura)**
55
+- Fixes code examples in README
56
+
57
+
58
+**@chad-russell**
59
+- ★ Support for serializing gin.H into XML
60
+
61
+
62
+**@dickeyxxx (Jeff Dickey)**
63
+- Typos in README
64
+- Add example about serving static files
65
+
66
+
67
+**@donileo (Adonis)**
68
+- Add NoMethod handler
69
+
70
+
71
+**@dutchcoders (DutchCoders)**
72
+- ★ Fix security bug that allows client to spoof ip
73
+- Fix typo. r.HTMLTemplates -> SetHTMLTemplate
74
+
75
+
76
+**@el3ctro- (Joshua Loper)**
77
+- Fix typo in example
78
+
79
+
80
+**@ethankan (Ethan Kan)**
81
+- Unsigned integers in binding
82
+
83
+
84
+**(Evgeny Persienko)**
85
+- Validate sub structures
86
+
87
+
88
+**@frankbille (Frank Bille)**
89
+- Add support for HTTP Realm Auth
90
+
91
+
92
+**@fmd (Fareed Dudhia)**
93
+- Fix typo. SetHTTPTemplate -> SetHTMLTemplate
94
+
95
+
96
+**@ironiridis (Christopher Harrington)**
97
+- Remove old reference
98
+
99
+
100
+**@jammie-stackhouse (Jamie Stackhouse)**
101
+- Add more shortcuts for router methods
102
+
103
+
104
+**@jasonrhansen**
105
+- Fix spelling and grammar errors in documentation
106
+
107
+
108
+**@JasonSoft (Jason Lee)**
109
+- Fix typo in comment
110
+
111
+
112
+**@joiggama (Ignacio Galindo)**
113
+- Add utf-8 charset header on renders
114
+
115
+
116
+**@julienschmidt (Julien Schmidt)**
117
+- gofmt the code examples
118
+
119
+
120
+**@kelcecil (Kel Cecil)**
121
+- Fix readme typo
122
+
123
+
124
+**@kyledinh (Kyle Dinh)**
125
+- Adds RunTLS()
126
+
127
+
128
+**@LinusU (Linus Unnebäck)**
129
+- Small fixes in README
130
+
131
+
132
+**@loongmxbt (Saint Asky)**
133
+- Fix typo in example
134
+
135
+
136
+**@lucas-clemente (Lucas Clemente)**
137
+- ★ work around path.Join removing trailing slashes from routes
138
+
139
+
140
+**@mattn (Yasuhiro Matsumoto)**
141
+- Improve color logger
142
+
143
+
144
+**@mdigger (Dmitry Sedykh)**
145
+- Fixes Form binding when content-type is x-www-form-urlencoded
146
+- No repeat call c.Writer.Status() in gin.Logger
147
+- Fixes Content-Type for json render
148
+
149
+
150
+**@mirzac (Mirza Ceric)**
151
+- Fix debug printing
152
+
153
+
154
+**@mopemope (Yutaka Matsubara)**
155
+- ★ Adds Godep support (Dependencies Manager)
156
+- Fix variadic parameter in the flexible render API
157
+- Fix Corrupted plain render
158
+- Add Pluggable View Renderer Example
159
+ 
160
+
161
+**@msemenistyi (Mykyta Semenistyi)**
162
+- update Readme.md. Add code to String method
163
+
164
+
165
+**@msoedov (Sasha Myasoedov)**
166
+- ★ Adds tons of unit tests.
167
+
168
+
169
+**@ngerakines (Nick Gerakines)**
170
+- ★ Improves API, c.GET() doesn't panic
171
+- Adds MustGet() method
172
+
173
+
174
+**@r8k (Rajiv Kilaparti)**
175
+- Fix Port usage in README.
176
+
177
+
178
+**@rayrod2030 (Ray Rodriguez)**
179
+- Fix typo in example
180
+
181
+
182
+**@rns**
183
+- Fix typo in example
184
+
185
+
186
+**@RobAWilkinson (Robert Wilkinson)**
187
+- Add example of forms and params
188
+
189
+
190
+**@rogierlommers (Rogier Lommers)**
191
+- Add updated static serve example
192
+
193
+
194
+**@se77en (Damon Zhao)**
195
+- Improve color logging
196
+
197
+
198
+**@silasb (Silas Baronda)**
199
+- Fixing quotes in README
200
+
201
+
202
+**@SkuliOskarsson (Skuli Oskarsson)**
203
+- Fixes some texts in README II
204
+
205
+
206
+**@slimmy (Jimmy Pettersson)**
207
+- Added messages for required bindings
208
+
209
+
210
+**@smira (Andrey Smirnov)**
211
+- Add support for ignored/unexported fields in binding
212
+
213
+
214
+**@superalsrk (SRK.Lyu)**
215
+- Update httprouter godeps
216
+
217
+
218
+**@tebeka (Miki Tebeka)**
219
+- Use net/http constants instead of numeric values
220
+
221
+
222
+**@techjanitor**
223
+- Update context.go reserved IPs
224
+
225
+
226
+**@yosssi (Keiji Yoshida)**
227
+- Fix link in README
228
+
229
+
230
+**@yuyabee**
231
+- Fixed README

+ 604
- 0
log/vendor/github.com/gin-gonic/gin/BENCHMARKS.md View File

@@ -0,0 +1,604 @@
1
+
2
+## Benchmark System
3
+
4
+**VM HOST:** DigitalOcean  
5
+**Machine:** 4 CPU, 8 GB RAM. Ubuntu 16.04.2 x64  
6
+**Date:** July 19th, 2017  
7
+**Go Version:** 1.8.3 linux/amd64  
8
+**Source:** [Go HTTP Router Benchmark](https://github.com/julienschmidt/go-http-routing-benchmark)  
9
+
10
+## Static Routes: 157
11
+
12
+```
13
+Gin:             30512 Bytes
14
+
15
+HttpServeMux:    17344 Bytes
16
+Ace:             30080 Bytes
17
+Bear:            30472 Bytes
18
+Beego:           96408 Bytes
19
+Bone:            37904 Bytes
20
+Denco:           10464 Bytes
21
+Echo:            73680 Bytes
22
+GocraftWeb:      55720 Bytes
23
+Goji:            27200 Bytes
24
+Gojiv2:         104464 Bytes
25
+GoJsonRest:     136472 Bytes
26
+GoRestful:      914904 Bytes
27
+GorillaMux:     675568 Bytes
28
+HttpRouter:      21128 Bytes
29
+HttpTreeMux:     73448 Bytes
30
+Kocha:          115072 Bytes
31
+LARS:            30120 Bytes
32
+Macaron:         37984 Bytes
33
+Martini:        310832 Bytes
34
+Pat:             20464 Bytes
35
+Possum:          91328 Bytes
36
+R2router:        23712 Bytes
37
+Rivet:           23880 Bytes
38
+Tango:           28008 Bytes
39
+TigerTonic:      80368 Bytes
40
+Traffic:        626480 Bytes
41
+Vulcan:         369064 Bytes
42
+```
43
+
44
+## GithubAPI Routes: 203
45
+
46
+```
47
+Gin:             52672 Bytes
48
+
49
+Ace:             48992 Bytes
50
+Bear:           161592 Bytes
51
+Beego:          147992 Bytes
52
+Bone:            97728 Bytes
53
+Denco:           36440 Bytes
54
+Echo:            95672 Bytes
55
+GocraftWeb:      95640 Bytes
56
+Goji:            86088 Bytes
57
+Gojiv2:         144392 Bytes
58
+GoJsonRest:     134648 Bytes
59
+GoRestful:     1410760 Bytes
60
+GorillaMux:    1509488 Bytes
61
+HttpRouter:      37464 Bytes
62
+HttpTreeMux:     78800 Bytes
63
+Kocha:          785408 Bytes
64
+LARS:            49032 Bytes
65
+Macaron:        132712 Bytes
66
+Martini:        564352 Bytes
67
+Pat:             21200 Bytes
68
+Possum:          83888 Bytes
69
+R2router:        47104 Bytes
70
+Rivet:           42840 Bytes
71
+Tango:           54584 Bytes
72
+TigerTonic:      96384 Bytes
73
+Traffic:       1061920 Bytes
74
+Vulcan:         465296 Bytes
75
+```
76
+
77
+## GPlusAPI Routes: 13
78
+
79
+```
80
+Gin:              3968 Bytes
81
+
82
+Ace:              3600 Bytes
83
+Bear:             7112 Bytes
84
+Beego:           10048 Bytes
85
+Bone:             6480 Bytes
86
+Denco:            3256 Bytes
87
+Echo:             9000 Bytes
88
+GocraftWeb:       7496 Bytes
89
+Goji:             2912 Bytes
90
+Gojiv2:           7376 Bytes
91
+GoJsonRest:      11544 Bytes
92
+GoRestful:       88776 Bytes
93
+GorillaMux:      71488 Bytes
94
+HttpRouter:       2712 Bytes
95
+HttpTreeMux:      7440 Bytes
96
+Kocha:          128880 Bytes
97
+LARS:             3640 Bytes
98
+Macaron:          8656 Bytes
99
+Martini:         23936 Bytes
100
+Pat:              1856 Bytes
101
+Possum:           7248 Bytes
102
+R2router:         3928 Bytes
103
+Rivet:            3064 Bytes
104
+Tango:            4912 Bytes
105
+TigerTonic:       9408 Bytes
106
+Traffic:         49472 Bytes
107
+Vulcan:          25496 Bytes
108
+```
109
+
110
+## ParseAPI Routes: 26
111
+
112
+```
113
+Gin:              6928 Bytes
114
+
115
+Ace:              6592 Bytes
116
+Bear:            12320 Bytes
117
+Beego:           18960 Bytes
118
+Bone:            11024 Bytes
119
+Denco:            4184 Bytes
120
+Echo:            11168 Bytes
121
+GocraftWeb:      12800 Bytes
122
+Goji:             5232 Bytes
123
+Gojiv2:          14464 Bytes
124
+GoJsonRest:      14216 Bytes
125
+GoRestful:      127368 Bytes
126
+GorillaMux:     123016 Bytes
127
+HttpRouter:       4976 Bytes
128
+HttpTreeMux:      7848 Bytes
129
+Kocha:          181712 Bytes
130
+LARS:             6632 Bytes
131
+Macaron:         13648 Bytes
132
+Martini:         45952 Bytes
133
+Pat:              2560 Bytes
134
+Possum:           9200 Bytes
135
+R2router:         7056 Bytes
136
+Rivet:            5680 Bytes
137
+Tango:            8664 Bytes
138
+TigerTonic:       9840 Bytes
139
+Traffic:         93480 Bytes
140
+Vulcan:          44504 Bytes
141
+```
142
+
143
+## Static Routes
144
+
145
+```
146
+BenchmarkGin_StaticAll                     50000             34506 ns/op               0 B/op          0 allocs/op
147
+
148
+BenchmarkAce_StaticAll                     30000             49657 ns/op               0 B/op          0 allocs/op
149
+BenchmarkHttpServeMux_StaticAll             2000           1183737 ns/op              96 B/op          8 allocs/op
150
+BenchmarkBeego_StaticAll                    5000            412621 ns/op           57776 B/op        628 allocs/op
151
+BenchmarkBear_StaticAll                    10000            149242 ns/op           20336 B/op        461 allocs/op
152
+BenchmarkBone_StaticAll                    10000            118583 ns/op               0 B/op          0 allocs/op
153
+BenchmarkDenco_StaticAll                  100000             13247 ns/op               0 B/op          0 allocs/op
154
+BenchmarkEcho_StaticAll                    20000             79914 ns/op            5024 B/op        157 allocs/op
155
+BenchmarkGocraftWeb_StaticAll              10000            211823 ns/op           46440 B/op        785 allocs/op
156
+BenchmarkGoji_StaticAll                    10000            109390 ns/op               0 B/op          0 allocs/op
157
+BenchmarkGojiv2_StaticAll                   3000            415533 ns/op          145696 B/op       1099 allocs/op
158
+BenchmarkGoJsonRest_StaticAll               5000            364403 ns/op           51653 B/op       1727 allocs/op
159
+BenchmarkGoRestful_StaticAll                 500           2578579 ns/op          314936 B/op       3144 allocs/op
160
+BenchmarkGorillaMux_StaticAll                500           2704856 ns/op          115648 B/op       1578 allocs/op
161
+BenchmarkHttpRouter_StaticAll             100000             18541 ns/op               0 B/op          0 allocs/op
162
+BenchmarkHttpTreeMux_StaticAll            100000             22332 ns/op               0 B/op          0 allocs/op
163
+BenchmarkKocha_StaticAll                   50000             31176 ns/op               0 B/op          0 allocs/op
164
+BenchmarkLARS_StaticAll                    50000             40840 ns/op               0 B/op          0 allocs/op
165
+BenchmarkMacaron_StaticAll                  5000            517656 ns/op          120576 B/op       1413 allocs/op
166
+BenchmarkMartini_StaticAll                   300           4462289 ns/op          125442 B/op       1717 allocs/op
167
+BenchmarkPat_StaticAll                       500           2157275 ns/op          533904 B/op      11123 allocs/op
168
+BenchmarkPossum_StaticAll                  10000            254701 ns/op           65312 B/op        471 allocs/op
169
+BenchmarkR2router_StaticAll                10000            133956 ns/op           22608 B/op        628 allocs/op
170
+BenchmarkRivet_StaticAll                   30000             46812 ns/op               0 B/op          0 allocs/op
171
+BenchmarkTango_StaticAll                    5000            390613 ns/op           39225 B/op       1256 allocs/op
172
+BenchmarkTigerTonic_StaticAll              20000             88060 ns/op            7504 B/op        157 allocs/op
173
+BenchmarkTraffic_StaticAll                   500           2910236 ns/op          729736 B/op      14287 allocs/op
174
+BenchmarkVulcan_StaticAll                   5000            277366 ns/op           15386 B/op        471 allocs/op
175
+```
176
+
177
+## Micro Benchmarks
178
+
179
+```
180
+BenchmarkGin_Param                      20000000               113 ns/op               0 B/op          0 allocs/op
181
+
182
+BenchmarkAce_Param                       5000000               375 ns/op              32 B/op          1 allocs/op
183
+BenchmarkBear_Param                      1000000              1709 ns/op             456 B/op          5 allocs/op
184
+BenchmarkBeego_Param                     1000000              2484 ns/op             368 B/op          4 allocs/op
185
+BenchmarkBone_Param                      1000000              2391 ns/op             688 B/op          5 allocs/op
186
+BenchmarkDenco_Param                    10000000               240 ns/op              32 B/op          1 allocs/op
187
+BenchmarkEcho_Param                      5000000               366 ns/op              32 B/op          1 allocs/op
188
+BenchmarkGocraftWeb_Param                1000000              2343 ns/op             648 B/op          8 allocs/op
189
+BenchmarkGoji_Param                      1000000              1197 ns/op             336 B/op          2 allocs/op
190
+BenchmarkGojiv2_Param                    1000000              2771 ns/op             944 B/op          8 allocs/op
191
+BenchmarkGoJsonRest_Param                1000000              2993 ns/op             649 B/op         13 allocs/op
192
+BenchmarkGoRestful_Param                  200000              8860 ns/op            2296 B/op         21 allocs/op
193
+BenchmarkGorillaMux_Param                 500000              4461 ns/op            1056 B/op         11 allocs/op
194
+BenchmarkHttpRouter_Param               10000000               175 ns/op              32 B/op          1 allocs/op
195
+BenchmarkHttpTreeMux_Param               1000000              1167 ns/op             352 B/op          3 allocs/op
196
+BenchmarkKocha_Param                     3000000               429 ns/op              56 B/op          3 allocs/op
197
+BenchmarkLARS_Param                     10000000               134 ns/op               0 B/op          0 allocs/op
198
+BenchmarkMacaron_Param                    500000              4635 ns/op            1056 B/op         10 allocs/op
199
+BenchmarkMartini_Param                    200000              9933 ns/op            1072 B/op         10 allocs/op
200
+BenchmarkPat_Param                       1000000              2929 ns/op             648 B/op         12 allocs/op
201
+BenchmarkPossum_Param                    1000000              2503 ns/op             560 B/op          6 allocs/op
202
+BenchmarkR2router_Param                  1000000              1507 ns/op             432 B/op          5 allocs/op
203
+BenchmarkRivet_Param                     5000000               297 ns/op              48 B/op          1 allocs/op
204
+BenchmarkTango_Param                     1000000              1862 ns/op             248 B/op          8 allocs/op
205
+BenchmarkTigerTonic_Param                 500000              5660 ns/op             992 B/op         17 allocs/op
206
+BenchmarkTraffic_Param                    200000              8408 ns/op            1960 B/op         21 allocs/op
207
+BenchmarkVulcan_Param                    2000000               963 ns/op              98 B/op          3 allocs/op
208
+BenchmarkAce_Param5                      2000000               740 ns/op             160 B/op          1 allocs/op
209
+BenchmarkBear_Param5                     1000000              2777 ns/op             501 B/op          5 allocs/op
210
+BenchmarkBeego_Param5                    1000000              3740 ns/op             368 B/op          4 allocs/op
211
+BenchmarkBone_Param5                     1000000              2950 ns/op             736 B/op          5 allocs/op
212
+BenchmarkDenco_Param5                    2000000               644 ns/op             160 B/op          1 allocs/op
213
+BenchmarkEcho_Param5                     3000000               558 ns/op              32 B/op          1 allocs/op
214
+BenchmarkGin_Param5                     10000000               198 ns/op               0 B/op          0 allocs/op
215
+BenchmarkGocraftWeb_Param5                500000              3870 ns/op             920 B/op         11 allocs/op
216
+BenchmarkGoji_Param5                     1000000              1746 ns/op             336 B/op          2 allocs/op
217
+BenchmarkGojiv2_Param5                   1000000              3214 ns/op            1008 B/op          8 allocs/op
218
+BenchmarkGoJsonRest_Param5                500000              5509 ns/op            1097 B/op         16 allocs/op
219
+BenchmarkGoRestful_Param5                 200000             11232 ns/op            2392 B/op         21 allocs/op
220
+BenchmarkGorillaMux_Param5                300000              7777 ns/op            1184 B/op         11 allocs/op
221
+BenchmarkHttpRouter_Param5               3000000               631 ns/op             160 B/op          1 allocs/op
222
+BenchmarkHttpTreeMux_Param5              1000000              2800 ns/op             576 B/op          6 allocs/op
223
+BenchmarkKocha_Param5                    1000000              2053 ns/op             440 B/op         10 allocs/op
224
+BenchmarkLARS_Param5                    10000000               232 ns/op               0 B/op          0 allocs/op
225
+BenchmarkMacaron_Param5                   500000              5888 ns/op            1056 B/op         10 allocs/op
226
+BenchmarkMartini_Param5                   200000             12807 ns/op            1232 B/op         11 allocs/op
227
+BenchmarkPat_Param5                       300000              7320 ns/op             964 B/op         32 allocs/op
228
+BenchmarkPossum_Param5                   1000000              2495 ns/op             560 B/op          6 allocs/op
229
+BenchmarkR2router_Param5                 1000000              1844 ns/op             432 B/op          5 allocs/op
230
+BenchmarkRivet_Param5                    2000000               935 ns/op             240 B/op          1 allocs/op
231
+BenchmarkTango_Param5                    1000000              2327 ns/op             360 B/op          8 allocs/op
232
+BenchmarkTigerTonic_Param5                100000             18514 ns/op            2551 B/op         43 allocs/op
233
+BenchmarkTraffic_Param5                   200000             11997 ns/op            2248 B/op         25 allocs/op
234
+BenchmarkVulcan_Param5                   1000000              1333 ns/op              98 B/op          3 allocs/op
235
+BenchmarkAce_Param20                     1000000              2031 ns/op             640 B/op          1 allocs/op
236
+BenchmarkBear_Param20                     200000              7285 ns/op            1664 B/op          5 allocs/op
237
+BenchmarkBeego_Param20                    300000              6224 ns/op             368 B/op          4 allocs/op
238
+BenchmarkBone_Param20                     200000              8023 ns/op            1903 B/op          5 allocs/op
239
+BenchmarkDenco_Param20                   1000000              2262 ns/op             640 B/op          1 allocs/op
240
+BenchmarkEcho_Param20                    1000000              1387 ns/op              32 B/op          1 allocs/op
241
+BenchmarkGin_Param20                     3000000               503 ns/op               0 B/op          0 allocs/op
242
+BenchmarkGocraftWeb_Param20               100000             14408 ns/op            3795 B/op         15 allocs/op
243
+BenchmarkGoji_Param20                     500000              5272 ns/op            1247 B/op          2 allocs/op
244
+BenchmarkGojiv2_Param20                  1000000              4163 ns/op            1248 B/op          8 allocs/op
245
+BenchmarkGoJsonRest_Param20               100000             17866 ns/op            4485 B/op         20 allocs/op
246
+BenchmarkGoRestful_Param20                100000             21022 ns/op            4724 B/op         23 allocs/op
247
+BenchmarkGorillaMux_Param20               100000             17055 ns/op            3547 B/op         13 allocs/op
248
+BenchmarkHttpRouter_Param20              1000000              1748 ns/op             640 B/op          1 allocs/op
249
+BenchmarkHttpTreeMux_Param20              200000             12246 ns/op            3196 B/op         10 allocs/op
250
+BenchmarkKocha_Param20                    300000              6861 ns/op            1808 B/op         27 allocs/op
251
+BenchmarkLARS_Param20                    3000000               526 ns/op               0 B/op          0 allocs/op
252
+BenchmarkMacaron_Param20                  100000             13069 ns/op            2906 B/op         12 allocs/op
253
+BenchmarkMartini_Param20                  100000             23602 ns/op            3597 B/op         13 allocs/op
254
+BenchmarkPat_Param20                       50000             32143 ns/op            4688 B/op        111 allocs/op
255
+BenchmarkPossum_Param20                  1000000              2396 ns/op             560 B/op          6 allocs/op
256
+BenchmarkR2router_Param20                 200000              8907 ns/op            2283 B/op          7 allocs/op
257
+BenchmarkRivet_Param20                   1000000              3280 ns/op            1024 B/op          1 allocs/op
258
+BenchmarkTango_Param20                    500000              4640 ns/op             856 B/op          8 allocs/op
259
+BenchmarkTigerTonic_Param20                20000             67581 ns/op           10532 B/op        138 allocs/op
260
+BenchmarkTraffic_Param20                   50000             40313 ns/op            7941 B/op         45 allocs/op
261
+BenchmarkVulcan_Param20                  1000000              2264 ns/op              98 B/op          3 allocs/op
262
+BenchmarkAce_ParamWrite                  3000000               532 ns/op              40 B/op          2 allocs/op
263
+BenchmarkBear_ParamWrite                 1000000              1778 ns/op             456 B/op          5 allocs/op
264
+BenchmarkBeego_ParamWrite                1000000              2596 ns/op             376 B/op          5 allocs/op
265
+BenchmarkBone_ParamWrite                 1000000              2519 ns/op             688 B/op          5 allocs/op
266
+BenchmarkDenco_ParamWrite                5000000               411 ns/op              32 B/op          1 allocs/op
267
+BenchmarkEcho_ParamWrite                 2000000               718 ns/op              40 B/op          2 allocs/op
268
+BenchmarkGin_ParamWrite                  5000000               283 ns/op               0 B/op          0 allocs/op
269
+BenchmarkGocraftWeb_ParamWrite           1000000              2561 ns/op             656 B/op          9 allocs/op
270
+BenchmarkGoji_ParamWrite                 1000000              1378 ns/op             336 B/op          2 allocs/op
271
+BenchmarkGojiv2_ParamWrite               1000000              3128 ns/op             976 B/op         10 allocs/op
272
+BenchmarkGoJsonRest_ParamWrite            500000              4446 ns/op            1128 B/op         18 allocs/op
273
+BenchmarkGoRestful_ParamWrite             200000             10291 ns/op            2304 B/op         22 allocs/op
274
+BenchmarkGorillaMux_ParamWrite            500000              5153 ns/op            1064 B/op         12 allocs/op
275
+BenchmarkHttpRouter_ParamWrite           5000000               263 ns/op              32 B/op          1 allocs/op
276
+BenchmarkHttpTreeMux_ParamWrite          1000000              1351 ns/op             352 B/op          3 allocs/op
277
+BenchmarkKocha_ParamWrite                3000000               538 ns/op              56 B/op          3 allocs/op
278
+BenchmarkLARS_ParamWrite                 5000000               316 ns/op               0 B/op          0 allocs/op
279
+BenchmarkMacaron_ParamWrite               500000              5756 ns/op            1160 B/op         14 allocs/op
280
+BenchmarkMartini_ParamWrite               200000             13097 ns/op            1176 B/op         14 allocs/op
281
+BenchmarkPat_ParamWrite                   500000              4954 ns/op            1072 B/op         17 allocs/op
282
+BenchmarkPossum_ParamWrite               1000000              2499 ns/op             560 B/op          6 allocs/op
283
+BenchmarkR2router_ParamWrite             1000000              1531 ns/op             432 B/op          5 allocs/op
284
+BenchmarkRivet_ParamWrite                3000000               570 ns/op             112 B/op          2 allocs/op
285
+BenchmarkTango_ParamWrite                2000000               957 ns/op             136 B/op          4 allocs/op
286
+BenchmarkTigerTonic_ParamWrite            200000              7025 ns/op            1424 B/op         23 allocs/op
287
+BenchmarkTraffic_ParamWrite               200000             10112 ns/op            2384 B/op         25 allocs/op
288
+BenchmarkVulcan_ParamWrite               1000000              1006 ns/op              98 B/op          3 allocs/op
289
+```
290
+
291
+## GitHub
292
+
293
+```
294
+BenchmarkGin_GithubStatic               10000000               156 ns/op               0 B/op          0 allocs/op
295
+
296
+BenchmarkAce_GithubStatic                5000000               294 ns/op               0 B/op          0 allocs/op
297
+BenchmarkBear_GithubStatic               2000000               893 ns/op             120 B/op          3 allocs/op
298
+BenchmarkBeego_GithubStatic              1000000              2491 ns/op             368 B/op          4 allocs/op
299
+BenchmarkBone_GithubStatic                 50000             25300 ns/op            2880 B/op         60 allocs/op
300
+BenchmarkDenco_GithubStatic             20000000                76.0 ns/op             0 B/op          0 allocs/op
301
+BenchmarkEcho_GithubStatic               2000000               516 ns/op              32 B/op          1 allocs/op
302
+BenchmarkGocraftWeb_GithubStatic         1000000              1448 ns/op             296 B/op          5 allocs/op
303
+BenchmarkGoji_GithubStatic               3000000               496 ns/op               0 B/op          0 allocs/op
304
+BenchmarkGojiv2_GithubStatic             1000000              2941 ns/op             928 B/op          7 allocs/op
305
+BenchmarkGoRestful_GithubStatic           100000             27256 ns/op            3224 B/op         22 allocs/op
306
+BenchmarkGoJsonRest_GithubStatic         1000000              2196 ns/op             329 B/op         11 allocs/op
307
+BenchmarkGorillaMux_GithubStatic           50000             31617 ns/op             736 B/op         10 allocs/op
308
+BenchmarkHttpRouter_GithubStatic        20000000                88.4 ns/op             0 B/op          0 allocs/op
309
+BenchmarkHttpTreeMux_GithubStatic       10000000               134 ns/op               0 B/op          0 allocs/op
310
+BenchmarkKocha_GithubStatic             20000000               113 ns/op               0 B/op          0 allocs/op
311
+BenchmarkLARS_GithubStatic              10000000               195 ns/op               0 B/op          0 allocs/op
312
+BenchmarkMacaron_GithubStatic             500000              3740 ns/op             768 B/op          9 allocs/op
313
+BenchmarkMartini_GithubStatic              50000             27673 ns/op             768 B/op          9 allocs/op
314
+BenchmarkPat_GithubStatic                 100000             19470 ns/op            3648 B/op         76 allocs/op
315
+BenchmarkPossum_GithubStatic             1000000              1729 ns/op             416 B/op          3 allocs/op
316
+BenchmarkR2router_GithubStatic           2000000               879 ns/op             144 B/op          4 allocs/op
317
+BenchmarkRivet_GithubStatic             10000000               231 ns/op               0 B/op          0 allocs/op
318
+BenchmarkTango_GithubStatic              1000000              2325 ns/op             248 B/op          8 allocs/op
319
+BenchmarkTigerTonic_GithubStatic         3000000               610 ns/op              48 B/op          1 allocs/op
320
+BenchmarkTraffic_GithubStatic              20000             62973 ns/op           18904 B/op        148 allocs/op
321
+BenchmarkVulcan_GithubStatic             1000000              1447 ns/op              98 B/op          3 allocs/op
322
+BenchmarkAce_GithubParam                 2000000               686 ns/op              96 B/op          1 allocs/op
323
+BenchmarkBear_GithubParam                1000000              2155 ns/op             496 B/op          5 allocs/op
324
+BenchmarkBeego_GithubParam               1000000              2713 ns/op             368 B/op          4 allocs/op
325
+BenchmarkBone_GithubParam                 100000             15088 ns/op            1760 B/op         18 allocs/op
326
+BenchmarkDenco_GithubParam               2000000               629 ns/op             128 B/op          1 allocs/op
327
+BenchmarkEcho_GithubParam                2000000               653 ns/op              32 B/op          1 allocs/op
328
+BenchmarkGin_GithubParam                 5000000               255 ns/op               0 B/op          0 allocs/op
329
+BenchmarkGocraftWeb_GithubParam          1000000              3145 ns/op             712 B/op          9 allocs/op
330
+BenchmarkGoji_GithubParam                1000000              1916 ns/op             336 B/op          2 allocs/op
331
+BenchmarkGojiv2_GithubParam              1000000              3975 ns/op            1024 B/op         10 allocs/op
332
+BenchmarkGoJsonRest_GithubParam           300000              4134 ns/op             713 B/op         14 allocs/op
333
+BenchmarkGoRestful_GithubParam             50000             30782 ns/op            2360 B/op         21 allocs/op
334
+BenchmarkGorillaMux_GithubParam           100000             17148 ns/op            1088 B/op         11 allocs/op
335
+BenchmarkHttpRouter_GithubParam          3000000               523 ns/op              96 B/op          1 allocs/op
336
+BenchmarkHttpTreeMux_GithubParam         1000000              1671 ns/op             384 B/op          4 allocs/op
337
+BenchmarkKocha_GithubParam               1000000              1021 ns/op             128 B/op          5 allocs/op
338
+BenchmarkLARS_GithubParam                5000000               283 ns/op               0 B/op          0 allocs/op
339
+BenchmarkMacaron_GithubParam              500000              4270 ns/op            1056 B/op         10 allocs/op
340
+BenchmarkMartini_GithubParam              100000             21728 ns/op            1152 B/op         11 allocs/op
341
+BenchmarkPat_GithubParam                  200000             11208 ns/op            2464 B/op         48 allocs/op
342
+BenchmarkPossum_GithubParam              1000000              2334 ns/op             560 B/op          6 allocs/op
343
+BenchmarkR2router_GithubParam            1000000              1487 ns/op             432 B/op          5 allocs/op
344
+BenchmarkRivet_GithubParam               2000000               782 ns/op              96 B/op          1 allocs/op
345
+BenchmarkTango_GithubParam               1000000              2653 ns/op             344 B/op          8 allocs/op
346
+BenchmarkTigerTonic_GithubParam           300000             14073 ns/op            1440 B/op         24 allocs/op
347
+BenchmarkTraffic_GithubParam               50000             29164 ns/op            5992 B/op         52 allocs/op
348
+BenchmarkVulcan_GithubParam              1000000              2529 ns/op              98 B/op          3 allocs/op
349
+BenchmarkAce_GithubAll                     10000            134059 ns/op           13792 B/op        167 allocs/op
350
+BenchmarkBear_GithubAll                     5000            534445 ns/op           86448 B/op        943 allocs/op
351
+BenchmarkBeego_GithubAll                    3000            592444 ns/op           74705 B/op        812 allocs/op
352
+BenchmarkBone_GithubAll                      200           6957308 ns/op          698784 B/op       8453 allocs/op
353
+BenchmarkDenco_GithubAll                   10000            158819 ns/op           20224 B/op        167 allocs/op
354
+BenchmarkEcho_GithubAll                    10000            154700 ns/op            6496 B/op        203 allocs/op
355
+BenchmarkGin_GithubAll                     30000             48375 ns/op               0 B/op          0 allocs/op
356
+BenchmarkGocraftWeb_GithubAll               3000            570806 ns/op          131656 B/op       1686 allocs/op
357
+BenchmarkGoji_GithubAll                     2000            818034 ns/op           56112 B/op        334 allocs/op
358
+BenchmarkGojiv2_GithubAll                   2000           1213973 ns/op          274768 B/op       3712 allocs/op
359
+BenchmarkGoJsonRest_GithubAll               2000            785796 ns/op          134371 B/op       2737 allocs/op
360
+BenchmarkGoRestful_GithubAll                 300           5238188 ns/op          689672 B/op       4519 allocs/op
361
+BenchmarkGorillaMux_GithubAll                100          10257726 ns/op          211840 B/op       2272 allocs/op
362
+BenchmarkHttpRouter_GithubAll              20000            105414 ns/op           13792 B/op        167 allocs/op
363
+BenchmarkHttpTreeMux_GithubAll             10000            319934 ns/op           65856 B/op        671 allocs/op
364
+BenchmarkKocha_GithubAll                   10000            209442 ns/op           23304 B/op        843 allocs/op
365
+BenchmarkLARS_GithubAll                    20000             62565 ns/op               0 B/op          0 allocs/op
366
+BenchmarkMacaron_GithubAll                  2000           1161270 ns/op          204194 B/op       2000 allocs/op
367
+BenchmarkMartini_GithubAll                   200           9991713 ns/op          226549 B/op       2325 allocs/op
368
+BenchmarkPat_GithubAll                       200           5590793 ns/op         1499568 B/op      27435 allocs/op
369
+BenchmarkPossum_GithubAll                  10000            319768 ns/op           84448 B/op        609 allocs/op
370
+BenchmarkR2router_GithubAll                10000            305134 ns/op           77328 B/op        979 allocs/op
371
+BenchmarkRivet_GithubAll                   10000            132134 ns/op           16272 B/op        167 allocs/op
372
+BenchmarkTango_GithubAll                    3000            552754 ns/op           63826 B/op       1618 allocs/op
373
+BenchmarkTigerTonic_GithubAll               1000           1439483 ns/op          239104 B/op       5374 allocs/op
374
+BenchmarkTraffic_GithubAll                   100          11383067 ns/op         2659329 B/op      21848 allocs/op
375
+BenchmarkVulcan_GithubAll                   5000            394253 ns/op           19894 B/op        609 allocs/op
376
+```
377
+
378
+## Google+
379
+
380
+```
381
+BenchmarkGin_GPlusStatic                10000000               183 ns/op               0 B/op          0 allocs/op
382
+
383
+BenchmarkAce_GPlusStatic                 5000000               276 ns/op               0 B/op          0 allocs/op
384
+BenchmarkBear_GPlusStatic                2000000               652 ns/op             104 B/op          3 allocs/op
385
+BenchmarkBeego_GPlusStatic               1000000              2239 ns/op             368 B/op          4 allocs/op
386
+BenchmarkBone_GPlusStatic                5000000               380 ns/op              32 B/op          1 allocs/op
387
+BenchmarkDenco_GPlusStatic              30000000                45.8 ns/op             0 B/op          0 allocs/op
388
+BenchmarkEcho_GPlusStatic                5000000               338 ns/op              32 B/op          1 allocs/op
389
+BenchmarkGocraftWeb_GPlusStatic          1000000              1158 ns/op             280 B/op          5 allocs/op
390
+BenchmarkGoji_GPlusStatic                5000000               331 ns/op               0 B/op          0 allocs/op
391
+BenchmarkGojiv2_GPlusStatic              1000000              2106 ns/op             928 B/op          7 allocs/op
392
+BenchmarkGoJsonRest_GPlusStatic          1000000              1626 ns/op             329 B/op         11 allocs/op
393
+BenchmarkGoRestful_GPlusStatic            300000              7598 ns/op            1976 B/op         20 allocs/op
394
+BenchmarkGorillaMux_GPlusStatic          1000000              2629 ns/op             736 B/op         10 allocs/op
395
+BenchmarkHttpRouter_GPlusStatic         30000000                52.5 ns/op             0 B/op          0 allocs/op
396
+BenchmarkHttpTreeMux_GPlusStatic        20000000                85.8 ns/op             0 B/op          0 allocs/op
397
+BenchmarkKocha_GPlusStatic              20000000                89.2 ns/op             0 B/op          0 allocs/op
398
+BenchmarkLARS_GPlusStatic               10000000               162 ns/op               0 B/op          0 allocs/op
399
+BenchmarkMacaron_GPlusStatic              500000              3479 ns/op             768 B/op          9 allocs/op
400
+BenchmarkMartini_GPlusStatic              200000              9092 ns/op             768 B/op          9 allocs/op
401
+BenchmarkPat_GPlusStatic                 3000000               493 ns/op              96 B/op          2 allocs/op
402
+BenchmarkPossum_GPlusStatic              1000000              1467 ns/op             416 B/op          3 allocs/op
403
+BenchmarkR2router_GPlusStatic            2000000               788 ns/op             144 B/op          4 allocs/op
404
+BenchmarkRivet_GPlusStatic              20000000               114 ns/op               0 B/op          0 allocs/op
405
+BenchmarkTango_GPlusStatic               1000000              1534 ns/op             200 B/op          8 allocs/op
406
+BenchmarkTigerTonic_GPlusStatic          5000000               282 ns/op              32 B/op          1 allocs/op
407
+BenchmarkTraffic_GPlusStatic              500000              3798 ns/op            1192 B/op         15 allocs/op
408
+BenchmarkVulcan_GPlusStatic              2000000              1125 ns/op              98 B/op          3 allocs/op
409
+BenchmarkAce_GPlusParam                  3000000               528 ns/op              64 B/op          1 allocs/op
410
+BenchmarkBear_GPlusParam                 1000000              1570 ns/op             480 B/op          5 allocs/op
411
+BenchmarkBeego_GPlusParam                1000000              2369 ns/op             368 B/op          4 allocs/op
412
+BenchmarkBone_GPlusParam                 1000000              2028 ns/op             688 B/op          5 allocs/op
413
+BenchmarkDenco_GPlusParam                5000000               385 ns/op              64 B/op          1 allocs/op
414
+BenchmarkEcho_GPlusParam                 3000000               441 ns/op              32 B/op          1 allocs/op
415
+BenchmarkGin_GPlusParam                 10000000               174 ns/op               0 B/op          0 allocs/op
416
+BenchmarkGocraftWeb_GPlusParam           1000000              2033 ns/op             648 B/op          8 allocs/op
417
+BenchmarkGoji_GPlusParam                 1000000              1399 ns/op             336 B/op          2 allocs/op
418
+BenchmarkGojiv2_GPlusParam               1000000              2641 ns/op             944 B/op          8 allocs/op
419
+BenchmarkGoJsonRest_GPlusParam           1000000              2824 ns/op             649 B/op         13 allocs/op
420
+BenchmarkGoRestful_GPlusParam             200000              8875 ns/op            2296 B/op         21 allocs/op
421
+BenchmarkGorillaMux_GPlusParam            200000              6291 ns/op            1056 B/op         11 allocs/op
422
+BenchmarkHttpRouter_GPlusParam           5000000               316 ns/op              64 B/op          1 allocs/op
423
+BenchmarkHttpTreeMux_GPlusParam          1000000              1129 ns/op             352 B/op          3 allocs/op
424
+BenchmarkKocha_GPlusParam                3000000               538 ns/op              56 B/op          3 allocs/op
425
+BenchmarkLARS_GPlusParam                10000000               198 ns/op               0 B/op          0 allocs/op
426
+BenchmarkMacaron_GPlusParam               500000              3554 ns/op            1056 B/op         10 allocs/op
427
+BenchmarkMartini_GPlusParam               200000              9831 ns/op            1072 B/op         10 allocs/op
428
+BenchmarkPat_GPlusParam                  1000000              2706 ns/op             688 B/op         12 allocs/op
429
+BenchmarkPossum_GPlusParam               1000000              2297 ns/op             560 B/op          6 allocs/op
430
+BenchmarkR2router_GPlusParam             1000000              1318 ns/op             432 B/op          5 allocs/op
431
+BenchmarkRivet_GPlusParam                5000000               399 ns/op              48 B/op          1 allocs/op
432
+BenchmarkTango_GPlusParam                1000000              2070 ns/op             264 B/op          8 allocs/op
433
+BenchmarkTigerTonic_GPlusParam            500000              4853 ns/op            1056 B/op         17 allocs/op
434
+BenchmarkTraffic_GPlusParam               200000              8278 ns/op            1976 B/op         21 allocs/op
435
+BenchmarkVulcan_GPlusParam               1000000              1243 ns/op              98 B/op          3 allocs/op
436
+BenchmarkAce_GPlus2Params                3000000               549 ns/op              64 B/op          1 allocs/op
437
+BenchmarkBear_GPlus2Params               1000000              2112 ns/op             496 B/op          5 allocs/op
438
+BenchmarkBeego_GPlus2Params               500000              2750 ns/op             368 B/op          4 allocs/op
439
+BenchmarkBone_GPlus2Params                300000              7032 ns/op            1040 B/op          9 allocs/op
440
+BenchmarkDenco_GPlus2Params              3000000               502 ns/op              64 B/op          1 allocs/op
441
+BenchmarkEcho_GPlus2Params               3000000               641 ns/op              32 B/op          1 allocs/op
442
+BenchmarkGin_GPlus2Params                5000000               250 ns/op               0 B/op          0 allocs/op
443
+BenchmarkGocraftWeb_GPlus2Params         1000000              2681 ns/op             712 B/op          9 allocs/op
444
+BenchmarkGoji_GPlus2Params               1000000              1926 ns/op             336 B/op          2 allocs/op
445
+BenchmarkGojiv2_GPlus2Params              500000              3996 ns/op            1024 B/op         11 allocs/op
446
+BenchmarkGoJsonRest_GPlus2Params          500000              3886 ns/op             713 B/op         14 allocs/op
447
+BenchmarkGoRestful_GPlus2Params           200000             10376 ns/op            2360 B/op         21 allocs/op
448
+BenchmarkGorillaMux_GPlus2Params          100000             14162 ns/op            1088 B/op         11 allocs/op
449
+BenchmarkHttpRouter_GPlus2Params         5000000               336 ns/op              64 B/op          1 allocs/op
450
+BenchmarkHttpTreeMux_GPlus2Params        1000000              1523 ns/op             384 B/op          4 allocs/op
451
+BenchmarkKocha_GPlus2Params              2000000               970 ns/op             128 B/op          5 allocs/op
452
+BenchmarkLARS_GPlus2Params               5000000               238 ns/op               0 B/op          0 allocs/op
453
+BenchmarkMacaron_GPlus2Params             500000              4016 ns/op            1056 B/op         10 allocs/op
454
+BenchmarkMartini_GPlus2Params             100000             21253 ns/op            1200 B/op         13 allocs/op
455
+BenchmarkPat_GPlus2Params                 200000              8632 ns/op            2256 B/op         34 allocs/op
456
+BenchmarkPossum_GPlus2Params             1000000              2171 ns/op             560 B/op          6 allocs/op
457
+BenchmarkR2router_GPlus2Params           1000000              1340 ns/op             432 B/op          5 allocs/op
458
+BenchmarkRivet_GPlus2Params              3000000               557 ns/op              96 B/op          1 allocs/op
459
+BenchmarkTango_GPlus2Params              1000000              2186 ns/op             344 B/op          8 allocs/op
460
+BenchmarkTigerTonic_GPlus2Params          200000              9060 ns/op            1488 B/op         24 allocs/op
461
+BenchmarkTraffic_GPlus2Params             100000             20324 ns/op            3272 B/op         31 allocs/op
462
+BenchmarkVulcan_GPlus2Params             1000000              2039 ns/op              98 B/op          3 allocs/op
463
+BenchmarkAce_GPlusAll                     300000              6603 ns/op             640 B/op         11 allocs/op
464
+BenchmarkBear_GPlusAll                    100000             22363 ns/op            5488 B/op         61 allocs/op
465
+BenchmarkBeego_GPlusAll                    50000             38757 ns/op            4784 B/op         52 allocs/op
466
+BenchmarkBone_GPlusAll                     20000             54916 ns/op           10336 B/op         98 allocs/op
467
+BenchmarkDenco_GPlusAll                   300000              4959 ns/op             672 B/op         11 allocs/op
468
+BenchmarkEcho_GPlusAll                    200000              6558 ns/op             416 B/op         13 allocs/op
469
+BenchmarkGin_GPlusAll                     500000              2757 ns/op               0 B/op          0 allocs/op
470
+BenchmarkGocraftWeb_GPlusAll               50000             34615 ns/op            8040 B/op        103 allocs/op
471
+BenchmarkGoji_GPlusAll                    100000             16002 ns/op            3696 B/op         22 allocs/op
472
+BenchmarkGojiv2_GPlusAll                   50000             35060 ns/op           12624 B/op        115 allocs/op
473
+BenchmarkGoJsonRest_GPlusAll               50000             41479 ns/op            8117 B/op        170 allocs/op
474
+BenchmarkGoRestful_GPlusAll                10000            131653 ns/op           32024 B/op        275 allocs/op
475
+BenchmarkGorillaMux_GPlusAll               10000            101380 ns/op           13296 B/op        142 allocs/op
476
+BenchmarkHttpRouter_GPlusAll              500000              3711 ns/op             640 B/op         11 allocs/op
477
+BenchmarkHttpTreeMux_GPlusAll             100000             14438 ns/op            4032 B/op         38 allocs/op
478
+BenchmarkKocha_GPlusAll                   200000              8039 ns/op             976 B/op         43 allocs/op
479
+BenchmarkLARS_GPlusAll                    500000              2630 ns/op               0 B/op          0 allocs/op
480
+BenchmarkMacaron_GPlusAll                  30000             51123 ns/op           13152 B/op        128 allocs/op
481
+BenchmarkMartini_GPlusAll                  10000            176157 ns/op           14016 B/op        145 allocs/op
482
+BenchmarkPat_GPlusAll                      20000             69911 ns/op           16576 B/op        298 allocs/op
483
+BenchmarkPossum_GPlusAll                  100000             20716 ns/op            5408 B/op         39 allocs/op
484
+BenchmarkR2router_GPlusAll                100000             17463 ns/op            5040 B/op         63 allocs/op
485
+BenchmarkRivet_GPlusAll                   300000              5142 ns/op             768 B/op         11 allocs/op
486
+BenchmarkTango_GPlusAll                    50000             27321 ns/op            3656 B/op        104 allocs/op
487
+BenchmarkTigerTonic_GPlusAll               20000             77597 ns/op           14512 B/op        288 allocs/op
488
+BenchmarkTraffic_GPlusAll                  10000            151406 ns/op           37360 B/op        392 allocs/op
489
+BenchmarkVulcan_GPlusAll                  100000             18555 ns/op            1274 B/op         39 allocs/op
490
+```
491
+
492
+## Parse.com
493
+
494
+```
495
+BenchmarkGin_ParseStatic                10000000               133 ns/op               0 B/op          0 allocs/op
496
+
497
+BenchmarkAce_ParseStatic                 5000000               241 ns/op               0 B/op          0 allocs/op
498
+BenchmarkBear_ParseStatic                2000000               728 ns/op             120 B/op          3 allocs/op
499
+BenchmarkBeego_ParseStatic               1000000              2623 ns/op             368 B/op          4 allocs/op
500
+BenchmarkBone_ParseStatic                1000000              1285 ns/op             144 B/op          3 allocs/op
501
+BenchmarkDenco_ParseStatic              30000000                57.8 ns/op             0 B/op          0 allocs/op
502
+BenchmarkEcho_ParseStatic                5000000               342 ns/op              32 B/op          1 allocs/op
503
+BenchmarkGocraftWeb_ParseStatic          1000000              1478 ns/op             296 B/op          5 allocs/op
504
+BenchmarkGoji_ParseStatic                3000000               415 ns/op               0 B/op          0 allocs/op
505
+BenchmarkGojiv2_ParseStatic              1000000              2087 ns/op             928 B/op          7 allocs/op
506
+BenchmarkGoJsonRest_ParseStatic          1000000              1712 ns/op             329 B/op         11 allocs/op
507
+BenchmarkGoRestful_ParseStatic            200000             11072 ns/op            3224 B/op         22 allocs/op
508
+BenchmarkGorillaMux_ParseStatic           500000              4129 ns/op             752 B/op         11 allocs/op
509
+BenchmarkHttpRouter_ParseStatic         30000000                52.4 ns/op             0 B/op          0 allocs/op
510
+BenchmarkHttpTreeMux_ParseStatic        20000000               109 ns/op               0 B/op          0 allocs/op
511
+BenchmarkKocha_ParseStatic              20000000                81.8 ns/op             0 B/op          0 allocs/op
512
+BenchmarkLARS_ParseStatic               10000000               150 ns/op               0 B/op          0 allocs/op
513
+BenchmarkMacaron_ParseStatic             1000000              3288 ns/op             768 B/op          9 allocs/op
514
+BenchmarkMartini_ParseStatic              200000              9110 ns/op             768 B/op          9 allocs/op
515
+BenchmarkPat_ParseStatic                 1000000              1135 ns/op             240 B/op          5 allocs/op
516
+BenchmarkPossum_ParseStatic              1000000              1557 ns/op             416 B/op          3 allocs/op
517
+BenchmarkR2router_ParseStatic            2000000               730 ns/op             144 B/op          4 allocs/op
518
+BenchmarkRivet_ParseStatic              10000000               121 ns/op               0 B/op          0 allocs/op
519
+BenchmarkTango_ParseStatic               1000000              1688 ns/op             248 B/op          8 allocs/op
520
+BenchmarkTigerTonic_ParseStatic          3000000               427 ns/op              48 B/op          1 allocs/op
521
+BenchmarkTraffic_ParseStatic              500000              5962 ns/op            1816 B/op         20 allocs/op
522
+BenchmarkVulcan_ParseStatic              2000000               969 ns/op              98 B/op          3 allocs/op
523
+BenchmarkAce_ParseParam                  3000000               497 ns/op              64 B/op          1 allocs/op
524
+BenchmarkBear_ParseParam                 1000000              1473 ns/op             467 B/op          5 allocs/op
525
+BenchmarkBeego_ParseParam                1000000              2384 ns/op             368 B/op          4 allocs/op
526
+BenchmarkBone_ParseParam                 1000000              2513 ns/op             768 B/op          6 allocs/op
527
+BenchmarkDenco_ParseParam                5000000               364 ns/op              64 B/op          1 allocs/op
528
+BenchmarkEcho_ParseParam                 5000000               418 ns/op              32 B/op          1 allocs/op
529
+BenchmarkGin_ParseParam                 10000000               163 ns/op               0 B/op          0 allocs/op
530
+BenchmarkGocraftWeb_ParseParam           1000000              2361 ns/op             664 B/op          8 allocs/op
531
+BenchmarkGoji_ParseParam                 1000000              1590 ns/op             336 B/op          2 allocs/op
532
+BenchmarkGojiv2_ParseParam               1000000              2851 ns/op             976 B/op          9 allocs/op
533
+BenchmarkGoJsonRest_ParseParam           1000000              2965 ns/op             649 B/op         13 allocs/op
534
+BenchmarkGoRestful_ParseParam             200000             12207 ns/op            3544 B/op         23 allocs/op
535
+BenchmarkGorillaMux_ParseParam            500000              5187 ns/op            1088 B/op         12 allocs/op
536
+BenchmarkHttpRouter_ParseParam           5000000               275 ns/op              64 B/op          1 allocs/op
537
+BenchmarkHttpTreeMux_ParseParam          1000000              1108 ns/op             352 B/op          3 allocs/op
538
+BenchmarkKocha_ParseParam                3000000               495 ns/op              56 B/op          3 allocs/op
539
+BenchmarkLARS_ParseParam                10000000               192 ns/op               0 B/op          0 allocs/op
540
+BenchmarkMacaron_ParseParam               500000              4103 ns/op            1056 B/op         10 allocs/op
541
+BenchmarkMartini_ParseParam               200000              9878 ns/op            1072 B/op         10 allocs/op
542
+BenchmarkPat_ParseParam                   500000              3657 ns/op            1120 B/op         17 allocs/op
543
+BenchmarkPossum_ParseParam               1000000              2084 ns/op             560 B/op          6 allocs/op
544
+BenchmarkR2router_ParseParam             1000000              1251 ns/op             432 B/op          5 allocs/op
545
+BenchmarkRivet_ParseParam                5000000               335 ns/op              48 B/op          1 allocs/op
546
+BenchmarkTango_ParseParam                1000000              1854 ns/op             280 B/op          8 allocs/op
547
+BenchmarkTigerTonic_ParseParam            500000              4582 ns/op            1008 B/op         17 allocs/op
548
+BenchmarkTraffic_ParseParam               200000              8125 ns/op            2248 B/op         23 allocs/op
549
+BenchmarkVulcan_ParseParam               1000000              1148 ns/op              98 B/op          3 allocs/op
550
+BenchmarkAce_Parse2Params                3000000               539 ns/op              64 B/op          1 allocs/op
551
+BenchmarkBear_Parse2Params               1000000              1778 ns/op             496 B/op          5 allocs/op
552
+BenchmarkBeego_Parse2Params              1000000              2519 ns/op             368 B/op          4 allocs/op
553
+BenchmarkBone_Parse2Params               1000000              2596 ns/op             720 B/op          5 allocs/op
554
+BenchmarkDenco_Parse2Params              3000000               492 ns/op              64 B/op          1 allocs/op
555
+BenchmarkEcho_Parse2Params               3000000               484 ns/op              32 B/op          1 allocs/op
556
+BenchmarkGin_Parse2Params               10000000               193 ns/op               0 B/op          0 allocs/op
557
+BenchmarkGocraftWeb_Parse2Params         1000000              2575 ns/op             712 B/op          9 allocs/op
558
+BenchmarkGoji_Parse2Params               1000000              1373 ns/op             336 B/op          2 allocs/op
559
+BenchmarkGojiv2_Parse2Params              500000              2416 ns/op             960 B/op          8 allocs/op
560
+BenchmarkGoJsonRest_Parse2Params          300000              3452 ns/op             713 B/op         14 allocs/op
561
+BenchmarkGoRestful_Parse2Params           100000             17719 ns/op            6008 B/op         25 allocs/op
562
+BenchmarkGorillaMux_Parse2Params          300000              5102 ns/op            1088 B/op         11 allocs/op
563
+BenchmarkHttpRouter_Parse2Params         5000000               303 ns/op              64 B/op          1 allocs/op
564
+BenchmarkHttpTreeMux_Parse2Params        1000000              1372 ns/op             384 B/op          4 allocs/op
565
+BenchmarkKocha_Parse2Params              2000000               874 ns/op             128 B/op          5 allocs/op
566
+BenchmarkLARS_Parse2Params              10000000               192 ns/op               0 B/op          0 allocs/op
567
+BenchmarkMacaron_Parse2Params             500000              3871 ns/op            1056 B/op         10 allocs/op
568
+BenchmarkMartini_Parse2Params             200000              9954 ns/op            1152 B/op         11 allocs/op
569
+BenchmarkPat_Parse2Params                 500000              4194 ns/op             832 B/op         17 allocs/op
570
+BenchmarkPossum_Parse2Params             1000000              2121 ns/op             560 B/op          6 allocs/op
571
+BenchmarkR2router_Parse2Params           1000000              1415 ns/op             432 B/op          5 allocs/op
572
+BenchmarkRivet_Parse2Params              3000000               457 ns/op              96 B/op          1 allocs/op
573
+BenchmarkTango_Parse2Params              1000000              1914 ns/op             312 B/op          8 allocs/op
574
+BenchmarkTigerTonic_Parse2Params          300000              6895 ns/op            1408 B/op         24 allocs/op
575
+BenchmarkTraffic_Parse2Params             200000              8317 ns/op            2040 B/op         22 allocs/op
576
+BenchmarkVulcan_Parse2Params             1000000              1274 ns/op              98 B/op          3 allocs/op
577
+BenchmarkAce_ParseAll                     200000             10401 ns/op             640 B/op         16 allocs/op
578
+BenchmarkBear_ParseAll                     50000             37743 ns/op            8928 B/op        110 allocs/op
579
+BenchmarkBeego_ParseAll                    20000             63193 ns/op            9568 B/op        104 allocs/op
580
+BenchmarkBone_ParseAll                     20000             61767 ns/op           14160 B/op        131 allocs/op
581
+BenchmarkDenco_ParseAll                   300000              7036 ns/op             928 B/op         16 allocs/op
582
+BenchmarkEcho_ParseAll                    200000             11824 ns/op             832 B/op         26 allocs/op
583
+BenchmarkGin_ParseAll                     300000              4199 ns/op               0 B/op          0 allocs/op
584
+BenchmarkGocraftWeb_ParseAll               30000             51758 ns/op           13728 B/op        181 allocs/op
585
+BenchmarkGoji_ParseAll                     50000             29614 ns/op            5376 B/op         32 allocs/op
586
+BenchmarkGojiv2_ParseAll                   20000             68676 ns/op           24464 B/op        199 allocs/op
587
+BenchmarkGoJsonRest_ParseAll               20000             76135 ns/op           13866 B/op        321 allocs/op
588
+BenchmarkGoRestful_ParseAll                 5000            389487 ns/op          110928 B/op        600 allocs/op
589
+BenchmarkGorillaMux_ParseAll               10000            221250 ns/op           24864 B/op        292 allocs/op
590
+BenchmarkHttpRouter_ParseAll              200000              6444 ns/op             640 B/op         16 allocs/op
591
+BenchmarkHttpTreeMux_ParseAll              50000             30702 ns/op            5728 B/op         51 allocs/op
592
+BenchmarkKocha_ParseAll                   200000             13712 ns/op            1112 B/op         54 allocs/op
593
+BenchmarkLARS_ParseAll                    300000              6925 ns/op               0 B/op          0 allocs/op
594
+BenchmarkMacaron_ParseAll                  20000             96278 ns/op           24576 B/op        250 allocs/op
595
+BenchmarkMartini_ParseAll                   5000            271352 ns/op           25072 B/op        253 allocs/op
596
+BenchmarkPat_ParseAll                      20000             74941 ns/op           17264 B/op        343 allocs/op
597
+BenchmarkPossum_ParseAll                   50000             39947 ns/op           10816 B/op         78 allocs/op
598
+BenchmarkR2router_ParseAll                 50000             42479 ns/op            8352 B/op        120 allocs/op
599
+BenchmarkRivet_ParseAll                   200000              7726 ns/op             912 B/op         16 allocs/op
600
+BenchmarkTango_ParseAll                    30000             50014 ns/op            7168 B/op        208 allocs/op
601
+BenchmarkTigerTonic_ParseAll               10000            106550 ns/op           19728 B/op        379 allocs/op
602
+BenchmarkTraffic_ParseAll                  10000            216037 ns/op           57776 B/op        642 allocs/op
603
+BenchmarkVulcan_ParseAll                   50000             34379 ns/op            2548 B/op         78 allocs/op
604
+```

+ 213
- 0
log/vendor/github.com/gin-gonic/gin/CHANGELOG.md View File

@@ -0,0 +1,213 @@
1
+# CHANGELOG
2
+
3
+### Gin 1.3.0
4
+
5
+- [NEW] Add [`func (*Context) QueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.QueryMap), [`func (*Context) GetQueryMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetQueryMap), [`func (*Context) PostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.PostFormMap) and [`func (*Context) GetPostFormMap`](https://godoc.org/github.com/gin-gonic/gin#Context.GetPostFormMap) to support `type map[string]string` as query string or form parameters, see [#1383](https://github.com/gin-gonic/gin/pull/1383)
6
+- [NEW] Add [`func (*Context) AsciiJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.AsciiJSON), see [#1358](https://github.com/gin-gonic/gin/pull/1358)
7
+- [NEW] Add `Pusher()` in [`type ResponseWriter`](https://godoc.org/github.com/gin-gonic/gin#ResponseWriter) for supporting http2 push, see [#1273](https://github.com/gin-gonic/gin/pull/1273)
8
+- [NEW] Add [`func (*Context) DataFromReader`](https://godoc.org/github.com/gin-gonic/gin#Context.DataFromReader) for serving dynamic data, see [#1304](https://github.com/gin-gonic/gin/pull/1304)
9
+- [NEW] Add [`func (*Context) ShouldBindBodyWith`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindBodyWith) allowing to call binding multiple times, see [#1341](https://github.com/gin-gonic/gin/pull/1341)
10
+- [NEW] Support pointers in form binding, see [#1336](https://github.com/gin-gonic/gin/pull/1336)
11
+- [NEW] Add [`func (*Context) JSONP`](https://godoc.org/github.com/gin-gonic/gin#Context.JSONP), see [#1333](https://github.com/gin-gonic/gin/pull/1333)
12
+- [NEW] Support default value in form binding, see [#1138](https://github.com/gin-gonic/gin/pull/1138)
13
+- [NEW] Expose validator engine in [`type StructValidator`](https://godoc.org/github.com/gin-gonic/gin/binding#StructValidator), see [#1277](https://github.com/gin-gonic/gin/pull/1277)
14
+- [NEW] Add [`func (*Context) ShouldBind`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBind), [`func (*Context) ShouldBindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindQuery) and [`func (*Context) ShouldBindJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.ShouldBindJSON), see [#1047](https://github.com/gin-gonic/gin/pull/1047)
15
+- [NEW] Add support for `time.Time` location in form binding, see [#1117](https://github.com/gin-gonic/gin/pull/1117)
16
+- [NEW] Add [`func (*Context) BindQuery`](https://godoc.org/github.com/gin-gonic/gin#Context.BindQuery), see [#1029](https://github.com/gin-gonic/gin/pull/1029)
17
+- [NEW] Make [jsonite](https://github.com/json-iterator/go) optional with build tags, see [#1026](https://github.com/gin-gonic/gin/pull/1026)
18
+- [NEW] Show query string in logger, see [#999](https://github.com/gin-gonic/gin/pull/999)
19
+- [NEW] Add [`func (*Context) SecureJSON`](https://godoc.org/github.com/gin-gonic/gin#Context.SecureJSON), see [#987](https://github.com/gin-gonic/gin/pull/987) and [#993](https://github.com/gin-gonic/gin/pull/993)
20
+- [DEPRECATE] `func (*Context) GetCookie` for [`func (*Context) Cookie`](https://godoc.org/github.com/gin-gonic/gin#Context.Cookie)
21
+- [FIX] Don't display color tags if [`func DisableConsoleColor`](https://godoc.org/github.com/gin-gonic/gin#DisableConsoleColor) called, see [#1072](https://github.com/gin-gonic/gin/pull/1072)
22
+- [FIX] Gin Mode `""` when calling [`func Mode`](https://godoc.org/github.com/gin-gonic/gin#Mode) now returns `const DebugMode`, see [#1250](https://github.com/gin-gonic/gin/pull/1250)
23
+- [FIX] `Flush()` now doesn't overwrite `responseWriter` status code, see [#1460](https://github.com/gin-gonic/gin/pull/1460)
24
+
25
+### Gin 1.2.0
26
+
27
+- [NEW] Switch from godeps to govendor
28
+- [NEW] Add support for Let's Encrypt via gin-gonic/autotls
29
+- [NEW] Improve README examples and add extra at examples folder
30
+- [NEW] Improved support with App Engine
31
+- [NEW] Add custom template delimiters, see #860
32
+- [NEW] Add Template Func Maps, see #962
33
+- [NEW] Add \*context.Handler(), see #928
34
+- [NEW] Add \*context.GetRawData()
35
+- [NEW] Add \*context.GetHeader() (request)
36
+- [NEW] Add \*context.AbortWithStatusJSON() (JSON content type)
37
+- [NEW] Add \*context.Keys type cast helpers
38
+- [NEW] Add \*context.ShouldBindWith()
39
+- [NEW] Add \*context.MustBindWith()
40
+- [NEW] Add \*engine.SetFuncMap()
41
+- [DEPRECATE] On next release: \*context.BindWith(), see #855
42
+- [FIX] Refactor render
43
+- [FIX] Reworked tests
44
+- [FIX] logger now supports cygwin
45
+- [FIX] Use X-Forwarded-For before X-Real-Ip
46
+- [FIX] time.Time binding (#904)
47
+
48
+### Gin 1.1.4
49
+
50
+- [NEW] Support google appengine for IsTerminal func
51
+
52
+### Gin 1.1.3
53
+
54
+- [FIX] Reverted Logger: skip ANSI color commands
55
+
56
+### Gin 1.1
57
+
58
+- [NEW] Implement QueryArray and PostArray methods 
59
+- [NEW] Refactor GetQuery and GetPostForm 
60
+- [NEW] Add contribution guide 
61
+- [FIX] Corrected typos in README
62
+- [FIX] Removed additional Iota  
63
+- [FIX] Changed imports to gopkg instead of github in README (#733) 
64
+- [FIX] Logger: skip ANSI color commands if output is not a tty
65
+
66
+### Gin 1.0rc2 (...)
67
+
68
+- [PERFORMANCE] Fast path for writing Content-Type.
69
+- [PERFORMANCE] Much faster 404 routing
70
+- [PERFORMANCE] Allocation optimizations
71
+- [PERFORMANCE] Faster root tree lookup
72
+- [PERFORMANCE] Zero overhead, String() and JSON() rendering.
73
+- [PERFORMANCE] Faster ClientIP parsing
74
+- [PERFORMANCE] Much faster SSE implementation
75
+- [NEW] Benchmarks suite
76
+- [NEW] Bind validation can be disabled and replaced with custom validators.
77
+- [NEW] More flexible HTML render
78
+- [NEW] Multipart and PostForm bindings
79
+- [NEW] Adds method to return all the registered routes
80
+- [NEW] Context.HandlerName() returns the main handler's name
81
+- [NEW] Adds Error.IsType() helper
82
+- [FIX] Binding multipart form
83
+- [FIX] Integration tests
84
+- [FIX] Crash when binding non struct object in Context.
85
+- [FIX] RunTLS() implementation
86
+- [FIX] Logger() unit tests
87
+- [FIX] Adds SetHTMLTemplate() warning
88
+- [FIX] Context.IsAborted()
89
+- [FIX] More unit tests
90
+- [FIX] JSON, XML, HTML renders accept custom content-types
91
+- [FIX] gin.AbortIndex is unexported
92
+- [FIX] Better approach to avoid directory listing in StaticFS()
93
+- [FIX] Context.ClientIP() always returns the IP with trimmed spaces.
94
+- [FIX] Better warning when running in debug mode.
95
+- [FIX] Google App Engine integration. debugPrint does not use os.Stdout
96
+- [FIX] Fixes integer overflow in error type
97
+- [FIX] Error implements the json.Marshaller interface
98
+- [FIX] MIT license in every file
99
+
100
+
101
+### Gin 1.0rc1 (May 22, 2015)
102
+
103
+- [PERFORMANCE] Zero allocation router
104
+- [PERFORMANCE] Faster JSON, XML and text rendering
105
+- [PERFORMANCE] Custom hand optimized HttpRouter for Gin
106
+- [PERFORMANCE] Misc code optimizations. Inlining, tail call optimizations
107
+- [NEW] Built-in support for golang.org/x/net/context
108
+- [NEW] Any(path, handler). Create a route that matches any path
109
+- [NEW] Refactored rendering pipeline (faster and static typeded)
110
+- [NEW] Refactored errors API
111
+- [NEW] IndentedJSON() prints pretty JSON
112
+- [NEW] Added gin.DefaultWriter
113
+- [NEW] UNIX socket support
114
+- [NEW] RouterGroup.BasePath is exposed
115
+- [NEW] JSON validation using go-validate-yourself (very powerful options)
116
+- [NEW] Completed suite of unit tests
117
+- [NEW] HTTP streaming with c.Stream()
118
+- [NEW] StaticFile() creates a router for serving just one file.
119
+- [NEW] StaticFS() has an option to disable directory listing.
120
+- [NEW] StaticFS() for serving static files through virtual filesystems
121
+- [NEW] Server-Sent Events native support
122
+- [NEW] WrapF() and WrapH() helpers for wrapping http.HandlerFunc and http.Handler
123
+- [NEW] Added LoggerWithWriter() middleware
124
+- [NEW] Added RecoveryWithWriter() middleware
125
+- [NEW] Added DefaultPostFormValue()
126
+- [NEW] Added DefaultFormValue()
127
+- [NEW] Added DefaultParamValue()
128
+- [FIX] BasicAuth() when using custom realm
129
+- [FIX] Bug when serving static files in nested routing group
130
+- [FIX] Redirect using built-in http.Redirect()
131
+- [FIX] Logger when printing the requested path
132
+- [FIX] Documentation typos
133
+- [FIX] Context.Engine renamed to Context.engine
134
+- [FIX] Better debugging messages
135
+- [FIX] ErrorLogger
136
+- [FIX] Debug HTTP render
137
+- [FIX] Refactored binding and render modules
138
+- [FIX] Refactored Context initialization
139
+- [FIX] Refactored BasicAuth()
140
+- [FIX] NoMethod/NoRoute handlers
141
+- [FIX] Hijacking http
142
+- [FIX] Better support for Google App Engine (using log instead of fmt)
143
+
144
+
145
+### Gin 0.6 (Mar 9, 2015)
146
+
147
+- [NEW] Support multipart/form-data
148
+- [NEW] NoMethod handler
149
+- [NEW] Validate sub structures
150
+- [NEW] Support for HTTP Realm Auth
151
+- [FIX] Unsigned integers in binding
152
+- [FIX] Improve color logger
153
+
154
+
155
+### Gin 0.5 (Feb 7, 2015)
156
+
157
+- [NEW] Content Negotiation
158
+- [FIX] Solved security bug that allow a client to spoof ip
159
+- [FIX] Fix unexported/ignored fields in binding
160
+
161
+
162
+### Gin 0.4 (Aug 21, 2014)
163
+
164
+- [NEW] Development mode
165
+- [NEW] Unit tests
166
+- [NEW] Add Content.Redirect()
167
+- [FIX] Deferring WriteHeader()
168
+- [FIX] Improved documentation for model binding
169
+
170
+
171
+### Gin 0.3 (Jul 18, 2014)
172
+
173
+- [PERFORMANCE] Normal log and error log are printed in the same call.
174
+- [PERFORMANCE] Improve performance of NoRouter()
175
+- [PERFORMANCE] Improve context's memory locality, reduce CPU cache faults.
176
+- [NEW] Flexible rendering API
177
+- [NEW] Add Context.File()
178
+- [NEW] Add shorcut RunTLS() for http.ListenAndServeTLS
179
+- [FIX] Rename NotFound404() to NoRoute()
180
+- [FIX] Errors in context are purged
181
+- [FIX] Adds HEAD method in Static file serving
182
+- [FIX] Refactors Static() file serving
183
+- [FIX] Using keyed initialization to fix app-engine integration
184
+- [FIX] Can't unmarshal JSON array, #63
185
+- [FIX] Renaming Context.Req to Context.Request
186
+- [FIX] Check application/x-www-form-urlencoded when parsing form
187
+
188
+
189
+### Gin 0.2b (Jul 08, 2014)
190
+- [PERFORMANCE] Using sync.Pool to allocatio/gc overhead
191
+- [NEW] Travis CI integration
192
+- [NEW] Completely new logger
193
+- [NEW] New API for serving static files. gin.Static()
194
+- [NEW] gin.H() can be serialized into XML
195
+- [NEW] Typed errors. Errors can be typed. Internet/external/custom.
196
+- [NEW] Support for Godeps
197
+- [NEW] Travis/Godocs badges in README
198
+- [NEW] New Bind() and BindWith() methods for parsing request body.
199
+- [NEW] Add Content.Copy()
200
+- [NEW] Add context.LastError()
201
+- [NEW] Add shorcut for OPTIONS HTTP method
202
+- [FIX] Tons of README fixes
203
+- [FIX] Header is written before body
204
+- [FIX] BasicAuth() and changes API a little bit
205
+- [FIX] Recovery() middleware only prints panics
206
+- [FIX] Context.Get() does not panic anymore. Use MustGet() instead.
207
+- [FIX] Multiple http.WriteHeader() in NotFound handlers
208
+- [FIX] Engine.Run() panics if http server can't be setted up
209
+- [FIX] Crash when route path doesn't start with '/'
210
+- [FIX] Do not update header when status code is negative
211
+- [FIX] Setting response headers before calling WriteHeader in context.String()
212
+- [FIX] Add MIT license
213
+- [FIX] Changes behaviour of ErrorLogger() and Logger()

+ 46
- 0
log/vendor/github.com/gin-gonic/gin/CODE_OF_CONDUCT.md View File

@@ -0,0 +1,46 @@
1
+# Contributor Covenant Code of Conduct
2
+
3
+## Our Pledge
4
+
5
+In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+## Our Standards
8
+
9
+Examples of behavior that contributes to creating a positive environment include:
10
+
11
+* Using welcoming and inclusive language
12
+* Being respectful of differing viewpoints and experiences
13
+* Gracefully accepting constructive criticism
14
+* Focusing on what is best for the community
15
+* Showing empathy towards other community members
16
+
17
+Examples of unacceptable behavior by participants include:
18
+
19
+* The use of sexualized language or imagery and unwelcome sexual attention or advances
20
+* Trolling, insulting/derogatory comments, and personal or political attacks
21
+* Public or private harassment
22
+* Publishing others' private information, such as a physical or electronic address, without explicit permission
23
+* Other conduct which could reasonably be considered inappropriate in a professional setting
24
+
25
+## Our Responsibilities
26
+
27
+Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28
+
29
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30
+
31
+## Scope
32
+
33
+This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34
+
35
+## Enforcement
36
+
37
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at teamgingonic@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38
+
39
+Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40
+
41
+## Attribution
42
+
43
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44
+
45
+[homepage]: http://contributor-covenant.org
46
+[version]: http://contributor-covenant.org/version/1/4/

+ 13
- 0
log/vendor/github.com/gin-gonic/gin/CONTRIBUTING.md View File

@@ -0,0 +1,13 @@
1
+## Contributing 
2
+
3
+- With issues:
4
+  - Use the search tool before opening a new issue.
5
+  - Please provide source code and commit sha if you found a bug.
6
+  - Review existing issues and provide feedback or react to them.
7
+
8
+- With pull requests:
9
+  - Open your pull request against `master`
10
+  - Your pull request should have no more than two commits, if not you should squash them.
11
+  - It should pass all tests in the available continuous integrations systems such as TravisCI.
12
+  - You should add/modify tests to cover your proposed code changes.
13
+  - If your pull request contains a new feature, please document it on the README.

+ 21
- 0
log/vendor/github.com/gin-gonic/gin/LICENSE View File

@@ -0,0 +1,21 @@
1
+The MIT License (MIT)
2
+
3
+Copyright (c) 2014 Manuel Martínez-Almeida
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in
13
+all copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+THE SOFTWARE.

+ 62
- 0
log/vendor/github.com/gin-gonic/gin/Makefile View File

@@ -0,0 +1,62 @@
1
+GOFMT ?= gofmt "-s"
2
+PACKAGES ?= $(shell go list ./... | grep -v /vendor/)
3
+VETPACKAGES ?= $(shell go list ./... | grep -v /vendor/ | grep -v /examples/)
4
+GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*")
5
+
6
+all: install
7
+
8
+install: deps
9
+	govendor sync
10
+
11
+.PHONY: test
12
+test:
13
+	sh coverage.sh
14
+
15
+.PHONY: fmt
16
+fmt:
17
+	$(GOFMT) -w $(GOFILES)
18
+
19
+.PHONY: fmt-check
20
+fmt-check:
21
+	# get all go files and run go fmt on them
22
+	@diff=$$($(GOFMT) -d $(GOFILES)); \
23
+	if [ -n "$$diff" ]; then \
24
+		echo "Please run 'make fmt' and commit the result:"; \
25
+		echo "$${diff}"; \
26
+		exit 1; \
27
+	fi;
28
+
29
+vet:
30
+	go vet $(VETPACKAGES)
31
+
32
+deps:
33
+	@hash govendor > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
34
+		go get -u github.com/kardianos/govendor; \
35
+	fi
36
+	@hash embedmd > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
37
+		go get -u github.com/campoy/embedmd; \
38
+	fi
39
+
40
+embedmd:
41
+	embedmd -d *.md
42
+
43
+.PHONY: lint
44
+lint:
45
+	@hash golint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
46
+		go get -u github.com/golang/lint/golint; \
47
+	fi
48
+	for PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done;
49
+
50
+.PHONY: misspell-check
51
+misspell-check:
52
+	@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
53
+		go get -u github.com/client9/misspell/cmd/misspell; \
54
+	fi
55
+	misspell -error $(GOFILES)
56
+
57
+.PHONY: misspell
58
+misspell:
59
+	@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
60
+		go get -u github.com/client9/misspell/cmd/misspell; \
61
+	fi
62
+	misspell -w $(GOFILES)

+ 1820
- 0
log/vendor/github.com/gin-gonic/gin/README.md
File diff suppressed because it is too large
View File


+ 96
- 0
log/vendor/github.com/gin-gonic/gin/auth.go View File

@@ -0,0 +1,96 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"crypto/subtle"
9
+	"encoding/base64"
10
+	"net/http"
11
+	"strconv"
12
+)
13
+
14
+// AuthUserKey is the cookie name for user credential in basic auth.
15
+const AuthUserKey = "user"
16
+
17
+// Accounts defines a key/value for user/pass list of authorized logins.
18
+type Accounts map[string]string
19
+
20
+type authPair struct {
21
+	value string
22
+	user  string
23
+}
24
+
25
+type authPairs []authPair
26
+
27
+func (a authPairs) searchCredential(authValue string) (string, bool) {
28
+	if authValue == "" {
29
+		return "", false
30
+	}
31
+	for _, pair := range a {
32
+		if pair.value == authValue {
33
+			return pair.user, true
34
+		}
35
+	}
36
+	return "", false
37
+}
38
+
39
+// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where
40
+// the key is the user name and the value is the password, as well as the name of the Realm.
41
+// If the realm is empty, "Authorization Required" will be used by default.
42
+// (see http://tools.ietf.org/html/rfc2617#section-1.2)
43
+func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {
44
+	if realm == "" {
45
+		realm = "Authorization Required"
46
+	}
47
+	realm = "Basic realm=" + strconv.Quote(realm)
48
+	pairs := processAccounts(accounts)
49
+	return func(c *Context) {
50
+		// Search user in the slice of allowed credentials
51
+		user, found := pairs.searchCredential(c.requestHeader("Authorization"))
52
+		if !found {
53
+			// Credentials doesn't match, we return 401 and abort handlers chain.
54
+			c.Header("WWW-Authenticate", realm)
55
+			c.AbortWithStatus(http.StatusUnauthorized)
56
+			return
57
+		}
58
+
59
+		// The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using
60
+		// c.MustGet(gin.AuthUserKey).
61
+		c.Set(AuthUserKey, user)
62
+	}
63
+}
64
+
65
+// BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where
66
+// the key is the user name and the value is the password.
67
+func BasicAuth(accounts Accounts) HandlerFunc {
68
+	return BasicAuthForRealm(accounts, "")
69
+}
70
+
71
+func processAccounts(accounts Accounts) authPairs {
72
+	assert1(len(accounts) > 0, "Empty list of authorized credentials")
73
+	pairs := make(authPairs, 0, len(accounts))
74
+	for user, password := range accounts {
75
+		assert1(user != "", "User can not be empty")
76
+		value := authorizationHeader(user, password)
77
+		pairs = append(pairs, authPair{
78
+			value: value,
79
+			user:  user,
80
+		})
81
+	}
82
+	return pairs
83
+}
84
+
85
+func authorizationHeader(user, password string) string {
86
+	base := user + ":" + password
87
+	return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
88
+}
89
+
90
+func secureCompare(given, actual string) bool {
91
+	if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
92
+		return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
93
+	}
94
+	// Securely compare actual to itself to keep constant time, but always return false.
95
+	return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
96
+}

+ 99
- 0
log/vendor/github.com/gin-gonic/gin/binding/binding.go View File

@@ -0,0 +1,99 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import "net/http"
8
+
9
+// Content-Type MIME of the most common data formats.
10
+const (
11
+	MIMEJSON              = "application/json"
12
+	MIMEHTML              = "text/html"
13
+	MIMEXML               = "application/xml"
14
+	MIMEXML2              = "text/xml"
15
+	MIMEPlain             = "text/plain"
16
+	MIMEPOSTForm          = "application/x-www-form-urlencoded"
17
+	MIMEMultipartPOSTForm = "multipart/form-data"
18
+	MIMEPROTOBUF          = "application/x-protobuf"
19
+	MIMEMSGPACK           = "application/x-msgpack"
20
+	MIMEMSGPACK2          = "application/msgpack"
21
+)
22
+
23
+// Binding describes the interface which needs to be implemented for binding the
24
+// data present in the request such as JSON request body, query parameters or
25
+// the form POST.
26
+type Binding interface {
27
+	Name() string
28
+	Bind(*http.Request, interface{}) error
29
+}
30
+
31
+// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
32
+// but it reads the body from supplied bytes instead of req.Body.
33
+type BindingBody interface {
34
+	Binding
35
+	BindBody([]byte, interface{}) error
36
+}
37
+
38
+// StructValidator is the minimal interface which needs to be implemented in
39
+// order for it to be used as the validator engine for ensuring the correctness
40
+// of the reqest. Gin provides a default implementation for this using
41
+// https://github.com/go-playground/validator/tree/v8.18.2.
42
+type StructValidator interface {
43
+	// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
44
+	// If the received type is not a struct, any validation should be skipped and nil must be returned.
45
+	// If the received type is a struct or pointer to a struct, the validation should be performed.
46
+	// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
47
+	// Otherwise nil must be returned.
48
+	ValidateStruct(interface{}) error
49
+
50
+	// Engine returns the underlying validator engine which powers the
51
+	// StructValidator implementation.
52
+	Engine() interface{}
53
+}
54
+
55
+// Validator is the default validator which implements the StructValidator
56
+// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2
57
+// under the hood.
58
+var Validator StructValidator = &defaultValidator{}
59
+
60
+// These implement the Binding interface and can be used to bind the data
61
+// present in the request to struct instances.
62
+var (
63
+	JSON          = jsonBinding{}
64
+	XML           = xmlBinding{}
65
+	Form          = formBinding{}
66
+	Query         = queryBinding{}
67
+	FormPost      = formPostBinding{}
68
+	FormMultipart = formMultipartBinding{}
69
+	ProtoBuf      = protobufBinding{}
70
+	MsgPack       = msgpackBinding{}
71
+)
72
+
73
+// Default returns the appropriate Binding instance based on the HTTP method
74
+// and the content type.
75
+func Default(method, contentType string) Binding {
76
+	if method == "GET" {
77
+		return Form
78
+	}
79
+
80
+	switch contentType {
81
+	case MIMEJSON:
82
+		return JSON
83
+	case MIMEXML, MIMEXML2:
84
+		return XML
85
+	case MIMEPROTOBUF:
86
+		return ProtoBuf
87
+	case MIMEMSGPACK, MIMEMSGPACK2:
88
+		return MsgPack
89
+	default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
90
+		return Form
91
+	}
92
+}
93
+
94
+func validate(obj interface{}) error {
95
+	if Validator == nil {
96
+		return nil
97
+	}
98
+	return Validator.ValidateStruct(obj)
99
+}

+ 51
- 0
log/vendor/github.com/gin-gonic/gin/binding/default_validator.go View File

@@ -0,0 +1,51 @@
1
+// Copyright 2017 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import (
8
+	"reflect"
9
+	"sync"
10
+
11
+	"gopkg.in/go-playground/validator.v8"
12
+)
13
+
14
+type defaultValidator struct {
15
+	once     sync.Once
16
+	validate *validator.Validate
17
+}
18
+
19
+var _ StructValidator = &defaultValidator{}
20
+
21
+// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
22
+func (v *defaultValidator) ValidateStruct(obj interface{}) error {
23
+	value := reflect.ValueOf(obj)
24
+	valueType := value.Kind()
25
+	if valueType == reflect.Ptr {
26
+		valueType = value.Elem().Kind()
27
+	}
28
+	if valueType == reflect.Struct {
29
+		v.lazyinit()
30
+		if err := v.validate.Struct(obj); err != nil {
31
+			return err
32
+		}
33
+	}
34
+	return nil
35
+}
36
+
37
+// Engine returns the underlying validator engine which powers the default
38
+// Validator instance. This is useful if you want to register custom validations
39
+// or struct level validations. See validator GoDoc for more info -
40
+// https://godoc.org/gopkg.in/go-playground/validator.v8
41
+func (v *defaultValidator) Engine() interface{} {
42
+	v.lazyinit()
43
+	return v.validate
44
+}
45
+
46
+func (v *defaultValidator) lazyinit() {
47
+	v.once.Do(func() {
48
+		config := &validator.Config{TagName: "binding"}
49
+		v.validate = validator.New(config)
50
+	})
51
+}

+ 56
- 0
log/vendor/github.com/gin-gonic/gin/binding/form.go View File

@@ -0,0 +1,56 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import "net/http"
8
+
9
+const defaultMemory = 32 * 1024 * 1024
10
+
11
+type formBinding struct{}
12
+type formPostBinding struct{}
13
+type formMultipartBinding struct{}
14
+
15
+func (formBinding) Name() string {
16
+	return "form"
17
+}
18
+
19
+func (formBinding) Bind(req *http.Request, obj interface{}) error {
20
+	if err := req.ParseForm(); err != nil {
21
+		return err
22
+	}
23
+	req.ParseMultipartForm(defaultMemory)
24
+	if err := mapForm(obj, req.Form); err != nil {
25
+		return err
26
+	}
27
+	return validate(obj)
28
+}
29
+
30
+func (formPostBinding) Name() string {
31
+	return "form-urlencoded"
32
+}
33
+
34
+func (formPostBinding) Bind(req *http.Request, obj interface{}) error {
35
+	if err := req.ParseForm(); err != nil {
36
+		return err
37
+	}
38
+	if err := mapForm(obj, req.PostForm); err != nil {
39
+		return err
40
+	}
41
+	return validate(obj)
42
+}
43
+
44
+func (formMultipartBinding) Name() string {
45
+	return "multipart/form-data"
46
+}
47
+
48
+func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error {
49
+	if err := req.ParseMultipartForm(defaultMemory); err != nil {
50
+		return err
51
+	}
52
+	if err := mapForm(obj, req.MultipartForm.Value); err != nil {
53
+		return err
54
+	}
55
+	return validate(obj)
56
+}

+ 209
- 0
log/vendor/github.com/gin-gonic/gin/binding/form_mapping.go View File

@@ -0,0 +1,209 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import (
8
+	"errors"
9
+	"reflect"
10
+	"strconv"
11
+	"strings"
12
+	"time"
13
+)
14
+
15
+func mapForm(ptr interface{}, form map[string][]string) error {
16
+	typ := reflect.TypeOf(ptr).Elem()
17
+	val := reflect.ValueOf(ptr).Elem()
18
+	for i := 0; i < typ.NumField(); i++ {
19
+		typeField := typ.Field(i)
20
+		structField := val.Field(i)
21
+		if !structField.CanSet() {
22
+			continue
23
+		}
24
+
25
+		structFieldKind := structField.Kind()
26
+		inputFieldName := typeField.Tag.Get("form")
27
+		inputFieldNameList := strings.Split(inputFieldName, ",")
28
+		inputFieldName = inputFieldNameList[0]
29
+		var defaultValue string
30
+		if len(inputFieldNameList) > 1 {
31
+			defaultList := strings.SplitN(inputFieldNameList[1], "=", 2)
32
+			if defaultList[0] == "default" {
33
+				defaultValue = defaultList[1]
34
+			}
35
+		}
36
+		if inputFieldName == "" {
37
+			inputFieldName = typeField.Name
38
+
39
+			// if "form" tag is nil, we inspect if the field is a struct or struct pointer.
40
+			// this would not make sense for JSON parsing but it does for a form
41
+			// since data is flatten
42
+			if structFieldKind == reflect.Ptr {
43
+				if !structField.Elem().IsValid() {
44
+					structField.Set(reflect.New(structField.Type().Elem()))
45
+				}
46
+				structField = structField.Elem()
47
+				structFieldKind = structField.Kind()
48
+			}
49
+			if structFieldKind == reflect.Struct {
50
+				err := mapForm(structField.Addr().Interface(), form)
51
+				if err != nil {
52
+					return err
53
+				}
54
+				continue
55
+			}
56
+		}
57
+		inputValue, exists := form[inputFieldName]
58
+
59
+		if !exists {
60
+			if defaultValue == "" {
61
+				continue
62
+			}
63
+			inputValue = make([]string, 1)
64
+			inputValue[0] = defaultValue
65
+		}
66
+
67
+		numElems := len(inputValue)
68
+		if structFieldKind == reflect.Slice && numElems > 0 {
69
+			sliceOf := structField.Type().Elem().Kind()
70
+			slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
71
+			for i := 0; i < numElems; i++ {
72
+				if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil {
73
+					return err
74
+				}
75
+			}
76
+			val.Field(i).Set(slice)
77
+		} else {
78
+			if _, isTime := structField.Interface().(time.Time); isTime {
79
+				if err := setTimeField(inputValue[0], typeField, structField); err != nil {
80
+					return err
81
+				}
82
+				continue
83
+			}
84
+			if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {
85
+				return err
86
+			}
87
+		}
88
+	}
89
+	return nil
90
+}
91
+
92
+func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {
93
+	switch valueKind {
94
+	case reflect.Int:
95
+		return setIntField(val, 0, structField)
96
+	case reflect.Int8:
97
+		return setIntField(val, 8, structField)
98
+	case reflect.Int16:
99
+		return setIntField(val, 16, structField)
100
+	case reflect.Int32:
101
+		return setIntField(val, 32, structField)
102
+	case reflect.Int64:
103
+		return setIntField(val, 64, structField)
104
+	case reflect.Uint:
105
+		return setUintField(val, 0, structField)
106
+	case reflect.Uint8:
107
+		return setUintField(val, 8, structField)
108
+	case reflect.Uint16:
109
+		return setUintField(val, 16, structField)
110
+	case reflect.Uint32:
111
+		return setUintField(val, 32, structField)
112
+	case reflect.Uint64:
113
+		return setUintField(val, 64, structField)
114
+	case reflect.Bool:
115
+		return setBoolField(val, structField)
116
+	case reflect.Float32:
117
+		return setFloatField(val, 32, structField)
118
+	case reflect.Float64:
119
+		return setFloatField(val, 64, structField)
120
+	case reflect.String:
121
+		structField.SetString(val)
122
+	case reflect.Ptr:
123
+		if !structField.Elem().IsValid() {
124
+			structField.Set(reflect.New(structField.Type().Elem()))
125
+		}
126
+		structFieldElem := structField.Elem()
127
+		return setWithProperType(structFieldElem.Kind(), val, structFieldElem)
128
+	default:
129
+		return errors.New("Unknown type")
130
+	}
131
+	return nil
132
+}
133
+
134
+func setIntField(val string, bitSize int, field reflect.Value) error {
135
+	if val == "" {
136
+		val = "0"
137
+	}
138
+	intVal, err := strconv.ParseInt(val, 10, bitSize)
139
+	if err == nil {
140
+		field.SetInt(intVal)
141
+	}
142
+	return err
143
+}
144
+
145
+func setUintField(val string, bitSize int, field reflect.Value) error {
146
+	if val == "" {
147
+		val = "0"
148
+	}
149
+	uintVal, err := strconv.ParseUint(val, 10, bitSize)
150
+	if err == nil {
151
+		field.SetUint(uintVal)
152
+	}
153
+	return err
154
+}
155
+
156
+func setBoolField(val string, field reflect.Value) error {
157
+	if val == "" {
158
+		val = "false"
159
+	}
160
+	boolVal, err := strconv.ParseBool(val)
161
+	if err == nil {
162
+		field.SetBool(boolVal)
163
+	}
164
+	return err
165
+}
166
+
167
+func setFloatField(val string, bitSize int, field reflect.Value) error {
168
+	if val == "" {
169
+		val = "0.0"
170
+	}
171
+	floatVal, err := strconv.ParseFloat(val, bitSize)
172
+	if err == nil {
173
+		field.SetFloat(floatVal)
174
+	}
175
+	return err
176
+}
177
+
178
+func setTimeField(val string, structField reflect.StructField, value reflect.Value) error {
179
+	timeFormat := structField.Tag.Get("time_format")
180
+	if timeFormat == "" {
181
+		return errors.New("Blank time format")
182
+	}
183
+
184
+	if val == "" {
185
+		value.Set(reflect.ValueOf(time.Time{}))
186
+		return nil
187
+	}
188
+
189
+	l := time.Local
190
+	if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC {
191
+		l = time.UTC
192
+	}
193
+
194
+	if locTag := structField.Tag.Get("time_location"); locTag != "" {
195
+		loc, err := time.LoadLocation(locTag)
196
+		if err != nil {
197
+			return err
198
+		}
199
+		l = loc
200
+	}
201
+
202
+	t, err := time.ParseInLocation(timeFormat, val, l)
203
+	if err != nil {
204
+		return err
205
+	}
206
+
207
+	value.Set(reflect.ValueOf(t))
208
+	return nil
209
+}

+ 43
- 0
log/vendor/github.com/gin-gonic/gin/binding/json.go View File

@@ -0,0 +1,43 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import (
8
+	"bytes"
9
+	"io"
10
+	"net/http"
11
+
12
+	"github.com/gin-gonic/gin/json"
13
+)
14
+
15
+// EnableDecoderUseNumber is used to call the UseNumber method on the JSON
16
+// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an
17
+// interface{} as a Number instead of as a float64.
18
+var EnableDecoderUseNumber = false
19
+
20
+type jsonBinding struct{}
21
+
22
+func (jsonBinding) Name() string {
23
+	return "json"
24
+}
25
+
26
+func (jsonBinding) Bind(req *http.Request, obj interface{}) error {
27
+	return decodeJSON(req.Body, obj)
28
+}
29
+
30
+func (jsonBinding) BindBody(body []byte, obj interface{}) error {
31
+	return decodeJSON(bytes.NewReader(body), obj)
32
+}
33
+
34
+func decodeJSON(r io.Reader, obj interface{}) error {
35
+	decoder := json.NewDecoder(r)
36
+	if EnableDecoderUseNumber {
37
+		decoder.UseNumber()
38
+	}
39
+	if err := decoder.Decode(obj); err != nil {
40
+		return err
41
+	}
42
+	return validate(obj)
43
+}

+ 35
- 0
log/vendor/github.com/gin-gonic/gin/binding/msgpack.go View File

@@ -0,0 +1,35 @@
1
+// Copyright 2017 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import (
8
+	"bytes"
9
+	"io"
10
+	"net/http"
11
+
12
+	"github.com/ugorji/go/codec"
13
+)
14
+
15
+type msgpackBinding struct{}
16
+
17
+func (msgpackBinding) Name() string {
18
+	return "msgpack"
19
+}
20
+
21
+func (msgpackBinding) Bind(req *http.Request, obj interface{}) error {
22
+	return decodeMsgPack(req.Body, obj)
23
+}
24
+
25
+func (msgpackBinding) BindBody(body []byte, obj interface{}) error {
26
+	return decodeMsgPack(bytes.NewReader(body), obj)
27
+}
28
+
29
+func decodeMsgPack(r io.Reader, obj interface{}) error {
30
+	cdc := new(codec.MsgpackHandle)
31
+	if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil {
32
+		return err
33
+	}
34
+	return validate(obj)
35
+}

+ 36
- 0
log/vendor/github.com/gin-gonic/gin/binding/protobuf.go View File

@@ -0,0 +1,36 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import (
8
+	"io/ioutil"
9
+	"net/http"
10
+
11
+	"github.com/golang/protobuf/proto"
12
+)
13
+
14
+type protobufBinding struct{}
15
+
16
+func (protobufBinding) Name() string {
17
+	return "protobuf"
18
+}
19
+
20
+func (b protobufBinding) Bind(req *http.Request, obj interface{}) error {
21
+	buf, err := ioutil.ReadAll(req.Body)
22
+	if err != nil {
23
+		return err
24
+	}
25
+	return b.BindBody(buf, obj)
26
+}
27
+
28
+func (protobufBinding) BindBody(body []byte, obj interface{}) error {
29
+	if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil {
30
+		return err
31
+	}
32
+	// Here it's same to return validate(obj), but util now we cann't add
33
+	// `binding:""` to the struct which automatically generate by gen-proto
34
+	return nil
35
+	// return validate(obj)
36
+}

+ 21
- 0
log/vendor/github.com/gin-gonic/gin/binding/query.go View File

@@ -0,0 +1,21 @@
1
+// Copyright 2017 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import "net/http"
8
+
9
+type queryBinding struct{}
10
+
11
+func (queryBinding) Name() string {
12
+	return "query"
13
+}
14
+
15
+func (queryBinding) Bind(req *http.Request, obj interface{}) error {
16
+	values := req.URL.Query()
17
+	if err := mapForm(obj, values); err != nil {
18
+		return err
19
+	}
20
+	return validate(obj)
21
+}

+ 33
- 0
log/vendor/github.com/gin-gonic/gin/binding/xml.go View File

@@ -0,0 +1,33 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package binding
6
+
7
+import (
8
+	"bytes"
9
+	"encoding/xml"
10
+	"io"
11
+	"net/http"
12
+)
13
+
14
+type xmlBinding struct{}
15
+
16
+func (xmlBinding) Name() string {
17
+	return "xml"
18
+}
19
+
20
+func (xmlBinding) Bind(req *http.Request, obj interface{}) error {
21
+	return decodeXML(req.Body, obj)
22
+}
23
+
24
+func (xmlBinding) BindBody(body []byte, obj interface{}) error {
25
+	return decodeXML(bytes.NewReader(body), obj)
26
+}
27
+func decodeXML(r io.Reader, obj interface{}) error {
28
+	decoder := xml.NewDecoder(r)
29
+	if err := decoder.Decode(obj); err != nil {
30
+		return err
31
+	}
32
+	return validate(obj)
33
+}

+ 5
- 0
log/vendor/github.com/gin-gonic/gin/codecov.yml View File

@@ -0,0 +1,5 @@
1
+coverage:
2
+  notify:
3
+    gitter:
4
+      default:
5
+        url: https://webhooks.gitter.im/e/d90dcdeeab2f1e357165

+ 933
- 0
log/vendor/github.com/gin-gonic/gin/context.go View File

@@ -0,0 +1,933 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"errors"
9
+	"io"
10
+	"io/ioutil"
11
+	"math"
12
+	"mime/multipart"
13
+	"net"
14
+	"net/http"
15
+	"net/url"
16
+	"os"
17
+	"strings"
18
+	"time"
19
+
20
+	"github.com/gin-contrib/sse"
21
+	"github.com/gin-gonic/gin/binding"
22
+	"github.com/gin-gonic/gin/render"
23
+)
24
+
25
+// Content-Type MIME of the most common data formats.
26
+const (
27
+	MIMEJSON              = binding.MIMEJSON
28
+	MIMEHTML              = binding.MIMEHTML
29
+	MIMEXML               = binding.MIMEXML
30
+	MIMEXML2              = binding.MIMEXML2
31
+	MIMEPlain             = binding.MIMEPlain
32
+	MIMEPOSTForm          = binding.MIMEPOSTForm
33
+	MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
34
+	BodyBytesKey          = "_gin-gonic/gin/bodybyteskey"
35
+)
36
+
37
+const abortIndex int8 = math.MaxInt8 / 2
38
+
39
+// Context is the most important part of gin. It allows us to pass variables between middleware,
40
+// manage the flow, validate the JSON of a request and render a JSON response for example.
41
+type Context struct {
42
+	writermem responseWriter
43
+	Request   *http.Request
44
+	Writer    ResponseWriter
45
+
46
+	Params   Params
47
+	handlers HandlersChain
48
+	index    int8
49
+
50
+	engine *Engine
51
+
52
+	// Keys is a key/value pair exclusively for the context of each request.
53
+	Keys map[string]interface{}
54
+
55
+	// Errors is a list of errors attached to all the handlers/middlewares who used this context.
56
+	Errors errorMsgs
57
+
58
+	// Accepted defines a list of manually accepted formats for content negotiation.
59
+	Accepted []string
60
+}
61
+
62
+/************************************/
63
+/********** CONTEXT CREATION ********/
64
+/************************************/
65
+
66
+func (c *Context) reset() {
67
+	c.Writer = &c.writermem
68
+	c.Params = c.Params[0:0]
69
+	c.handlers = nil
70
+	c.index = -1
71
+	c.Keys = nil
72
+	c.Errors = c.Errors[0:0]
73
+	c.Accepted = nil
74
+}
75
+
76
+// Copy returns a copy of the current context that can be safely used outside the request's scope.
77
+// This has to be used when the context has to be passed to a goroutine.
78
+func (c *Context) Copy() *Context {
79
+	var cp = *c
80
+	cp.writermem.ResponseWriter = nil
81
+	cp.Writer = &cp.writermem
82
+	cp.index = abortIndex
83
+	cp.handlers = nil
84
+	return &cp
85
+}
86
+
87
+// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()",
88
+// this function will return "main.handleGetUsers".
89
+func (c *Context) HandlerName() string {
90
+	return nameOfFunction(c.handlers.Last())
91
+}
92
+
93
+// Handler returns the main handler.
94
+func (c *Context) Handler() HandlerFunc {
95
+	return c.handlers.Last()
96
+}
97
+
98
+/************************************/
99
+/*********** FLOW CONTROL ***********/
100
+/************************************/
101
+
102
+// Next should be used only inside middleware.
103
+// It executes the pending handlers in the chain inside the calling handler.
104
+// See example in GitHub.
105
+func (c *Context) Next() {
106
+	c.index++
107
+	for s := int8(len(c.handlers)); c.index < s; c.index++ {
108
+		c.handlers[c.index](c)
109
+	}
110
+}
111
+
112
+// IsAborted returns true if the current context was aborted.
113
+func (c *Context) IsAborted() bool {
114
+	return c.index >= abortIndex
115
+}
116
+
117
+// Abort prevents pending handlers from being called. Note that this will not stop the current handler.
118
+// Let's say you have an authorization middleware that validates that the current request is authorized.
119
+// If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
120
+// for this request are not called.
121
+func (c *Context) Abort() {
122
+	c.index = abortIndex
123
+}
124
+
125
+// AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
126
+// For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
127
+func (c *Context) AbortWithStatus(code int) {
128
+	c.Status(code)
129
+	c.Writer.WriteHeaderNow()
130
+	c.Abort()
131
+}
132
+
133
+// AbortWithStatusJSON calls `Abort()` and then `JSON` internally.
134
+// This method stops the chain, writes the status code and return a JSON body.
135
+// It also sets the Content-Type as "application/json".
136
+func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {
137
+	c.Abort()
138
+	c.JSON(code, jsonObj)
139
+}
140
+
141
+// AbortWithError calls `AbortWithStatus()` and `Error()` internally.
142
+// This method stops the chain, writes the status code and pushes the specified error to `c.Errors`.
143
+// See Context.Error() for more details.
144
+func (c *Context) AbortWithError(code int, err error) *Error {
145
+	c.AbortWithStatus(code)
146
+	return c.Error(err)
147
+}
148
+
149
+/************************************/
150
+/********* ERROR MANAGEMENT *********/
151
+/************************************/
152
+
153
+// Error attaches an error to the current context. The error is pushed to a list of errors.
154
+// It's a good idea to call Error for each error that occurred during the resolution of a request.
155
+// A middleware can be used to collect all the errors and push them to a database together,
156
+// print a log, or append it in the HTTP response.
157
+// Error will panic if err is nil.
158
+func (c *Context) Error(err error) *Error {
159
+	if err == nil {
160
+		panic("err is nil")
161
+	}
162
+
163
+	parsedError, ok := err.(*Error)
164
+	if !ok {
165
+		parsedError = &Error{
166
+			Err:  err,
167
+			Type: ErrorTypePrivate,
168
+		}
169
+	}
170
+
171
+	c.Errors = append(c.Errors, parsedError)
172
+	return parsedError
173
+}
174
+
175
+/************************************/
176
+/******** METADATA MANAGEMENT********/
177
+/************************************/
178
+
179
+// Set is used to store a new key/value pair exclusively for this context.
180
+// It also lazy initializes  c.Keys if it was not used previously.
181
+func (c *Context) Set(key string, value interface{}) {
182
+	if c.Keys == nil {
183
+		c.Keys = make(map[string]interface{})
184
+	}
185
+	c.Keys[key] = value
186
+}
187
+
188
+// Get returns the value for the given key, ie: (value, true).
189
+// If the value does not exists it returns (nil, false)
190
+func (c *Context) Get(key string) (value interface{}, exists bool) {
191
+	value, exists = c.Keys[key]
192
+	return
193
+}
194
+
195
+// MustGet returns the value for the given key if it exists, otherwise it panics.
196
+func (c *Context) MustGet(key string) interface{} {
197
+	if value, exists := c.Get(key); exists {
198
+		return value
199
+	}
200
+	panic("Key \"" + key + "\" does not exist")
201
+}
202
+
203
+// GetString returns the value associated with the key as a string.
204
+func (c *Context) GetString(key string) (s string) {
205
+	if val, ok := c.Get(key); ok && val != nil {
206
+		s, _ = val.(string)
207
+	}
208
+	return
209
+}
210
+
211
+// GetBool returns the value associated with the key as a boolean.
212
+func (c *Context) GetBool(key string) (b bool) {
213
+	if val, ok := c.Get(key); ok && val != nil {
214
+		b, _ = val.(bool)
215
+	}
216
+	return
217
+}
218
+
219
+// GetInt returns the value associated with the key as an integer.
220
+func (c *Context) GetInt(key string) (i int) {
221
+	if val, ok := c.Get(key); ok && val != nil {
222
+		i, _ = val.(int)
223
+	}
224
+	return
225
+}
226
+
227
+// GetInt64 returns the value associated with the key as an integer.
228
+func (c *Context) GetInt64(key string) (i64 int64) {
229
+	if val, ok := c.Get(key); ok && val != nil {
230
+		i64, _ = val.(int64)
231
+	}
232
+	return
233
+}
234
+
235
+// GetFloat64 returns the value associated with the key as a float64.
236
+func (c *Context) GetFloat64(key string) (f64 float64) {
237
+	if val, ok := c.Get(key); ok && val != nil {
238
+		f64, _ = val.(float64)
239
+	}
240
+	return
241
+}
242
+
243
+// GetTime returns the value associated with the key as time.
244
+func (c *Context) GetTime(key string) (t time.Time) {
245
+	if val, ok := c.Get(key); ok && val != nil {
246
+		t, _ = val.(time.Time)
247
+	}
248
+	return
249
+}
250
+
251
+// GetDuration returns the value associated with the key as a duration.
252
+func (c *Context) GetDuration(key string) (d time.Duration) {
253
+	if val, ok := c.Get(key); ok && val != nil {
254
+		d, _ = val.(time.Duration)
255
+	}
256
+	return
257
+}
258
+
259
+// GetStringSlice returns the value associated with the key as a slice of strings.
260
+func (c *Context) GetStringSlice(key string) (ss []string) {
261
+	if val, ok := c.Get(key); ok && val != nil {
262
+		ss, _ = val.([]string)
263
+	}
264
+	return
265
+}
266
+
267
+// GetStringMap returns the value associated with the key as a map of interfaces.
268
+func (c *Context) GetStringMap(key string) (sm map[string]interface{}) {
269
+	if val, ok := c.Get(key); ok && val != nil {
270
+		sm, _ = val.(map[string]interface{})
271
+	}
272
+	return
273
+}
274
+
275
+// GetStringMapString returns the value associated with the key as a map of strings.
276
+func (c *Context) GetStringMapString(key string) (sms map[string]string) {
277
+	if val, ok := c.Get(key); ok && val != nil {
278
+		sms, _ = val.(map[string]string)
279
+	}
280
+	return
281
+}
282
+
283
+// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
284
+func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) {
285
+	if val, ok := c.Get(key); ok && val != nil {
286
+		smss, _ = val.(map[string][]string)
287
+	}
288
+	return
289
+}
290
+
291
+/************************************/
292
+/************ INPUT DATA ************/
293
+/************************************/
294
+
295
+// Param returns the value of the URL param.
296
+// It is a shortcut for c.Params.ByName(key)
297
+//     router.GET("/user/:id", func(c *gin.Context) {
298
+//         // a GET request to /user/john
299
+//         id := c.Param("id") // id == "john"
300
+//     })
301
+func (c *Context) Param(key string) string {
302
+	return c.Params.ByName(key)
303
+}
304
+
305
+// Query returns the keyed url query value if it exists,
306
+// otherwise it returns an empty string `("")`.
307
+// It is shortcut for `c.Request.URL.Query().Get(key)`
308
+//     GET /path?id=1234&name=Manu&value=
309
+// 	   c.Query("id") == "1234"
310
+// 	   c.Query("name") == "Manu"
311
+// 	   c.Query("value") == ""
312
+// 	   c.Query("wtf") == ""
313
+func (c *Context) Query(key string) string {
314
+	value, _ := c.GetQuery(key)
315
+	return value
316
+}
317
+
318
+// DefaultQuery returns the keyed url query value if it exists,
319
+// otherwise it returns the specified defaultValue string.
320
+// See: Query() and GetQuery() for further information.
321
+//     GET /?name=Manu&lastname=
322
+//     c.DefaultQuery("name", "unknown") == "Manu"
323
+//     c.DefaultQuery("id", "none") == "none"
324
+//     c.DefaultQuery("lastname", "none") == ""
325
+func (c *Context) DefaultQuery(key, defaultValue string) string {
326
+	if value, ok := c.GetQuery(key); ok {
327
+		return value
328
+	}
329
+	return defaultValue
330
+}
331
+
332
+// GetQuery is like Query(), it returns the keyed url query value
333
+// if it exists `(value, true)` (even when the value is an empty string),
334
+// otherwise it returns `("", false)`.
335
+// It is shortcut for `c.Request.URL.Query().Get(key)`
336
+//     GET /?name=Manu&lastname=
337
+//     ("Manu", true) == c.GetQuery("name")
338
+//     ("", false) == c.GetQuery("id")
339
+//     ("", true) == c.GetQuery("lastname")
340
+func (c *Context) GetQuery(key string) (string, bool) {
341
+	if values, ok := c.GetQueryArray(key); ok {
342
+		return values[0], ok
343
+	}
344
+	return "", false
345
+}
346
+
347
+// QueryArray returns a slice of strings for a given query key.
348
+// The length of the slice depends on the number of params with the given key.
349
+func (c *Context) QueryArray(key string) []string {
350
+	values, _ := c.GetQueryArray(key)
351
+	return values
352
+}
353
+
354
+// GetQueryArray returns a slice of strings for a given query key, plus
355
+// a boolean value whether at least one value exists for the given key.
356
+func (c *Context) GetQueryArray(key string) ([]string, bool) {
357
+	if values, ok := c.Request.URL.Query()[key]; ok && len(values) > 0 {
358
+		return values, true
359
+	}
360
+	return []string{}, false
361
+}
362
+
363
+// QueryMap returns a map for a given query key.
364
+func (c *Context) QueryMap(key string) map[string]string {
365
+	dicts, _ := c.GetQueryMap(key)
366
+	return dicts
367
+}
368
+
369
+// GetQueryMap returns a map for a given query key, plus a boolean value
370
+// whether at least one value exists for the given key.
371
+func (c *Context) GetQueryMap(key string) (map[string]string, bool) {
372
+	return c.get(c.Request.URL.Query(), key)
373
+}
374
+
375
+// PostForm returns the specified key from a POST urlencoded form or multipart form
376
+// when it exists, otherwise it returns an empty string `("")`.
377
+func (c *Context) PostForm(key string) string {
378
+	value, _ := c.GetPostForm(key)
379
+	return value
380
+}
381
+
382
+// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
383
+// when it exists, otherwise it returns the specified defaultValue string.
384
+// See: PostForm() and GetPostForm() for further information.
385
+func (c *Context) DefaultPostForm(key, defaultValue string) string {
386
+	if value, ok := c.GetPostForm(key); ok {
387
+		return value
388
+	}
389
+	return defaultValue
390
+}
391
+
392
+// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
393
+// form or multipart form when it exists `(value, true)` (even when the value is an empty string),
394
+// otherwise it returns ("", false).
395
+// For example, during a PATCH request to update the user's email:
396
+//     email=mail@example.com  -->  ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
397
+// 	   email=                  -->  ("", true) := GetPostForm("email") // set email to ""
398
+//                             -->  ("", false) := GetPostForm("email") // do nothing with email
399
+func (c *Context) GetPostForm(key string) (string, bool) {
400
+	if values, ok := c.GetPostFormArray(key); ok {
401
+		return values[0], ok
402
+	}
403
+	return "", false
404
+}
405
+
406
+// PostFormArray returns a slice of strings for a given form key.
407
+// The length of the slice depends on the number of params with the given key.
408
+func (c *Context) PostFormArray(key string) []string {
409
+	values, _ := c.GetPostFormArray(key)
410
+	return values
411
+}
412
+
413
+// GetPostFormArray returns a slice of strings for a given form key, plus
414
+// a boolean value whether at least one value exists for the given key.
415
+func (c *Context) GetPostFormArray(key string) ([]string, bool) {
416
+	req := c.Request
417
+	req.ParseForm()
418
+	req.ParseMultipartForm(c.engine.MaxMultipartMemory)
419
+	if values := req.PostForm[key]; len(values) > 0 {
420
+		return values, true
421
+	}
422
+	if req.MultipartForm != nil && req.MultipartForm.File != nil {
423
+		if values := req.MultipartForm.Value[key]; len(values) > 0 {
424
+			return values, true
425
+		}
426
+	}
427
+	return []string{}, false
428
+}
429
+
430
+// PostFormMap returns a map for a given form key.
431
+func (c *Context) PostFormMap(key string) map[string]string {
432
+	dicts, _ := c.GetPostFormMap(key)
433
+	return dicts
434
+}
435
+
436
+// GetPostFormMap returns a map for a given form key, plus a boolean value
437
+// whether at least one value exists for the given key.
438
+func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {
439
+	req := c.Request
440
+	req.ParseForm()
441
+	req.ParseMultipartForm(c.engine.MaxMultipartMemory)
442
+	dicts, exist := c.get(req.PostForm, key)
443
+
444
+	if !exist && req.MultipartForm != nil && req.MultipartForm.File != nil {
445
+		dicts, exist = c.get(req.MultipartForm.Value, key)
446
+	}
447
+
448
+	return dicts, exist
449
+}
450
+
451
+// get is an internal method and returns a map which satisfy conditions.
452
+func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) {
453
+	dicts := make(map[string]string)
454
+	exist := false
455
+	for k, v := range m {
456
+		if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {
457
+			if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {
458
+				exist = true
459
+				dicts[k[i+1:][:j]] = v[0]
460
+			}
461
+		}
462
+	}
463
+	return dicts, exist
464
+}
465
+
466
+// FormFile returns the first file for the provided form key.
467
+func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
468
+	_, fh, err := c.Request.FormFile(name)
469
+	return fh, err
470
+}
471
+
472
+// MultipartForm is the parsed multipart form, including file uploads.
473
+func (c *Context) MultipartForm() (*multipart.Form, error) {
474
+	err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
475
+	return c.Request.MultipartForm, err
476
+}
477
+
478
+// SaveUploadedFile uploads the form file to specific dst.
479
+func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
480
+	src, err := file.Open()
481
+	if err != nil {
482
+		return err
483
+	}
484
+	defer src.Close()
485
+
486
+	out, err := os.Create(dst)
487
+	if err != nil {
488
+		return err
489
+	}
490
+	defer out.Close()
491
+
492
+	io.Copy(out, src)
493
+	return nil
494
+}
495
+
496
+// Bind checks the Content-Type to select a binding engine automatically,
497
+// Depending the "Content-Type" header different bindings are used:
498
+//     "application/json" --> JSON binding
499
+//     "application/xml"  --> XML binding
500
+// otherwise --> returns an error.
501
+// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
502
+// It decodes the json payload into the struct specified as a pointer.
503
+// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
504
+func (c *Context) Bind(obj interface{}) error {
505
+	b := binding.Default(c.Request.Method, c.ContentType())
506
+	return c.MustBindWith(obj, b)
507
+}
508
+
509
+// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
510
+func (c *Context) BindJSON(obj interface{}) error {
511
+	return c.MustBindWith(obj, binding.JSON)
512
+}
513
+
514
+// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).
515
+func (c *Context) BindQuery(obj interface{}) error {
516
+	return c.MustBindWith(obj, binding.Query)
517
+}
518
+
519
+// MustBindWith binds the passed struct pointer using the specified binding engine.
520
+// It will abort the request with HTTP 400 if any error ocurrs.
521
+// See the binding package.
522
+func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) {
523
+	if err = c.ShouldBindWith(obj, b); err != nil {
524
+		c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind)
525
+	}
526
+
527
+	return
528
+}
529
+
530
+// ShouldBind checks the Content-Type to select a binding engine automatically,
531
+// Depending the "Content-Type" header different bindings are used:
532
+//     "application/json" --> JSON binding
533
+//     "application/xml"  --> XML binding
534
+// otherwise --> returns an error
535
+// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
536
+// It decodes the json payload into the struct specified as a pointer.
537
+// Like c.Bind() but this method does not set the response status code to 400 and abort if the json is not valid.
538
+func (c *Context) ShouldBind(obj interface{}) error {
539
+	b := binding.Default(c.Request.Method, c.ContentType())
540
+	return c.ShouldBindWith(obj, b)
541
+}
542
+
543
+// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
544
+func (c *Context) ShouldBindJSON(obj interface{}) error {
545
+	return c.ShouldBindWith(obj, binding.JSON)
546
+}
547
+
548
+// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).
549
+func (c *Context) ShouldBindQuery(obj interface{}) error {
550
+	return c.ShouldBindWith(obj, binding.Query)
551
+}
552
+
553
+// ShouldBindWith binds the passed struct pointer using the specified binding engine.
554
+// See the binding package.
555
+func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
556
+	return b.Bind(c.Request, obj)
557
+}
558
+
559
+// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
560
+// body into the context, and reuse when it is called again.
561
+//
562
+// NOTE: This method reads the body before binding. So you should use
563
+// ShouldBindWith for better performance if you need to call only once.
564
+func (c *Context) ShouldBindBodyWith(
565
+	obj interface{}, bb binding.BindingBody,
566
+) (err error) {
567
+	var body []byte
568
+	if cb, ok := c.Get(BodyBytesKey); ok {
569
+		if cbb, ok := cb.([]byte); ok {
570
+			body = cbb
571
+		}
572
+	}
573
+	if body == nil {
574
+		body, err = ioutil.ReadAll(c.Request.Body)
575
+		if err != nil {
576
+			return err
577
+		}
578
+		c.Set(BodyBytesKey, body)
579
+	}
580
+	return bb.BindBody(body, obj)
581
+}
582
+
583
+// ClientIP implements a best effort algorithm to return the real client IP, it parses
584
+// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
585
+// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
586
+func (c *Context) ClientIP() string {
587
+	if c.engine.ForwardedByClientIP {
588
+		clientIP := c.requestHeader("X-Forwarded-For")
589
+		clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
590
+		if clientIP == "" {
591
+			clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
592
+		}
593
+		if clientIP != "" {
594
+			return clientIP
595
+		}
596
+	}
597
+
598
+	if c.engine.AppEngine {
599
+		if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {
600
+			return addr
601
+		}
602
+	}
603
+
604
+	if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
605
+		return ip
606
+	}
607
+
608
+	return ""
609
+}
610
+
611
+// ContentType returns the Content-Type header of the request.
612
+func (c *Context) ContentType() string {
613
+	return filterFlags(c.requestHeader("Content-Type"))
614
+}
615
+
616
+// IsWebsocket returns true if the request headers indicate that a websocket
617
+// handshake is being initiated by the client.
618
+func (c *Context) IsWebsocket() bool {
619
+	if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
620
+		strings.ToLower(c.requestHeader("Upgrade")) == "websocket" {
621
+		return true
622
+	}
623
+	return false
624
+}
625
+
626
+func (c *Context) requestHeader(key string) string {
627
+	return c.Request.Header.Get(key)
628
+}
629
+
630
+/************************************/
631
+/******** RESPONSE RENDERING ********/
632
+/************************************/
633
+
634
+// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
635
+func bodyAllowedForStatus(status int) bool {
636
+	switch {
637
+	case status >= 100 && status <= 199:
638
+		return false
639
+	case status == http.StatusNoContent:
640
+		return false
641
+	case status == http.StatusNotModified:
642
+		return false
643
+	}
644
+	return true
645
+}
646
+
647
+// Status sets the HTTP response code.
648
+func (c *Context) Status(code int) {
649
+	c.writermem.WriteHeader(code)
650
+}
651
+
652
+// Header is a intelligent shortcut for c.Writer.Header().Set(key, value).
653
+// It writes a header in the response.
654
+// If value == "", this method removes the header `c.Writer.Header().Del(key)`
655
+func (c *Context) Header(key, value string) {
656
+	if value == "" {
657
+		c.Writer.Header().Del(key)
658
+	} else {
659
+		c.Writer.Header().Set(key, value)
660
+	}
661
+}
662
+
663
+// GetHeader returns value from request headers.
664
+func (c *Context) GetHeader(key string) string {
665
+	return c.requestHeader(key)
666
+}
667
+
668
+// GetRawData return stream data.
669
+func (c *Context) GetRawData() ([]byte, error) {
670
+	return ioutil.ReadAll(c.Request.Body)
671
+}
672
+
673
+// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
674
+// The provided cookie must have a valid Name. Invalid cookies may be
675
+// silently dropped.
676
+func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
677
+	if path == "" {
678
+		path = "/"
679
+	}
680
+	http.SetCookie(c.Writer, &http.Cookie{
681
+		Name:     name,
682
+		Value:    url.QueryEscape(value),
683
+		MaxAge:   maxAge,
684
+		Path:     path,
685
+		Domain:   domain,
686
+		Secure:   secure,
687
+		HttpOnly: httpOnly,
688
+	})
689
+}
690
+
691
+// Cookie returns the named cookie provided in the request or
692
+// ErrNoCookie if not found. And return the named cookie is unescaped.
693
+// If multiple cookies match the given name, only one cookie will
694
+// be returned.
695
+func (c *Context) Cookie(name string) (string, error) {
696
+	cookie, err := c.Request.Cookie(name)
697
+	if err != nil {
698
+		return "", err
699
+	}
700
+	val, _ := url.QueryUnescape(cookie.Value)
701
+	return val, nil
702
+}
703
+
704
+func (c *Context) Render(code int, r render.Render) {
705
+	c.Status(code)
706
+
707
+	if !bodyAllowedForStatus(code) {
708
+		r.WriteContentType(c.Writer)
709
+		c.Writer.WriteHeaderNow()
710
+		return
711
+	}
712
+
713
+	if err := r.Render(c.Writer); err != nil {
714
+		panic(err)
715
+	}
716
+}
717
+
718
+// HTML renders the HTTP template specified by its file name.
719
+// It also updates the HTTP code and sets the Content-Type as "text/html".
720
+// See http://golang.org/doc/articles/wiki/
721
+func (c *Context) HTML(code int, name string, obj interface{}) {
722
+	instance := c.engine.HTMLRender.Instance(name, obj)
723
+	c.Render(code, instance)
724
+}
725
+
726
+// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
727
+// It also sets the Content-Type as "application/json".
728
+// WARNING: we recommend to use this only for development purposes since printing pretty JSON is
729
+// more CPU and bandwidth consuming. Use Context.JSON() instead.
730
+func (c *Context) IndentedJSON(code int, obj interface{}) {
731
+	c.Render(code, render.IndentedJSON{Data: obj})
732
+}
733
+
734
+// SecureJSON serializes the given struct as Secure JSON into the response body.
735
+// Default prepends "while(1)," to response body if the given struct is array values.
736
+// It also sets the Content-Type as "application/json".
737
+func (c *Context) SecureJSON(code int, obj interface{}) {
738
+	c.Render(code, render.SecureJSON{Prefix: c.engine.secureJsonPrefix, Data: obj})
739
+}
740
+
741
+// JSONP serializes the given struct as JSON into the response body.
742
+// It add padding to response body to request data from a server residing in a different domain than the client.
743
+// It also sets the Content-Type as "application/javascript".
744
+func (c *Context) JSONP(code int, obj interface{}) {
745
+	callback := c.DefaultQuery("callback", "")
746
+	if callback == "" {
747
+		c.Render(code, render.JSON{Data: obj})
748
+	} else {
749
+		c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
750
+	}
751
+}
752
+
753
+// JSON serializes the given struct as JSON into the response body.
754
+// It also sets the Content-Type as "application/json".
755
+func (c *Context) JSON(code int, obj interface{}) {
756
+	c.Render(code, render.JSON{Data: obj})
757
+}
758
+
759
+// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.
760
+// It also sets the Content-Type as "application/json".
761
+func (c *Context) AsciiJSON(code int, obj interface{}) {
762
+	c.Render(code, render.AsciiJSON{Data: obj})
763
+}
764
+
765
+// XML serializes the given struct as XML into the response body.
766
+// It also sets the Content-Type as "application/xml".
767
+func (c *Context) XML(code int, obj interface{}) {
768
+	c.Render(code, render.XML{Data: obj})
769
+}
770
+
771
+// YAML serializes the given struct as YAML into the response body.
772
+func (c *Context) YAML(code int, obj interface{}) {
773
+	c.Render(code, render.YAML{Data: obj})
774
+}
775
+
776
+// String writes the given string into the response body.
777
+func (c *Context) String(code int, format string, values ...interface{}) {
778
+	c.Render(code, render.String{Format: format, Data: values})
779
+}
780
+
781
+// Redirect returns a HTTP redirect to the specific location.
782
+func (c *Context) Redirect(code int, location string) {
783
+	c.Render(-1, render.Redirect{
784
+		Code:     code,
785
+		Location: location,
786
+		Request:  c.Request,
787
+	})
788
+}
789
+
790
+// Data writes some data into the body stream and updates the HTTP code.
791
+func (c *Context) Data(code int, contentType string, data []byte) {
792
+	c.Render(code, render.Data{
793
+		ContentType: contentType,
794
+		Data:        data,
795
+	})
796
+}
797
+
798
+// DataFromReader writes the specified reader into the body stream and updates the HTTP code.
799
+func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {
800
+	c.Render(code, render.Reader{
801
+		Headers:       extraHeaders,
802
+		ContentType:   contentType,
803
+		ContentLength: contentLength,
804
+		Reader:        reader,
805
+	})
806
+}
807
+
808
+// File writes the specified file into the body stream in a efficient way.
809
+func (c *Context) File(filepath string) {
810
+	http.ServeFile(c.Writer, c.Request, filepath)
811
+}
812
+
813
+// SSEvent writes a Server-Sent Event into the body stream.
814
+func (c *Context) SSEvent(name string, message interface{}) {
815
+	c.Render(-1, sse.Event{
816
+		Event: name,
817
+		Data:  message,
818
+	})
819
+}
820
+
821
+func (c *Context) Stream(step func(w io.Writer) bool) {
822
+	w := c.Writer
823
+	clientGone := w.CloseNotify()
824
+	for {
825
+		select {
826
+		case <-clientGone:
827
+			return
828
+		default:
829
+			keepOpen := step(w)
830
+			w.Flush()
831
+			if !keepOpen {
832
+				return
833
+			}
834
+		}
835
+	}
836
+}
837
+
838
+/************************************/
839
+/******** CONTENT NEGOTIATION *******/
840
+/************************************/
841
+
842
+type Negotiate struct {
843
+	Offered  []string
844
+	HTMLName string
845
+	HTMLData interface{}
846
+	JSONData interface{}
847
+	XMLData  interface{}
848
+	Data     interface{}
849
+}
850
+
851
+func (c *Context) Negotiate(code int, config Negotiate) {
852
+	switch c.NegotiateFormat(config.Offered...) {
853
+	case binding.MIMEJSON:
854
+		data := chooseData(config.JSONData, config.Data)
855
+		c.JSON(code, data)
856
+
857
+	case binding.MIMEHTML:
858
+		data := chooseData(config.HTMLData, config.Data)
859
+		c.HTML(code, config.HTMLName, data)
860
+
861
+	case binding.MIMEXML:
862
+		data := chooseData(config.XMLData, config.Data)
863
+		c.XML(code, data)
864
+
865
+	default:
866
+		c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
867
+	}
868
+}
869
+
870
+func (c *Context) NegotiateFormat(offered ...string) string {
871
+	assert1(len(offered) > 0, "you must provide at least one offer")
872
+
873
+	if c.Accepted == nil {
874
+		c.Accepted = parseAccept(c.requestHeader("Accept"))
875
+	}
876
+	if len(c.Accepted) == 0 {
877
+		return offered[0]
878
+	}
879
+	for _, accepted := range c.Accepted {
880
+		for _, offert := range offered {
881
+			if accepted == offert {
882
+				return offert
883
+			}
884
+		}
885
+	}
886
+	return ""
887
+}
888
+
889
+func (c *Context) SetAccepted(formats ...string) {
890
+	c.Accepted = formats
891
+}
892
+
893
+/************************************/
894
+/***** GOLANG.ORG/X/NET/CONTEXT *****/
895
+/************************************/
896
+
897
+// Deadline returns the time when work done on behalf of this context
898
+// should be canceled. Deadline returns ok==false when no deadline is
899
+// set. Successive calls to Deadline return the same results.
900
+func (c *Context) Deadline() (deadline time.Time, ok bool) {
901
+	return
902
+}
903
+
904
+// Done returns a channel that's closed when work done on behalf of this
905
+// context should be canceled. Done may return nil if this context can
906
+// never be canceled. Successive calls to Done return the same value.
907
+func (c *Context) Done() <-chan struct{} {
908
+	return nil
909
+}
910
+
911
+// Err returns a non-nil error value after Done is closed,
912
+// successive calls to Err return the same error.
913
+// If Done is not yet closed, Err returns nil.
914
+// If Done is closed, Err returns a non-nil error explaining why:
915
+// Canceled if the context was canceled
916
+// or DeadlineExceeded if the context's deadline passed.
917
+func (c *Context) Err() error {
918
+	return nil
919
+}
920
+
921
+// Value returns the value associated with this context for key, or nil
922
+// if no value is associated with key. Successive calls to Value with
923
+// the same key returns the same result.
924
+func (c *Context) Value(key interface{}) interface{} {
925
+	if key == 0 {
926
+		return c.Request
927
+	}
928
+	if keyAsString, ok := key.(string); ok {
929
+		val, _ := c.Get(keyAsString)
930
+		return val
931
+	}
932
+	return nil
933
+}

+ 11
- 0
log/vendor/github.com/gin-gonic/gin/context_appengine.go View File

@@ -0,0 +1,11 @@
1
+// +build appengine
2
+
3
+// Copyright 2017 Manu Martinez-Almeida.  All rights reserved.
4
+// Use of this source code is governed by a MIT style
5
+// license that can be found in the LICENSE file.
6
+
7
+package gin
8
+
9
+func init() {
10
+	defaultAppEngine = true
11
+}

+ 13
- 0
log/vendor/github.com/gin-gonic/gin/coverage.sh View File

@@ -0,0 +1,13 @@
1
+#!/usr/bin/env bash
2
+
3
+set -e
4
+
5
+echo "mode: count" > coverage.out
6
+
7
+for d in $(go list ./... | grep -E 'gin$|binding$|render$' | grep -v 'examples'); do
8
+    go test -v -covermode=count -coverprofile=profile.out $d
9
+    if [ -f profile.out ]; then
10
+        cat profile.out | grep -v "mode:" >> coverage.out
11
+        rm profile.out
12
+    fi
13
+done

+ 80
- 0
log/vendor/github.com/gin-gonic/gin/debug.go View File

@@ -0,0 +1,80 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"bytes"
9
+	"html/template"
10
+	"log"
11
+)
12
+
13
+func init() {
14
+	log.SetFlags(0)
15
+}
16
+
17
+// IsDebugging returns true if the framework is running in debug mode.
18
+// Use SetMode(gin.ReleaseMode) to disable debug mode.
19
+func IsDebugging() bool {
20
+	return ginMode == debugCode
21
+}
22
+
23
+func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {
24
+	if IsDebugging() {
25
+		nuHandlers := len(handlers)
26
+		handlerName := nameOfFunction(handlers.Last())
27
+		debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)
28
+	}
29
+}
30
+
31
+func debugPrintLoadTemplate(tmpl *template.Template) {
32
+	if IsDebugging() {
33
+		var buf bytes.Buffer
34
+		for _, tmpl := range tmpl.Templates() {
35
+			buf.WriteString("\t- ")
36
+			buf.WriteString(tmpl.Name())
37
+			buf.WriteString("\n")
38
+		}
39
+		debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String())
40
+	}
41
+}
42
+
43
+func debugPrint(format string, values ...interface{}) {
44
+	if IsDebugging() {
45
+		log.Printf("[GIN-debug] "+format, values...)
46
+	}
47
+}
48
+
49
+func debugPrintWARNINGDefault() {
50
+	debugPrint(`[WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.
51
+
52
+`)
53
+	debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
54
+
55
+`)
56
+}
57
+
58
+func debugPrintWARNINGNew() {
59
+	debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production.
60
+ - using env:	export GIN_MODE=release
61
+ - using code:	gin.SetMode(gin.ReleaseMode)
62
+
63
+`)
64
+}
65
+
66
+func debugPrintWARNINGSetHTMLTemplate() {
67
+	debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called
68
+at initialization. ie. before any route is registered or the router is listening in a socket:
69
+
70
+	router := gin.Default()
71
+	router.SetHTMLTemplate(template) // << good place
72
+
73
+`)
74
+}
75
+
76
+func debugPrintError(err error) {
77
+	if err != nil {
78
+		debugPrint("[ERROR] %v\n", err)
79
+	}
80
+}

+ 21
- 0
log/vendor/github.com/gin-gonic/gin/deprecated.go View File

@@ -0,0 +1,21 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"log"
9
+
10
+	"github.com/gin-gonic/gin/binding"
11
+)
12
+
13
+// BindWith binds the passed struct pointer using the specified binding engine.
14
+// See the binding package.
15
+func (c *Context) BindWith(obj interface{}, b binding.Binding) error {
16
+	log.Println(`BindWith(\"interface{}, binding.Binding\") error is going to
17
+	be deprecated, please check issue #662 and either use MustBindWith() if you
18
+	want HTTP 400 to be automatically returned if any error occur, or use
19
+	ShouldBindWith() if you need to manage the error.`)
20
+	return c.MustBindWith(obj, b)
21
+}

+ 6
- 0
log/vendor/github.com/gin-gonic/gin/doc.go View File

@@ -0,0 +1,6 @@
1
+/*
2
+Package gin implements a HTTP web framework called gin.
3
+
4
+See https://gin-gonic.github.io/gin/ for more information about gin.
5
+*/
6
+package gin // import "github.com/gin-gonic/gin"

+ 157
- 0
log/vendor/github.com/gin-gonic/gin/errors.go View File

@@ -0,0 +1,157 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"bytes"
9
+	"fmt"
10
+	"reflect"
11
+
12
+	"github.com/gin-gonic/gin/json"
13
+)
14
+
15
+type ErrorType uint64
16
+
17
+const (
18
+	ErrorTypeBind    ErrorType = 1 << 63 // used when c.Bind() fails
19
+	ErrorTypeRender  ErrorType = 1 << 62 // used when c.Render() fails
20
+	ErrorTypePrivate ErrorType = 1 << 0
21
+	ErrorTypePublic  ErrorType = 1 << 1
22
+
23
+	ErrorTypeAny ErrorType = 1<<64 - 1
24
+	ErrorTypeNu            = 2
25
+)
26
+
27
+type Error struct {
28
+	Err  error
29
+	Type ErrorType
30
+	Meta interface{}
31
+}
32
+
33
+type errorMsgs []*Error
34
+
35
+var _ error = &Error{}
36
+
37
+func (msg *Error) SetType(flags ErrorType) *Error {
38
+	msg.Type = flags
39
+	return msg
40
+}
41
+
42
+func (msg *Error) SetMeta(data interface{}) *Error {
43
+	msg.Meta = data
44
+	return msg
45
+}
46
+
47
+func (msg *Error) JSON() interface{} {
48
+	json := H{}
49
+	if msg.Meta != nil {
50
+		value := reflect.ValueOf(msg.Meta)
51
+		switch value.Kind() {
52
+		case reflect.Struct:
53
+			return msg.Meta
54
+		case reflect.Map:
55
+			for _, key := range value.MapKeys() {
56
+				json[key.String()] = value.MapIndex(key).Interface()
57
+			}
58
+		default:
59
+			json["meta"] = msg.Meta
60
+		}
61
+	}
62
+	if _, ok := json["error"]; !ok {
63
+		json["error"] = msg.Error()
64
+	}
65
+	return json
66
+}
67
+
68
+// MarshalJSON implements the json.Marshaller interface.
69
+func (msg *Error) MarshalJSON() ([]byte, error) {
70
+	return json.Marshal(msg.JSON())
71
+}
72
+
73
+// Error implements the error interface
74
+func (msg Error) Error() string {
75
+	return msg.Err.Error()
76
+}
77
+
78
+func (msg *Error) IsType(flags ErrorType) bool {
79
+	return (msg.Type & flags) > 0
80
+}
81
+
82
+// ByType returns a readonly copy filtered the byte.
83
+// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic.
84
+func (a errorMsgs) ByType(typ ErrorType) errorMsgs {
85
+	if len(a) == 0 {
86
+		return nil
87
+	}
88
+	if typ == ErrorTypeAny {
89
+		return a
90
+	}
91
+	var result errorMsgs
92
+	for _, msg := range a {
93
+		if msg.IsType(typ) {
94
+			result = append(result, msg)
95
+		}
96
+	}
97
+	return result
98
+}
99
+
100
+// Last returns the last error in the slice. It returns nil if the array is empty.
101
+// Shortcut for errors[len(errors)-1].
102
+func (a errorMsgs) Last() *Error {
103
+	if length := len(a); length > 0 {
104
+		return a[length-1]
105
+	}
106
+	return nil
107
+}
108
+
109
+// Errors returns an array will all the error messages.
110
+// Example:
111
+// 		c.Error(errors.New("first"))
112
+// 		c.Error(errors.New("second"))
113
+// 		c.Error(errors.New("third"))
114
+// 		c.Errors.Errors() // == []string{"first", "second", "third"}
115
+func (a errorMsgs) Errors() []string {
116
+	if len(a) == 0 {
117
+		return nil
118
+	}
119
+	errorStrings := make([]string, len(a))
120
+	for i, err := range a {
121
+		errorStrings[i] = err.Error()
122
+	}
123
+	return errorStrings
124
+}
125
+
126
+func (a errorMsgs) JSON() interface{} {
127
+	switch len(a) {
128
+	case 0:
129
+		return nil
130
+	case 1:
131
+		return a.Last().JSON()
132
+	default:
133
+		json := make([]interface{}, len(a))
134
+		for i, err := range a {
135
+			json[i] = err.JSON()
136
+		}
137
+		return json
138
+	}
139
+}
140
+
141
+func (a errorMsgs) MarshalJSON() ([]byte, error) {
142
+	return json.Marshal(a.JSON())
143
+}
144
+
145
+func (a errorMsgs) String() string {
146
+	if len(a) == 0 {
147
+		return ""
148
+	}
149
+	var buffer bytes.Buffer
150
+	for i, msg := range a {
151
+		fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err)
152
+		if msg.Meta != nil {
153
+			fmt.Fprintf(&buffer, "     Meta: %v\n", msg.Meta)
154
+		}
155
+	}
156
+	return buffer.String()
157
+}

+ 45
- 0
log/vendor/github.com/gin-gonic/gin/fs.go View File

@@ -0,0 +1,45 @@
1
+// Copyright 2017 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"net/http"
9
+	"os"
10
+)
11
+
12
+type onlyfilesFS struct {
13
+	fs http.FileSystem
14
+}
15
+
16
+type neuteredReaddirFile struct {
17
+	http.File
18
+}
19
+
20
+// Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally
21
+// in router.Static().
22
+// if listDirectory == true, then it works the same as http.Dir() otherwise it returns
23
+// a filesystem that prevents http.FileServer() to list the directory files.
24
+func Dir(root string, listDirectory bool) http.FileSystem {
25
+	fs := http.Dir(root)
26
+	if listDirectory {
27
+		return fs
28
+	}
29
+	return &onlyfilesFS{fs}
30
+}
31
+
32
+// Open conforms to http.Filesystem.
33
+func (fs onlyfilesFS) Open(name string) (http.File, error) {
34
+	f, err := fs.fs.Open(name)
35
+	if err != nil {
36
+		return nil, err
37
+	}
38
+	return neuteredReaddirFile{f}, nil
39
+}
40
+
41
+// Readdir overrides the http.File default implementation.
42
+func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
43
+	// this disables directory listing
44
+	return nil, nil
45
+}

+ 443
- 0
log/vendor/github.com/gin-gonic/gin/gin.go View File

@@ -0,0 +1,443 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"html/template"
9
+	"net"
10
+	"net/http"
11
+	"os"
12
+	"sync"
13
+
14
+	"github.com/gin-gonic/gin/render"
15
+)
16
+
17
+const (
18
+	// Version is Framework's version.
19
+	Version                = "v1.3.0"
20
+	defaultMultipartMemory = 32 << 20 // 32 MB
21
+)
22
+
23
+var (
24
+	default404Body   = []byte("404 page not found")
25
+	default405Body   = []byte("405 method not allowed")
26
+	defaultAppEngine bool
27
+)
28
+
29
+type HandlerFunc func(*Context)
30
+type HandlersChain []HandlerFunc
31
+
32
+// Last returns the last handler in the chain. ie. the last handler is the main own.
33
+func (c HandlersChain) Last() HandlerFunc {
34
+	if length := len(c); length > 0 {
35
+		return c[length-1]
36
+	}
37
+	return nil
38
+}
39
+
40
+type RouteInfo struct {
41
+	Method  string
42
+	Path    string
43
+	Handler string
44
+}
45
+
46
+type RoutesInfo []RouteInfo
47
+
48
+// Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
49
+// Create an instance of Engine, by using New() or Default()
50
+type Engine struct {
51
+	RouterGroup
52
+
53
+	// Enables automatic redirection if the current route can't be matched but a
54
+	// handler for the path with (without) the trailing slash exists.
55
+	// For example if /foo/ is requested but a route only exists for /foo, the
56
+	// client is redirected to /foo with http status code 301 for GET requests
57
+	// and 307 for all other request methods.
58
+	RedirectTrailingSlash bool
59
+
60
+	// If enabled, the router tries to fix the current request path, if no
61
+	// handle is registered for it.
62
+	// First superfluous path elements like ../ or // are removed.
63
+	// Afterwards the router does a case-insensitive lookup of the cleaned path.
64
+	// If a handle can be found for this route, the router makes a redirection
65
+	// to the corrected path with status code 301 for GET requests and 307 for
66
+	// all other request methods.
67
+	// For example /FOO and /..//Foo could be redirected to /foo.
68
+	// RedirectTrailingSlash is independent of this option.
69
+	RedirectFixedPath bool
70
+
71
+	// If enabled, the router checks if another method is allowed for the
72
+	// current route, if the current request can not be routed.
73
+	// If this is the case, the request is answered with 'Method Not Allowed'
74
+	// and HTTP status code 405.
75
+	// If no other Method is allowed, the request is delegated to the NotFound
76
+	// handler.
77
+	HandleMethodNotAllowed bool
78
+	ForwardedByClientIP    bool
79
+
80
+	// #726 #755 If enabled, it will thrust some headers starting with
81
+	// 'X-AppEngine...' for better integration with that PaaS.
82
+	AppEngine bool
83
+
84
+	// If enabled, the url.RawPath will be used to find parameters.
85
+	UseRawPath bool
86
+
87
+	// If true, the path value will be unescaped.
88
+	// If UseRawPath is false (by default), the UnescapePathValues effectively is true,
89
+	// as url.Path gonna be used, which is already unescaped.
90
+	UnescapePathValues bool
91
+
92
+	// Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm
93
+	// method call.
94
+	MaxMultipartMemory int64
95
+
96
+	delims           render.Delims
97
+	secureJsonPrefix string
98
+	HTMLRender       render.HTMLRender
99
+	FuncMap          template.FuncMap
100
+	allNoRoute       HandlersChain
101
+	allNoMethod      HandlersChain
102
+	noRoute          HandlersChain
103
+	noMethod         HandlersChain
104
+	pool             sync.Pool
105
+	trees            methodTrees
106
+}
107
+
108
+var _ IRouter = &Engine{}
109
+
110
+// New returns a new blank Engine instance without any middleware attached.
111
+// By default the configuration is:
112
+// - RedirectTrailingSlash:  true
113
+// - RedirectFixedPath:      false
114
+// - HandleMethodNotAllowed: false
115
+// - ForwardedByClientIP:    true
116
+// - UseRawPath:             false
117
+// - UnescapePathValues:     true
118
+func New() *Engine {
119
+	debugPrintWARNINGNew()
120
+	engine := &Engine{
121
+		RouterGroup: RouterGroup{
122
+			Handlers: nil,
123
+			basePath: "/",
124
+			root:     true,
125
+		},
126
+		FuncMap:                template.FuncMap{},
127
+		RedirectTrailingSlash:  true,
128
+		RedirectFixedPath:      false,
129
+		HandleMethodNotAllowed: false,
130
+		ForwardedByClientIP:    true,
131
+		AppEngine:              defaultAppEngine,
132
+		UseRawPath:             false,
133
+		UnescapePathValues:     true,
134
+		MaxMultipartMemory:     defaultMultipartMemory,
135
+		trees:                  make(methodTrees, 0, 9),
136
+		delims:                 render.Delims{Left: "{{", Right: "}}"},
137
+		secureJsonPrefix:       "while(1);",
138
+	}
139
+	engine.RouterGroup.engine = engine
140
+	engine.pool.New = func() interface{} {
141
+		return engine.allocateContext()
142
+	}
143
+	return engine
144
+}
145
+
146
+// Default returns an Engine instance with the Logger and Recovery middleware already attached.
147
+func Default() *Engine {
148
+	debugPrintWARNINGDefault()
149
+	engine := New()
150
+	engine.Use(Logger(), Recovery())
151
+	return engine
152
+}
153
+
154
+func (engine *Engine) allocateContext() *Context {
155
+	return &Context{engine: engine}
156
+}
157
+
158
+func (engine *Engine) Delims(left, right string) *Engine {
159
+	engine.delims = render.Delims{Left: left, Right: right}
160
+	return engine
161
+}
162
+
163
+// SecureJsonPrefix sets the secureJsonPrefix used in Context.SecureJSON.
164
+func (engine *Engine) SecureJsonPrefix(prefix string) *Engine {
165
+	engine.secureJsonPrefix = prefix
166
+	return engine
167
+}
168
+
169
+// LoadHTMLGlob loads HTML files identified by glob pattern
170
+// and associates the result with HTML renderer.
171
+func (engine *Engine) LoadHTMLGlob(pattern string) {
172
+	left := engine.delims.Left
173
+	right := engine.delims.Right
174
+	templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern))
175
+
176
+	if IsDebugging() {
177
+		debugPrintLoadTemplate(templ)
178
+		engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims}
179
+		return
180
+	}
181
+
182
+	engine.SetHTMLTemplate(templ)
183
+}
184
+
185
+// LoadHTMLFiles loads a slice of HTML files
186
+// and associates the result with HTML renderer.
187
+func (engine *Engine) LoadHTMLFiles(files ...string) {
188
+	if IsDebugging() {
189
+		engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims}
190
+		return
191
+	}
192
+
193
+	templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...))
194
+	engine.SetHTMLTemplate(templ)
195
+}
196
+
197
+// SetHTMLTemplate associate a template with HTML renderer.
198
+func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
199
+	if len(engine.trees) > 0 {
200
+		debugPrintWARNINGSetHTMLTemplate()
201
+	}
202
+
203
+	engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)}
204
+}
205
+
206
+// SetFuncMap sets the FuncMap used for template.FuncMap.
207
+func (engine *Engine) SetFuncMap(funcMap template.FuncMap) {
208
+	engine.FuncMap = funcMap
209
+}
210
+
211
+// NoRoute adds handlers for NoRoute. It return a 404 code by default.
212
+func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
213
+	engine.noRoute = handlers
214
+	engine.rebuild404Handlers()
215
+}
216
+
217
+// NoMethod sets the handlers called when... TODO.
218
+func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
219
+	engine.noMethod = handlers
220
+	engine.rebuild405Handlers()
221
+}
222
+
223
+// Use attachs a global middleware to the router. ie. the middleware attached though Use() will be
224
+// included in the handlers chain for every single request. Even 404, 405, static files...
225
+// For example, this is the right place for a logger or error management middleware.
226
+func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
227
+	engine.RouterGroup.Use(middleware...)
228
+	engine.rebuild404Handlers()
229
+	engine.rebuild405Handlers()
230
+	return engine
231
+}
232
+
233
+func (engine *Engine) rebuild404Handlers() {
234
+	engine.allNoRoute = engine.combineHandlers(engine.noRoute)
235
+}
236
+
237
+func (engine *Engine) rebuild405Handlers() {
238
+	engine.allNoMethod = engine.combineHandlers(engine.noMethod)
239
+}
240
+
241
+func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
242
+	assert1(path[0] == '/', "path must begin with '/'")
243
+	assert1(method != "", "HTTP method can not be empty")
244
+	assert1(len(handlers) > 0, "there must be at least one handler")
245
+
246
+	debugPrintRoute(method, path, handlers)
247
+	root := engine.trees.get(method)
248
+	if root == nil {
249
+		root = new(node)
250
+		engine.trees = append(engine.trees, methodTree{method: method, root: root})
251
+	}
252
+	root.addRoute(path, handlers)
253
+}
254
+
255
+// Routes returns a slice of registered routes, including some useful information, such as:
256
+// the http method, path and the handler name.
257
+func (engine *Engine) Routes() (routes RoutesInfo) {
258
+	for _, tree := range engine.trees {
259
+		routes = iterate("", tree.method, routes, tree.root)
260
+	}
261
+	return routes
262
+}
263
+
264
+func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {
265
+	path += root.path
266
+	if len(root.handlers) > 0 {
267
+		routes = append(routes, RouteInfo{
268
+			Method:  method,
269
+			Path:    path,
270
+			Handler: nameOfFunction(root.handlers.Last()),
271
+		})
272
+	}
273
+	for _, child := range root.children {
274
+		routes = iterate(path, method, routes, child)
275
+	}
276
+	return routes
277
+}
278
+
279
+// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
280
+// It is a shortcut for http.ListenAndServe(addr, router)
281
+// Note: this method will block the calling goroutine indefinitely unless an error happens.
282
+func (engine *Engine) Run(addr ...string) (err error) {
283
+	defer func() { debugPrintError(err) }()
284
+
285
+	address := resolveAddress(addr)
286
+	debugPrint("Listening and serving HTTP on %s\n", address)
287
+	err = http.ListenAndServe(address, engine)
288
+	return
289
+}
290
+
291
+// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
292
+// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
293
+// Note: this method will block the calling goroutine indefinitely unless an error happens.
294
+func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) {
295
+	debugPrint("Listening and serving HTTPS on %s\n", addr)
296
+	defer func() { debugPrintError(err) }()
297
+
298
+	err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
299
+	return
300
+}
301
+
302
+// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
303
+// through the specified unix socket (ie. a file).
304
+// Note: this method will block the calling goroutine indefinitely unless an error happens.
305
+func (engine *Engine) RunUnix(file string) (err error) {
306
+	debugPrint("Listening and serving HTTP on unix:/%s", file)
307
+	defer func() { debugPrintError(err) }()
308
+
309
+	os.Remove(file)
310
+	listener, err := net.Listen("unix", file)
311
+	if err != nil {
312
+		return
313
+	}
314
+	defer listener.Close()
315
+	err = http.Serve(listener, engine)
316
+	return
317
+}
318
+
319
+// ServeHTTP conforms to the http.Handler interface.
320
+func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
321
+	c := engine.pool.Get().(*Context)
322
+	c.writermem.reset(w)
323
+	c.Request = req
324
+	c.reset()
325
+
326
+	engine.handleHTTPRequest(c)
327
+
328
+	engine.pool.Put(c)
329
+}
330
+
331
+// HandleContext re-enter a context that has been rewritten.
332
+// This can be done by setting c.Request.URL.Path to your new target.
333
+// Disclaimer: You can loop yourself to death with this, use wisely.
334
+func (engine *Engine) HandleContext(c *Context) {
335
+	c.reset()
336
+	engine.handleHTTPRequest(c)
337
+	engine.pool.Put(c)
338
+}
339
+
340
+func (engine *Engine) handleHTTPRequest(c *Context) {
341
+	httpMethod := c.Request.Method
342
+	path := c.Request.URL.Path
343
+	unescape := false
344
+	if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {
345
+		path = c.Request.URL.RawPath
346
+		unescape = engine.UnescapePathValues
347
+	}
348
+
349
+	// Find root of the tree for the given HTTP method
350
+	t := engine.trees
351
+	for i, tl := 0, len(t); i < tl; i++ {
352
+		if t[i].method != httpMethod {
353
+			continue
354
+		}
355
+		root := t[i].root
356
+		// Find route in tree
357
+		handlers, params, tsr := root.getValue(path, c.Params, unescape)
358
+		if handlers != nil {
359
+			c.handlers = handlers
360
+			c.Params = params
361
+			c.Next()
362
+			c.writermem.WriteHeaderNow()
363
+			return
364
+		}
365
+		if httpMethod != "CONNECT" && path != "/" {
366
+			if tsr && engine.RedirectTrailingSlash {
367
+				redirectTrailingSlash(c)
368
+				return
369
+			}
370
+			if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) {
371
+				return
372
+			}
373
+		}
374
+		break
375
+	}
376
+
377
+	if engine.HandleMethodNotAllowed {
378
+		for _, tree := range engine.trees {
379
+			if tree.method == httpMethod {
380
+				continue
381
+			}
382
+			if handlers, _, _ := tree.root.getValue(path, nil, unescape); handlers != nil {
383
+				c.handlers = engine.allNoMethod
384
+				serveError(c, http.StatusMethodNotAllowed, default405Body)
385
+				return
386
+			}
387
+		}
388
+	}
389
+	c.handlers = engine.allNoRoute
390
+	serveError(c, http.StatusNotFound, default404Body)
391
+}
392
+
393
+var mimePlain = []string{MIMEPlain}
394
+
395
+func serveError(c *Context, code int, defaultMessage []byte) {
396
+	c.writermem.status = code
397
+	c.Next()
398
+	if c.writermem.Written() {
399
+		return
400
+	}
401
+	if c.writermem.Status() == code {
402
+		c.writermem.Header()["Content-Type"] = mimePlain
403
+		c.Writer.Write(defaultMessage)
404
+		return
405
+	}
406
+	c.writermem.WriteHeaderNow()
407
+	return
408
+}
409
+
410
+func redirectTrailingSlash(c *Context) {
411
+	req := c.Request
412
+	path := req.URL.Path
413
+	code := http.StatusMovedPermanently // Permanent redirect, request with GET method
414
+	if req.Method != "GET" {
415
+		code = http.StatusTemporaryRedirect
416
+	}
417
+
418
+	req.URL.Path = path + "/"
419
+	if length := len(path); length > 1 && path[length-1] == '/' {
420
+		req.URL.Path = path[:length-1]
421
+	}
422
+	debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
423
+	http.Redirect(c.Writer, req, req.URL.String(), code)
424
+	c.writermem.WriteHeaderNow()
425
+}
426
+
427
+func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {
428
+	req := c.Request
429
+	path := req.URL.Path
430
+
431
+	if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(path), trailingSlash); ok {
432
+		code := http.StatusMovedPermanently // Permanent redirect, request with GET method
433
+		if req.Method != "GET" {
434
+			code = http.StatusTemporaryRedirect
435
+		}
436
+		req.URL.Path = string(fixedPath)
437
+		debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
438
+		http.Redirect(c.Writer, req, req.URL.String(), code)
439
+		c.writermem.WriteHeaderNow()
440
+		return true
441
+	}
442
+	return false
443
+}

+ 15
- 0
log/vendor/github.com/gin-gonic/gin/json/json.go View File

@@ -0,0 +1,15 @@
1
+// Copyright 2017 Bo-Yi Wu.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+// +build !jsoniter
6
+
7
+package json
8
+
9
+import "encoding/json"
10
+
11
+var (
12
+	Marshal       = json.Marshal
13
+	MarshalIndent = json.MarshalIndent
14
+	NewDecoder    = json.NewDecoder
15
+)

+ 16
- 0
log/vendor/github.com/gin-gonic/gin/json/jsoniter.go View File

@@ -0,0 +1,16 @@
1
+// Copyright 2017 Bo-Yi Wu.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+// +build jsoniter
6
+
7
+package json
8
+
9
+import "github.com/json-iterator/go"
10
+
11
+var (
12
+	json          = jsoniter.ConfigCompatibleWithStandardLibrary
13
+	Marshal       = json.Marshal
14
+	MarshalIndent = json.MarshalIndent
15
+	NewDecoder    = json.NewDecoder
16
+)

+ 152
- 0
log/vendor/github.com/gin-gonic/gin/logger.go View File

@@ -0,0 +1,152 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"fmt"
9
+	"io"
10
+	"net/http"
11
+	"os"
12
+	"time"
13
+
14
+	"github.com/mattn/go-isatty"
15
+)
16
+
17
+var (
18
+	green        = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
19
+	white        = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
20
+	yellow       = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
21
+	red          = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
22
+	blue         = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
23
+	magenta      = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
24
+	cyan         = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
25
+	reset        = string([]byte{27, 91, 48, 109})
26
+	disableColor = false
27
+)
28
+
29
+// DisableConsoleColor disables color output in the console.
30
+func DisableConsoleColor() {
31
+	disableColor = true
32
+}
33
+
34
+// ErrorLogger returns a handlerfunc for any error type.
35
+func ErrorLogger() HandlerFunc {
36
+	return ErrorLoggerT(ErrorTypeAny)
37
+}
38
+
39
+// ErrorLoggerT returns a handlerfunc for a given error type.
40
+func ErrorLoggerT(typ ErrorType) HandlerFunc {
41
+	return func(c *Context) {
42
+		c.Next()
43
+		errors := c.Errors.ByType(typ)
44
+		if len(errors) > 0 {
45
+			c.JSON(-1, errors)
46
+		}
47
+	}
48
+}
49
+
50
+// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.
51
+// By default gin.DefaultWriter = os.Stdout.
52
+func Logger() HandlerFunc {
53
+	return LoggerWithWriter(DefaultWriter)
54
+}
55
+
56
+// LoggerWithWriter instance a Logger middleware with the specified writter buffer.
57
+// Example: os.Stdout, a file opened in write mode, a socket...
58
+func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
59
+	isTerm := true
60
+
61
+	if w, ok := out.(*os.File); !ok ||
62
+		(os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd()))) ||
63
+		disableColor {
64
+		isTerm = false
65
+	}
66
+
67
+	var skip map[string]struct{}
68
+
69
+	if length := len(notlogged); length > 0 {
70
+		skip = make(map[string]struct{}, length)
71
+
72
+		for _, path := range notlogged {
73
+			skip[path] = struct{}{}
74
+		}
75
+	}
76
+
77
+	return func(c *Context) {
78
+		// Start timer
79
+		start := time.Now()
80
+		path := c.Request.URL.Path
81
+		raw := c.Request.URL.RawQuery
82
+
83
+		// Process request
84
+		c.Next()
85
+
86
+		// Log only when path is not being skipped
87
+		if _, ok := skip[path]; !ok {
88
+			// Stop timer
89
+			end := time.Now()
90
+			latency := end.Sub(start)
91
+
92
+			clientIP := c.ClientIP()
93
+			method := c.Request.Method
94
+			statusCode := c.Writer.Status()
95
+			var statusColor, methodColor, resetColor string
96
+			if isTerm {
97
+				statusColor = colorForStatus(statusCode)
98
+				methodColor = colorForMethod(method)
99
+				resetColor = reset
100
+			}
101
+			comment := c.Errors.ByType(ErrorTypePrivate).String()
102
+
103
+			if raw != "" {
104
+				path = path + "?" + raw
105
+			}
106
+
107
+			fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",
108
+				end.Format("2006/01/02 - 15:04:05"),
109
+				statusColor, statusCode, resetColor,
110
+				latency,
111
+				clientIP,
112
+				methodColor, method, resetColor,
113
+				path,
114
+				comment,
115
+			)
116
+		}
117
+	}
118
+}
119
+
120
+func colorForStatus(code int) string {
121
+	switch {
122
+	case code >= http.StatusOK && code < http.StatusMultipleChoices:
123
+		return green
124
+	case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:
125
+		return white
126
+	case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
127
+		return yellow
128
+	default:
129
+		return red
130
+	}
131
+}
132
+
133
+func colorForMethod(method string) string {
134
+	switch method {
135
+	case "GET":
136
+		return blue
137
+	case "POST":
138
+		return cyan
139
+	case "PUT":
140
+		return yellow
141
+	case "DELETE":
142
+		return red
143
+	case "PATCH":
144
+		return green
145
+	case "HEAD":
146
+		return magenta
147
+	case "OPTIONS":
148
+		return white
149
+	default:
150
+		return reset
151
+	}
152
+}

+ 72
- 0
log/vendor/github.com/gin-gonic/gin/mode.go View File

@@ -0,0 +1,72 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"io"
9
+	"os"
10
+
11
+	"github.com/gin-gonic/gin/binding"
12
+)
13
+
14
+const ENV_GIN_MODE = "GIN_MODE"
15
+
16
+const (
17
+	DebugMode   = "debug"
18
+	ReleaseMode = "release"
19
+	TestMode    = "test"
20
+)
21
+const (
22
+	debugCode = iota
23
+	releaseCode
24
+	testCode
25
+)
26
+
27
+// DefaultWriter is the default io.Writer used the Gin for debug output and
28
+// middleware output like Logger() or Recovery().
29
+// Note that both Logger and Recovery provides custom ways to configure their
30
+// output io.Writer.
31
+// To support coloring in Windows use:
32
+// 		import "github.com/mattn/go-colorable"
33
+// 		gin.DefaultWriter = colorable.NewColorableStdout()
34
+var DefaultWriter io.Writer = os.Stdout
35
+var DefaultErrorWriter io.Writer = os.Stderr
36
+
37
+var ginMode = debugCode
38
+var modeName = DebugMode
39
+
40
+func init() {
41
+	mode := os.Getenv(ENV_GIN_MODE)
42
+	SetMode(mode)
43
+}
44
+
45
+func SetMode(value string) {
46
+	switch value {
47
+	case DebugMode, "":
48
+		ginMode = debugCode
49
+	case ReleaseMode:
50
+		ginMode = releaseCode
51
+	case TestMode:
52
+		ginMode = testCode
53
+	default:
54
+		panic("gin mode unknown: " + value)
55
+	}
56
+	if value == "" {
57
+		value = DebugMode
58
+	}
59
+	modeName = value
60
+}
61
+
62
+func DisableBindValidation() {
63
+	binding.Validator = nil
64
+}
65
+
66
+func EnableJsonDecoderUseNumber() {
67
+	binding.EnableDecoderUseNumber = true
68
+}
69
+
70
+func Mode() string {
71
+	return modeName
72
+}

+ 123
- 0
log/vendor/github.com/gin-gonic/gin/path.go View File

@@ -0,0 +1,123 @@
1
+// Copyright 2013 Julien Schmidt. All rights reserved.
2
+// Based on the path package, Copyright 2009 The Go Authors.
3
+// Use of this source code is governed by a BSD-style license that can be found
4
+// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE.
5
+
6
+package gin
7
+
8
+// cleanPath is the URL version of path.Clean, it returns a canonical URL path
9
+// for p, eliminating . and .. elements.
10
+//
11
+// The following rules are applied iteratively until no further processing can
12
+// be done:
13
+//	1. Replace multiple slashes with a single slash.
14
+//	2. Eliminate each . path name element (the current directory).
15
+//	3. Eliminate each inner .. path name element (the parent directory)
16
+//	   along with the non-.. element that precedes it.
17
+//	4. Eliminate .. elements that begin a rooted path:
18
+//	   that is, replace "/.." by "/" at the beginning of a path.
19
+//
20
+// If the result of this process is an empty string, "/" is returned.
21
+func cleanPath(p string) string {
22
+	// Turn empty string into "/"
23
+	if p == "" {
24
+		return "/"
25
+	}
26
+
27
+	n := len(p)
28
+	var buf []byte
29
+
30
+	// Invariants:
31
+	//      reading from path; r is index of next byte to process.
32
+	//      writing to buf; w is index of next byte to write.
33
+
34
+	// path must start with '/'
35
+	r := 1
36
+	w := 1
37
+
38
+	if p[0] != '/' {
39
+		r = 0
40
+		buf = make([]byte, n+1)
41
+		buf[0] = '/'
42
+	}
43
+
44
+	trailing := n > 1 && p[n-1] == '/'
45
+
46
+	// A bit more clunky without a 'lazybuf' like the path package, but the loop
47
+	// gets completely inlined (bufApp). So in contrast to the path package this
48
+	// loop has no expensive function calls (except 1x make)
49
+
50
+	for r < n {
51
+		switch {
52
+		case p[r] == '/':
53
+			// empty path element, trailing slash is added after the end
54
+			r++
55
+
56
+		case p[r] == '.' && r+1 == n:
57
+			trailing = true
58
+			r++
59
+
60
+		case p[r] == '.' && p[r+1] == '/':
61
+			// . element
62
+			r += 2
63
+
64
+		case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
65
+			// .. element: remove to last /
66
+			r += 3
67
+
68
+			if w > 1 {
69
+				// can backtrack
70
+				w--
71
+
72
+				if buf == nil {
73
+					for w > 1 && p[w] != '/' {
74
+						w--
75
+					}
76
+				} else {
77
+					for w > 1 && buf[w] != '/' {
78
+						w--
79
+					}
80
+				}
81
+			}
82
+
83
+		default:
84
+			// real path element.
85
+			// add slash if needed
86
+			if w > 1 {
87
+				bufApp(&buf, p, w, '/')
88
+				w++
89
+			}
90
+
91
+			// copy element
92
+			for r < n && p[r] != '/' {
93
+				bufApp(&buf, p, w, p[r])
94
+				w++
95
+				r++
96
+			}
97
+		}
98
+	}
99
+
100
+	// re-append trailing slash
101
+	if trailing && w > 1 {
102
+		bufApp(&buf, p, w, '/')
103
+		w++
104
+	}
105
+
106
+	if buf == nil {
107
+		return p[:w]
108
+	}
109
+	return string(buf[:w])
110
+}
111
+
112
+// internal helper to lazily create a buffer if necessary.
113
+func bufApp(buf *[]byte, s string, w int, c byte) {
114
+	if *buf == nil {
115
+		if s[w] == c {
116
+			return
117
+		}
118
+
119
+		*buf = make([]byte, len(s))
120
+		copy(*buf, s[:w])
121
+	}
122
+	(*buf)[w] = c
123
+}

+ 116
- 0
log/vendor/github.com/gin-gonic/gin/recovery.go View File

@@ -0,0 +1,116 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"bytes"
9
+	"fmt"
10
+	"io"
11
+	"io/ioutil"
12
+	"log"
13
+	"net/http"
14
+	"net/http/httputil"
15
+	"runtime"
16
+	"time"
17
+)
18
+
19
+var (
20
+	dunno     = []byte("???")
21
+	centerDot = []byte("·")
22
+	dot       = []byte(".")
23
+	slash     = []byte("/")
24
+)
25
+
26
+// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
27
+func Recovery() HandlerFunc {
28
+	return RecoveryWithWriter(DefaultErrorWriter)
29
+}
30
+
31
+// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
32
+func RecoveryWithWriter(out io.Writer) HandlerFunc {
33
+	var logger *log.Logger
34
+	if out != nil {
35
+		logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)
36
+	}
37
+	return func(c *Context) {
38
+		defer func() {
39
+			if err := recover(); err != nil {
40
+				if logger != nil {
41
+					stack := stack(3)
42
+					httprequest, _ := httputil.DumpRequest(c.Request, false)
43
+					logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s", timeFormat(time.Now()), string(httprequest), err, stack, reset)
44
+				}
45
+				c.AbortWithStatus(http.StatusInternalServerError)
46
+			}
47
+		}()
48
+		c.Next()
49
+	}
50
+}
51
+
52
+// stack returns a nicely formatted stack frame, skipping skip frames.
53
+func stack(skip int) []byte {
54
+	buf := new(bytes.Buffer) // the returned data
55
+	// As we loop, we open files and read them. These variables record the currently
56
+	// loaded file.
57
+	var lines [][]byte
58
+	var lastFile string
59
+	for i := skip; ; i++ { // Skip the expected number of frames
60
+		pc, file, line, ok := runtime.Caller(i)
61
+		if !ok {
62
+			break
63
+		}
64
+		// Print this much at least.  If we can't find the source, it won't show.
65
+		fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
66
+		if file != lastFile {
67
+			data, err := ioutil.ReadFile(file)
68
+			if err != nil {
69
+				continue
70
+			}
71
+			lines = bytes.Split(data, []byte{'\n'})
72
+			lastFile = file
73
+		}
74
+		fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
75
+	}
76
+	return buf.Bytes()
77
+}
78
+
79
+// source returns a space-trimmed slice of the n'th line.
80
+func source(lines [][]byte, n int) []byte {
81
+	n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
82
+	if n < 0 || n >= len(lines) {
83
+		return dunno
84
+	}
85
+	return bytes.TrimSpace(lines[n])
86
+}
87
+
88
+// function returns, if possible, the name of the function containing the PC.
89
+func function(pc uintptr) []byte {
90
+	fn := runtime.FuncForPC(pc)
91
+	if fn == nil {
92
+		return dunno
93
+	}
94
+	name := []byte(fn.Name())
95
+	// The name includes the path name to the package, which is unnecessary
96
+	// since the file name is already included.  Plus, it has center dots.
97
+	// That is, we see
98
+	//	runtime/debug.*T·ptrmethod
99
+	// and want
100
+	//	*T.ptrmethod
101
+	// Also the package path might contains dot (e.g. code.google.com/...),
102
+	// so first eliminate the path prefix
103
+	if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
104
+		name = name[lastslash+1:]
105
+	}
106
+	if period := bytes.Index(name, dot); period >= 0 {
107
+		name = name[period+1:]
108
+	}
109
+	name = bytes.Replace(name, centerDot, dot, -1)
110
+	return name
111
+}
112
+
113
+func timeFormat(t time.Time) string {
114
+	var timeString = t.Format("2006/01/02 - 15:04:05")
115
+	return timeString
116
+}

+ 23
- 0
log/vendor/github.com/gin-gonic/gin/render/data.go View File

@@ -0,0 +1,23 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import "net/http"
8
+
9
+type Data struct {
10
+	ContentType string
11
+	Data        []byte
12
+}
13
+
14
+// Render (Data) writes data with custom ContentType.
15
+func (r Data) Render(w http.ResponseWriter) (err error) {
16
+	r.WriteContentType(w)
17
+	_, err = w.Write(r.Data)
18
+	return
19
+}
20
+
21
+func (r Data) WriteContentType(w http.ResponseWriter) {
22
+	writeContentType(w, []string{r.ContentType})
23
+}

+ 80
- 0
log/vendor/github.com/gin-gonic/gin/render/html.go View File

@@ -0,0 +1,80 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import (
8
+	"html/template"
9
+	"net/http"
10
+)
11
+
12
+type Delims struct {
13
+	Left  string
14
+	Right string
15
+}
16
+
17
+type HTMLRender interface {
18
+	Instance(string, interface{}) Render
19
+}
20
+
21
+type HTMLProduction struct {
22
+	Template *template.Template
23
+	Delims   Delims
24
+}
25
+
26
+type HTMLDebug struct {
27
+	Files   []string
28
+	Glob    string
29
+	Delims  Delims
30
+	FuncMap template.FuncMap
31
+}
32
+
33
+type HTML struct {
34
+	Template *template.Template
35
+	Name     string
36
+	Data     interface{}
37
+}
38
+
39
+var htmlContentType = []string{"text/html; charset=utf-8"}
40
+
41
+func (r HTMLProduction) Instance(name string, data interface{}) Render {
42
+	return HTML{
43
+		Template: r.Template,
44
+		Name:     name,
45
+		Data:     data,
46
+	}
47
+}
48
+
49
+func (r HTMLDebug) Instance(name string, data interface{}) Render {
50
+	return HTML{
51
+		Template: r.loadTemplate(),
52
+		Name:     name,
53
+		Data:     data,
54
+	}
55
+}
56
+func (r HTMLDebug) loadTemplate() *template.Template {
57
+	if r.FuncMap == nil {
58
+		r.FuncMap = template.FuncMap{}
59
+	}
60
+	if len(r.Files) > 0 {
61
+		return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...))
62
+	}
63
+	if r.Glob != "" {
64
+		return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob))
65
+	}
66
+	panic("the HTML debug render was created without files or glob pattern")
67
+}
68
+
69
+func (r HTML) Render(w http.ResponseWriter) error {
70
+	r.WriteContentType(w)
71
+
72
+	if r.Name == "" {
73
+		return r.Template.Execute(w, r.Data)
74
+	}
75
+	return r.Template.ExecuteTemplate(w, r.Name, r.Data)
76
+}
77
+
78
+func (r HTML) WriteContentType(w http.ResponseWriter) {
79
+	writeContentType(w, htmlContentType)
80
+}

+ 146
- 0
log/vendor/github.com/gin-gonic/gin/render/json.go View File

@@ -0,0 +1,146 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import (
8
+	"bytes"
9
+	"fmt"
10
+	"html/template"
11
+	"net/http"
12
+
13
+	"github.com/gin-gonic/gin/json"
14
+)
15
+
16
+type JSON struct {
17
+	Data interface{}
18
+}
19
+
20
+type IndentedJSON struct {
21
+	Data interface{}
22
+}
23
+
24
+type SecureJSON struct {
25
+	Prefix string
26
+	Data   interface{}
27
+}
28
+
29
+type JsonpJSON struct {
30
+	Callback string
31
+	Data     interface{}
32
+}
33
+
34
+type AsciiJSON struct {
35
+	Data interface{}
36
+}
37
+
38
+type SecureJSONPrefix string
39
+
40
+var jsonContentType = []string{"application/json; charset=utf-8"}
41
+var jsonpContentType = []string{"application/javascript; charset=utf-8"}
42
+var jsonAsciiContentType = []string{"application/json"}
43
+
44
+func (r JSON) Render(w http.ResponseWriter) (err error) {
45
+	if err = WriteJSON(w, r.Data); err != nil {
46
+		panic(err)
47
+	}
48
+	return
49
+}
50
+
51
+func (r JSON) WriteContentType(w http.ResponseWriter) {
52
+	writeContentType(w, jsonContentType)
53
+}
54
+
55
+func WriteJSON(w http.ResponseWriter, obj interface{}) error {
56
+	writeContentType(w, jsonContentType)
57
+	jsonBytes, err := json.Marshal(obj)
58
+	if err != nil {
59
+		return err
60
+	}
61
+	w.Write(jsonBytes)
62
+	return nil
63
+}
64
+
65
+func (r IndentedJSON) Render(w http.ResponseWriter) error {
66
+	r.WriteContentType(w)
67
+	jsonBytes, err := json.MarshalIndent(r.Data, "", "    ")
68
+	if err != nil {
69
+		return err
70
+	}
71
+	w.Write(jsonBytes)
72
+	return nil
73
+}
74
+
75
+func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {
76
+	writeContentType(w, jsonContentType)
77
+}
78
+
79
+func (r SecureJSON) Render(w http.ResponseWriter) error {
80
+	r.WriteContentType(w)
81
+	jsonBytes, err := json.Marshal(r.Data)
82
+	if err != nil {
83
+		return err
84
+	}
85
+	// if the jsonBytes is array values
86
+	if bytes.HasPrefix(jsonBytes, []byte("[")) && bytes.HasSuffix(jsonBytes, []byte("]")) {
87
+		w.Write([]byte(r.Prefix))
88
+	}
89
+	w.Write(jsonBytes)
90
+	return nil
91
+}
92
+
93
+func (r SecureJSON) WriteContentType(w http.ResponseWriter) {
94
+	writeContentType(w, jsonContentType)
95
+}
96
+
97
+func (r JsonpJSON) Render(w http.ResponseWriter) (err error) {
98
+	r.WriteContentType(w)
99
+	ret, err := json.Marshal(r.Data)
100
+	if err != nil {
101
+		return err
102
+	}
103
+
104
+	if r.Callback == "" {
105
+		w.Write(ret)
106
+		return nil
107
+	}
108
+
109
+	callback := template.JSEscapeString(r.Callback)
110
+	w.Write([]byte(callback))
111
+	w.Write([]byte("("))
112
+	w.Write(ret)
113
+	w.Write([]byte(")"))
114
+
115
+	return nil
116
+}
117
+
118
+func (r JsonpJSON) WriteContentType(w http.ResponseWriter) {
119
+	writeContentType(w, jsonpContentType)
120
+}
121
+
122
+func (r AsciiJSON) Render(w http.ResponseWriter) (err error) {
123
+	r.WriteContentType(w)
124
+	ret, err := json.Marshal(r.Data)
125
+	if err != nil {
126
+		return err
127
+	}
128
+
129
+	var buffer bytes.Buffer
130
+	for _, r := range string(ret) {
131
+		cvt := ""
132
+		if r < 128 {
133
+			cvt = string(r)
134
+		} else {
135
+			cvt = fmt.Sprintf("\\u%04x", int64(r))
136
+		}
137
+		buffer.WriteString(cvt)
138
+	}
139
+
140
+	w.Write(buffer.Bytes())
141
+	return nil
142
+}
143
+
144
+func (r AsciiJSON) WriteContentType(w http.ResponseWriter) {
145
+	writeContentType(w, jsonAsciiContentType)
146
+}

+ 31
- 0
log/vendor/github.com/gin-gonic/gin/render/msgpack.go View File

@@ -0,0 +1,31 @@
1
+// Copyright 2017 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import (
8
+	"net/http"
9
+
10
+	"github.com/ugorji/go/codec"
11
+)
12
+
13
+type MsgPack struct {
14
+	Data interface{}
15
+}
16
+
17
+var msgpackContentType = []string{"application/msgpack; charset=utf-8"}
18
+
19
+func (r MsgPack) WriteContentType(w http.ResponseWriter) {
20
+	writeContentType(w, msgpackContentType)
21
+}
22
+
23
+func (r MsgPack) Render(w http.ResponseWriter) error {
24
+	return WriteMsgPack(w, r.Data)
25
+}
26
+
27
+func WriteMsgPack(w http.ResponseWriter, obj interface{}) error {
28
+	writeContentType(w, msgpackContentType)
29
+	var h codec.Handle = new(codec.MsgpackHandle)
30
+	return codec.NewEncoder(w, h).Encode(obj)
31
+}

+ 36
- 0
log/vendor/github.com/gin-gonic/gin/render/reader.go View File

@@ -0,0 +1,36 @@
1
+package render
2
+
3
+import (
4
+	"io"
5
+	"net/http"
6
+	"strconv"
7
+)
8
+
9
+type Reader struct {
10
+	ContentType   string
11
+	ContentLength int64
12
+	Reader        io.Reader
13
+	Headers       map[string]string
14
+}
15
+
16
+// Render (Reader) writes data with custom ContentType and headers.
17
+func (r Reader) Render(w http.ResponseWriter) (err error) {
18
+	r.WriteContentType(w)
19
+	r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
20
+	r.writeHeaders(w, r.Headers)
21
+	_, err = io.Copy(w, r.Reader)
22
+	return
23
+}
24
+
25
+func (r Reader) WriteContentType(w http.ResponseWriter) {
26
+	writeContentType(w, []string{r.ContentType})
27
+}
28
+
29
+func (r Reader) writeHeaders(w http.ResponseWriter, headers map[string]string) {
30
+	header := w.Header()
31
+	for k, v := range headers {
32
+		if val := header[k]; len(val) == 0 {
33
+			header[k] = []string{v}
34
+		}
35
+	}
36
+}

+ 28
- 0
log/vendor/github.com/gin-gonic/gin/render/redirect.go View File

@@ -0,0 +1,28 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import (
8
+	"fmt"
9
+	"net/http"
10
+)
11
+
12
+type Redirect struct {
13
+	Code     int
14
+	Request  *http.Request
15
+	Location string
16
+}
17
+
18
+func (r Redirect) Render(w http.ResponseWriter) error {
19
+	// todo(thinkerou): go1.6 not support StatusPermanentRedirect(308)
20
+	// when we upgrade go version we can use http.StatusPermanentRedirect
21
+	if (r.Code < 300 || r.Code > 308) && r.Code != 201 {
22
+		panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code))
23
+	}
24
+	http.Redirect(w, r.Request, r.Location, r.Code)
25
+	return nil
26
+}
27
+
28
+func (r Redirect) WriteContentType(http.ResponseWriter) {}

+ 37
- 0
log/vendor/github.com/gin-gonic/gin/render/render.go View File

@@ -0,0 +1,37 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import "net/http"
8
+
9
+type Render interface {
10
+	Render(http.ResponseWriter) error
11
+	WriteContentType(w http.ResponseWriter)
12
+}
13
+
14
+var (
15
+	_ Render     = JSON{}
16
+	_ Render     = IndentedJSON{}
17
+	_ Render     = SecureJSON{}
18
+	_ Render     = JsonpJSON{}
19
+	_ Render     = XML{}
20
+	_ Render     = String{}
21
+	_ Render     = Redirect{}
22
+	_ Render     = Data{}
23
+	_ Render     = HTML{}
24
+	_ HTMLRender = HTMLDebug{}
25
+	_ HTMLRender = HTMLProduction{}
26
+	_ Render     = YAML{}
27
+	_ Render     = MsgPack{}
28
+	_ Render     = Reader{}
29
+	_ Render     = AsciiJSON{}
30
+)
31
+
32
+func writeContentType(w http.ResponseWriter, value []string) {
33
+	header := w.Header()
34
+	if val := header["Content-Type"]; len(val) == 0 {
35
+		header["Content-Type"] = value
36
+	}
37
+}

+ 36
- 0
log/vendor/github.com/gin-gonic/gin/render/text.go View File

@@ -0,0 +1,36 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import (
8
+	"fmt"
9
+	"io"
10
+	"net/http"
11
+)
12
+
13
+type String struct {
14
+	Format string
15
+	Data   []interface{}
16
+}
17
+
18
+var plainContentType = []string{"text/plain; charset=utf-8"}
19
+
20
+func (r String) Render(w http.ResponseWriter) error {
21
+	WriteString(w, r.Format, r.Data)
22
+	return nil
23
+}
24
+
25
+func (r String) WriteContentType(w http.ResponseWriter) {
26
+	writeContentType(w, plainContentType)
27
+}
28
+
29
+func WriteString(w http.ResponseWriter, format string, data []interface{}) {
30
+	writeContentType(w, plainContentType)
31
+	if len(data) > 0 {
32
+		fmt.Fprintf(w, format, data...)
33
+	} else {
34
+		io.WriteString(w, format)
35
+	}
36
+}

+ 25
- 0
log/vendor/github.com/gin-gonic/gin/render/xml.go View File

@@ -0,0 +1,25 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import (
8
+	"encoding/xml"
9
+	"net/http"
10
+)
11
+
12
+type XML struct {
13
+	Data interface{}
14
+}
15
+
16
+var xmlContentType = []string{"application/xml; charset=utf-8"}
17
+
18
+func (r XML) Render(w http.ResponseWriter) error {
19
+	r.WriteContentType(w)
20
+	return xml.NewEncoder(w).Encode(r.Data)
21
+}
22
+
23
+func (r XML) WriteContentType(w http.ResponseWriter) {
24
+	writeContentType(w, xmlContentType)
25
+}

+ 33
- 0
log/vendor/github.com/gin-gonic/gin/render/yaml.go View File

@@ -0,0 +1,33 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package render
6
+
7
+import (
8
+	"net/http"
9
+
10
+	"gopkg.in/yaml.v2"
11
+)
12
+
13
+type YAML struct {
14
+	Data interface{}
15
+}
16
+
17
+var yamlContentType = []string{"application/x-yaml; charset=utf-8"}
18
+
19
+func (r YAML) Render(w http.ResponseWriter) error {
20
+	r.WriteContentType(w)
21
+
22
+	bytes, err := yaml.Marshal(r.Data)
23
+	if err != nil {
24
+		return err
25
+	}
26
+
27
+	w.Write(bytes)
28
+	return nil
29
+}
30
+
31
+func (r YAML) WriteContentType(w http.ResponseWriter) {
32
+	writeContentType(w, yamlContentType)
33
+}

+ 115
- 0
log/vendor/github.com/gin-gonic/gin/response_writer.go View File

@@ -0,0 +1,115 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"bufio"
9
+	"io"
10
+	"net"
11
+	"net/http"
12
+)
13
+
14
+const (
15
+	noWritten     = -1
16
+	defaultStatus = http.StatusOK
17
+)
18
+
19
+type responseWriterBase interface {
20
+	http.ResponseWriter
21
+	http.Hijacker
22
+	http.Flusher
23
+	http.CloseNotifier
24
+
25
+	// Returns the HTTP response status code of the current request.
26
+	Status() int
27
+
28
+	// Returns the number of bytes already written into the response http body.
29
+	// See Written()
30
+	Size() int
31
+
32
+	// Writes the string into the response body.
33
+	WriteString(string) (int, error)
34
+
35
+	// Returns true if the response body was already written.
36
+	Written() bool
37
+
38
+	// Forces to write the http header (status code + headers).
39
+	WriteHeaderNow()
40
+}
41
+
42
+type responseWriter struct {
43
+	http.ResponseWriter
44
+	size   int
45
+	status int
46
+}
47
+
48
+var _ ResponseWriter = &responseWriter{}
49
+
50
+func (w *responseWriter) reset(writer http.ResponseWriter) {
51
+	w.ResponseWriter = writer
52
+	w.size = noWritten
53
+	w.status = defaultStatus
54
+}
55
+
56
+func (w *responseWriter) WriteHeader(code int) {
57
+	if code > 0 && w.status != code {
58
+		if w.Written() {
59
+			debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)
60
+		}
61
+		w.status = code
62
+	}
63
+}
64
+
65
+func (w *responseWriter) WriteHeaderNow() {
66
+	if !w.Written() {
67
+		w.size = 0
68
+		w.ResponseWriter.WriteHeader(w.status)
69
+	}
70
+}
71
+
72
+func (w *responseWriter) Write(data []byte) (n int, err error) {
73
+	w.WriteHeaderNow()
74
+	n, err = w.ResponseWriter.Write(data)
75
+	w.size += n
76
+	return
77
+}
78
+
79
+func (w *responseWriter) WriteString(s string) (n int, err error) {
80
+	w.WriteHeaderNow()
81
+	n, err = io.WriteString(w.ResponseWriter, s)
82
+	w.size += n
83
+	return
84
+}
85
+
86
+func (w *responseWriter) Status() int {
87
+	return w.status
88
+}
89
+
90
+func (w *responseWriter) Size() int {
91
+	return w.size
92
+}
93
+
94
+func (w *responseWriter) Written() bool {
95
+	return w.size != noWritten
96
+}
97
+
98
+// Hijack implements the http.Hijacker interface.
99
+func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
100
+	if w.size < 0 {
101
+		w.size = 0
102
+	}
103
+	return w.ResponseWriter.(http.Hijacker).Hijack()
104
+}
105
+
106
+// CloseNotify implements the http.CloseNotify interface.
107
+func (w *responseWriter) CloseNotify() <-chan bool {
108
+	return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
109
+}
110
+
111
+// Flush implements the http.Flush interface.
112
+func (w *responseWriter) Flush() {
113
+	w.WriteHeaderNow()
114
+	w.ResponseWriter.(http.Flusher).Flush()
115
+}

+ 12
- 0
log/vendor/github.com/gin-gonic/gin/response_writer_1.7.go View File

@@ -0,0 +1,12 @@
1
+// +build !go1.8
2
+
3
+// Copyright 2018 Gin Core Team.  All rights reserved.
4
+// Use of this source code is governed by a MIT style
5
+// license that can be found in the LICENSE file.
6
+
7
+package gin
8
+
9
+// ResponseWriter ...
10
+type ResponseWriter interface {
11
+	responseWriterBase
12
+}

+ 25
- 0
log/vendor/github.com/gin-gonic/gin/response_writer_1.8.go View File

@@ -0,0 +1,25 @@
1
+// +build go1.8
2
+
3
+// Copyright 2018 Gin Core Team.  All rights reserved.
4
+// Use of this source code is governed by a MIT style
5
+// license that can be found in the LICENSE file.
6
+
7
+package gin
8
+
9
+import (
10
+	"net/http"
11
+)
12
+
13
+// ResponseWriter ...
14
+type ResponseWriter interface {
15
+	responseWriterBase
16
+	// get the http.Pusher for server push
17
+	Pusher() http.Pusher
18
+}
19
+
20
+func (w *responseWriter) Pusher() (pusher http.Pusher) {
21
+	if pusher, ok := w.ResponseWriter.(http.Pusher); ok {
22
+		return pusher
23
+	}
24
+	return nil
25
+}

+ 213
- 0
log/vendor/github.com/gin-gonic/gin/routergroup.go View File

@@ -0,0 +1,213 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"net/http"
9
+	"path"
10
+	"regexp"
11
+	"strings"
12
+)
13
+
14
+type IRouter interface {
15
+	IRoutes
16
+	Group(string, ...HandlerFunc) *RouterGroup
17
+}
18
+
19
+type IRoutes interface {
20
+	Use(...HandlerFunc) IRoutes
21
+
22
+	Handle(string, string, ...HandlerFunc) IRoutes
23
+	Any(string, ...HandlerFunc) IRoutes
24
+	GET(string, ...HandlerFunc) IRoutes
25
+	POST(string, ...HandlerFunc) IRoutes
26
+	DELETE(string, ...HandlerFunc) IRoutes
27
+	PATCH(string, ...HandlerFunc) IRoutes
28
+	PUT(string, ...HandlerFunc) IRoutes
29
+	OPTIONS(string, ...HandlerFunc) IRoutes
30
+	HEAD(string, ...HandlerFunc) IRoutes
31
+
32
+	StaticFile(string, string) IRoutes
33
+	Static(string, string) IRoutes
34
+	StaticFS(string, http.FileSystem) IRoutes
35
+}
36
+
37
+// RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix
38
+// and an array of handlers (middleware).
39
+type RouterGroup struct {
40
+	Handlers HandlersChain
41
+	basePath string
42
+	engine   *Engine
43
+	root     bool
44
+}
45
+
46
+var _ IRouter = &RouterGroup{}
47
+
48
+// Use adds middleware to the group, see example code in github.
49
+func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
50
+	group.Handlers = append(group.Handlers, middleware...)
51
+	return group.returnObj()
52
+}
53
+
54
+// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
55
+// For example, all the routes that use a common middlware for authorization could be grouped.
56
+func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
57
+	return &RouterGroup{
58
+		Handlers: group.combineHandlers(handlers),
59
+		basePath: group.calculateAbsolutePath(relativePath),
60
+		engine:   group.engine,
61
+	}
62
+}
63
+
64
+func (group *RouterGroup) BasePath() string {
65
+	return group.basePath
66
+}
67
+
68
+func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
69
+	absolutePath := group.calculateAbsolutePath(relativePath)
70
+	handlers = group.combineHandlers(handlers)
71
+	group.engine.addRoute(httpMethod, absolutePath, handlers)
72
+	return group.returnObj()
73
+}
74
+
75
+// Handle registers a new request handle and middleware with the given path and method.
76
+// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.
77
+// See the example code in github.
78
+//
79
+// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
80
+// functions can be used.
81
+//
82
+// This function is intended for bulk loading and to allow the usage of less
83
+// frequently used, non-standardized or custom methods (e.g. for internal
84
+// communication with a proxy).
85
+func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
86
+	if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {
87
+		panic("http method " + httpMethod + " is not valid")
88
+	}
89
+	return group.handle(httpMethod, relativePath, handlers)
90
+}
91
+
92
+// POST is a shortcut for router.Handle("POST", path, handle).
93
+func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {
94
+	return group.handle("POST", relativePath, handlers)
95
+}
96
+
97
+// GET is a shortcut for router.Handle("GET", path, handle).
98
+func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
99
+	return group.handle("GET", relativePath, handlers)
100
+}
101
+
102
+// DELETE is a shortcut for router.Handle("DELETE", path, handle).
103
+func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {
104
+	return group.handle("DELETE", relativePath, handlers)
105
+}
106
+
107
+// PATCH is a shortcut for router.Handle("PATCH", path, handle).
108
+func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {
109
+	return group.handle("PATCH", relativePath, handlers)
110
+}
111
+
112
+// PUT is a shortcut for router.Handle("PUT", path, handle).
113
+func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {
114
+	return group.handle("PUT", relativePath, handlers)
115
+}
116
+
117
+// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).
118
+func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {
119
+	return group.handle("OPTIONS", relativePath, handlers)
120
+}
121
+
122
+// HEAD is a shortcut for router.Handle("HEAD", path, handle).
123
+func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {
124
+	return group.handle("HEAD", relativePath, handlers)
125
+}
126
+
127
+// Any registers a route that matches all the HTTP methods.
128
+// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
129
+func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
130
+	group.handle("GET", relativePath, handlers)
131
+	group.handle("POST", relativePath, handlers)
132
+	group.handle("PUT", relativePath, handlers)
133
+	group.handle("PATCH", relativePath, handlers)
134
+	group.handle("HEAD", relativePath, handlers)
135
+	group.handle("OPTIONS", relativePath, handlers)
136
+	group.handle("DELETE", relativePath, handlers)
137
+	group.handle("CONNECT", relativePath, handlers)
138
+	group.handle("TRACE", relativePath, handlers)
139
+	return group.returnObj()
140
+}
141
+
142
+// StaticFile registers a single route in order to serve a single file of the local filesystem.
143
+// router.StaticFile("favicon.ico", "./resources/favicon.ico")
144
+func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {
145
+	if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
146
+		panic("URL parameters can not be used when serving a static file")
147
+	}
148
+	handler := func(c *Context) {
149
+		c.File(filepath)
150
+	}
151
+	group.GET(relativePath, handler)
152
+	group.HEAD(relativePath, handler)
153
+	return group.returnObj()
154
+}
155
+
156
+// Static serves files from the given file system root.
157
+// Internally a http.FileServer is used, therefore http.NotFound is used instead
158
+// of the Router's NotFound handler.
159
+// To use the operating system's file system implementation,
160
+// use :
161
+//     router.Static("/static", "/var/www")
162
+func (group *RouterGroup) Static(relativePath, root string) IRoutes {
163
+	return group.StaticFS(relativePath, Dir(root, false))
164
+}
165
+
166
+// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
167
+// Gin by default user: gin.Dir()
168
+func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
169
+	if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
170
+		panic("URL parameters can not be used when serving a static folder")
171
+	}
172
+	handler := group.createStaticHandler(relativePath, fs)
173
+	urlPattern := path.Join(relativePath, "/*filepath")
174
+
175
+	// Register GET and HEAD handlers
176
+	group.GET(urlPattern, handler)
177
+	group.HEAD(urlPattern, handler)
178
+	return group.returnObj()
179
+}
180
+
181
+func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
182
+	absolutePath := group.calculateAbsolutePath(relativePath)
183
+	fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
184
+	_, nolisting := fs.(*onlyfilesFS)
185
+	return func(c *Context) {
186
+		if nolisting {
187
+			c.Writer.WriteHeader(http.StatusNotFound)
188
+		}
189
+		fileServer.ServeHTTP(c.Writer, c.Request)
190
+	}
191
+}
192
+
193
+func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
194
+	finalSize := len(group.Handlers) + len(handlers)
195
+	if finalSize >= int(abortIndex) {
196
+		panic("too many handlers")
197
+	}
198
+	mergedHandlers := make(HandlersChain, finalSize)
199
+	copy(mergedHandlers, group.Handlers)
200
+	copy(mergedHandlers[len(group.Handlers):], handlers)
201
+	return mergedHandlers
202
+}
203
+
204
+func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
205
+	return joinPaths(group.basePath, relativePath)
206
+}
207
+
208
+func (group *RouterGroup) returnObj() IRoutes {
209
+	if group.root {
210
+		return group.engine
211
+	}
212
+	return group
213
+}

+ 16
- 0
log/vendor/github.com/gin-gonic/gin/test_helpers.go View File

@@ -0,0 +1,16 @@
1
+// Copyright 2017 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import "net/http"
8
+
9
+// CreateTestContext returns a fresh engine and context for testing purposes
10
+func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
11
+	r = New()
12
+	c = r.allocateContext()
13
+	c.reset()
14
+	c.writermem.reset(w)
15
+	return
16
+}

+ 620
- 0
log/vendor/github.com/gin-gonic/gin/tree.go View File

@@ -0,0 +1,620 @@
1
+// Copyright 2013 Julien Schmidt. All rights reserved.
2
+// Use of this source code is governed by a BSD-style license that can be found
3
+// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE
4
+
5
+package gin
6
+
7
+import (
8
+	"net/url"
9
+	"strings"
10
+	"unicode"
11
+)
12
+
13
+// Param is a single URL parameter, consisting of a key and a value.
14
+type Param struct {
15
+	Key   string
16
+	Value string
17
+}
18
+
19
+// Params is a Param-slice, as returned by the router.
20
+// The slice is ordered, the first URL parameter is also the first slice value.
21
+// It is therefore safe to read values by the index.
22
+type Params []Param
23
+
24
+// Get returns the value of the first Param which key matches the given name.
25
+// If no matching Param is found, an empty string is returned.
26
+func (ps Params) Get(name string) (string, bool) {
27
+	for _, entry := range ps {
28
+		if entry.Key == name {
29
+			return entry.Value, true
30
+		}
31
+	}
32
+	return "", false
33
+}
34
+
35
+// ByName returns the value of the first Param which key matches the given name.
36
+// If no matching Param is found, an empty string is returned.
37
+func (ps Params) ByName(name string) (va string) {
38
+	va, _ = ps.Get(name)
39
+	return
40
+}
41
+
42
+type methodTree struct {
43
+	method string
44
+	root   *node
45
+}
46
+
47
+type methodTrees []methodTree
48
+
49
+func (trees methodTrees) get(method string) *node {
50
+	for _, tree := range trees {
51
+		if tree.method == method {
52
+			return tree.root
53
+		}
54
+	}
55
+	return nil
56
+}
57
+
58
+func min(a, b int) int {
59
+	if a <= b {
60
+		return a
61
+	}
62
+	return b
63
+}
64
+
65
+func countParams(path string) uint8 {
66
+	var n uint
67
+	for i := 0; i < len(path); i++ {
68
+		if path[i] != ':' && path[i] != '*' {
69
+			continue
70
+		}
71
+		n++
72
+	}
73
+	if n >= 255 {
74
+		return 255
75
+	}
76
+	return uint8(n)
77
+}
78
+
79
+type nodeType uint8
80
+
81
+const (
82
+	static nodeType = iota // default
83
+	root
84
+	param
85
+	catchAll
86
+)
87
+
88
+type node struct {
89
+	path      string
90
+	indices   string
91
+	children  []*node
92
+	handlers  HandlersChain
93
+	priority  uint32
94
+	nType     nodeType
95
+	maxParams uint8
96
+	wildChild bool
97
+}
98
+
99
+// increments priority of the given child and reorders if necessary.
100
+func (n *node) incrementChildPrio(pos int) int {
101
+	n.children[pos].priority++
102
+	prio := n.children[pos].priority
103
+
104
+	// adjust position (move to front)
105
+	newPos := pos
106
+	for newPos > 0 && n.children[newPos-1].priority < prio {
107
+		// swap node positions
108
+		n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1]
109
+
110
+		newPos--
111
+	}
112
+
113
+	// build new index char string
114
+	if newPos != pos {
115
+		n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
116
+			n.indices[pos:pos+1] + // the index char we move
117
+			n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
118
+	}
119
+
120
+	return newPos
121
+}
122
+
123
+// addRoute adds a node with the given handle to the path.
124
+// Not concurrency-safe!
125
+func (n *node) addRoute(path string, handlers HandlersChain) {
126
+	fullPath := path
127
+	n.priority++
128
+	numParams := countParams(path)
129
+
130
+	// non-empty tree
131
+	if len(n.path) > 0 || len(n.children) > 0 {
132
+	walk:
133
+		for {
134
+			// Update maxParams of the current node
135
+			if numParams > n.maxParams {
136
+				n.maxParams = numParams
137
+			}
138
+
139
+			// Find the longest common prefix.
140
+			// This also implies that the common prefix contains no ':' or '*'
141
+			// since the existing key can't contain those chars.
142
+			i := 0
143
+			max := min(len(path), len(n.path))
144
+			for i < max && path[i] == n.path[i] {
145
+				i++
146
+			}
147
+
148
+			// Split edge
149
+			if i < len(n.path) {
150
+				child := node{
151
+					path:      n.path[i:],
152
+					wildChild: n.wildChild,
153
+					indices:   n.indices,
154
+					children:  n.children,
155
+					handlers:  n.handlers,
156
+					priority:  n.priority - 1,
157
+				}
158
+
159
+				// Update maxParams (max of all children)
160
+				for i := range child.children {
161
+					if child.children[i].maxParams > child.maxParams {
162
+						child.maxParams = child.children[i].maxParams
163
+					}
164
+				}
165
+
166
+				n.children = []*node{&child}
167
+				// []byte for proper unicode char conversion, see #65
168
+				n.indices = string([]byte{n.path[i]})
169
+				n.path = path[:i]
170
+				n.handlers = nil
171
+				n.wildChild = false
172
+			}
173
+
174
+			// Make new node a child of this node
175
+			if i < len(path) {
176
+				path = path[i:]
177
+
178
+				if n.wildChild {
179
+					n = n.children[0]
180
+					n.priority++
181
+
182
+					// Update maxParams of the child node
183
+					if numParams > n.maxParams {
184
+						n.maxParams = numParams
185
+					}
186
+					numParams--
187
+
188
+					// Check if the wildcard matches
189
+					if len(path) >= len(n.path) && n.path == path[:len(n.path)] {
190
+						// check for longer wildcard, e.g. :name and :names
191
+						if len(n.path) >= len(path) || path[len(n.path)] == '/' {
192
+							continue walk
193
+						}
194
+					}
195
+
196
+					panic("path segment '" + path +
197
+						"' conflicts with existing wildcard '" + n.path +
198
+						"' in path '" + fullPath + "'")
199
+				}
200
+
201
+				c := path[0]
202
+
203
+				// slash after param
204
+				if n.nType == param && c == '/' && len(n.children) == 1 {
205
+					n = n.children[0]
206
+					n.priority++
207
+					continue walk
208
+				}
209
+
210
+				// Check if a child with the next path byte exists
211
+				for i := 0; i < len(n.indices); i++ {
212
+					if c == n.indices[i] {
213
+						i = n.incrementChildPrio(i)
214
+						n = n.children[i]
215
+						continue walk
216
+					}
217
+				}
218
+
219
+				// Otherwise insert it
220
+				if c != ':' && c != '*' {
221
+					// []byte for proper unicode char conversion, see #65
222
+					n.indices += string([]byte{c})
223
+					child := &node{
224
+						maxParams: numParams,
225
+					}
226
+					n.children = append(n.children, child)
227
+					n.incrementChildPrio(len(n.indices) - 1)
228
+					n = child
229
+				}
230
+				n.insertChild(numParams, path, fullPath, handlers)
231
+				return
232
+
233
+			} else if i == len(path) { // Make node a (in-path) leaf
234
+				if n.handlers != nil {
235
+					panic("handlers are already registered for path '" + fullPath + "'")
236
+				}
237
+				n.handlers = handlers
238
+			}
239
+			return
240
+		}
241
+	} else { // Empty tree
242
+		n.insertChild(numParams, path, fullPath, handlers)
243
+		n.nType = root
244
+	}
245
+}
246
+
247
+func (n *node) insertChild(numParams uint8, path string, fullPath string, handlers HandlersChain) {
248
+	var offset int // already handled bytes of the path
249
+
250
+	// find prefix until first wildcard (beginning with ':' or '*')
251
+	for i, max := 0, len(path); numParams > 0; i++ {
252
+		c := path[i]
253
+		if c != ':' && c != '*' {
254
+			continue
255
+		}
256
+
257
+		// find wildcard end (either '/' or path end)
258
+		end := i + 1
259
+		for end < max && path[end] != '/' {
260
+			switch path[end] {
261
+			// the wildcard name must not contain ':' and '*'
262
+			case ':', '*':
263
+				panic("only one wildcard per path segment is allowed, has: '" +
264
+					path[i:] + "' in path '" + fullPath + "'")
265
+			default:
266
+				end++
267
+			}
268
+		}
269
+
270
+		// check if this Node existing children which would be
271
+		// unreachable if we insert the wildcard here
272
+		if len(n.children) > 0 {
273
+			panic("wildcard route '" + path[i:end] +
274
+				"' conflicts with existing children in path '" + fullPath + "'")
275
+		}
276
+
277
+		// check if the wildcard has a name
278
+		if end-i < 2 {
279
+			panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
280
+		}
281
+
282
+		if c == ':' { // param
283
+			// split path at the beginning of the wildcard
284
+			if i > 0 {
285
+				n.path = path[offset:i]
286
+				offset = i
287
+			}
288
+
289
+			child := &node{
290
+				nType:     param,
291
+				maxParams: numParams,
292
+			}
293
+			n.children = []*node{child}
294
+			n.wildChild = true
295
+			n = child
296
+			n.priority++
297
+			numParams--
298
+
299
+			// if the path doesn't end with the wildcard, then there
300
+			// will be another non-wildcard subpath starting with '/'
301
+			if end < max {
302
+				n.path = path[offset:end]
303
+				offset = end
304
+
305
+				child := &node{
306
+					maxParams: numParams,
307
+					priority:  1,
308
+				}
309
+				n.children = []*node{child}
310
+				n = child
311
+			}
312
+
313
+		} else { // catchAll
314
+			if end != max || numParams > 1 {
315
+				panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
316
+			}
317
+
318
+			if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
319
+				panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
320
+			}
321
+
322
+			// currently fixed width 1 for '/'
323
+			i--
324
+			if path[i] != '/' {
325
+				panic("no / before catch-all in path '" + fullPath + "'")
326
+			}
327
+
328
+			n.path = path[offset:i]
329
+
330
+			// first node: catchAll node with empty path
331
+			child := &node{
332
+				wildChild: true,
333
+				nType:     catchAll,
334
+				maxParams: 1,
335
+			}
336
+			n.children = []*node{child}
337
+			n.indices = string(path[i])
338
+			n = child
339
+			n.priority++
340
+
341
+			// second node: node holding the variable
342
+			child = &node{
343
+				path:      path[i:],
344
+				nType:     catchAll,
345
+				maxParams: 1,
346
+				handlers:  handlers,
347
+				priority:  1,
348
+			}
349
+			n.children = []*node{child}
350
+
351
+			return
352
+		}
353
+	}
354
+
355
+	// insert remaining path part and handle to the leaf
356
+	n.path = path[offset:]
357
+	n.handlers = handlers
358
+}
359
+
360
+// getValue returns the handle registered with the given path (key). The values of
361
+// wildcards are saved to a map.
362
+// If no handle can be found, a TSR (trailing slash redirect) recommendation is
363
+// made if a handle exists with an extra (without the) trailing slash for the
364
+// given path.
365
+func (n *node) getValue(path string, po Params, unescape bool) (handlers HandlersChain, p Params, tsr bool) {
366
+	p = po
367
+walk: // Outer loop for walking the tree
368
+	for {
369
+		if len(path) > len(n.path) {
370
+			if path[:len(n.path)] == n.path {
371
+				path = path[len(n.path):]
372
+				// If this node does not have a wildcard (param or catchAll)
373
+				// child,  we can just look up the next child node and continue
374
+				// to walk down the tree
375
+				if !n.wildChild {
376
+					c := path[0]
377
+					for i := 0; i < len(n.indices); i++ {
378
+						if c == n.indices[i] {
379
+							n = n.children[i]
380
+							continue walk
381
+						}
382
+					}
383
+
384
+					// Nothing found.
385
+					// We can recommend to redirect to the same URL without a
386
+					// trailing slash if a leaf exists for that path.
387
+					tsr = path == "/" && n.handlers != nil
388
+					return
389
+				}
390
+
391
+				// handle wildcard child
392
+				n = n.children[0]
393
+				switch n.nType {
394
+				case param:
395
+					// find param end (either '/' or path end)
396
+					end := 0
397
+					for end < len(path) && path[end] != '/' {
398
+						end++
399
+					}
400
+
401
+					// save param value
402
+					if cap(p) < int(n.maxParams) {
403
+						p = make(Params, 0, n.maxParams)
404
+					}
405
+					i := len(p)
406
+					p = p[:i+1] // expand slice within preallocated capacity
407
+					p[i].Key = n.path[1:]
408
+					val := path[:end]
409
+					if unescape {
410
+						var err error
411
+						if p[i].Value, err = url.QueryUnescape(val); err != nil {
412
+							p[i].Value = val // fallback, in case of error
413
+						}
414
+					} else {
415
+						p[i].Value = val
416
+					}
417
+
418
+					// we need to go deeper!
419
+					if end < len(path) {
420
+						if len(n.children) > 0 {
421
+							path = path[end:]
422
+							n = n.children[0]
423
+							continue walk
424
+						}
425
+
426
+						// ... but we can't
427
+						tsr = len(path) == end+1
428
+						return
429
+					}
430
+
431
+					if handlers = n.handlers; handlers != nil {
432
+						return
433
+					}
434
+					if len(n.children) == 1 {
435
+						// No handle found. Check if a handle for this path + a
436
+						// trailing slash exists for TSR recommendation
437
+						n = n.children[0]
438
+						tsr = n.path == "/" && n.handlers != nil
439
+					}
440
+
441
+					return
442
+
443
+				case catchAll:
444
+					// save param value
445
+					if cap(p) < int(n.maxParams) {
446
+						p = make(Params, 0, n.maxParams)
447
+					}
448
+					i := len(p)
449
+					p = p[:i+1] // expand slice within preallocated capacity
450
+					p[i].Key = n.path[2:]
451
+					if unescape {
452
+						var err error
453
+						if p[i].Value, err = url.QueryUnescape(path); err != nil {
454
+							p[i].Value = path // fallback, in case of error
455
+						}
456
+					} else {
457
+						p[i].Value = path
458
+					}
459
+
460
+					handlers = n.handlers
461
+					return
462
+
463
+				default:
464
+					panic("invalid node type")
465
+				}
466
+			}
467
+		} else if path == n.path {
468
+			// We should have reached the node containing the handle.
469
+			// Check if this node has a handle registered.
470
+			if handlers = n.handlers; handlers != nil {
471
+				return
472
+			}
473
+
474
+			if path == "/" && n.wildChild && n.nType != root {
475
+				tsr = true
476
+				return
477
+			}
478
+
479
+			// No handle found. Check if a handle for this path + a
480
+			// trailing slash exists for trailing slash recommendation
481
+			for i := 0; i < len(n.indices); i++ {
482
+				if n.indices[i] == '/' {
483
+					n = n.children[i]
484
+					tsr = (len(n.path) == 1 && n.handlers != nil) ||
485
+						(n.nType == catchAll && n.children[0].handlers != nil)
486
+					return
487
+				}
488
+			}
489
+
490
+			return
491
+		}
492
+
493
+		// Nothing found. We can recommend to redirect to the same URL with an
494
+		// extra trailing slash if a leaf exists for that path
495
+		tsr = (path == "/") ||
496
+			(len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
497
+				path == n.path[:len(n.path)-1] && n.handlers != nil)
498
+		return
499
+	}
500
+}
501
+
502
+// findCaseInsensitivePath makes a case-insensitive lookup of the given path and tries to find a handler.
503
+// It can optionally also fix trailing slashes.
504
+// It returns the case-corrected path and a bool indicating whether the lookup
505
+// was successful.
506
+func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
507
+	ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory
508
+
509
+	// Outer loop for walking the tree
510
+	for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) {
511
+		path = path[len(n.path):]
512
+		ciPath = append(ciPath, n.path...)
513
+
514
+		if len(path) > 0 {
515
+			// If this node does not have a wildcard (param or catchAll) child,
516
+			// we can just look up the next child node and continue to walk down
517
+			// the tree
518
+			if !n.wildChild {
519
+				r := unicode.ToLower(rune(path[0]))
520
+				for i, index := range n.indices {
521
+					// must use recursive approach since both index and
522
+					// ToLower(index) could exist. We must check both.
523
+					if r == unicode.ToLower(index) {
524
+						out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)
525
+						if found {
526
+							return append(ciPath, out...), true
527
+						}
528
+					}
529
+				}
530
+
531
+				// Nothing found. We can recommend to redirect to the same URL
532
+				// without a trailing slash if a leaf exists for that path
533
+				found = fixTrailingSlash && path == "/" && n.handlers != nil
534
+				return
535
+			}
536
+
537
+			n = n.children[0]
538
+			switch n.nType {
539
+			case param:
540
+				// find param end (either '/' or path end)
541
+				k := 0
542
+				for k < len(path) && path[k] != '/' {
543
+					k++
544
+				}
545
+
546
+				// add param value to case insensitive path
547
+				ciPath = append(ciPath, path[:k]...)
548
+
549
+				// we need to go deeper!
550
+				if k < len(path) {
551
+					if len(n.children) > 0 {
552
+						path = path[k:]
553
+						n = n.children[0]
554
+						continue
555
+					}
556
+
557
+					// ... but we can't
558
+					if fixTrailingSlash && len(path) == k+1 {
559
+						return ciPath, true
560
+					}
561
+					return
562
+				}
563
+
564
+				if n.handlers != nil {
565
+					return ciPath, true
566
+				} else if fixTrailingSlash && len(n.children) == 1 {
567
+					// No handle found. Check if a handle for this path + a
568
+					// trailing slash exists
569
+					n = n.children[0]
570
+					if n.path == "/" && n.handlers != nil {
571
+						return append(ciPath, '/'), true
572
+					}
573
+				}
574
+				return
575
+
576
+			case catchAll:
577
+				return append(ciPath, path...), true
578
+
579
+			default:
580
+				panic("invalid node type")
581
+			}
582
+		} else {
583
+			// We should have reached the node containing the handle.
584
+			// Check if this node has a handle registered.
585
+			if n.handlers != nil {
586
+				return ciPath, true
587
+			}
588
+
589
+			// No handle found.
590
+			// Try to fix the path by adding a trailing slash
591
+			if fixTrailingSlash {
592
+				for i := 0; i < len(n.indices); i++ {
593
+					if n.indices[i] == '/' {
594
+						n = n.children[i]
595
+						if (len(n.path) == 1 && n.handlers != nil) ||
596
+							(n.nType == catchAll && n.children[0].handlers != nil) {
597
+							return append(ciPath, '/'), true
598
+						}
599
+						return
600
+					}
601
+				}
602
+			}
603
+			return
604
+		}
605
+	}
606
+
607
+	// Nothing found.
608
+	// Try to fix the path by adding / removing a trailing slash
609
+	if fixTrailingSlash {
610
+		if path == "/" {
611
+			return ciPath, true
612
+		}
613
+		if len(path)+1 == len(n.path) && n.path[len(path)] == '/' &&
614
+			strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) &&
615
+			n.handlers != nil {
616
+			return append(ciPath, n.path...), true
617
+		}
618
+	}
619
+	return
620
+}

+ 151
- 0
log/vendor/github.com/gin-gonic/gin/utils.go View File

@@ -0,0 +1,151 @@
1
+// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
2
+// Use of this source code is governed by a MIT style
3
+// license that can be found in the LICENSE file.
4
+
5
+package gin
6
+
7
+import (
8
+	"encoding/xml"
9
+	"net/http"
10
+	"os"
11
+	"path"
12
+	"reflect"
13
+	"runtime"
14
+	"strings"
15
+)
16
+
17
+const BindKey = "_gin-gonic/gin/bindkey"
18
+
19
+func Bind(val interface{}) HandlerFunc {
20
+	value := reflect.ValueOf(val)
21
+	if value.Kind() == reflect.Ptr {
22
+		panic(`Bind struct can not be a pointer. Example:
23
+	Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{})
24
+`)
25
+	}
26
+	typ := value.Type()
27
+
28
+	return func(c *Context) {
29
+		obj := reflect.New(typ).Interface()
30
+		if c.Bind(obj) == nil {
31
+			c.Set(BindKey, obj)
32
+		}
33
+	}
34
+}
35
+
36
+// WrapF is a helper function for wrapping http.HandlerFunc
37
+// Returns a Gin middleware
38
+func WrapF(f http.HandlerFunc) HandlerFunc {
39
+	return func(c *Context) {
40
+		f(c.Writer, c.Request)
41
+	}
42
+}
43
+
44
+// WrapH is a helper function for wrapping http.Handler
45
+// Returns a Gin middleware
46
+func WrapH(h http.Handler) HandlerFunc {
47
+	return func(c *Context) {
48
+		h.ServeHTTP(c.Writer, c.Request)
49
+	}
50
+}
51
+
52
+// H is a shortcut for map[string]interface{}
53
+type H map[string]interface{}
54
+
55
+// MarshalXML allows type H to be used with xml.Marshal.
56
+func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
57
+	start.Name = xml.Name{
58
+		Space: "",
59
+		Local: "map",
60
+	}
61
+	if err := e.EncodeToken(start); err != nil {
62
+		return err
63
+	}
64
+	for key, value := range h {
65
+		elem := xml.StartElement{
66
+			Name: xml.Name{Space: "", Local: key},
67
+			Attr: []xml.Attr{},
68
+		}
69
+		if err := e.EncodeElement(value, elem); err != nil {
70
+			return err
71
+		}
72
+	}
73
+
74
+	return e.EncodeToken(xml.EndElement{Name: start.Name})
75
+}
76
+
77
+func assert1(guard bool, text string) {
78
+	if !guard {
79
+		panic(text)
80
+	}
81
+}
82
+
83
+func filterFlags(content string) string {
84
+	for i, char := range content {
85
+		if char == ' ' || char == ';' {
86
+			return content[:i]
87
+		}
88
+	}
89
+	return content
90
+}
91
+
92
+func chooseData(custom, wildcard interface{}) interface{} {
93
+	if custom == nil {
94
+		if wildcard == nil {
95
+			panic("negotiation config is invalid")
96
+		}
97
+		return wildcard
98
+	}
99
+	return custom
100
+}
101
+
102
+func parseAccept(acceptHeader string) []string {
103
+	parts := strings.Split(acceptHeader, ",")
104
+	out := make([]string, 0, len(parts))
105
+	for _, part := range parts {
106
+		if part = strings.TrimSpace(strings.Split(part, ";")[0]); part != "" {
107
+			out = append(out, part)
108
+		}
109
+	}
110
+	return out
111
+}
112
+
113
+func lastChar(str string) uint8 {
114
+	if str == "" {
115
+		panic("The length of the string can't be 0")
116
+	}
117
+	return str[len(str)-1]
118
+}
119
+
120
+func nameOfFunction(f interface{}) string {
121
+	return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
122
+}
123
+
124
+func joinPaths(absolutePath, relativePath string) string {
125
+	if relativePath == "" {
126
+		return absolutePath
127
+	}
128
+
129
+	finalPath := path.Join(absolutePath, relativePath)
130
+	appendSlash := lastChar(relativePath) == '/' && lastChar(finalPath) != '/'
131
+	if appendSlash {
132
+		return finalPath + "/"
133
+	}
134
+	return finalPath
135
+}
136
+
137
+func resolveAddress(addr []string) string {
138
+	switch len(addr) {
139
+	case 0:
140
+		if port := os.Getenv("PORT"); port != "" {
141
+			debugPrint("Environment variable PORT=\"%s\"", port)
142
+			return ":" + port
143
+		}
144
+		debugPrint("Environment variable PORT is undefined. Using port :8080 by default")
145
+		return ":8080"
146
+	case 1:
147
+		return addr[0]
148
+	default:
149
+		panic("too much parameters")
150
+	}
151
+}

+ 1
- 0
log/vendor/github.com/gin-gonic/gin/wercker.yml View File

@@ -0,0 +1 @@
1
+box: wercker/default

+ 3
- 0
log/vendor/github.com/golang/protobuf/AUTHORS View File

@@ -0,0 +1,3 @@
1
+# This source code refers to The Go Authors for copyright purposes.
2
+# The master list of authors is in the main Go distribution,
3
+# visible at http://tip.golang.org/AUTHORS.

+ 3
- 0
log/vendor/github.com/golang/protobuf/CONTRIBUTORS View File

@@ -0,0 +1,3 @@
1
+# This source code was written by the Go contributors.
2
+# The master list of contributors is in the main Go distribution,
3
+# visible at http://tip.golang.org/CONTRIBUTORS.

+ 28
- 0
log/vendor/github.com/golang/protobuf/LICENSE View File

@@ -0,0 +1,28 @@
1
+Copyright 2010 The Go Authors.  All rights reserved.
2
+
3
+Redistribution and use in source and binary forms, with or without
4
+modification, are permitted provided that the following conditions are
5
+met:
6
+
7
+    * Redistributions of source code must retain the above copyright
8
+notice, this list of conditions and the following disclaimer.
9
+    * Redistributions in binary form must reproduce the above
10
+copyright notice, this list of conditions and the following disclaimer
11
+in the documentation and/or other materials provided with the
12
+distribution.
13
+    * Neither the name of Google Inc. nor the names of its
14
+contributors may be used to endorse or promote products derived from
15
+this software without specific prior written permission.
16
+
17
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+

+ 253
- 0
log/vendor/github.com/golang/protobuf/proto/clone.go View File

@@ -0,0 +1,253 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2011 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+// Protocol buffer deep copy and merge.
33
+// TODO: RawMessage.
34
+
35
+package proto
36
+
37
+import (
38
+	"fmt"
39
+	"log"
40
+	"reflect"
41
+	"strings"
42
+)
43
+
44
+// Clone returns a deep copy of a protocol buffer.
45
+func Clone(src Message) Message {
46
+	in := reflect.ValueOf(src)
47
+	if in.IsNil() {
48
+		return src
49
+	}
50
+	out := reflect.New(in.Type().Elem())
51
+	dst := out.Interface().(Message)
52
+	Merge(dst, src)
53
+	return dst
54
+}
55
+
56
+// Merger is the interface representing objects that can merge messages of the same type.
57
+type Merger interface {
58
+	// Merge merges src into this message.
59
+	// Required and optional fields that are set in src will be set to that value in dst.
60
+	// Elements of repeated fields will be appended.
61
+	//
62
+	// Merge may panic if called with a different argument type than the receiver.
63
+	Merge(src Message)
64
+}
65
+
66
+// generatedMerger is the custom merge method that generated protos will have.
67
+// We must add this method since a generate Merge method will conflict with
68
+// many existing protos that have a Merge data field already defined.
69
+type generatedMerger interface {
70
+	XXX_Merge(src Message)
71
+}
72
+
73
+// Merge merges src into dst.
74
+// Required and optional fields that are set in src will be set to that value in dst.
75
+// Elements of repeated fields will be appended.
76
+// Merge panics if src and dst are not the same type, or if dst is nil.
77
+func Merge(dst, src Message) {
78
+	if m, ok := dst.(Merger); ok {
79
+		m.Merge(src)
80
+		return
81
+	}
82
+
83
+	in := reflect.ValueOf(src)
84
+	out := reflect.ValueOf(dst)
85
+	if out.IsNil() {
86
+		panic("proto: nil destination")
87
+	}
88
+	if in.Type() != out.Type() {
89
+		panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
90
+	}
91
+	if in.IsNil() {
92
+		return // Merge from nil src is a noop
93
+	}
94
+	if m, ok := dst.(generatedMerger); ok {
95
+		m.XXX_Merge(src)
96
+		return
97
+	}
98
+	mergeStruct(out.Elem(), in.Elem())
99
+}
100
+
101
+func mergeStruct(out, in reflect.Value) {
102
+	sprop := GetProperties(in.Type())
103
+	for i := 0; i < in.NumField(); i++ {
104
+		f := in.Type().Field(i)
105
+		if strings.HasPrefix(f.Name, "XXX_") {
106
+			continue
107
+		}
108
+		mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
109
+	}
110
+
111
+	if emIn, err := extendable(in.Addr().Interface()); err == nil {
112
+		emOut, _ := extendable(out.Addr().Interface())
113
+		mIn, muIn := emIn.extensionsRead()
114
+		if mIn != nil {
115
+			mOut := emOut.extensionsWrite()
116
+			muIn.Lock()
117
+			mergeExtension(mOut, mIn)
118
+			muIn.Unlock()
119
+		}
120
+	}
121
+
122
+	uf := in.FieldByName("XXX_unrecognized")
123
+	if !uf.IsValid() {
124
+		return
125
+	}
126
+	uin := uf.Bytes()
127
+	if len(uin) > 0 {
128
+		out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
129
+	}
130
+}
131
+
132
+// mergeAny performs a merge between two values of the same type.
133
+// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
134
+// prop is set if this is a struct field (it may be nil).
135
+func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
136
+	if in.Type() == protoMessageType {
137
+		if !in.IsNil() {
138
+			if out.IsNil() {
139
+				out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
140
+			} else {
141
+				Merge(out.Interface().(Message), in.Interface().(Message))
142
+			}
143
+		}
144
+		return
145
+	}
146
+	switch in.Kind() {
147
+	case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
148
+		reflect.String, reflect.Uint32, reflect.Uint64:
149
+		if !viaPtr && isProto3Zero(in) {
150
+			return
151
+		}
152
+		out.Set(in)
153
+	case reflect.Interface:
154
+		// Probably a oneof field; copy non-nil values.
155
+		if in.IsNil() {
156
+			return
157
+		}
158
+		// Allocate destination if it is not set, or set to a different type.
159
+		// Otherwise we will merge as normal.
160
+		if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
161
+			out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
162
+		}
163
+		mergeAny(out.Elem(), in.Elem(), false, nil)
164
+	case reflect.Map:
165
+		if in.Len() == 0 {
166
+			return
167
+		}
168
+		if out.IsNil() {
169
+			out.Set(reflect.MakeMap(in.Type()))
170
+		}
171
+		// For maps with value types of *T or []byte we need to deep copy each value.
172
+		elemKind := in.Type().Elem().Kind()
173
+		for _, key := range in.MapKeys() {
174
+			var val reflect.Value
175
+			switch elemKind {
176
+			case reflect.Ptr:
177
+				val = reflect.New(in.Type().Elem().Elem())
178
+				mergeAny(val, in.MapIndex(key), false, nil)
179
+			case reflect.Slice:
180
+				val = in.MapIndex(key)
181
+				val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
182
+			default:
183
+				val = in.MapIndex(key)
184
+			}
185
+			out.SetMapIndex(key, val)
186
+		}
187
+	case reflect.Ptr:
188
+		if in.IsNil() {
189
+			return
190
+		}
191
+		if out.IsNil() {
192
+			out.Set(reflect.New(in.Elem().Type()))
193
+		}
194
+		mergeAny(out.Elem(), in.Elem(), true, nil)
195
+	case reflect.Slice:
196
+		if in.IsNil() {
197
+			return
198
+		}
199
+		if in.Type().Elem().Kind() == reflect.Uint8 {
200
+			// []byte is a scalar bytes field, not a repeated field.
201
+
202
+			// Edge case: if this is in a proto3 message, a zero length
203
+			// bytes field is considered the zero value, and should not
204
+			// be merged.
205
+			if prop != nil && prop.proto3 && in.Len() == 0 {
206
+				return
207
+			}
208
+
209
+			// Make a deep copy.
210
+			// Append to []byte{} instead of []byte(nil) so that we never end up
211
+			// with a nil result.
212
+			out.SetBytes(append([]byte{}, in.Bytes()...))
213
+			return
214
+		}
215
+		n := in.Len()
216
+		if out.IsNil() {
217
+			out.Set(reflect.MakeSlice(in.Type(), 0, n))
218
+		}
219
+		switch in.Type().Elem().Kind() {
220
+		case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
221
+			reflect.String, reflect.Uint32, reflect.Uint64:
222
+			out.Set(reflect.AppendSlice(out, in))
223
+		default:
224
+			for i := 0; i < n; i++ {
225
+				x := reflect.Indirect(reflect.New(in.Type().Elem()))
226
+				mergeAny(x, in.Index(i), false, nil)
227
+				out.Set(reflect.Append(out, x))
228
+			}
229
+		}
230
+	case reflect.Struct:
231
+		mergeStruct(out, in)
232
+	default:
233
+		// unknown type, so not a protocol buffer
234
+		log.Printf("proto: don't know how to copy %v", in)
235
+	}
236
+}
237
+
238
+func mergeExtension(out, in map[int32]Extension) {
239
+	for extNum, eIn := range in {
240
+		eOut := Extension{desc: eIn.desc}
241
+		if eIn.value != nil {
242
+			v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
243
+			mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
244
+			eOut.value = v.Interface()
245
+		}
246
+		if eIn.enc != nil {
247
+			eOut.enc = make([]byte, len(eIn.enc))
248
+			copy(eOut.enc, eIn.enc)
249
+		}
250
+
251
+		out[extNum] = eOut
252
+	}
253
+}

+ 427
- 0
log/vendor/github.com/golang/protobuf/proto/decode.go View File

@@ -0,0 +1,427 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+/*
35
+ * Routines for decoding protocol buffer data to construct in-memory representations.
36
+ */
37
+
38
+import (
39
+	"errors"
40
+	"fmt"
41
+	"io"
42
+)
43
+
44
+// errOverflow is returned when an integer is too large to be represented.
45
+var errOverflow = errors.New("proto: integer overflow")
46
+
47
+// ErrInternalBadWireType is returned by generated code when an incorrect
48
+// wire type is encountered. It does not get returned to user code.
49
+var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
50
+
51
+// DecodeVarint reads a varint-encoded integer from the slice.
52
+// It returns the integer and the number of bytes consumed, or
53
+// zero if there is not enough.
54
+// This is the format for the
55
+// int32, int64, uint32, uint64, bool, and enum
56
+// protocol buffer types.
57
+func DecodeVarint(buf []byte) (x uint64, n int) {
58
+	for shift := uint(0); shift < 64; shift += 7 {
59
+		if n >= len(buf) {
60
+			return 0, 0
61
+		}
62
+		b := uint64(buf[n])
63
+		n++
64
+		x |= (b & 0x7F) << shift
65
+		if (b & 0x80) == 0 {
66
+			return x, n
67
+		}
68
+	}
69
+
70
+	// The number is too large to represent in a 64-bit value.
71
+	return 0, 0
72
+}
73
+
74
+func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
75
+	i := p.index
76
+	l := len(p.buf)
77
+
78
+	for shift := uint(0); shift < 64; shift += 7 {
79
+		if i >= l {
80
+			err = io.ErrUnexpectedEOF
81
+			return
82
+		}
83
+		b := p.buf[i]
84
+		i++
85
+		x |= (uint64(b) & 0x7F) << shift
86
+		if b < 0x80 {
87
+			p.index = i
88
+			return
89
+		}
90
+	}
91
+
92
+	// The number is too large to represent in a 64-bit value.
93
+	err = errOverflow
94
+	return
95
+}
96
+
97
+// DecodeVarint reads a varint-encoded integer from the Buffer.
98
+// This is the format for the
99
+// int32, int64, uint32, uint64, bool, and enum
100
+// protocol buffer types.
101
+func (p *Buffer) DecodeVarint() (x uint64, err error) {
102
+	i := p.index
103
+	buf := p.buf
104
+
105
+	if i >= len(buf) {
106
+		return 0, io.ErrUnexpectedEOF
107
+	} else if buf[i] < 0x80 {
108
+		p.index++
109
+		return uint64(buf[i]), nil
110
+	} else if len(buf)-i < 10 {
111
+		return p.decodeVarintSlow()
112
+	}
113
+
114
+	var b uint64
115
+	// we already checked the first byte
116
+	x = uint64(buf[i]) - 0x80
117
+	i++
118
+
119
+	b = uint64(buf[i])
120
+	i++
121
+	x += b << 7
122
+	if b&0x80 == 0 {
123
+		goto done
124
+	}
125
+	x -= 0x80 << 7
126
+
127
+	b = uint64(buf[i])
128
+	i++
129
+	x += b << 14
130
+	if b&0x80 == 0 {
131
+		goto done
132
+	}
133
+	x -= 0x80 << 14
134
+
135
+	b = uint64(buf[i])
136
+	i++
137
+	x += b << 21
138
+	if b&0x80 == 0 {
139
+		goto done
140
+	}
141
+	x -= 0x80 << 21
142
+
143
+	b = uint64(buf[i])
144
+	i++
145
+	x += b << 28
146
+	if b&0x80 == 0 {
147
+		goto done
148
+	}
149
+	x -= 0x80 << 28
150
+
151
+	b = uint64(buf[i])
152
+	i++
153
+	x += b << 35
154
+	if b&0x80 == 0 {
155
+		goto done
156
+	}
157
+	x -= 0x80 << 35
158
+
159
+	b = uint64(buf[i])
160
+	i++
161
+	x += b << 42
162
+	if b&0x80 == 0 {
163
+		goto done
164
+	}
165
+	x -= 0x80 << 42
166
+
167
+	b = uint64(buf[i])
168
+	i++
169
+	x += b << 49
170
+	if b&0x80 == 0 {
171
+		goto done
172
+	}
173
+	x -= 0x80 << 49
174
+
175
+	b = uint64(buf[i])
176
+	i++
177
+	x += b << 56
178
+	if b&0x80 == 0 {
179
+		goto done
180
+	}
181
+	x -= 0x80 << 56
182
+
183
+	b = uint64(buf[i])
184
+	i++
185
+	x += b << 63
186
+	if b&0x80 == 0 {
187
+		goto done
188
+	}
189
+
190
+	return 0, errOverflow
191
+
192
+done:
193
+	p.index = i
194
+	return x, nil
195
+}
196
+
197
+// DecodeFixed64 reads a 64-bit integer from the Buffer.
198
+// This is the format for the
199
+// fixed64, sfixed64, and double protocol buffer types.
200
+func (p *Buffer) DecodeFixed64() (x uint64, err error) {
201
+	// x, err already 0
202
+	i := p.index + 8
203
+	if i < 0 || i > len(p.buf) {
204
+		err = io.ErrUnexpectedEOF
205
+		return
206
+	}
207
+	p.index = i
208
+
209
+	x = uint64(p.buf[i-8])
210
+	x |= uint64(p.buf[i-7]) << 8
211
+	x |= uint64(p.buf[i-6]) << 16
212
+	x |= uint64(p.buf[i-5]) << 24
213
+	x |= uint64(p.buf[i-4]) << 32
214
+	x |= uint64(p.buf[i-3]) << 40
215
+	x |= uint64(p.buf[i-2]) << 48
216
+	x |= uint64(p.buf[i-1]) << 56
217
+	return
218
+}
219
+
220
+// DecodeFixed32 reads a 32-bit integer from the Buffer.
221
+// This is the format for the
222
+// fixed32, sfixed32, and float protocol buffer types.
223
+func (p *Buffer) DecodeFixed32() (x uint64, err error) {
224
+	// x, err already 0
225
+	i := p.index + 4
226
+	if i < 0 || i > len(p.buf) {
227
+		err = io.ErrUnexpectedEOF
228
+		return
229
+	}
230
+	p.index = i
231
+
232
+	x = uint64(p.buf[i-4])
233
+	x |= uint64(p.buf[i-3]) << 8
234
+	x |= uint64(p.buf[i-2]) << 16
235
+	x |= uint64(p.buf[i-1]) << 24
236
+	return
237
+}
238
+
239
+// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
240
+// from the Buffer.
241
+// This is the format used for the sint64 protocol buffer type.
242
+func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
243
+	x, err = p.DecodeVarint()
244
+	if err != nil {
245
+		return
246
+	}
247
+	x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
248
+	return
249
+}
250
+
251
+// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
252
+// from  the Buffer.
253
+// This is the format used for the sint32 protocol buffer type.
254
+func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
255
+	x, err = p.DecodeVarint()
256
+	if err != nil {
257
+		return
258
+	}
259
+	x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
260
+	return
261
+}
262
+
263
+// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
264
+// This is the format used for the bytes protocol buffer
265
+// type and for embedded messages.
266
+func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
267
+	n, err := p.DecodeVarint()
268
+	if err != nil {
269
+		return nil, err
270
+	}
271
+
272
+	nb := int(n)
273
+	if nb < 0 {
274
+		return nil, fmt.Errorf("proto: bad byte length %d", nb)
275
+	}
276
+	end := p.index + nb
277
+	if end < p.index || end > len(p.buf) {
278
+		return nil, io.ErrUnexpectedEOF
279
+	}
280
+
281
+	if !alloc {
282
+		// todo: check if can get more uses of alloc=false
283
+		buf = p.buf[p.index:end]
284
+		p.index += nb
285
+		return
286
+	}
287
+
288
+	buf = make([]byte, nb)
289
+	copy(buf, p.buf[p.index:])
290
+	p.index += nb
291
+	return
292
+}
293
+
294
+// DecodeStringBytes reads an encoded string from the Buffer.
295
+// This is the format used for the proto2 string type.
296
+func (p *Buffer) DecodeStringBytes() (s string, err error) {
297
+	buf, err := p.DecodeRawBytes(false)
298
+	if err != nil {
299
+		return
300
+	}
301
+	return string(buf), nil
302
+}
303
+
304
+// Unmarshaler is the interface representing objects that can
305
+// unmarshal themselves.  The argument points to data that may be
306
+// overwritten, so implementations should not keep references to the
307
+// buffer.
308
+// Unmarshal implementations should not clear the receiver.
309
+// Any unmarshaled data should be merged into the receiver.
310
+// Callers of Unmarshal that do not want to retain existing data
311
+// should Reset the receiver before calling Unmarshal.
312
+type Unmarshaler interface {
313
+	Unmarshal([]byte) error
314
+}
315
+
316
+// newUnmarshaler is the interface representing objects that can
317
+// unmarshal themselves. The semantics are identical to Unmarshaler.
318
+//
319
+// This exists to support protoc-gen-go generated messages.
320
+// The proto package will stop type-asserting to this interface in the future.
321
+//
322
+// DO NOT DEPEND ON THIS.
323
+type newUnmarshaler interface {
324
+	XXX_Unmarshal([]byte) error
325
+}
326
+
327
+// Unmarshal parses the protocol buffer representation in buf and places the
328
+// decoded result in pb.  If the struct underlying pb does not match
329
+// the data in buf, the results can be unpredictable.
330
+//
331
+// Unmarshal resets pb before starting to unmarshal, so any
332
+// existing data in pb is always removed. Use UnmarshalMerge
333
+// to preserve and append to existing data.
334
+func Unmarshal(buf []byte, pb Message) error {
335
+	pb.Reset()
336
+	if u, ok := pb.(newUnmarshaler); ok {
337
+		return u.XXX_Unmarshal(buf)
338
+	}
339
+	if u, ok := pb.(Unmarshaler); ok {
340
+		return u.Unmarshal(buf)
341
+	}
342
+	return NewBuffer(buf).Unmarshal(pb)
343
+}
344
+
345
+// UnmarshalMerge parses the protocol buffer representation in buf and
346
+// writes the decoded result to pb.  If the struct underlying pb does not match
347
+// the data in buf, the results can be unpredictable.
348
+//
349
+// UnmarshalMerge merges into existing data in pb.
350
+// Most code should use Unmarshal instead.
351
+func UnmarshalMerge(buf []byte, pb Message) error {
352
+	if u, ok := pb.(newUnmarshaler); ok {
353
+		return u.XXX_Unmarshal(buf)
354
+	}
355
+	if u, ok := pb.(Unmarshaler); ok {
356
+		// NOTE: The history of proto have unfortunately been inconsistent
357
+		// whether Unmarshaler should or should not implicitly clear itself.
358
+		// Some implementations do, most do not.
359
+		// Thus, calling this here may or may not do what people want.
360
+		//
361
+		// See https://github.com/golang/protobuf/issues/424
362
+		return u.Unmarshal(buf)
363
+	}
364
+	return NewBuffer(buf).Unmarshal(pb)
365
+}
366
+
367
+// DecodeMessage reads a count-delimited message from the Buffer.
368
+func (p *Buffer) DecodeMessage(pb Message) error {
369
+	enc, err := p.DecodeRawBytes(false)
370
+	if err != nil {
371
+		return err
372
+	}
373
+	return NewBuffer(enc).Unmarshal(pb)
374
+}
375
+
376
+// DecodeGroup reads a tag-delimited group from the Buffer.
377
+// StartGroup tag is already consumed. This function consumes
378
+// EndGroup tag.
379
+func (p *Buffer) DecodeGroup(pb Message) error {
380
+	b := p.buf[p.index:]
381
+	x, y := findEndGroup(b)
382
+	if x < 0 {
383
+		return io.ErrUnexpectedEOF
384
+	}
385
+	err := Unmarshal(b[:x], pb)
386
+	p.index += y
387
+	return err
388
+}
389
+
390
+// Unmarshal parses the protocol buffer representation in the
391
+// Buffer and places the decoded result in pb.  If the struct
392
+// underlying pb does not match the data in the buffer, the results can be
393
+// unpredictable.
394
+//
395
+// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
396
+func (p *Buffer) Unmarshal(pb Message) error {
397
+	// If the object can unmarshal itself, let it.
398
+	if u, ok := pb.(newUnmarshaler); ok {
399
+		err := u.XXX_Unmarshal(p.buf[p.index:])
400
+		p.index = len(p.buf)
401
+		return err
402
+	}
403
+	if u, ok := pb.(Unmarshaler); ok {
404
+		// NOTE: The history of proto have unfortunately been inconsistent
405
+		// whether Unmarshaler should or should not implicitly clear itself.
406
+		// Some implementations do, most do not.
407
+		// Thus, calling this here may or may not do what people want.
408
+		//
409
+		// See https://github.com/golang/protobuf/issues/424
410
+		err := u.Unmarshal(p.buf[p.index:])
411
+		p.index = len(p.buf)
412
+		return err
413
+	}
414
+
415
+	// Slow workaround for messages that aren't Unmarshalers.
416
+	// This includes some hand-coded .pb.go files and
417
+	// bootstrap protos.
418
+	// TODO: fix all of those and then add Unmarshal to
419
+	// the Message interface. Then:
420
+	// The cast above and code below can be deleted.
421
+	// The old unmarshaler can be deleted.
422
+	// Clients can call Unmarshal directly (can already do that, actually).
423
+	var info InternalMessageInfo
424
+	err := info.Unmarshal(pb, p.buf[p.index:])
425
+	p.index = len(p.buf)
426
+	return err
427
+}

+ 63
- 0
log/vendor/github.com/golang/protobuf/proto/deprecated.go View File

@@ -0,0 +1,63 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2018 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+import "errors"
35
+
36
+// Deprecated: do not use.
37
+type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 }
38
+
39
+// Deprecated: do not use.
40
+func GetStats() Stats { return Stats{} }
41
+
42
+// Deprecated: do not use.
43
+func MarshalMessageSet(interface{}) ([]byte, error) {
44
+	return nil, errors.New("proto: not implemented")
45
+}
46
+
47
+// Deprecated: do not use.
48
+func UnmarshalMessageSet([]byte, interface{}) error {
49
+	return errors.New("proto: not implemented")
50
+}
51
+
52
+// Deprecated: do not use.
53
+func MarshalMessageSetJSON(interface{}) ([]byte, error) {
54
+	return nil, errors.New("proto: not implemented")
55
+}
56
+
57
+// Deprecated: do not use.
58
+func UnmarshalMessageSetJSON([]byte, interface{}) error {
59
+	return errors.New("proto: not implemented")
60
+}
61
+
62
+// Deprecated: do not use.
63
+func RegisterMessageSetType(Message, int32, string) {}

+ 350
- 0
log/vendor/github.com/golang/protobuf/proto/discard.go View File

@@ -0,0 +1,350 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2017 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+import (
35
+	"fmt"
36
+	"reflect"
37
+	"strings"
38
+	"sync"
39
+	"sync/atomic"
40
+)
41
+
42
+type generatedDiscarder interface {
43
+	XXX_DiscardUnknown()
44
+}
45
+
46
+// DiscardUnknown recursively discards all unknown fields from this message
47
+// and all embedded messages.
48
+//
49
+// When unmarshaling a message with unrecognized fields, the tags and values
50
+// of such fields are preserved in the Message. This allows a later call to
51
+// marshal to be able to produce a message that continues to have those
52
+// unrecognized fields. To avoid this, DiscardUnknown is used to
53
+// explicitly clear the unknown fields after unmarshaling.
54
+//
55
+// For proto2 messages, the unknown fields of message extensions are only
56
+// discarded from messages that have been accessed via GetExtension.
57
+func DiscardUnknown(m Message) {
58
+	if m, ok := m.(generatedDiscarder); ok {
59
+		m.XXX_DiscardUnknown()
60
+		return
61
+	}
62
+	// TODO: Dynamically populate a InternalMessageInfo for legacy messages,
63
+	// but the master branch has no implementation for InternalMessageInfo,
64
+	// so it would be more work to replicate that approach.
65
+	discardLegacy(m)
66
+}
67
+
68
+// DiscardUnknown recursively discards all unknown fields.
69
+func (a *InternalMessageInfo) DiscardUnknown(m Message) {
70
+	di := atomicLoadDiscardInfo(&a.discard)
71
+	if di == nil {
72
+		di = getDiscardInfo(reflect.TypeOf(m).Elem())
73
+		atomicStoreDiscardInfo(&a.discard, di)
74
+	}
75
+	di.discard(toPointer(&m))
76
+}
77
+
78
+type discardInfo struct {
79
+	typ reflect.Type
80
+
81
+	initialized int32 // 0: only typ is valid, 1: everything is valid
82
+	lock        sync.Mutex
83
+
84
+	fields       []discardFieldInfo
85
+	unrecognized field
86
+}
87
+
88
+type discardFieldInfo struct {
89
+	field   field // Offset of field, guaranteed to be valid
90
+	discard func(src pointer)
91
+}
92
+
93
+var (
94
+	discardInfoMap  = map[reflect.Type]*discardInfo{}
95
+	discardInfoLock sync.Mutex
96
+)
97
+
98
+func getDiscardInfo(t reflect.Type) *discardInfo {
99
+	discardInfoLock.Lock()
100
+	defer discardInfoLock.Unlock()
101
+	di := discardInfoMap[t]
102
+	if di == nil {
103
+		di = &discardInfo{typ: t}
104
+		discardInfoMap[t] = di
105
+	}
106
+	return di
107
+}
108
+
109
+func (di *discardInfo) discard(src pointer) {
110
+	if src.isNil() {
111
+		return // Nothing to do.
112
+	}
113
+
114
+	if atomic.LoadInt32(&di.initialized) == 0 {
115
+		di.computeDiscardInfo()
116
+	}
117
+
118
+	for _, fi := range di.fields {
119
+		sfp := src.offset(fi.field)
120
+		fi.discard(sfp)
121
+	}
122
+
123
+	// For proto2 messages, only discard unknown fields in message extensions
124
+	// that have been accessed via GetExtension.
125
+	if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
126
+		// Ignore lock since DiscardUnknown is not concurrency safe.
127
+		emm, _ := em.extensionsRead()
128
+		for _, mx := range emm {
129
+			if m, ok := mx.value.(Message); ok {
130
+				DiscardUnknown(m)
131
+			}
132
+		}
133
+	}
134
+
135
+	if di.unrecognized.IsValid() {
136
+		*src.offset(di.unrecognized).toBytes() = nil
137
+	}
138
+}
139
+
140
+func (di *discardInfo) computeDiscardInfo() {
141
+	di.lock.Lock()
142
+	defer di.lock.Unlock()
143
+	if di.initialized != 0 {
144
+		return
145
+	}
146
+	t := di.typ
147
+	n := t.NumField()
148
+
149
+	for i := 0; i < n; i++ {
150
+		f := t.Field(i)
151
+		if strings.HasPrefix(f.Name, "XXX_") {
152
+			continue
153
+		}
154
+
155
+		dfi := discardFieldInfo{field: toField(&f)}
156
+		tf := f.Type
157
+
158
+		// Unwrap tf to get its most basic type.
159
+		var isPointer, isSlice bool
160
+		if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
161
+			isSlice = true
162
+			tf = tf.Elem()
163
+		}
164
+		if tf.Kind() == reflect.Ptr {
165
+			isPointer = true
166
+			tf = tf.Elem()
167
+		}
168
+		if isPointer && isSlice && tf.Kind() != reflect.Struct {
169
+			panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
170
+		}
171
+
172
+		switch tf.Kind() {
173
+		case reflect.Struct:
174
+			switch {
175
+			case !isPointer:
176
+				panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
177
+			case isSlice: // E.g., []*pb.T
178
+				di := getDiscardInfo(tf)
179
+				dfi.discard = func(src pointer) {
180
+					sps := src.getPointerSlice()
181
+					for _, sp := range sps {
182
+						if !sp.isNil() {
183
+							di.discard(sp)
184
+						}
185
+					}
186
+				}
187
+			default: // E.g., *pb.T
188
+				di := getDiscardInfo(tf)
189
+				dfi.discard = func(src pointer) {
190
+					sp := src.getPointer()
191
+					if !sp.isNil() {
192
+						di.discard(sp)
193
+					}
194
+				}
195
+			}
196
+		case reflect.Map:
197
+			switch {
198
+			case isPointer || isSlice:
199
+				panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
200
+			default: // E.g., map[K]V
201
+				if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
202
+					dfi.discard = func(src pointer) {
203
+						sm := src.asPointerTo(tf).Elem()
204
+						if sm.Len() == 0 {
205
+							return
206
+						}
207
+						for _, key := range sm.MapKeys() {
208
+							val := sm.MapIndex(key)
209
+							DiscardUnknown(val.Interface().(Message))
210
+						}
211
+					}
212
+				} else {
213
+					dfi.discard = func(pointer) {} // Noop
214
+				}
215
+			}
216
+		case reflect.Interface:
217
+			// Must be oneof field.
218
+			switch {
219
+			case isPointer || isSlice:
220
+				panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
221
+			default: // E.g., interface{}
222
+				// TODO: Make this faster?
223
+				dfi.discard = func(src pointer) {
224
+					su := src.asPointerTo(tf).Elem()
225
+					if !su.IsNil() {
226
+						sv := su.Elem().Elem().Field(0)
227
+						if sv.Kind() == reflect.Ptr && sv.IsNil() {
228
+							return
229
+						}
230
+						switch sv.Type().Kind() {
231
+						case reflect.Ptr: // Proto struct (e.g., *T)
232
+							DiscardUnknown(sv.Interface().(Message))
233
+						}
234
+					}
235
+				}
236
+			}
237
+		default:
238
+			continue
239
+		}
240
+		di.fields = append(di.fields, dfi)
241
+	}
242
+
243
+	di.unrecognized = invalidField
244
+	if f, ok := t.FieldByName("XXX_unrecognized"); ok {
245
+		if f.Type != reflect.TypeOf([]byte{}) {
246
+			panic("expected XXX_unrecognized to be of type []byte")
247
+		}
248
+		di.unrecognized = toField(&f)
249
+	}
250
+
251
+	atomic.StoreInt32(&di.initialized, 1)
252
+}
253
+
254
+func discardLegacy(m Message) {
255
+	v := reflect.ValueOf(m)
256
+	if v.Kind() != reflect.Ptr || v.IsNil() {
257
+		return
258
+	}
259
+	v = v.Elem()
260
+	if v.Kind() != reflect.Struct {
261
+		return
262
+	}
263
+	t := v.Type()
264
+
265
+	for i := 0; i < v.NumField(); i++ {
266
+		f := t.Field(i)
267
+		if strings.HasPrefix(f.Name, "XXX_") {
268
+			continue
269
+		}
270
+		vf := v.Field(i)
271
+		tf := f.Type
272
+
273
+		// Unwrap tf to get its most basic type.
274
+		var isPointer, isSlice bool
275
+		if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
276
+			isSlice = true
277
+			tf = tf.Elem()
278
+		}
279
+		if tf.Kind() == reflect.Ptr {
280
+			isPointer = true
281
+			tf = tf.Elem()
282
+		}
283
+		if isPointer && isSlice && tf.Kind() != reflect.Struct {
284
+			panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
285
+		}
286
+
287
+		switch tf.Kind() {
288
+		case reflect.Struct:
289
+			switch {
290
+			case !isPointer:
291
+				panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
292
+			case isSlice: // E.g., []*pb.T
293
+				for j := 0; j < vf.Len(); j++ {
294
+					discardLegacy(vf.Index(j).Interface().(Message))
295
+				}
296
+			default: // E.g., *pb.T
297
+				discardLegacy(vf.Interface().(Message))
298
+			}
299
+		case reflect.Map:
300
+			switch {
301
+			case isPointer || isSlice:
302
+				panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
303
+			default: // E.g., map[K]V
304
+				tv := vf.Type().Elem()
305
+				if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
306
+					for _, key := range vf.MapKeys() {
307
+						val := vf.MapIndex(key)
308
+						discardLegacy(val.Interface().(Message))
309
+					}
310
+				}
311
+			}
312
+		case reflect.Interface:
313
+			// Must be oneof field.
314
+			switch {
315
+			case isPointer || isSlice:
316
+				panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
317
+			default: // E.g., test_proto.isCommunique_Union interface
318
+				if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
319
+					vf = vf.Elem() // E.g., *test_proto.Communique_Msg
320
+					if !vf.IsNil() {
321
+						vf = vf.Elem()   // E.g., test_proto.Communique_Msg
322
+						vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
323
+						if vf.Kind() == reflect.Ptr {
324
+							discardLegacy(vf.Interface().(Message))
325
+						}
326
+					}
327
+				}
328
+			}
329
+		}
330
+	}
331
+
332
+	if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
333
+		if vf.Type() != reflect.TypeOf([]byte{}) {
334
+			panic("expected XXX_unrecognized to be of type []byte")
335
+		}
336
+		vf.Set(reflect.ValueOf([]byte(nil)))
337
+	}
338
+
339
+	// For proto2 messages, only discard unknown fields in message extensions
340
+	// that have been accessed via GetExtension.
341
+	if em, err := extendable(m); err == nil {
342
+		// Ignore lock since discardLegacy is not concurrency safe.
343
+		emm, _ := em.extensionsRead()
344
+		for _, mx := range emm {
345
+			if m, ok := mx.value.(Message); ok {
346
+				discardLegacy(m)
347
+			}
348
+		}
349
+	}
350
+}

+ 203
- 0
log/vendor/github.com/golang/protobuf/proto/encode.go View File

@@ -0,0 +1,203 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+/*
35
+ * Routines for encoding data into the wire format for protocol buffers.
36
+ */
37
+
38
+import (
39
+	"errors"
40
+	"reflect"
41
+)
42
+
43
+var (
44
+	// errRepeatedHasNil is the error returned if Marshal is called with
45
+	// a struct with a repeated field containing a nil element.
46
+	errRepeatedHasNil = errors.New("proto: repeated field has nil element")
47
+
48
+	// errOneofHasNil is the error returned if Marshal is called with
49
+	// a struct with a oneof field containing a nil element.
50
+	errOneofHasNil = errors.New("proto: oneof field has nil value")
51
+
52
+	// ErrNil is the error returned if Marshal is called with nil.
53
+	ErrNil = errors.New("proto: Marshal called with nil")
54
+
55
+	// ErrTooLarge is the error returned if Marshal is called with a
56
+	// message that encodes to >2GB.
57
+	ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
58
+)
59
+
60
+// The fundamental encoders that put bytes on the wire.
61
+// Those that take integer types all accept uint64 and are
62
+// therefore of type valueEncoder.
63
+
64
+const maxVarintBytes = 10 // maximum length of a varint
65
+
66
+// EncodeVarint returns the varint encoding of x.
67
+// This is the format for the
68
+// int32, int64, uint32, uint64, bool, and enum
69
+// protocol buffer types.
70
+// Not used by the package itself, but helpful to clients
71
+// wishing to use the same encoding.
72
+func EncodeVarint(x uint64) []byte {
73
+	var buf [maxVarintBytes]byte
74
+	var n int
75
+	for n = 0; x > 127; n++ {
76
+		buf[n] = 0x80 | uint8(x&0x7F)
77
+		x >>= 7
78
+	}
79
+	buf[n] = uint8(x)
80
+	n++
81
+	return buf[0:n]
82
+}
83
+
84
+// EncodeVarint writes a varint-encoded integer to the Buffer.
85
+// This is the format for the
86
+// int32, int64, uint32, uint64, bool, and enum
87
+// protocol buffer types.
88
+func (p *Buffer) EncodeVarint(x uint64) error {
89
+	for x >= 1<<7 {
90
+		p.buf = append(p.buf, uint8(x&0x7f|0x80))
91
+		x >>= 7
92
+	}
93
+	p.buf = append(p.buf, uint8(x))
94
+	return nil
95
+}
96
+
97
+// SizeVarint returns the varint encoding size of an integer.
98
+func SizeVarint(x uint64) int {
99
+	switch {
100
+	case x < 1<<7:
101
+		return 1
102
+	case x < 1<<14:
103
+		return 2
104
+	case x < 1<<21:
105
+		return 3
106
+	case x < 1<<28:
107
+		return 4
108
+	case x < 1<<35:
109
+		return 5
110
+	case x < 1<<42:
111
+		return 6
112
+	case x < 1<<49:
113
+		return 7
114
+	case x < 1<<56:
115
+		return 8
116
+	case x < 1<<63:
117
+		return 9
118
+	}
119
+	return 10
120
+}
121
+
122
+// EncodeFixed64 writes a 64-bit integer to the Buffer.
123
+// This is the format for the
124
+// fixed64, sfixed64, and double protocol buffer types.
125
+func (p *Buffer) EncodeFixed64(x uint64) error {
126
+	p.buf = append(p.buf,
127
+		uint8(x),
128
+		uint8(x>>8),
129
+		uint8(x>>16),
130
+		uint8(x>>24),
131
+		uint8(x>>32),
132
+		uint8(x>>40),
133
+		uint8(x>>48),
134
+		uint8(x>>56))
135
+	return nil
136
+}
137
+
138
+// EncodeFixed32 writes a 32-bit integer to the Buffer.
139
+// This is the format for the
140
+// fixed32, sfixed32, and float protocol buffer types.
141
+func (p *Buffer) EncodeFixed32(x uint64) error {
142
+	p.buf = append(p.buf,
143
+		uint8(x),
144
+		uint8(x>>8),
145
+		uint8(x>>16),
146
+		uint8(x>>24))
147
+	return nil
148
+}
149
+
150
+// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
151
+// to the Buffer.
152
+// This is the format used for the sint64 protocol buffer type.
153
+func (p *Buffer) EncodeZigzag64(x uint64) error {
154
+	// use signed number to get arithmetic right shift.
155
+	return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
156
+}
157
+
158
+// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
159
+// to the Buffer.
160
+// This is the format used for the sint32 protocol buffer type.
161
+func (p *Buffer) EncodeZigzag32(x uint64) error {
162
+	// use signed number to get arithmetic right shift.
163
+	return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
164
+}
165
+
166
+// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
167
+// This is the format used for the bytes protocol buffer
168
+// type and for embedded messages.
169
+func (p *Buffer) EncodeRawBytes(b []byte) error {
170
+	p.EncodeVarint(uint64(len(b)))
171
+	p.buf = append(p.buf, b...)
172
+	return nil
173
+}
174
+
175
+// EncodeStringBytes writes an encoded string to the Buffer.
176
+// This is the format used for the proto2 string type.
177
+func (p *Buffer) EncodeStringBytes(s string) error {
178
+	p.EncodeVarint(uint64(len(s)))
179
+	p.buf = append(p.buf, s...)
180
+	return nil
181
+}
182
+
183
+// Marshaler is the interface representing objects that can marshal themselves.
184
+type Marshaler interface {
185
+	Marshal() ([]byte, error)
186
+}
187
+
188
+// EncodeMessage writes the protocol buffer to the Buffer,
189
+// prefixed by a varint-encoded length.
190
+func (p *Buffer) EncodeMessage(pb Message) error {
191
+	siz := Size(pb)
192
+	p.EncodeVarint(uint64(siz))
193
+	return p.Marshal(pb)
194
+}
195
+
196
+// All protocol buffer fields are nillable, but be careful.
197
+func isNil(v reflect.Value) bool {
198
+	switch v.Kind() {
199
+	case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
200
+		return v.IsNil()
201
+	}
202
+	return false
203
+}

+ 301
- 0
log/vendor/github.com/golang/protobuf/proto/equal.go View File

@@ -0,0 +1,301 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2011 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+// Protocol buffer comparison.
33
+
34
+package proto
35
+
36
+import (
37
+	"bytes"
38
+	"log"
39
+	"reflect"
40
+	"strings"
41
+)
42
+
43
+/*
44
+Equal returns true iff protocol buffers a and b are equal.
45
+The arguments must both be pointers to protocol buffer structs.
46
+
47
+Equality is defined in this way:
48
+  - Two messages are equal iff they are the same type,
49
+    corresponding fields are equal, unknown field sets
50
+    are equal, and extensions sets are equal.
51
+  - Two set scalar fields are equal iff their values are equal.
52
+    If the fields are of a floating-point type, remember that
53
+    NaN != x for all x, including NaN. If the message is defined
54
+    in a proto3 .proto file, fields are not "set"; specifically,
55
+    zero length proto3 "bytes" fields are equal (nil == {}).
56
+  - Two repeated fields are equal iff their lengths are the same,
57
+    and their corresponding elements are equal. Note a "bytes" field,
58
+    although represented by []byte, is not a repeated field and the
59
+    rule for the scalar fields described above applies.
60
+  - Two unset fields are equal.
61
+  - Two unknown field sets are equal if their current
62
+    encoded state is equal.
63
+  - Two extension sets are equal iff they have corresponding
64
+    elements that are pairwise equal.
65
+  - Two map fields are equal iff their lengths are the same,
66
+    and they contain the same set of elements. Zero-length map
67
+    fields are equal.
68
+  - Every other combination of things are not equal.
69
+
70
+The return value is undefined if a and b are not protocol buffers.
71
+*/
72
+func Equal(a, b Message) bool {
73
+	if a == nil || b == nil {
74
+		return a == b
75
+	}
76
+	v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
77
+	if v1.Type() != v2.Type() {
78
+		return false
79
+	}
80
+	if v1.Kind() == reflect.Ptr {
81
+		if v1.IsNil() {
82
+			return v2.IsNil()
83
+		}
84
+		if v2.IsNil() {
85
+			return false
86
+		}
87
+		v1, v2 = v1.Elem(), v2.Elem()
88
+	}
89
+	if v1.Kind() != reflect.Struct {
90
+		return false
91
+	}
92
+	return equalStruct(v1, v2)
93
+}
94
+
95
+// v1 and v2 are known to have the same type.
96
+func equalStruct(v1, v2 reflect.Value) bool {
97
+	sprop := GetProperties(v1.Type())
98
+	for i := 0; i < v1.NumField(); i++ {
99
+		f := v1.Type().Field(i)
100
+		if strings.HasPrefix(f.Name, "XXX_") {
101
+			continue
102
+		}
103
+		f1, f2 := v1.Field(i), v2.Field(i)
104
+		if f.Type.Kind() == reflect.Ptr {
105
+			if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
106
+				// both unset
107
+				continue
108
+			} else if n1 != n2 {
109
+				// set/unset mismatch
110
+				return false
111
+			}
112
+			f1, f2 = f1.Elem(), f2.Elem()
113
+		}
114
+		if !equalAny(f1, f2, sprop.Prop[i]) {
115
+			return false
116
+		}
117
+	}
118
+
119
+	if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
120
+		em2 := v2.FieldByName("XXX_InternalExtensions")
121
+		if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
122
+			return false
123
+		}
124
+	}
125
+
126
+	if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
127
+		em2 := v2.FieldByName("XXX_extensions")
128
+		if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
129
+			return false
130
+		}
131
+	}
132
+
133
+	uf := v1.FieldByName("XXX_unrecognized")
134
+	if !uf.IsValid() {
135
+		return true
136
+	}
137
+
138
+	u1 := uf.Bytes()
139
+	u2 := v2.FieldByName("XXX_unrecognized").Bytes()
140
+	return bytes.Equal(u1, u2)
141
+}
142
+
143
+// v1 and v2 are known to have the same type.
144
+// prop may be nil.
145
+func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
146
+	if v1.Type() == protoMessageType {
147
+		m1, _ := v1.Interface().(Message)
148
+		m2, _ := v2.Interface().(Message)
149
+		return Equal(m1, m2)
150
+	}
151
+	switch v1.Kind() {
152
+	case reflect.Bool:
153
+		return v1.Bool() == v2.Bool()
154
+	case reflect.Float32, reflect.Float64:
155
+		return v1.Float() == v2.Float()
156
+	case reflect.Int32, reflect.Int64:
157
+		return v1.Int() == v2.Int()
158
+	case reflect.Interface:
159
+		// Probably a oneof field; compare the inner values.
160
+		n1, n2 := v1.IsNil(), v2.IsNil()
161
+		if n1 || n2 {
162
+			return n1 == n2
163
+		}
164
+		e1, e2 := v1.Elem(), v2.Elem()
165
+		if e1.Type() != e2.Type() {
166
+			return false
167
+		}
168
+		return equalAny(e1, e2, nil)
169
+	case reflect.Map:
170
+		if v1.Len() != v2.Len() {
171
+			return false
172
+		}
173
+		for _, key := range v1.MapKeys() {
174
+			val2 := v2.MapIndex(key)
175
+			if !val2.IsValid() {
176
+				// This key was not found in the second map.
177
+				return false
178
+			}
179
+			if !equalAny(v1.MapIndex(key), val2, nil) {
180
+				return false
181
+			}
182
+		}
183
+		return true
184
+	case reflect.Ptr:
185
+		// Maps may have nil values in them, so check for nil.
186
+		if v1.IsNil() && v2.IsNil() {
187
+			return true
188
+		}
189
+		if v1.IsNil() != v2.IsNil() {
190
+			return false
191
+		}
192
+		return equalAny(v1.Elem(), v2.Elem(), prop)
193
+	case reflect.Slice:
194
+		if v1.Type().Elem().Kind() == reflect.Uint8 {
195
+			// short circuit: []byte
196
+
197
+			// Edge case: if this is in a proto3 message, a zero length
198
+			// bytes field is considered the zero value.
199
+			if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
200
+				return true
201
+			}
202
+			if v1.IsNil() != v2.IsNil() {
203
+				return false
204
+			}
205
+			return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
206
+		}
207
+
208
+		if v1.Len() != v2.Len() {
209
+			return false
210
+		}
211
+		for i := 0; i < v1.Len(); i++ {
212
+			if !equalAny(v1.Index(i), v2.Index(i), prop) {
213
+				return false
214
+			}
215
+		}
216
+		return true
217
+	case reflect.String:
218
+		return v1.Interface().(string) == v2.Interface().(string)
219
+	case reflect.Struct:
220
+		return equalStruct(v1, v2)
221
+	case reflect.Uint32, reflect.Uint64:
222
+		return v1.Uint() == v2.Uint()
223
+	}
224
+
225
+	// unknown type, so not a protocol buffer
226
+	log.Printf("proto: don't know how to compare %v", v1)
227
+	return false
228
+}
229
+
230
+// base is the struct type that the extensions are based on.
231
+// x1 and x2 are InternalExtensions.
232
+func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
233
+	em1, _ := x1.extensionsRead()
234
+	em2, _ := x2.extensionsRead()
235
+	return equalExtMap(base, em1, em2)
236
+}
237
+
238
+func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
239
+	if len(em1) != len(em2) {
240
+		return false
241
+	}
242
+
243
+	for extNum, e1 := range em1 {
244
+		e2, ok := em2[extNum]
245
+		if !ok {
246
+			return false
247
+		}
248
+
249
+		m1 := extensionAsLegacyType(e1.value)
250
+		m2 := extensionAsLegacyType(e2.value)
251
+
252
+		if m1 == nil && m2 == nil {
253
+			// Both have only encoded form.
254
+			if bytes.Equal(e1.enc, e2.enc) {
255
+				continue
256
+			}
257
+			// The bytes are different, but the extensions might still be
258
+			// equal. We need to decode them to compare.
259
+		}
260
+
261
+		if m1 != nil && m2 != nil {
262
+			// Both are unencoded.
263
+			if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
264
+				return false
265
+			}
266
+			continue
267
+		}
268
+
269
+		// At least one is encoded. To do a semantically correct comparison
270
+		// we need to unmarshal them first.
271
+		var desc *ExtensionDesc
272
+		if m := extensionMaps[base]; m != nil {
273
+			desc = m[extNum]
274
+		}
275
+		if desc == nil {
276
+			// If both have only encoded form and the bytes are the same,
277
+			// it is handled above. We get here when the bytes are different.
278
+			// We don't know how to decode it, so just compare them as byte
279
+			// slices.
280
+			log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
281
+			return false
282
+		}
283
+		var err error
284
+		if m1 == nil {
285
+			m1, err = decodeExtension(e1.enc, desc)
286
+		}
287
+		if m2 == nil && err == nil {
288
+			m2, err = decodeExtension(e2.enc, desc)
289
+		}
290
+		if err != nil {
291
+			// The encoded form is invalid.
292
+			log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
293
+			return false
294
+		}
295
+		if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
296
+			return false
297
+		}
298
+	}
299
+
300
+	return true
301
+}

+ 607
- 0
log/vendor/github.com/golang/protobuf/proto/extensions.go View File

@@ -0,0 +1,607 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+/*
35
+ * Types and routines for supporting protocol buffer extensions.
36
+ */
37
+
38
+import (
39
+	"errors"
40
+	"fmt"
41
+	"io"
42
+	"reflect"
43
+	"strconv"
44
+	"sync"
45
+)
46
+
47
+// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
48
+var ErrMissingExtension = errors.New("proto: missing extension")
49
+
50
+// ExtensionRange represents a range of message extensions for a protocol buffer.
51
+// Used in code generated by the protocol compiler.
52
+type ExtensionRange struct {
53
+	Start, End int32 // both inclusive
54
+}
55
+
56
+// extendableProto is an interface implemented by any protocol buffer generated by the current
57
+// proto compiler that may be extended.
58
+type extendableProto interface {
59
+	Message
60
+	ExtensionRangeArray() []ExtensionRange
61
+	extensionsWrite() map[int32]Extension
62
+	extensionsRead() (map[int32]Extension, sync.Locker)
63
+}
64
+
65
+// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
66
+// version of the proto compiler that may be extended.
67
+type extendableProtoV1 interface {
68
+	Message
69
+	ExtensionRangeArray() []ExtensionRange
70
+	ExtensionMap() map[int32]Extension
71
+}
72
+
73
+// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
74
+type extensionAdapter struct {
75
+	extendableProtoV1
76
+}
77
+
78
+func (e extensionAdapter) extensionsWrite() map[int32]Extension {
79
+	return e.ExtensionMap()
80
+}
81
+
82
+func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
83
+	return e.ExtensionMap(), notLocker{}
84
+}
85
+
86
+// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
87
+type notLocker struct{}
88
+
89
+func (n notLocker) Lock()   {}
90
+func (n notLocker) Unlock() {}
91
+
92
+// extendable returns the extendableProto interface for the given generated proto message.
93
+// If the proto message has the old extension format, it returns a wrapper that implements
94
+// the extendableProto interface.
95
+func extendable(p interface{}) (extendableProto, error) {
96
+	switch p := p.(type) {
97
+	case extendableProto:
98
+		if isNilPtr(p) {
99
+			return nil, fmt.Errorf("proto: nil %T is not extendable", p)
100
+		}
101
+		return p, nil
102
+	case extendableProtoV1:
103
+		if isNilPtr(p) {
104
+			return nil, fmt.Errorf("proto: nil %T is not extendable", p)
105
+		}
106
+		return extensionAdapter{p}, nil
107
+	}
108
+	// Don't allocate a specific error containing %T:
109
+	// this is the hot path for Clone and MarshalText.
110
+	return nil, errNotExtendable
111
+}
112
+
113
+var errNotExtendable = errors.New("proto: not an extendable proto.Message")
114
+
115
+func isNilPtr(x interface{}) bool {
116
+	v := reflect.ValueOf(x)
117
+	return v.Kind() == reflect.Ptr && v.IsNil()
118
+}
119
+
120
+// XXX_InternalExtensions is an internal representation of proto extensions.
121
+//
122
+// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
123
+// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
124
+//
125
+// The methods of XXX_InternalExtensions are not concurrency safe in general,
126
+// but calls to logically read-only methods such as has and get may be executed concurrently.
127
+type XXX_InternalExtensions struct {
128
+	// The struct must be indirect so that if a user inadvertently copies a
129
+	// generated message and its embedded XXX_InternalExtensions, they
130
+	// avoid the mayhem of a copied mutex.
131
+	//
132
+	// The mutex serializes all logically read-only operations to p.extensionMap.
133
+	// It is up to the client to ensure that write operations to p.extensionMap are
134
+	// mutually exclusive with other accesses.
135
+	p *struct {
136
+		mu           sync.Mutex
137
+		extensionMap map[int32]Extension
138
+	}
139
+}
140
+
141
+// extensionsWrite returns the extension map, creating it on first use.
142
+func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
143
+	if e.p == nil {
144
+		e.p = new(struct {
145
+			mu           sync.Mutex
146
+			extensionMap map[int32]Extension
147
+		})
148
+		e.p.extensionMap = make(map[int32]Extension)
149
+	}
150
+	return e.p.extensionMap
151
+}
152
+
153
+// extensionsRead returns the extensions map for read-only use.  It may be nil.
154
+// The caller must hold the returned mutex's lock when accessing Elements within the map.
155
+func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
156
+	if e.p == nil {
157
+		return nil, nil
158
+	}
159
+	return e.p.extensionMap, &e.p.mu
160
+}
161
+
162
+// ExtensionDesc represents an extension specification.
163
+// Used in generated code from the protocol compiler.
164
+type ExtensionDesc struct {
165
+	ExtendedType  Message     // nil pointer to the type that is being extended
166
+	ExtensionType interface{} // nil pointer to the extension type
167
+	Field         int32       // field number
168
+	Name          string      // fully-qualified name of extension, for text formatting
169
+	Tag           string      // protobuf tag style
170
+	Filename      string      // name of the file in which the extension is defined
171
+}
172
+
173
+func (ed *ExtensionDesc) repeated() bool {
174
+	t := reflect.TypeOf(ed.ExtensionType)
175
+	return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
176
+}
177
+
178
+// Extension represents an extension in a message.
179
+type Extension struct {
180
+	// When an extension is stored in a message using SetExtension
181
+	// only desc and value are set. When the message is marshaled
182
+	// enc will be set to the encoded form of the message.
183
+	//
184
+	// When a message is unmarshaled and contains extensions, each
185
+	// extension will have only enc set. When such an extension is
186
+	// accessed using GetExtension (or GetExtensions) desc and value
187
+	// will be set.
188
+	desc *ExtensionDesc
189
+
190
+	// value is a concrete value for the extension field. Let the type of
191
+	// desc.ExtensionType be the "API type" and the type of Extension.value
192
+	// be the "storage type". The API type and storage type are the same except:
193
+	//	* For scalars (except []byte), the API type uses *T,
194
+	//	while the storage type uses T.
195
+	//	* For repeated fields, the API type uses []T, while the storage type
196
+	//	uses *[]T.
197
+	//
198
+	// The reason for the divergence is so that the storage type more naturally
199
+	// matches what is expected of when retrieving the values through the
200
+	// protobuf reflection APIs.
201
+	//
202
+	// The value may only be populated if desc is also populated.
203
+	value interface{}
204
+
205
+	// enc is the raw bytes for the extension field.
206
+	enc []byte
207
+}
208
+
209
+// SetRawExtension is for testing only.
210
+func SetRawExtension(base Message, id int32, b []byte) {
211
+	epb, err := extendable(base)
212
+	if err != nil {
213
+		return
214
+	}
215
+	extmap := epb.extensionsWrite()
216
+	extmap[id] = Extension{enc: b}
217
+}
218
+
219
+// isExtensionField returns true iff the given field number is in an extension range.
220
+func isExtensionField(pb extendableProto, field int32) bool {
221
+	for _, er := range pb.ExtensionRangeArray() {
222
+		if er.Start <= field && field <= er.End {
223
+			return true
224
+		}
225
+	}
226
+	return false
227
+}
228
+
229
+// checkExtensionTypes checks that the given extension is valid for pb.
230
+func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
231
+	var pbi interface{} = pb
232
+	// Check the extended type.
233
+	if ea, ok := pbi.(extensionAdapter); ok {
234
+		pbi = ea.extendableProtoV1
235
+	}
236
+	if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
237
+		return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a)
238
+	}
239
+	// Check the range.
240
+	if !isExtensionField(pb, extension.Field) {
241
+		return errors.New("proto: bad extension number; not in declared ranges")
242
+	}
243
+	return nil
244
+}
245
+
246
+// extPropKey is sufficient to uniquely identify an extension.
247
+type extPropKey struct {
248
+	base  reflect.Type
249
+	field int32
250
+}
251
+
252
+var extProp = struct {
253
+	sync.RWMutex
254
+	m map[extPropKey]*Properties
255
+}{
256
+	m: make(map[extPropKey]*Properties),
257
+}
258
+
259
+func extensionProperties(ed *ExtensionDesc) *Properties {
260
+	key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
261
+
262
+	extProp.RLock()
263
+	if prop, ok := extProp.m[key]; ok {
264
+		extProp.RUnlock()
265
+		return prop
266
+	}
267
+	extProp.RUnlock()
268
+
269
+	extProp.Lock()
270
+	defer extProp.Unlock()
271
+	// Check again.
272
+	if prop, ok := extProp.m[key]; ok {
273
+		return prop
274
+	}
275
+
276
+	prop := new(Properties)
277
+	prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
278
+	extProp.m[key] = prop
279
+	return prop
280
+}
281
+
282
+// HasExtension returns whether the given extension is present in pb.
283
+func HasExtension(pb Message, extension *ExtensionDesc) bool {
284
+	// TODO: Check types, field numbers, etc.?
285
+	epb, err := extendable(pb)
286
+	if err != nil {
287
+		return false
288
+	}
289
+	extmap, mu := epb.extensionsRead()
290
+	if extmap == nil {
291
+		return false
292
+	}
293
+	mu.Lock()
294
+	_, ok := extmap[extension.Field]
295
+	mu.Unlock()
296
+	return ok
297
+}
298
+
299
+// ClearExtension removes the given extension from pb.
300
+func ClearExtension(pb Message, extension *ExtensionDesc) {
301
+	epb, err := extendable(pb)
302
+	if err != nil {
303
+		return
304
+	}
305
+	// TODO: Check types, field numbers, etc.?
306
+	extmap := epb.extensionsWrite()
307
+	delete(extmap, extension.Field)
308
+}
309
+
310
+// GetExtension retrieves a proto2 extended field from pb.
311
+//
312
+// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil),
313
+// then GetExtension parses the encoded field and returns a Go value of the specified type.
314
+// If the field is not present, then the default value is returned (if one is specified),
315
+// otherwise ErrMissingExtension is reported.
316
+//
317
+// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil),
318
+// then GetExtension returns the raw encoded bytes of the field extension.
319
+func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
320
+	epb, err := extendable(pb)
321
+	if err != nil {
322
+		return nil, err
323
+	}
324
+
325
+	if extension.ExtendedType != nil {
326
+		// can only check type if this is a complete descriptor
327
+		if err := checkExtensionTypes(epb, extension); err != nil {
328
+			return nil, err
329
+		}
330
+	}
331
+
332
+	emap, mu := epb.extensionsRead()
333
+	if emap == nil {
334
+		return defaultExtensionValue(extension)
335
+	}
336
+	mu.Lock()
337
+	defer mu.Unlock()
338
+	e, ok := emap[extension.Field]
339
+	if !ok {
340
+		// defaultExtensionValue returns the default value or
341
+		// ErrMissingExtension if there is no default.
342
+		return defaultExtensionValue(extension)
343
+	}
344
+
345
+	if e.value != nil {
346
+		// Already decoded. Check the descriptor, though.
347
+		if e.desc != extension {
348
+			// This shouldn't happen. If it does, it means that
349
+			// GetExtension was called twice with two different
350
+			// descriptors with the same field number.
351
+			return nil, errors.New("proto: descriptor conflict")
352
+		}
353
+		return extensionAsLegacyType(e.value), nil
354
+	}
355
+
356
+	if extension.ExtensionType == nil {
357
+		// incomplete descriptor
358
+		return e.enc, nil
359
+	}
360
+
361
+	v, err := decodeExtension(e.enc, extension)
362
+	if err != nil {
363
+		return nil, err
364
+	}
365
+
366
+	// Remember the decoded version and drop the encoded version.
367
+	// That way it is safe to mutate what we return.
368
+	e.value = extensionAsStorageType(v)
369
+	e.desc = extension
370
+	e.enc = nil
371
+	emap[extension.Field] = e
372
+	return extensionAsLegacyType(e.value), nil
373
+}
374
+
375
+// defaultExtensionValue returns the default value for extension.
376
+// If no default for an extension is defined ErrMissingExtension is returned.
377
+func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
378
+	if extension.ExtensionType == nil {
379
+		// incomplete descriptor, so no default
380
+		return nil, ErrMissingExtension
381
+	}
382
+
383
+	t := reflect.TypeOf(extension.ExtensionType)
384
+	props := extensionProperties(extension)
385
+
386
+	sf, _, err := fieldDefault(t, props)
387
+	if err != nil {
388
+		return nil, err
389
+	}
390
+
391
+	if sf == nil || sf.value == nil {
392
+		// There is no default value.
393
+		return nil, ErrMissingExtension
394
+	}
395
+
396
+	if t.Kind() != reflect.Ptr {
397
+		// We do not need to return a Ptr, we can directly return sf.value.
398
+		return sf.value, nil
399
+	}
400
+
401
+	// We need to return an interface{} that is a pointer to sf.value.
402
+	value := reflect.New(t).Elem()
403
+	value.Set(reflect.New(value.Type().Elem()))
404
+	if sf.kind == reflect.Int32 {
405
+		// We may have an int32 or an enum, but the underlying data is int32.
406
+		// Since we can't set an int32 into a non int32 reflect.value directly
407
+		// set it as a int32.
408
+		value.Elem().SetInt(int64(sf.value.(int32)))
409
+	} else {
410
+		value.Elem().Set(reflect.ValueOf(sf.value))
411
+	}
412
+	return value.Interface(), nil
413
+}
414
+
415
+// decodeExtension decodes an extension encoded in b.
416
+func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
417
+	t := reflect.TypeOf(extension.ExtensionType)
418
+	unmarshal := typeUnmarshaler(t, extension.Tag)
419
+
420
+	// t is a pointer to a struct, pointer to basic type or a slice.
421
+	// Allocate space to store the pointer/slice.
422
+	value := reflect.New(t).Elem()
423
+
424
+	var err error
425
+	for {
426
+		x, n := decodeVarint(b)
427
+		if n == 0 {
428
+			return nil, io.ErrUnexpectedEOF
429
+		}
430
+		b = b[n:]
431
+		wire := int(x) & 7
432
+
433
+		b, err = unmarshal(b, valToPointer(value.Addr()), wire)
434
+		if err != nil {
435
+			return nil, err
436
+		}
437
+
438
+		if len(b) == 0 {
439
+			break
440
+		}
441
+	}
442
+	return value.Interface(), nil
443
+}
444
+
445
+// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
446
+// The returned slice has the same length as es; missing extensions will appear as nil elements.
447
+func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
448
+	epb, err := extendable(pb)
449
+	if err != nil {
450
+		return nil, err
451
+	}
452
+	extensions = make([]interface{}, len(es))
453
+	for i, e := range es {
454
+		extensions[i], err = GetExtension(epb, e)
455
+		if err == ErrMissingExtension {
456
+			err = nil
457
+		}
458
+		if err != nil {
459
+			return
460
+		}
461
+	}
462
+	return
463
+}
464
+
465
+// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
466
+// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
467
+// just the Field field, which defines the extension's field number.
468
+func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
469
+	epb, err := extendable(pb)
470
+	if err != nil {
471
+		return nil, err
472
+	}
473
+	registeredExtensions := RegisteredExtensions(pb)
474
+
475
+	emap, mu := epb.extensionsRead()
476
+	if emap == nil {
477
+		return nil, nil
478
+	}
479
+	mu.Lock()
480
+	defer mu.Unlock()
481
+	extensions := make([]*ExtensionDesc, 0, len(emap))
482
+	for extid, e := range emap {
483
+		desc := e.desc
484
+		if desc == nil {
485
+			desc = registeredExtensions[extid]
486
+			if desc == nil {
487
+				desc = &ExtensionDesc{Field: extid}
488
+			}
489
+		}
490
+
491
+		extensions = append(extensions, desc)
492
+	}
493
+	return extensions, nil
494
+}
495
+
496
+// SetExtension sets the specified extension of pb to the specified value.
497
+func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
498
+	epb, err := extendable(pb)
499
+	if err != nil {
500
+		return err
501
+	}
502
+	if err := checkExtensionTypes(epb, extension); err != nil {
503
+		return err
504
+	}
505
+	typ := reflect.TypeOf(extension.ExtensionType)
506
+	if typ != reflect.TypeOf(value) {
507
+		return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType)
508
+	}
509
+	// nil extension values need to be caught early, because the
510
+	// encoder can't distinguish an ErrNil due to a nil extension
511
+	// from an ErrNil due to a missing field. Extensions are
512
+	// always optional, so the encoder would just swallow the error
513
+	// and drop all the extensions from the encoded message.
514
+	if reflect.ValueOf(value).IsNil() {
515
+		return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
516
+	}
517
+
518
+	extmap := epb.extensionsWrite()
519
+	extmap[extension.Field] = Extension{desc: extension, value: extensionAsStorageType(value)}
520
+	return nil
521
+}
522
+
523
+// ClearAllExtensions clears all extensions from pb.
524
+func ClearAllExtensions(pb Message) {
525
+	epb, err := extendable(pb)
526
+	if err != nil {
527
+		return
528
+	}
529
+	m := epb.extensionsWrite()
530
+	for k := range m {
531
+		delete(m, k)
532
+	}
533
+}
534
+
535
+// A global registry of extensions.
536
+// The generated code will register the generated descriptors by calling RegisterExtension.
537
+
538
+var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
539
+
540
+// RegisterExtension is called from the generated code.
541
+func RegisterExtension(desc *ExtensionDesc) {
542
+	st := reflect.TypeOf(desc.ExtendedType).Elem()
543
+	m := extensionMaps[st]
544
+	if m == nil {
545
+		m = make(map[int32]*ExtensionDesc)
546
+		extensionMaps[st] = m
547
+	}
548
+	if _, ok := m[desc.Field]; ok {
549
+		panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
550
+	}
551
+	m[desc.Field] = desc
552
+}
553
+
554
+// RegisteredExtensions returns a map of the registered extensions of a
555
+// protocol buffer struct, indexed by the extension number.
556
+// The argument pb should be a nil pointer to the struct type.
557
+func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
558
+	return extensionMaps[reflect.TypeOf(pb).Elem()]
559
+}
560
+
561
+// extensionAsLegacyType converts an value in the storage type as the API type.
562
+// See Extension.value.
563
+func extensionAsLegacyType(v interface{}) interface{} {
564
+	switch rv := reflect.ValueOf(v); rv.Kind() {
565
+	case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
566
+		// Represent primitive types as a pointer to the value.
567
+		rv2 := reflect.New(rv.Type())
568
+		rv2.Elem().Set(rv)
569
+		v = rv2.Interface()
570
+	case reflect.Ptr:
571
+		// Represent slice types as the value itself.
572
+		switch rv.Type().Elem().Kind() {
573
+		case reflect.Slice:
574
+			if rv.IsNil() {
575
+				v = reflect.Zero(rv.Type().Elem()).Interface()
576
+			} else {
577
+				v = rv.Elem().Interface()
578
+			}
579
+		}
580
+	}
581
+	return v
582
+}
583
+
584
+// extensionAsStorageType converts an value in the API type as the storage type.
585
+// See Extension.value.
586
+func extensionAsStorageType(v interface{}) interface{} {
587
+	switch rv := reflect.ValueOf(v); rv.Kind() {
588
+	case reflect.Ptr:
589
+		// Represent slice types as the value itself.
590
+		switch rv.Type().Elem().Kind() {
591
+		case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
592
+			if rv.IsNil() {
593
+				v = reflect.Zero(rv.Type().Elem()).Interface()
594
+			} else {
595
+				v = rv.Elem().Interface()
596
+			}
597
+		}
598
+	case reflect.Slice:
599
+		// Represent slice types as a pointer to the value.
600
+		if rv.Type().Elem().Kind() != reflect.Uint8 {
601
+			rv2 := reflect.New(rv.Type())
602
+			rv2.Elem().Set(rv)
603
+			v = rv2.Interface()
604
+		}
605
+	}
606
+	return v
607
+}

+ 965
- 0
log/vendor/github.com/golang/protobuf/proto/lib.go View File

@@ -0,0 +1,965 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+/*
33
+Package proto converts data structures to and from the wire format of
34
+protocol buffers.  It works in concert with the Go source code generated
35
+for .proto files by the protocol compiler.
36
+
37
+A summary of the properties of the protocol buffer interface
38
+for a protocol buffer variable v:
39
+
40
+  - Names are turned from camel_case to CamelCase for export.
41
+  - There are no methods on v to set fields; just treat
42
+	them as structure fields.
43
+  - There are getters that return a field's value if set,
44
+	and return the field's default value if unset.
45
+	The getters work even if the receiver is a nil message.
46
+  - The zero value for a struct is its correct initialization state.
47
+	All desired fields must be set before marshaling.
48
+  - A Reset() method will restore a protobuf struct to its zero state.
49
+  - Non-repeated fields are pointers to the values; nil means unset.
50
+	That is, optional or required field int32 f becomes F *int32.
51
+  - Repeated fields are slices.
52
+  - Helper functions are available to aid the setting of fields.
53
+	msg.Foo = proto.String("hello") // set field
54
+  - Constants are defined to hold the default values of all fields that
55
+	have them.  They have the form Default_StructName_FieldName.
56
+	Because the getter methods handle defaulted values,
57
+	direct use of these constants should be rare.
58
+  - Enums are given type names and maps from names to values.
59
+	Enum values are prefixed by the enclosing message's name, or by the
60
+	enum's type name if it is a top-level enum. Enum types have a String
61
+	method, and a Enum method to assist in message construction.
62
+  - Nested messages, groups and enums have type names prefixed with the name of
63
+	the surrounding message type.
64
+  - Extensions are given descriptor names that start with E_,
65
+	followed by an underscore-delimited list of the nested messages
66
+	that contain it (if any) followed by the CamelCased name of the
67
+	extension field itself.  HasExtension, ClearExtension, GetExtension
68
+	and SetExtension are functions for manipulating extensions.
69
+  - Oneof field sets are given a single field in their message,
70
+	with distinguished wrapper types for each possible field value.
71
+  - Marshal and Unmarshal are functions to encode and decode the wire format.
72
+
73
+When the .proto file specifies `syntax="proto3"`, there are some differences:
74
+
75
+  - Non-repeated fields of non-message type are values instead of pointers.
76
+  - Enum types do not get an Enum method.
77
+
78
+The simplest way to describe this is to see an example.
79
+Given file test.proto, containing
80
+
81
+	package example;
82
+
83
+	enum FOO { X = 17; }
84
+
85
+	message Test {
86
+	  required string label = 1;
87
+	  optional int32 type = 2 [default=77];
88
+	  repeated int64 reps = 3;
89
+	  optional group OptionalGroup = 4 {
90
+	    required string RequiredField = 5;
91
+	  }
92
+	  oneof union {
93
+	    int32 number = 6;
94
+	    string name = 7;
95
+	  }
96
+	}
97
+
98
+The resulting file, test.pb.go, is:
99
+
100
+	package example
101
+
102
+	import proto "github.com/golang/protobuf/proto"
103
+	import math "math"
104
+
105
+	type FOO int32
106
+	const (
107
+		FOO_X FOO = 17
108
+	)
109
+	var FOO_name = map[int32]string{
110
+		17: "X",
111
+	}
112
+	var FOO_value = map[string]int32{
113
+		"X": 17,
114
+	}
115
+
116
+	func (x FOO) Enum() *FOO {
117
+		p := new(FOO)
118
+		*p = x
119
+		return p
120
+	}
121
+	func (x FOO) String() string {
122
+		return proto.EnumName(FOO_name, int32(x))
123
+	}
124
+	func (x *FOO) UnmarshalJSON(data []byte) error {
125
+		value, err := proto.UnmarshalJSONEnum(FOO_value, data)
126
+		if err != nil {
127
+			return err
128
+		}
129
+		*x = FOO(value)
130
+		return nil
131
+	}
132
+
133
+	type Test struct {
134
+		Label         *string             `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
135
+		Type          *int32              `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
136
+		Reps          []int64             `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
137
+		Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
138
+		// Types that are valid to be assigned to Union:
139
+		//	*Test_Number
140
+		//	*Test_Name
141
+		Union            isTest_Union `protobuf_oneof:"union"`
142
+		XXX_unrecognized []byte       `json:"-"`
143
+	}
144
+	func (m *Test) Reset()         { *m = Test{} }
145
+	func (m *Test) String() string { return proto.CompactTextString(m) }
146
+	func (*Test) ProtoMessage() {}
147
+
148
+	type isTest_Union interface {
149
+		isTest_Union()
150
+	}
151
+
152
+	type Test_Number struct {
153
+		Number int32 `protobuf:"varint,6,opt,name=number"`
154
+	}
155
+	type Test_Name struct {
156
+		Name string `protobuf:"bytes,7,opt,name=name"`
157
+	}
158
+
159
+	func (*Test_Number) isTest_Union() {}
160
+	func (*Test_Name) isTest_Union()   {}
161
+
162
+	func (m *Test) GetUnion() isTest_Union {
163
+		if m != nil {
164
+			return m.Union
165
+		}
166
+		return nil
167
+	}
168
+	const Default_Test_Type int32 = 77
169
+
170
+	func (m *Test) GetLabel() string {
171
+		if m != nil && m.Label != nil {
172
+			return *m.Label
173
+		}
174
+		return ""
175
+	}
176
+
177
+	func (m *Test) GetType() int32 {
178
+		if m != nil && m.Type != nil {
179
+			return *m.Type
180
+		}
181
+		return Default_Test_Type
182
+	}
183
+
184
+	func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
185
+		if m != nil {
186
+			return m.Optionalgroup
187
+		}
188
+		return nil
189
+	}
190
+
191
+	type Test_OptionalGroup struct {
192
+		RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
193
+	}
194
+	func (m *Test_OptionalGroup) Reset()         { *m = Test_OptionalGroup{} }
195
+	func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
196
+
197
+	func (m *Test_OptionalGroup) GetRequiredField() string {
198
+		if m != nil && m.RequiredField != nil {
199
+			return *m.RequiredField
200
+		}
201
+		return ""
202
+	}
203
+
204
+	func (m *Test) GetNumber() int32 {
205
+		if x, ok := m.GetUnion().(*Test_Number); ok {
206
+			return x.Number
207
+		}
208
+		return 0
209
+	}
210
+
211
+	func (m *Test) GetName() string {
212
+		if x, ok := m.GetUnion().(*Test_Name); ok {
213
+			return x.Name
214
+		}
215
+		return ""
216
+	}
217
+
218
+	func init() {
219
+		proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
220
+	}
221
+
222
+To create and play with a Test object:
223
+
224
+	package main
225
+
226
+	import (
227
+		"log"
228
+
229
+		"github.com/golang/protobuf/proto"
230
+		pb "./example.pb"
231
+	)
232
+
233
+	func main() {
234
+		test := &pb.Test{
235
+			Label: proto.String("hello"),
236
+			Type:  proto.Int32(17),
237
+			Reps:  []int64{1, 2, 3},
238
+			Optionalgroup: &pb.Test_OptionalGroup{
239
+				RequiredField: proto.String("good bye"),
240
+			},
241
+			Union: &pb.Test_Name{"fred"},
242
+		}
243
+		data, err := proto.Marshal(test)
244
+		if err != nil {
245
+			log.Fatal("marshaling error: ", err)
246
+		}
247
+		newTest := &pb.Test{}
248
+		err = proto.Unmarshal(data, newTest)
249
+		if err != nil {
250
+			log.Fatal("unmarshaling error: ", err)
251
+		}
252
+		// Now test and newTest contain the same data.
253
+		if test.GetLabel() != newTest.GetLabel() {
254
+			log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
255
+		}
256
+		// Use a type switch to determine which oneof was set.
257
+		switch u := test.Union.(type) {
258
+		case *pb.Test_Number: // u.Number contains the number.
259
+		case *pb.Test_Name: // u.Name contains the string.
260
+		}
261
+		// etc.
262
+	}
263
+*/
264
+package proto
265
+
266
+import (
267
+	"encoding/json"
268
+	"fmt"
269
+	"log"
270
+	"reflect"
271
+	"sort"
272
+	"strconv"
273
+	"sync"
274
+)
275
+
276
+// RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
277
+// Marshal reports this when a required field is not initialized.
278
+// Unmarshal reports this when a required field is missing from the wire data.
279
+type RequiredNotSetError struct{ field string }
280
+
281
+func (e *RequiredNotSetError) Error() string {
282
+	if e.field == "" {
283
+		return fmt.Sprintf("proto: required field not set")
284
+	}
285
+	return fmt.Sprintf("proto: required field %q not set", e.field)
286
+}
287
+func (e *RequiredNotSetError) RequiredNotSet() bool {
288
+	return true
289
+}
290
+
291
+type invalidUTF8Error struct{ field string }
292
+
293
+func (e *invalidUTF8Error) Error() string {
294
+	if e.field == "" {
295
+		return "proto: invalid UTF-8 detected"
296
+	}
297
+	return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
298
+}
299
+func (e *invalidUTF8Error) InvalidUTF8() bool {
300
+	return true
301
+}
302
+
303
+// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
304
+// This error should not be exposed to the external API as such errors should
305
+// be recreated with the field information.
306
+var errInvalidUTF8 = &invalidUTF8Error{}
307
+
308
+// isNonFatal reports whether the error is either a RequiredNotSet error
309
+// or a InvalidUTF8 error.
310
+func isNonFatal(err error) bool {
311
+	if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
312
+		return true
313
+	}
314
+	if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
315
+		return true
316
+	}
317
+	return false
318
+}
319
+
320
+type nonFatal struct{ E error }
321
+
322
+// Merge merges err into nf and reports whether it was successful.
323
+// Otherwise it returns false for any fatal non-nil errors.
324
+func (nf *nonFatal) Merge(err error) (ok bool) {
325
+	if err == nil {
326
+		return true // not an error
327
+	}
328
+	if !isNonFatal(err) {
329
+		return false // fatal error
330
+	}
331
+	if nf.E == nil {
332
+		nf.E = err // store first instance of non-fatal error
333
+	}
334
+	return true
335
+}
336
+
337
+// Message is implemented by generated protocol buffer messages.
338
+type Message interface {
339
+	Reset()
340
+	String() string
341
+	ProtoMessage()
342
+}
343
+
344
+// A Buffer is a buffer manager for marshaling and unmarshaling
345
+// protocol buffers.  It may be reused between invocations to
346
+// reduce memory usage.  It is not necessary to use a Buffer;
347
+// the global functions Marshal and Unmarshal create a
348
+// temporary Buffer and are fine for most applications.
349
+type Buffer struct {
350
+	buf   []byte // encode/decode byte stream
351
+	index int    // read point
352
+
353
+	deterministic bool
354
+}
355
+
356
+// NewBuffer allocates a new Buffer and initializes its internal data to
357
+// the contents of the argument slice.
358
+func NewBuffer(e []byte) *Buffer {
359
+	return &Buffer{buf: e}
360
+}
361
+
362
+// Reset resets the Buffer, ready for marshaling a new protocol buffer.
363
+func (p *Buffer) Reset() {
364
+	p.buf = p.buf[0:0] // for reading/writing
365
+	p.index = 0        // for reading
366
+}
367
+
368
+// SetBuf replaces the internal buffer with the slice,
369
+// ready for unmarshaling the contents of the slice.
370
+func (p *Buffer) SetBuf(s []byte) {
371
+	p.buf = s
372
+	p.index = 0
373
+}
374
+
375
+// Bytes returns the contents of the Buffer.
376
+func (p *Buffer) Bytes() []byte { return p.buf }
377
+
378
+// SetDeterministic sets whether to use deterministic serialization.
379
+//
380
+// Deterministic serialization guarantees that for a given binary, equal
381
+// messages will always be serialized to the same bytes. This implies:
382
+//
383
+//   - Repeated serialization of a message will return the same bytes.
384
+//   - Different processes of the same binary (which may be executing on
385
+//     different machines) will serialize equal messages to the same bytes.
386
+//
387
+// Note that the deterministic serialization is NOT canonical across
388
+// languages. It is not guaranteed to remain stable over time. It is unstable
389
+// across different builds with schema changes due to unknown fields.
390
+// Users who need canonical serialization (e.g., persistent storage in a
391
+// canonical form, fingerprinting, etc.) should define their own
392
+// canonicalization specification and implement their own serializer rather
393
+// than relying on this API.
394
+//
395
+// If deterministic serialization is requested, map entries will be sorted
396
+// by keys in lexographical order. This is an implementation detail and
397
+// subject to change.
398
+func (p *Buffer) SetDeterministic(deterministic bool) {
399
+	p.deterministic = deterministic
400
+}
401
+
402
+/*
403
+ * Helper routines for simplifying the creation of optional fields of basic type.
404
+ */
405
+
406
+// Bool is a helper routine that allocates a new bool value
407
+// to store v and returns a pointer to it.
408
+func Bool(v bool) *bool {
409
+	return &v
410
+}
411
+
412
+// Int32 is a helper routine that allocates a new int32 value
413
+// to store v and returns a pointer to it.
414
+func Int32(v int32) *int32 {
415
+	return &v
416
+}
417
+
418
+// Int is a helper routine that allocates a new int32 value
419
+// to store v and returns a pointer to it, but unlike Int32
420
+// its argument value is an int.
421
+func Int(v int) *int32 {
422
+	p := new(int32)
423
+	*p = int32(v)
424
+	return p
425
+}
426
+
427
+// Int64 is a helper routine that allocates a new int64 value
428
+// to store v and returns a pointer to it.
429
+func Int64(v int64) *int64 {
430
+	return &v
431
+}
432
+
433
+// Float32 is a helper routine that allocates a new float32 value
434
+// to store v and returns a pointer to it.
435
+func Float32(v float32) *float32 {
436
+	return &v
437
+}
438
+
439
+// Float64 is a helper routine that allocates a new float64 value
440
+// to store v and returns a pointer to it.
441
+func Float64(v float64) *float64 {
442
+	return &v
443
+}
444
+
445
+// Uint32 is a helper routine that allocates a new uint32 value
446
+// to store v and returns a pointer to it.
447
+func Uint32(v uint32) *uint32 {
448
+	return &v
449
+}
450
+
451
+// Uint64 is a helper routine that allocates a new uint64 value
452
+// to store v and returns a pointer to it.
453
+func Uint64(v uint64) *uint64 {
454
+	return &v
455
+}
456
+
457
+// String is a helper routine that allocates a new string value
458
+// to store v and returns a pointer to it.
459
+func String(v string) *string {
460
+	return &v
461
+}
462
+
463
+// EnumName is a helper function to simplify printing protocol buffer enums
464
+// by name.  Given an enum map and a value, it returns a useful string.
465
+func EnumName(m map[int32]string, v int32) string {
466
+	s, ok := m[v]
467
+	if ok {
468
+		return s
469
+	}
470
+	return strconv.Itoa(int(v))
471
+}
472
+
473
+// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
474
+// from their JSON-encoded representation. Given a map from the enum's symbolic
475
+// names to its int values, and a byte buffer containing the JSON-encoded
476
+// value, it returns an int32 that can be cast to the enum type by the caller.
477
+//
478
+// The function can deal with both JSON representations, numeric and symbolic.
479
+func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
480
+	if data[0] == '"' {
481
+		// New style: enums are strings.
482
+		var repr string
483
+		if err := json.Unmarshal(data, &repr); err != nil {
484
+			return -1, err
485
+		}
486
+		val, ok := m[repr]
487
+		if !ok {
488
+			return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
489
+		}
490
+		return val, nil
491
+	}
492
+	// Old style: enums are ints.
493
+	var val int32
494
+	if err := json.Unmarshal(data, &val); err != nil {
495
+		return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
496
+	}
497
+	return val, nil
498
+}
499
+
500
+// DebugPrint dumps the encoded data in b in a debugging format with a header
501
+// including the string s. Used in testing but made available for general debugging.
502
+func (p *Buffer) DebugPrint(s string, b []byte) {
503
+	var u uint64
504
+
505
+	obuf := p.buf
506
+	index := p.index
507
+	p.buf = b
508
+	p.index = 0
509
+	depth := 0
510
+
511
+	fmt.Printf("\n--- %s ---\n", s)
512
+
513
+out:
514
+	for {
515
+		for i := 0; i < depth; i++ {
516
+			fmt.Print("  ")
517
+		}
518
+
519
+		index := p.index
520
+		if index == len(p.buf) {
521
+			break
522
+		}
523
+
524
+		op, err := p.DecodeVarint()
525
+		if err != nil {
526
+			fmt.Printf("%3d: fetching op err %v\n", index, err)
527
+			break out
528
+		}
529
+		tag := op >> 3
530
+		wire := op & 7
531
+
532
+		switch wire {
533
+		default:
534
+			fmt.Printf("%3d: t=%3d unknown wire=%d\n",
535
+				index, tag, wire)
536
+			break out
537
+
538
+		case WireBytes:
539
+			var r []byte
540
+
541
+			r, err = p.DecodeRawBytes(false)
542
+			if err != nil {
543
+				break out
544
+			}
545
+			fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
546
+			if len(r) <= 6 {
547
+				for i := 0; i < len(r); i++ {
548
+					fmt.Printf(" %.2x", r[i])
549
+				}
550
+			} else {
551
+				for i := 0; i < 3; i++ {
552
+					fmt.Printf(" %.2x", r[i])
553
+				}
554
+				fmt.Printf(" ..")
555
+				for i := len(r) - 3; i < len(r); i++ {
556
+					fmt.Printf(" %.2x", r[i])
557
+				}
558
+			}
559
+			fmt.Printf("\n")
560
+
561
+		case WireFixed32:
562
+			u, err = p.DecodeFixed32()
563
+			if err != nil {
564
+				fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
565
+				break out
566
+			}
567
+			fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
568
+
569
+		case WireFixed64:
570
+			u, err = p.DecodeFixed64()
571
+			if err != nil {
572
+				fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
573
+				break out
574
+			}
575
+			fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
576
+
577
+		case WireVarint:
578
+			u, err = p.DecodeVarint()
579
+			if err != nil {
580
+				fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
581
+				break out
582
+			}
583
+			fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
584
+
585
+		case WireStartGroup:
586
+			fmt.Printf("%3d: t=%3d start\n", index, tag)
587
+			depth++
588
+
589
+		case WireEndGroup:
590
+			depth--
591
+			fmt.Printf("%3d: t=%3d end\n", index, tag)
592
+		}
593
+	}
594
+
595
+	if depth != 0 {
596
+		fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
597
+	}
598
+	fmt.Printf("\n")
599
+
600
+	p.buf = obuf
601
+	p.index = index
602
+}
603
+
604
+// SetDefaults sets unset protocol buffer fields to their default values.
605
+// It only modifies fields that are both unset and have defined defaults.
606
+// It recursively sets default values in any non-nil sub-messages.
607
+func SetDefaults(pb Message) {
608
+	setDefaults(reflect.ValueOf(pb), true, false)
609
+}
610
+
611
+// v is a pointer to a struct.
612
+func setDefaults(v reflect.Value, recur, zeros bool) {
613
+	v = v.Elem()
614
+
615
+	defaultMu.RLock()
616
+	dm, ok := defaults[v.Type()]
617
+	defaultMu.RUnlock()
618
+	if !ok {
619
+		dm = buildDefaultMessage(v.Type())
620
+		defaultMu.Lock()
621
+		defaults[v.Type()] = dm
622
+		defaultMu.Unlock()
623
+	}
624
+
625
+	for _, sf := range dm.scalars {
626
+		f := v.Field(sf.index)
627
+		if !f.IsNil() {
628
+			// field already set
629
+			continue
630
+		}
631
+		dv := sf.value
632
+		if dv == nil && !zeros {
633
+			// no explicit default, and don't want to set zeros
634
+			continue
635
+		}
636
+		fptr := f.Addr().Interface() // **T
637
+		// TODO: Consider batching the allocations we do here.
638
+		switch sf.kind {
639
+		case reflect.Bool:
640
+			b := new(bool)
641
+			if dv != nil {
642
+				*b = dv.(bool)
643
+			}
644
+			*(fptr.(**bool)) = b
645
+		case reflect.Float32:
646
+			f := new(float32)
647
+			if dv != nil {
648
+				*f = dv.(float32)
649
+			}
650
+			*(fptr.(**float32)) = f
651
+		case reflect.Float64:
652
+			f := new(float64)
653
+			if dv != nil {
654
+				*f = dv.(float64)
655
+			}
656
+			*(fptr.(**float64)) = f
657
+		case reflect.Int32:
658
+			// might be an enum
659
+			if ft := f.Type(); ft != int32PtrType {
660
+				// enum
661
+				f.Set(reflect.New(ft.Elem()))
662
+				if dv != nil {
663
+					f.Elem().SetInt(int64(dv.(int32)))
664
+				}
665
+			} else {
666
+				// int32 field
667
+				i := new(int32)
668
+				if dv != nil {
669
+					*i = dv.(int32)
670
+				}
671
+				*(fptr.(**int32)) = i
672
+			}
673
+		case reflect.Int64:
674
+			i := new(int64)
675
+			if dv != nil {
676
+				*i = dv.(int64)
677
+			}
678
+			*(fptr.(**int64)) = i
679
+		case reflect.String:
680
+			s := new(string)
681
+			if dv != nil {
682
+				*s = dv.(string)
683
+			}
684
+			*(fptr.(**string)) = s
685
+		case reflect.Uint8:
686
+			// exceptional case: []byte
687
+			var b []byte
688
+			if dv != nil {
689
+				db := dv.([]byte)
690
+				b = make([]byte, len(db))
691
+				copy(b, db)
692
+			} else {
693
+				b = []byte{}
694
+			}
695
+			*(fptr.(*[]byte)) = b
696
+		case reflect.Uint32:
697
+			u := new(uint32)
698
+			if dv != nil {
699
+				*u = dv.(uint32)
700
+			}
701
+			*(fptr.(**uint32)) = u
702
+		case reflect.Uint64:
703
+			u := new(uint64)
704
+			if dv != nil {
705
+				*u = dv.(uint64)
706
+			}
707
+			*(fptr.(**uint64)) = u
708
+		default:
709
+			log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
710
+		}
711
+	}
712
+
713
+	for _, ni := range dm.nested {
714
+		f := v.Field(ni)
715
+		// f is *T or []*T or map[T]*T
716
+		switch f.Kind() {
717
+		case reflect.Ptr:
718
+			if f.IsNil() {
719
+				continue
720
+			}
721
+			setDefaults(f, recur, zeros)
722
+
723
+		case reflect.Slice:
724
+			for i := 0; i < f.Len(); i++ {
725
+				e := f.Index(i)
726
+				if e.IsNil() {
727
+					continue
728
+				}
729
+				setDefaults(e, recur, zeros)
730
+			}
731
+
732
+		case reflect.Map:
733
+			for _, k := range f.MapKeys() {
734
+				e := f.MapIndex(k)
735
+				if e.IsNil() {
736
+					continue
737
+				}
738
+				setDefaults(e, recur, zeros)
739
+			}
740
+		}
741
+	}
742
+}
743
+
744
+var (
745
+	// defaults maps a protocol buffer struct type to a slice of the fields,
746
+	// with its scalar fields set to their proto-declared non-zero default values.
747
+	defaultMu sync.RWMutex
748
+	defaults  = make(map[reflect.Type]defaultMessage)
749
+
750
+	int32PtrType = reflect.TypeOf((*int32)(nil))
751
+)
752
+
753
+// defaultMessage represents information about the default values of a message.
754
+type defaultMessage struct {
755
+	scalars []scalarField
756
+	nested  []int // struct field index of nested messages
757
+}
758
+
759
+type scalarField struct {
760
+	index int          // struct field index
761
+	kind  reflect.Kind // element type (the T in *T or []T)
762
+	value interface{}  // the proto-declared default value, or nil
763
+}
764
+
765
+// t is a struct type.
766
+func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
767
+	sprop := GetProperties(t)
768
+	for _, prop := range sprop.Prop {
769
+		fi, ok := sprop.decoderTags.get(prop.Tag)
770
+		if !ok {
771
+			// XXX_unrecognized
772
+			continue
773
+		}
774
+		ft := t.Field(fi).Type
775
+
776
+		sf, nested, err := fieldDefault(ft, prop)
777
+		switch {
778
+		case err != nil:
779
+			log.Print(err)
780
+		case nested:
781
+			dm.nested = append(dm.nested, fi)
782
+		case sf != nil:
783
+			sf.index = fi
784
+			dm.scalars = append(dm.scalars, *sf)
785
+		}
786
+	}
787
+
788
+	return dm
789
+}
790
+
791
+// fieldDefault returns the scalarField for field type ft.
792
+// sf will be nil if the field can not have a default.
793
+// nestedMessage will be true if this is a nested message.
794
+// Note that sf.index is not set on return.
795
+func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
796
+	var canHaveDefault bool
797
+	switch ft.Kind() {
798
+	case reflect.Ptr:
799
+		if ft.Elem().Kind() == reflect.Struct {
800
+			nestedMessage = true
801
+		} else {
802
+			canHaveDefault = true // proto2 scalar field
803
+		}
804
+
805
+	case reflect.Slice:
806
+		switch ft.Elem().Kind() {
807
+		case reflect.Ptr:
808
+			nestedMessage = true // repeated message
809
+		case reflect.Uint8:
810
+			canHaveDefault = true // bytes field
811
+		}
812
+
813
+	case reflect.Map:
814
+		if ft.Elem().Kind() == reflect.Ptr {
815
+			nestedMessage = true // map with message values
816
+		}
817
+	}
818
+
819
+	if !canHaveDefault {
820
+		if nestedMessage {
821
+			return nil, true, nil
822
+		}
823
+		return nil, false, nil
824
+	}
825
+
826
+	// We now know that ft is a pointer or slice.
827
+	sf = &scalarField{kind: ft.Elem().Kind()}
828
+
829
+	// scalar fields without defaults
830
+	if !prop.HasDefault {
831
+		return sf, false, nil
832
+	}
833
+
834
+	// a scalar field: either *T or []byte
835
+	switch ft.Elem().Kind() {
836
+	case reflect.Bool:
837
+		x, err := strconv.ParseBool(prop.Default)
838
+		if err != nil {
839
+			return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
840
+		}
841
+		sf.value = x
842
+	case reflect.Float32:
843
+		x, err := strconv.ParseFloat(prop.Default, 32)
844
+		if err != nil {
845
+			return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
846
+		}
847
+		sf.value = float32(x)
848
+	case reflect.Float64:
849
+		x, err := strconv.ParseFloat(prop.Default, 64)
850
+		if err != nil {
851
+			return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
852
+		}
853
+		sf.value = x
854
+	case reflect.Int32:
855
+		x, err := strconv.ParseInt(prop.Default, 10, 32)
856
+		if err != nil {
857
+			return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
858
+		}
859
+		sf.value = int32(x)
860
+	case reflect.Int64:
861
+		x, err := strconv.ParseInt(prop.Default, 10, 64)
862
+		if err != nil {
863
+			return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
864
+		}
865
+		sf.value = x
866
+	case reflect.String:
867
+		sf.value = prop.Default
868
+	case reflect.Uint8:
869
+		// []byte (not *uint8)
870
+		sf.value = []byte(prop.Default)
871
+	case reflect.Uint32:
872
+		x, err := strconv.ParseUint(prop.Default, 10, 32)
873
+		if err != nil {
874
+			return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
875
+		}
876
+		sf.value = uint32(x)
877
+	case reflect.Uint64:
878
+		x, err := strconv.ParseUint(prop.Default, 10, 64)
879
+		if err != nil {
880
+			return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
881
+		}
882
+		sf.value = x
883
+	default:
884
+		return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
885
+	}
886
+
887
+	return sf, false, nil
888
+}
889
+
890
+// mapKeys returns a sort.Interface to be used for sorting the map keys.
891
+// Map fields may have key types of non-float scalars, strings and enums.
892
+func mapKeys(vs []reflect.Value) sort.Interface {
893
+	s := mapKeySorter{vs: vs}
894
+
895
+	// Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
896
+	if len(vs) == 0 {
897
+		return s
898
+	}
899
+	switch vs[0].Kind() {
900
+	case reflect.Int32, reflect.Int64:
901
+		s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
902
+	case reflect.Uint32, reflect.Uint64:
903
+		s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
904
+	case reflect.Bool:
905
+		s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
906
+	case reflect.String:
907
+		s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
908
+	default:
909
+		panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
910
+	}
911
+
912
+	return s
913
+}
914
+
915
+type mapKeySorter struct {
916
+	vs   []reflect.Value
917
+	less func(a, b reflect.Value) bool
918
+}
919
+
920
+func (s mapKeySorter) Len() int      { return len(s.vs) }
921
+func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
922
+func (s mapKeySorter) Less(i, j int) bool {
923
+	return s.less(s.vs[i], s.vs[j])
924
+}
925
+
926
+// isProto3Zero reports whether v is a zero proto3 value.
927
+func isProto3Zero(v reflect.Value) bool {
928
+	switch v.Kind() {
929
+	case reflect.Bool:
930
+		return !v.Bool()
931
+	case reflect.Int32, reflect.Int64:
932
+		return v.Int() == 0
933
+	case reflect.Uint32, reflect.Uint64:
934
+		return v.Uint() == 0
935
+	case reflect.Float32, reflect.Float64:
936
+		return v.Float() == 0
937
+	case reflect.String:
938
+		return v.String() == ""
939
+	}
940
+	return false
941
+}
942
+
943
+const (
944
+	// ProtoPackageIsVersion3 is referenced from generated protocol buffer files
945
+	// to assert that that code is compatible with this version of the proto package.
946
+	ProtoPackageIsVersion3 = true
947
+
948
+	// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
949
+	// to assert that that code is compatible with this version of the proto package.
950
+	ProtoPackageIsVersion2 = true
951
+
952
+	// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
953
+	// to assert that that code is compatible with this version of the proto package.
954
+	ProtoPackageIsVersion1 = true
955
+)
956
+
957
+// InternalMessageInfo is a type used internally by generated .pb.go files.
958
+// This type is not intended to be used by non-generated code.
959
+// This type is not subject to any compatibility guarantee.
960
+type InternalMessageInfo struct {
961
+	marshal   *marshalInfo
962
+	unmarshal *unmarshalInfo
963
+	merge     *mergeInfo
964
+	discard   *discardInfo
965
+}

+ 181
- 0
log/vendor/github.com/golang/protobuf/proto/message_set.go View File

@@ -0,0 +1,181 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+/*
35
+ * Support for message sets.
36
+ */
37
+
38
+import (
39
+	"errors"
40
+)
41
+
42
+// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
43
+// A message type ID is required for storing a protocol buffer in a message set.
44
+var errNoMessageTypeID = errors.New("proto does not have a message type ID")
45
+
46
+// The first two types (_MessageSet_Item and messageSet)
47
+// model what the protocol compiler produces for the following protocol message:
48
+//   message MessageSet {
49
+//     repeated group Item = 1 {
50
+//       required int32 type_id = 2;
51
+//       required string message = 3;
52
+//     };
53
+//   }
54
+// That is the MessageSet wire format. We can't use a proto to generate these
55
+// because that would introduce a circular dependency between it and this package.
56
+
57
+type _MessageSet_Item struct {
58
+	TypeId  *int32 `protobuf:"varint,2,req,name=type_id"`
59
+	Message []byte `protobuf:"bytes,3,req,name=message"`
60
+}
61
+
62
+type messageSet struct {
63
+	Item             []*_MessageSet_Item `protobuf:"group,1,rep"`
64
+	XXX_unrecognized []byte
65
+	// TODO: caching?
66
+}
67
+
68
+// Make sure messageSet is a Message.
69
+var _ Message = (*messageSet)(nil)
70
+
71
+// messageTypeIder is an interface satisfied by a protocol buffer type
72
+// that may be stored in a MessageSet.
73
+type messageTypeIder interface {
74
+	MessageTypeId() int32
75
+}
76
+
77
+func (ms *messageSet) find(pb Message) *_MessageSet_Item {
78
+	mti, ok := pb.(messageTypeIder)
79
+	if !ok {
80
+		return nil
81
+	}
82
+	id := mti.MessageTypeId()
83
+	for _, item := range ms.Item {
84
+		if *item.TypeId == id {
85
+			return item
86
+		}
87
+	}
88
+	return nil
89
+}
90
+
91
+func (ms *messageSet) Has(pb Message) bool {
92
+	return ms.find(pb) != nil
93
+}
94
+
95
+func (ms *messageSet) Unmarshal(pb Message) error {
96
+	if item := ms.find(pb); item != nil {
97
+		return Unmarshal(item.Message, pb)
98
+	}
99
+	if _, ok := pb.(messageTypeIder); !ok {
100
+		return errNoMessageTypeID
101
+	}
102
+	return nil // TODO: return error instead?
103
+}
104
+
105
+func (ms *messageSet) Marshal(pb Message) error {
106
+	msg, err := Marshal(pb)
107
+	if err != nil {
108
+		return err
109
+	}
110
+	if item := ms.find(pb); item != nil {
111
+		// reuse existing item
112
+		item.Message = msg
113
+		return nil
114
+	}
115
+
116
+	mti, ok := pb.(messageTypeIder)
117
+	if !ok {
118
+		return errNoMessageTypeID
119
+	}
120
+
121
+	mtid := mti.MessageTypeId()
122
+	ms.Item = append(ms.Item, &_MessageSet_Item{
123
+		TypeId:  &mtid,
124
+		Message: msg,
125
+	})
126
+	return nil
127
+}
128
+
129
+func (ms *messageSet) Reset()         { *ms = messageSet{} }
130
+func (ms *messageSet) String() string { return CompactTextString(ms) }
131
+func (*messageSet) ProtoMessage()     {}
132
+
133
+// Support for the message_set_wire_format message option.
134
+
135
+func skipVarint(buf []byte) []byte {
136
+	i := 0
137
+	for ; buf[i]&0x80 != 0; i++ {
138
+	}
139
+	return buf[i+1:]
140
+}
141
+
142
+// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
143
+// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
144
+func unmarshalMessageSet(buf []byte, exts interface{}) error {
145
+	var m map[int32]Extension
146
+	switch exts := exts.(type) {
147
+	case *XXX_InternalExtensions:
148
+		m = exts.extensionsWrite()
149
+	case map[int32]Extension:
150
+		m = exts
151
+	default:
152
+		return errors.New("proto: not an extension map")
153
+	}
154
+
155
+	ms := new(messageSet)
156
+	if err := Unmarshal(buf, ms); err != nil {
157
+		return err
158
+	}
159
+	for _, item := range ms.Item {
160
+		id := *item.TypeId
161
+		msg := item.Message
162
+
163
+		// Restore wire type and field number varint, plus length varint.
164
+		// Be careful to preserve duplicate items.
165
+		b := EncodeVarint(uint64(id)<<3 | WireBytes)
166
+		if ext, ok := m[id]; ok {
167
+			// Existing data; rip off the tag and length varint
168
+			// so we join the new data correctly.
169
+			// We can assume that ext.enc is set because we are unmarshaling.
170
+			o := ext.enc[len(b):]   // skip wire type and field number
171
+			_, n := DecodeVarint(o) // calculate length of length varint
172
+			o = o[n:]               // skip length varint
173
+			msg = append(o, msg...) // join old data and new data
174
+		}
175
+		b = append(b, EncodeVarint(uint64(len(msg)))...)
176
+		b = append(b, msg...)
177
+
178
+		m[id] = Extension{enc: b}
179
+	}
180
+	return nil
181
+}

+ 360
- 0
log/vendor/github.com/golang/protobuf/proto/pointer_reflect.go View File

@@ -0,0 +1,360 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2012 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+// +build purego appengine js
33
+
34
+// This file contains an implementation of proto field accesses using package reflect.
35
+// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
36
+// be used on App Engine.
37
+
38
+package proto
39
+
40
+import (
41
+	"reflect"
42
+	"sync"
43
+)
44
+
45
+const unsafeAllowed = false
46
+
47
+// A field identifies a field in a struct, accessible from a pointer.
48
+// In this implementation, a field is identified by the sequence of field indices
49
+// passed to reflect's FieldByIndex.
50
+type field []int
51
+
52
+// toField returns a field equivalent to the given reflect field.
53
+func toField(f *reflect.StructField) field {
54
+	return f.Index
55
+}
56
+
57
+// invalidField is an invalid field identifier.
58
+var invalidField = field(nil)
59
+
60
+// zeroField is a noop when calling pointer.offset.
61
+var zeroField = field([]int{})
62
+
63
+// IsValid reports whether the field identifier is valid.
64
+func (f field) IsValid() bool { return f != nil }
65
+
66
+// The pointer type is for the table-driven decoder.
67
+// The implementation here uses a reflect.Value of pointer type to
68
+// create a generic pointer. In pointer_unsafe.go we use unsafe
69
+// instead of reflect to implement the same (but faster) interface.
70
+type pointer struct {
71
+	v reflect.Value
72
+}
73
+
74
+// toPointer converts an interface of pointer type to a pointer
75
+// that points to the same target.
76
+func toPointer(i *Message) pointer {
77
+	return pointer{v: reflect.ValueOf(*i)}
78
+}
79
+
80
+// toAddrPointer converts an interface to a pointer that points to
81
+// the interface data.
82
+func toAddrPointer(i *interface{}, isptr, deref bool) pointer {
83
+	v := reflect.ValueOf(*i)
84
+	u := reflect.New(v.Type())
85
+	u.Elem().Set(v)
86
+	if deref {
87
+		u = u.Elem()
88
+	}
89
+	return pointer{v: u}
90
+}
91
+
92
+// valToPointer converts v to a pointer.  v must be of pointer type.
93
+func valToPointer(v reflect.Value) pointer {
94
+	return pointer{v: v}
95
+}
96
+
97
+// offset converts from a pointer to a structure to a pointer to
98
+// one of its fields.
99
+func (p pointer) offset(f field) pointer {
100
+	return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
101
+}
102
+
103
+func (p pointer) isNil() bool {
104
+	return p.v.IsNil()
105
+}
106
+
107
+// grow updates the slice s in place to make it one element longer.
108
+// s must be addressable.
109
+// Returns the (addressable) new element.
110
+func grow(s reflect.Value) reflect.Value {
111
+	n, m := s.Len(), s.Cap()
112
+	if n < m {
113
+		s.SetLen(n + 1)
114
+	} else {
115
+		s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem())))
116
+	}
117
+	return s.Index(n)
118
+}
119
+
120
+func (p pointer) toInt64() *int64 {
121
+	return p.v.Interface().(*int64)
122
+}
123
+func (p pointer) toInt64Ptr() **int64 {
124
+	return p.v.Interface().(**int64)
125
+}
126
+func (p pointer) toInt64Slice() *[]int64 {
127
+	return p.v.Interface().(*[]int64)
128
+}
129
+
130
+var int32ptr = reflect.TypeOf((*int32)(nil))
131
+
132
+func (p pointer) toInt32() *int32 {
133
+	return p.v.Convert(int32ptr).Interface().(*int32)
134
+}
135
+
136
+// The toInt32Ptr/Slice methods don't work because of enums.
137
+// Instead, we must use set/get methods for the int32ptr/slice case.
138
+/*
139
+	func (p pointer) toInt32Ptr() **int32 {
140
+		return p.v.Interface().(**int32)
141
+}
142
+	func (p pointer) toInt32Slice() *[]int32 {
143
+		return p.v.Interface().(*[]int32)
144
+}
145
+*/
146
+func (p pointer) getInt32Ptr() *int32 {
147
+	if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
148
+		// raw int32 type
149
+		return p.v.Elem().Interface().(*int32)
150
+	}
151
+	// an enum
152
+	return p.v.Elem().Convert(int32PtrType).Interface().(*int32)
153
+}
154
+func (p pointer) setInt32Ptr(v int32) {
155
+	// Allocate value in a *int32. Possibly convert that to a *enum.
156
+	// Then assign it to a **int32 or **enum.
157
+	// Note: we can convert *int32 to *enum, but we can't convert
158
+	// **int32 to **enum!
159
+	p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem()))
160
+}
161
+
162
+// getInt32Slice copies []int32 from p as a new slice.
163
+// This behavior differs from the implementation in pointer_unsafe.go.
164
+func (p pointer) getInt32Slice() []int32 {
165
+	if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
166
+		// raw int32 type
167
+		return p.v.Elem().Interface().([]int32)
168
+	}
169
+	// an enum
170
+	// Allocate a []int32, then assign []enum's values into it.
171
+	// Note: we can't convert []enum to []int32.
172
+	slice := p.v.Elem()
173
+	s := make([]int32, slice.Len())
174
+	for i := 0; i < slice.Len(); i++ {
175
+		s[i] = int32(slice.Index(i).Int())
176
+	}
177
+	return s
178
+}
179
+
180
+// setInt32Slice copies []int32 into p as a new slice.
181
+// This behavior differs from the implementation in pointer_unsafe.go.
182
+func (p pointer) setInt32Slice(v []int32) {
183
+	if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
184
+		// raw int32 type
185
+		p.v.Elem().Set(reflect.ValueOf(v))
186
+		return
187
+	}
188
+	// an enum
189
+	// Allocate a []enum, then assign []int32's values into it.
190
+	// Note: we can't convert []enum to []int32.
191
+	slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v))
192
+	for i, x := range v {
193
+		slice.Index(i).SetInt(int64(x))
194
+	}
195
+	p.v.Elem().Set(slice)
196
+}
197
+func (p pointer) appendInt32Slice(v int32) {
198
+	grow(p.v.Elem()).SetInt(int64(v))
199
+}
200
+
201
+func (p pointer) toUint64() *uint64 {
202
+	return p.v.Interface().(*uint64)
203
+}
204
+func (p pointer) toUint64Ptr() **uint64 {
205
+	return p.v.Interface().(**uint64)
206
+}
207
+func (p pointer) toUint64Slice() *[]uint64 {
208
+	return p.v.Interface().(*[]uint64)
209
+}
210
+func (p pointer) toUint32() *uint32 {
211
+	return p.v.Interface().(*uint32)
212
+}
213
+func (p pointer) toUint32Ptr() **uint32 {
214
+	return p.v.Interface().(**uint32)
215
+}
216
+func (p pointer) toUint32Slice() *[]uint32 {
217
+	return p.v.Interface().(*[]uint32)
218
+}
219
+func (p pointer) toBool() *bool {
220
+	return p.v.Interface().(*bool)
221
+}
222
+func (p pointer) toBoolPtr() **bool {
223
+	return p.v.Interface().(**bool)
224
+}
225
+func (p pointer) toBoolSlice() *[]bool {
226
+	return p.v.Interface().(*[]bool)
227
+}
228
+func (p pointer) toFloat64() *float64 {
229
+	return p.v.Interface().(*float64)
230
+}
231
+func (p pointer) toFloat64Ptr() **float64 {
232
+	return p.v.Interface().(**float64)
233
+}
234
+func (p pointer) toFloat64Slice() *[]float64 {
235
+	return p.v.Interface().(*[]float64)
236
+}
237
+func (p pointer) toFloat32() *float32 {
238
+	return p.v.Interface().(*float32)
239
+}
240
+func (p pointer) toFloat32Ptr() **float32 {
241
+	return p.v.Interface().(**float32)
242
+}
243
+func (p pointer) toFloat32Slice() *[]float32 {
244
+	return p.v.Interface().(*[]float32)
245
+}
246
+func (p pointer) toString() *string {
247
+	return p.v.Interface().(*string)
248
+}
249
+func (p pointer) toStringPtr() **string {
250
+	return p.v.Interface().(**string)
251
+}
252
+func (p pointer) toStringSlice() *[]string {
253
+	return p.v.Interface().(*[]string)
254
+}
255
+func (p pointer) toBytes() *[]byte {
256
+	return p.v.Interface().(*[]byte)
257
+}
258
+func (p pointer) toBytesSlice() *[][]byte {
259
+	return p.v.Interface().(*[][]byte)
260
+}
261
+func (p pointer) toExtensions() *XXX_InternalExtensions {
262
+	return p.v.Interface().(*XXX_InternalExtensions)
263
+}
264
+func (p pointer) toOldExtensions() *map[int32]Extension {
265
+	return p.v.Interface().(*map[int32]Extension)
266
+}
267
+func (p pointer) getPointer() pointer {
268
+	return pointer{v: p.v.Elem()}
269
+}
270
+func (p pointer) setPointer(q pointer) {
271
+	p.v.Elem().Set(q.v)
272
+}
273
+func (p pointer) appendPointer(q pointer) {
274
+	grow(p.v.Elem()).Set(q.v)
275
+}
276
+
277
+// getPointerSlice copies []*T from p as a new []pointer.
278
+// This behavior differs from the implementation in pointer_unsafe.go.
279
+func (p pointer) getPointerSlice() []pointer {
280
+	if p.v.IsNil() {
281
+		return nil
282
+	}
283
+	n := p.v.Elem().Len()
284
+	s := make([]pointer, n)
285
+	for i := 0; i < n; i++ {
286
+		s[i] = pointer{v: p.v.Elem().Index(i)}
287
+	}
288
+	return s
289
+}
290
+
291
+// setPointerSlice copies []pointer into p as a new []*T.
292
+// This behavior differs from the implementation in pointer_unsafe.go.
293
+func (p pointer) setPointerSlice(v []pointer) {
294
+	if v == nil {
295
+		p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem())
296
+		return
297
+	}
298
+	s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v))
299
+	for _, p := range v {
300
+		s = reflect.Append(s, p.v)
301
+	}
302
+	p.v.Elem().Set(s)
303
+}
304
+
305
+// getInterfacePointer returns a pointer that points to the
306
+// interface data of the interface pointed by p.
307
+func (p pointer) getInterfacePointer() pointer {
308
+	if p.v.Elem().IsNil() {
309
+		return pointer{v: p.v.Elem()}
310
+	}
311
+	return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct
312
+}
313
+
314
+func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
315
+	// TODO: check that p.v.Type().Elem() == t?
316
+	return p.v
317
+}
318
+
319
+func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
320
+	atomicLock.Lock()
321
+	defer atomicLock.Unlock()
322
+	return *p
323
+}
324
+func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
325
+	atomicLock.Lock()
326
+	defer atomicLock.Unlock()
327
+	*p = v
328
+}
329
+func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
330
+	atomicLock.Lock()
331
+	defer atomicLock.Unlock()
332
+	return *p
333
+}
334
+func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
335
+	atomicLock.Lock()
336
+	defer atomicLock.Unlock()
337
+	*p = v
338
+}
339
+func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
340
+	atomicLock.Lock()
341
+	defer atomicLock.Unlock()
342
+	return *p
343
+}
344
+func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
345
+	atomicLock.Lock()
346
+	defer atomicLock.Unlock()
347
+	*p = v
348
+}
349
+func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
350
+	atomicLock.Lock()
351
+	defer atomicLock.Unlock()
352
+	return *p
353
+}
354
+func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
355
+	atomicLock.Lock()
356
+	defer atomicLock.Unlock()
357
+	*p = v
358
+}
359
+
360
+var atomicLock sync.Mutex

+ 313
- 0
log/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go View File

@@ -0,0 +1,313 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2012 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+// +build !purego,!appengine,!js
33
+
34
+// This file contains the implementation of the proto field accesses using package unsafe.
35
+
36
+package proto
37
+
38
+import (
39
+	"reflect"
40
+	"sync/atomic"
41
+	"unsafe"
42
+)
43
+
44
+const unsafeAllowed = true
45
+
46
+// A field identifies a field in a struct, accessible from a pointer.
47
+// In this implementation, a field is identified by its byte offset from the start of the struct.
48
+type field uintptr
49
+
50
+// toField returns a field equivalent to the given reflect field.
51
+func toField(f *reflect.StructField) field {
52
+	return field(f.Offset)
53
+}
54
+
55
+// invalidField is an invalid field identifier.
56
+const invalidField = ^field(0)
57
+
58
+// zeroField is a noop when calling pointer.offset.
59
+const zeroField = field(0)
60
+
61
+// IsValid reports whether the field identifier is valid.
62
+func (f field) IsValid() bool {
63
+	return f != invalidField
64
+}
65
+
66
+// The pointer type below is for the new table-driven encoder/decoder.
67
+// The implementation here uses unsafe.Pointer to create a generic pointer.
68
+// In pointer_reflect.go we use reflect instead of unsafe to implement
69
+// the same (but slower) interface.
70
+type pointer struct {
71
+	p unsafe.Pointer
72
+}
73
+
74
+// size of pointer
75
+var ptrSize = unsafe.Sizeof(uintptr(0))
76
+
77
+// toPointer converts an interface of pointer type to a pointer
78
+// that points to the same target.
79
+func toPointer(i *Message) pointer {
80
+	// Super-tricky - read pointer out of data word of interface value.
81
+	// Saves ~25ns over the equivalent:
82
+	// return valToPointer(reflect.ValueOf(*i))
83
+	return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
84
+}
85
+
86
+// toAddrPointer converts an interface to a pointer that points to
87
+// the interface data.
88
+func toAddrPointer(i *interface{}, isptr, deref bool) (p pointer) {
89
+	// Super-tricky - read or get the address of data word of interface value.
90
+	if isptr {
91
+		// The interface is of pointer type, thus it is a direct interface.
92
+		// The data word is the pointer data itself. We take its address.
93
+		p = pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)}
94
+	} else {
95
+		// The interface is not of pointer type. The data word is the pointer
96
+		// to the data.
97
+		p = pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
98
+	}
99
+	if deref {
100
+		p.p = *(*unsafe.Pointer)(p.p)
101
+	}
102
+	return p
103
+}
104
+
105
+// valToPointer converts v to a pointer. v must be of pointer type.
106
+func valToPointer(v reflect.Value) pointer {
107
+	return pointer{p: unsafe.Pointer(v.Pointer())}
108
+}
109
+
110
+// offset converts from a pointer to a structure to a pointer to
111
+// one of its fields.
112
+func (p pointer) offset(f field) pointer {
113
+	// For safety, we should panic if !f.IsValid, however calling panic causes
114
+	// this to no longer be inlineable, which is a serious performance cost.
115
+	/*
116
+		if !f.IsValid() {
117
+			panic("invalid field")
118
+		}
119
+	*/
120
+	return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))}
121
+}
122
+
123
+func (p pointer) isNil() bool {
124
+	return p.p == nil
125
+}
126
+
127
+func (p pointer) toInt64() *int64 {
128
+	return (*int64)(p.p)
129
+}
130
+func (p pointer) toInt64Ptr() **int64 {
131
+	return (**int64)(p.p)
132
+}
133
+func (p pointer) toInt64Slice() *[]int64 {
134
+	return (*[]int64)(p.p)
135
+}
136
+func (p pointer) toInt32() *int32 {
137
+	return (*int32)(p.p)
138
+}
139
+
140
+// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist.
141
+/*
142
+	func (p pointer) toInt32Ptr() **int32 {
143
+		return (**int32)(p.p)
144
+	}
145
+	func (p pointer) toInt32Slice() *[]int32 {
146
+		return (*[]int32)(p.p)
147
+	}
148
+*/
149
+func (p pointer) getInt32Ptr() *int32 {
150
+	return *(**int32)(p.p)
151
+}
152
+func (p pointer) setInt32Ptr(v int32) {
153
+	*(**int32)(p.p) = &v
154
+}
155
+
156
+// getInt32Slice loads a []int32 from p.
157
+// The value returned is aliased with the original slice.
158
+// This behavior differs from the implementation in pointer_reflect.go.
159
+func (p pointer) getInt32Slice() []int32 {
160
+	return *(*[]int32)(p.p)
161
+}
162
+
163
+// setInt32Slice stores a []int32 to p.
164
+// The value set is aliased with the input slice.
165
+// This behavior differs from the implementation in pointer_reflect.go.
166
+func (p pointer) setInt32Slice(v []int32) {
167
+	*(*[]int32)(p.p) = v
168
+}
169
+
170
+// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead?
171
+func (p pointer) appendInt32Slice(v int32) {
172
+	s := (*[]int32)(p.p)
173
+	*s = append(*s, v)
174
+}
175
+
176
+func (p pointer) toUint64() *uint64 {
177
+	return (*uint64)(p.p)
178
+}
179
+func (p pointer) toUint64Ptr() **uint64 {
180
+	return (**uint64)(p.p)
181
+}
182
+func (p pointer) toUint64Slice() *[]uint64 {
183
+	return (*[]uint64)(p.p)
184
+}
185
+func (p pointer) toUint32() *uint32 {
186
+	return (*uint32)(p.p)
187
+}
188
+func (p pointer) toUint32Ptr() **uint32 {
189
+	return (**uint32)(p.p)
190
+}
191
+func (p pointer) toUint32Slice() *[]uint32 {
192
+	return (*[]uint32)(p.p)
193
+}
194
+func (p pointer) toBool() *bool {
195
+	return (*bool)(p.p)
196
+}
197
+func (p pointer) toBoolPtr() **bool {
198
+	return (**bool)(p.p)
199
+}
200
+func (p pointer) toBoolSlice() *[]bool {
201
+	return (*[]bool)(p.p)
202
+}
203
+func (p pointer) toFloat64() *float64 {
204
+	return (*float64)(p.p)
205
+}
206
+func (p pointer) toFloat64Ptr() **float64 {
207
+	return (**float64)(p.p)
208
+}
209
+func (p pointer) toFloat64Slice() *[]float64 {
210
+	return (*[]float64)(p.p)
211
+}
212
+func (p pointer) toFloat32() *float32 {
213
+	return (*float32)(p.p)
214
+}
215
+func (p pointer) toFloat32Ptr() **float32 {
216
+	return (**float32)(p.p)
217
+}
218
+func (p pointer) toFloat32Slice() *[]float32 {
219
+	return (*[]float32)(p.p)
220
+}
221
+func (p pointer) toString() *string {
222
+	return (*string)(p.p)
223
+}
224
+func (p pointer) toStringPtr() **string {
225
+	return (**string)(p.p)
226
+}
227
+func (p pointer) toStringSlice() *[]string {
228
+	return (*[]string)(p.p)
229
+}
230
+func (p pointer) toBytes() *[]byte {
231
+	return (*[]byte)(p.p)
232
+}
233
+func (p pointer) toBytesSlice() *[][]byte {
234
+	return (*[][]byte)(p.p)
235
+}
236
+func (p pointer) toExtensions() *XXX_InternalExtensions {
237
+	return (*XXX_InternalExtensions)(p.p)
238
+}
239
+func (p pointer) toOldExtensions() *map[int32]Extension {
240
+	return (*map[int32]Extension)(p.p)
241
+}
242
+
243
+// getPointerSlice loads []*T from p as a []pointer.
244
+// The value returned is aliased with the original slice.
245
+// This behavior differs from the implementation in pointer_reflect.go.
246
+func (p pointer) getPointerSlice() []pointer {
247
+	// Super-tricky - p should point to a []*T where T is a
248
+	// message type. We load it as []pointer.
249
+	return *(*[]pointer)(p.p)
250
+}
251
+
252
+// setPointerSlice stores []pointer into p as a []*T.
253
+// The value set is aliased with the input slice.
254
+// This behavior differs from the implementation in pointer_reflect.go.
255
+func (p pointer) setPointerSlice(v []pointer) {
256
+	// Super-tricky - p should point to a []*T where T is a
257
+	// message type. We store it as []pointer.
258
+	*(*[]pointer)(p.p) = v
259
+}
260
+
261
+// getPointer loads the pointer at p and returns it.
262
+func (p pointer) getPointer() pointer {
263
+	return pointer{p: *(*unsafe.Pointer)(p.p)}
264
+}
265
+
266
+// setPointer stores the pointer q at p.
267
+func (p pointer) setPointer(q pointer) {
268
+	*(*unsafe.Pointer)(p.p) = q.p
269
+}
270
+
271
+// append q to the slice pointed to by p.
272
+func (p pointer) appendPointer(q pointer) {
273
+	s := (*[]unsafe.Pointer)(p.p)
274
+	*s = append(*s, q.p)
275
+}
276
+
277
+// getInterfacePointer returns a pointer that points to the
278
+// interface data of the interface pointed by p.
279
+func (p pointer) getInterfacePointer() pointer {
280
+	// Super-tricky - read pointer out of data word of interface value.
281
+	return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]}
282
+}
283
+
284
+// asPointerTo returns a reflect.Value that is a pointer to an
285
+// object of type t stored at p.
286
+func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
287
+	return reflect.NewAt(t, p.p)
288
+}
289
+
290
+func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
291
+	return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
292
+}
293
+func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
294
+	atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
295
+}
296
+func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
297
+	return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
298
+}
299
+func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
300
+	atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
301
+}
302
+func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
303
+	return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
304
+}
305
+func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
306
+	atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
307
+}
308
+func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
309
+	return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
310
+}
311
+func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
312
+	atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
313
+}

+ 545
- 0
log/vendor/github.com/golang/protobuf/proto/properties.go View File

@@ -0,0 +1,545 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+/*
35
+ * Routines for encoding data into the wire format for protocol buffers.
36
+ */
37
+
38
+import (
39
+	"fmt"
40
+	"log"
41
+	"os"
42
+	"reflect"
43
+	"sort"
44
+	"strconv"
45
+	"strings"
46
+	"sync"
47
+)
48
+
49
+const debug bool = false
50
+
51
+// Constants that identify the encoding of a value on the wire.
52
+const (
53
+	WireVarint     = 0
54
+	WireFixed64    = 1
55
+	WireBytes      = 2
56
+	WireStartGroup = 3
57
+	WireEndGroup   = 4
58
+	WireFixed32    = 5
59
+)
60
+
61
+// tagMap is an optimization over map[int]int for typical protocol buffer
62
+// use-cases. Encoded protocol buffers are often in tag order with small tag
63
+// numbers.
64
+type tagMap struct {
65
+	fastTags []int
66
+	slowTags map[int]int
67
+}
68
+
69
+// tagMapFastLimit is the upper bound on the tag number that will be stored in
70
+// the tagMap slice rather than its map.
71
+const tagMapFastLimit = 1024
72
+
73
+func (p *tagMap) get(t int) (int, bool) {
74
+	if t > 0 && t < tagMapFastLimit {
75
+		if t >= len(p.fastTags) {
76
+			return 0, false
77
+		}
78
+		fi := p.fastTags[t]
79
+		return fi, fi >= 0
80
+	}
81
+	fi, ok := p.slowTags[t]
82
+	return fi, ok
83
+}
84
+
85
+func (p *tagMap) put(t int, fi int) {
86
+	if t > 0 && t < tagMapFastLimit {
87
+		for len(p.fastTags) < t+1 {
88
+			p.fastTags = append(p.fastTags, -1)
89
+		}
90
+		p.fastTags[t] = fi
91
+		return
92
+	}
93
+	if p.slowTags == nil {
94
+		p.slowTags = make(map[int]int)
95
+	}
96
+	p.slowTags[t] = fi
97
+}
98
+
99
+// StructProperties represents properties for all the fields of a struct.
100
+// decoderTags and decoderOrigNames should only be used by the decoder.
101
+type StructProperties struct {
102
+	Prop             []*Properties  // properties for each field
103
+	reqCount         int            // required count
104
+	decoderTags      tagMap         // map from proto tag to struct field number
105
+	decoderOrigNames map[string]int // map from original name to struct field number
106
+	order            []int          // list of struct field numbers in tag order
107
+
108
+	// OneofTypes contains information about the oneof fields in this message.
109
+	// It is keyed by the original name of a field.
110
+	OneofTypes map[string]*OneofProperties
111
+}
112
+
113
+// OneofProperties represents information about a specific field in a oneof.
114
+type OneofProperties struct {
115
+	Type  reflect.Type // pointer to generated struct type for this oneof field
116
+	Field int          // struct field number of the containing oneof in the message
117
+	Prop  *Properties
118
+}
119
+
120
+// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
121
+// See encode.go, (*Buffer).enc_struct.
122
+
123
+func (sp *StructProperties) Len() int { return len(sp.order) }
124
+func (sp *StructProperties) Less(i, j int) bool {
125
+	return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
126
+}
127
+func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
128
+
129
+// Properties represents the protocol-specific behavior of a single struct field.
130
+type Properties struct {
131
+	Name     string // name of the field, for error messages
132
+	OrigName string // original name before protocol compiler (always set)
133
+	JSONName string // name to use for JSON; determined by protoc
134
+	Wire     string
135
+	WireType int
136
+	Tag      int
137
+	Required bool
138
+	Optional bool
139
+	Repeated bool
140
+	Packed   bool   // relevant for repeated primitives only
141
+	Enum     string // set for enum types only
142
+	proto3   bool   // whether this is known to be a proto3 field
143
+	oneof    bool   // whether this is a oneof field
144
+
145
+	Default    string // default value
146
+	HasDefault bool   // whether an explicit default was provided
147
+
148
+	stype reflect.Type      // set for struct types only
149
+	sprop *StructProperties // set for struct types only
150
+
151
+	mtype      reflect.Type // set for map types only
152
+	MapKeyProp *Properties  // set for map types only
153
+	MapValProp *Properties  // set for map types only
154
+}
155
+
156
+// String formats the properties in the protobuf struct field tag style.
157
+func (p *Properties) String() string {
158
+	s := p.Wire
159
+	s += ","
160
+	s += strconv.Itoa(p.Tag)
161
+	if p.Required {
162
+		s += ",req"
163
+	}
164
+	if p.Optional {
165
+		s += ",opt"
166
+	}
167
+	if p.Repeated {
168
+		s += ",rep"
169
+	}
170
+	if p.Packed {
171
+		s += ",packed"
172
+	}
173
+	s += ",name=" + p.OrigName
174
+	if p.JSONName != p.OrigName {
175
+		s += ",json=" + p.JSONName
176
+	}
177
+	if p.proto3 {
178
+		s += ",proto3"
179
+	}
180
+	if p.oneof {
181
+		s += ",oneof"
182
+	}
183
+	if len(p.Enum) > 0 {
184
+		s += ",enum=" + p.Enum
185
+	}
186
+	if p.HasDefault {
187
+		s += ",def=" + p.Default
188
+	}
189
+	return s
190
+}
191
+
192
+// Parse populates p by parsing a string in the protobuf struct field tag style.
193
+func (p *Properties) Parse(s string) {
194
+	// "bytes,49,opt,name=foo,def=hello!"
195
+	fields := strings.Split(s, ",") // breaks def=, but handled below.
196
+	if len(fields) < 2 {
197
+		fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
198
+		return
199
+	}
200
+
201
+	p.Wire = fields[0]
202
+	switch p.Wire {
203
+	case "varint":
204
+		p.WireType = WireVarint
205
+	case "fixed32":
206
+		p.WireType = WireFixed32
207
+	case "fixed64":
208
+		p.WireType = WireFixed64
209
+	case "zigzag32":
210
+		p.WireType = WireVarint
211
+	case "zigzag64":
212
+		p.WireType = WireVarint
213
+	case "bytes", "group":
214
+		p.WireType = WireBytes
215
+		// no numeric converter for non-numeric types
216
+	default:
217
+		fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
218
+		return
219
+	}
220
+
221
+	var err error
222
+	p.Tag, err = strconv.Atoi(fields[1])
223
+	if err != nil {
224
+		return
225
+	}
226
+
227
+outer:
228
+	for i := 2; i < len(fields); i++ {
229
+		f := fields[i]
230
+		switch {
231
+		case f == "req":
232
+			p.Required = true
233
+		case f == "opt":
234
+			p.Optional = true
235
+		case f == "rep":
236
+			p.Repeated = true
237
+		case f == "packed":
238
+			p.Packed = true
239
+		case strings.HasPrefix(f, "name="):
240
+			p.OrigName = f[5:]
241
+		case strings.HasPrefix(f, "json="):
242
+			p.JSONName = f[5:]
243
+		case strings.HasPrefix(f, "enum="):
244
+			p.Enum = f[5:]
245
+		case f == "proto3":
246
+			p.proto3 = true
247
+		case f == "oneof":
248
+			p.oneof = true
249
+		case strings.HasPrefix(f, "def="):
250
+			p.HasDefault = true
251
+			p.Default = f[4:] // rest of string
252
+			if i+1 < len(fields) {
253
+				// Commas aren't escaped, and def is always last.
254
+				p.Default += "," + strings.Join(fields[i+1:], ",")
255
+				break outer
256
+			}
257
+		}
258
+	}
259
+}
260
+
261
+var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
262
+
263
+// setFieldProps initializes the field properties for submessages and maps.
264
+func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
265
+	switch t1 := typ; t1.Kind() {
266
+	case reflect.Ptr:
267
+		if t1.Elem().Kind() == reflect.Struct {
268
+			p.stype = t1.Elem()
269
+		}
270
+
271
+	case reflect.Slice:
272
+		if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct {
273
+			p.stype = t2.Elem()
274
+		}
275
+
276
+	case reflect.Map:
277
+		p.mtype = t1
278
+		p.MapKeyProp = &Properties{}
279
+		p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
280
+		p.MapValProp = &Properties{}
281
+		vtype := p.mtype.Elem()
282
+		if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
283
+			// The value type is not a message (*T) or bytes ([]byte),
284
+			// so we need encoders for the pointer to this type.
285
+			vtype = reflect.PtrTo(vtype)
286
+		}
287
+		p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
288
+	}
289
+
290
+	if p.stype != nil {
291
+		if lockGetProp {
292
+			p.sprop = GetProperties(p.stype)
293
+		} else {
294
+			p.sprop = getPropertiesLocked(p.stype)
295
+		}
296
+	}
297
+}
298
+
299
+var (
300
+	marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
301
+)
302
+
303
+// Init populates the properties from a protocol buffer struct tag.
304
+func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
305
+	p.init(typ, name, tag, f, true)
306
+}
307
+
308
+func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
309
+	// "bytes,49,opt,def=hello!"
310
+	p.Name = name
311
+	p.OrigName = name
312
+	if tag == "" {
313
+		return
314
+	}
315
+	p.Parse(tag)
316
+	p.setFieldProps(typ, f, lockGetProp)
317
+}
318
+
319
+var (
320
+	propertiesMu  sync.RWMutex
321
+	propertiesMap = make(map[reflect.Type]*StructProperties)
322
+)
323
+
324
+// GetProperties returns the list of properties for the type represented by t.
325
+// t must represent a generated struct type of a protocol message.
326
+func GetProperties(t reflect.Type) *StructProperties {
327
+	if t.Kind() != reflect.Struct {
328
+		panic("proto: type must have kind struct")
329
+	}
330
+
331
+	// Most calls to GetProperties in a long-running program will be
332
+	// retrieving details for types we have seen before.
333
+	propertiesMu.RLock()
334
+	sprop, ok := propertiesMap[t]
335
+	propertiesMu.RUnlock()
336
+	if ok {
337
+		return sprop
338
+	}
339
+
340
+	propertiesMu.Lock()
341
+	sprop = getPropertiesLocked(t)
342
+	propertiesMu.Unlock()
343
+	return sprop
344
+}
345
+
346
+type (
347
+	oneofFuncsIface interface {
348
+		XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
349
+	}
350
+	oneofWrappersIface interface {
351
+		XXX_OneofWrappers() []interface{}
352
+	}
353
+)
354
+
355
+// getPropertiesLocked requires that propertiesMu is held.
356
+func getPropertiesLocked(t reflect.Type) *StructProperties {
357
+	if prop, ok := propertiesMap[t]; ok {
358
+		return prop
359
+	}
360
+
361
+	prop := new(StructProperties)
362
+	// in case of recursive protos, fill this in now.
363
+	propertiesMap[t] = prop
364
+
365
+	// build properties
366
+	prop.Prop = make([]*Properties, t.NumField())
367
+	prop.order = make([]int, t.NumField())
368
+
369
+	for i := 0; i < t.NumField(); i++ {
370
+		f := t.Field(i)
371
+		p := new(Properties)
372
+		name := f.Name
373
+		p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
374
+
375
+		oneof := f.Tag.Get("protobuf_oneof") // special case
376
+		if oneof != "" {
377
+			// Oneof fields don't use the traditional protobuf tag.
378
+			p.OrigName = oneof
379
+		}
380
+		prop.Prop[i] = p
381
+		prop.order[i] = i
382
+		if debug {
383
+			print(i, " ", f.Name, " ", t.String(), " ")
384
+			if p.Tag > 0 {
385
+				print(p.String())
386
+			}
387
+			print("\n")
388
+		}
389
+	}
390
+
391
+	// Re-order prop.order.
392
+	sort.Sort(prop)
393
+
394
+	var oots []interface{}
395
+	switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
396
+	case oneofFuncsIface:
397
+		_, _, _, oots = m.XXX_OneofFuncs()
398
+	case oneofWrappersIface:
399
+		oots = m.XXX_OneofWrappers()
400
+	}
401
+	if len(oots) > 0 {
402
+		// Interpret oneof metadata.
403
+		prop.OneofTypes = make(map[string]*OneofProperties)
404
+		for _, oot := range oots {
405
+			oop := &OneofProperties{
406
+				Type: reflect.ValueOf(oot).Type(), // *T
407
+				Prop: new(Properties),
408
+			}
409
+			sft := oop.Type.Elem().Field(0)
410
+			oop.Prop.Name = sft.Name
411
+			oop.Prop.Parse(sft.Tag.Get("protobuf"))
412
+			// There will be exactly one interface field that
413
+			// this new value is assignable to.
414
+			for i := 0; i < t.NumField(); i++ {
415
+				f := t.Field(i)
416
+				if f.Type.Kind() != reflect.Interface {
417
+					continue
418
+				}
419
+				if !oop.Type.AssignableTo(f.Type) {
420
+					continue
421
+				}
422
+				oop.Field = i
423
+				break
424
+			}
425
+			prop.OneofTypes[oop.Prop.OrigName] = oop
426
+		}
427
+	}
428
+
429
+	// build required counts
430
+	// build tags
431
+	reqCount := 0
432
+	prop.decoderOrigNames = make(map[string]int)
433
+	for i, p := range prop.Prop {
434
+		if strings.HasPrefix(p.Name, "XXX_") {
435
+			// Internal fields should not appear in tags/origNames maps.
436
+			// They are handled specially when encoding and decoding.
437
+			continue
438
+		}
439
+		if p.Required {
440
+			reqCount++
441
+		}
442
+		prop.decoderTags.put(p.Tag, i)
443
+		prop.decoderOrigNames[p.OrigName] = i
444
+	}
445
+	prop.reqCount = reqCount
446
+
447
+	return prop
448
+}
449
+
450
+// A global registry of enum types.
451
+// The generated code will register the generated maps by calling RegisterEnum.
452
+
453
+var enumValueMaps = make(map[string]map[string]int32)
454
+
455
+// RegisterEnum is called from the generated code to install the enum descriptor
456
+// maps into the global table to aid parsing text format protocol buffers.
457
+func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
458
+	if _, ok := enumValueMaps[typeName]; ok {
459
+		panic("proto: duplicate enum registered: " + typeName)
460
+	}
461
+	enumValueMaps[typeName] = valueMap
462
+}
463
+
464
+// EnumValueMap returns the mapping from names to integers of the
465
+// enum type enumType, or a nil if not found.
466
+func EnumValueMap(enumType string) map[string]int32 {
467
+	return enumValueMaps[enumType]
468
+}
469
+
470
+// A registry of all linked message types.
471
+// The string is a fully-qualified proto name ("pkg.Message").
472
+var (
473
+	protoTypedNils = make(map[string]Message)      // a map from proto names to typed nil pointers
474
+	protoMapTypes  = make(map[string]reflect.Type) // a map from proto names to map types
475
+	revProtoTypes  = make(map[reflect.Type]string)
476
+)
477
+
478
+// RegisterType is called from generated code and maps from the fully qualified
479
+// proto name to the type (pointer to struct) of the protocol buffer.
480
+func RegisterType(x Message, name string) {
481
+	if _, ok := protoTypedNils[name]; ok {
482
+		// TODO: Some day, make this a panic.
483
+		log.Printf("proto: duplicate proto type registered: %s", name)
484
+		return
485
+	}
486
+	t := reflect.TypeOf(x)
487
+	if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 {
488
+		// Generated code always calls RegisterType with nil x.
489
+		// This check is just for extra safety.
490
+		protoTypedNils[name] = x
491
+	} else {
492
+		protoTypedNils[name] = reflect.Zero(t).Interface().(Message)
493
+	}
494
+	revProtoTypes[t] = name
495
+}
496
+
497
+// RegisterMapType is called from generated code and maps from the fully qualified
498
+// proto name to the native map type of the proto map definition.
499
+func RegisterMapType(x interface{}, name string) {
500
+	if reflect.TypeOf(x).Kind() != reflect.Map {
501
+		panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name))
502
+	}
503
+	if _, ok := protoMapTypes[name]; ok {
504
+		log.Printf("proto: duplicate proto type registered: %s", name)
505
+		return
506
+	}
507
+	t := reflect.TypeOf(x)
508
+	protoMapTypes[name] = t
509
+	revProtoTypes[t] = name
510
+}
511
+
512
+// MessageName returns the fully-qualified proto name for the given message type.
513
+func MessageName(x Message) string {
514
+	type xname interface {
515
+		XXX_MessageName() string
516
+	}
517
+	if m, ok := x.(xname); ok {
518
+		return m.XXX_MessageName()
519
+	}
520
+	return revProtoTypes[reflect.TypeOf(x)]
521
+}
522
+
523
+// MessageType returns the message type (pointer to struct) for a named message.
524
+// The type is not guaranteed to implement proto.Message if the name refers to a
525
+// map entry.
526
+func MessageType(name string) reflect.Type {
527
+	if t, ok := protoTypedNils[name]; ok {
528
+		return reflect.TypeOf(t)
529
+	}
530
+	return protoMapTypes[name]
531
+}
532
+
533
+// A registry of all linked proto files.
534
+var (
535
+	protoFiles = make(map[string][]byte) // file name => fileDescriptor
536
+)
537
+
538
+// RegisterFile is called from generated code and maps from the
539
+// full file name of a .proto file to its compressed FileDescriptorProto.
540
+func RegisterFile(filename string, fileDescriptor []byte) {
541
+	protoFiles[filename] = fileDescriptor
542
+}
543
+
544
+// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
545
+func FileDescriptor(filename string) []byte { return protoFiles[filename] }

+ 2776
- 0
log/vendor/github.com/golang/protobuf/proto/table_marshal.go
File diff suppressed because it is too large
View File


+ 654
- 0
log/vendor/github.com/golang/protobuf/proto/table_merge.go View File

@@ -0,0 +1,654 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2016 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+import (
35
+	"fmt"
36
+	"reflect"
37
+	"strings"
38
+	"sync"
39
+	"sync/atomic"
40
+)
41
+
42
+// Merge merges the src message into dst.
43
+// This assumes that dst and src of the same type and are non-nil.
44
+func (a *InternalMessageInfo) Merge(dst, src Message) {
45
+	mi := atomicLoadMergeInfo(&a.merge)
46
+	if mi == nil {
47
+		mi = getMergeInfo(reflect.TypeOf(dst).Elem())
48
+		atomicStoreMergeInfo(&a.merge, mi)
49
+	}
50
+	mi.merge(toPointer(&dst), toPointer(&src))
51
+}
52
+
53
+type mergeInfo struct {
54
+	typ reflect.Type
55
+
56
+	initialized int32 // 0: only typ is valid, 1: everything is valid
57
+	lock        sync.Mutex
58
+
59
+	fields       []mergeFieldInfo
60
+	unrecognized field // Offset of XXX_unrecognized
61
+}
62
+
63
+type mergeFieldInfo struct {
64
+	field field // Offset of field, guaranteed to be valid
65
+
66
+	// isPointer reports whether the value in the field is a pointer.
67
+	// This is true for the following situations:
68
+	//	* Pointer to struct
69
+	//	* Pointer to basic type (proto2 only)
70
+	//	* Slice (first value in slice header is a pointer)
71
+	//	* String (first value in string header is a pointer)
72
+	isPointer bool
73
+
74
+	// basicWidth reports the width of the field assuming that it is directly
75
+	// embedded in the struct (as is the case for basic types in proto3).
76
+	// The possible values are:
77
+	// 	0: invalid
78
+	//	1: bool
79
+	//	4: int32, uint32, float32
80
+	//	8: int64, uint64, float64
81
+	basicWidth int
82
+
83
+	// Where dst and src are pointers to the types being merged.
84
+	merge func(dst, src pointer)
85
+}
86
+
87
+var (
88
+	mergeInfoMap  = map[reflect.Type]*mergeInfo{}
89
+	mergeInfoLock sync.Mutex
90
+)
91
+
92
+func getMergeInfo(t reflect.Type) *mergeInfo {
93
+	mergeInfoLock.Lock()
94
+	defer mergeInfoLock.Unlock()
95
+	mi := mergeInfoMap[t]
96
+	if mi == nil {
97
+		mi = &mergeInfo{typ: t}
98
+		mergeInfoMap[t] = mi
99
+	}
100
+	return mi
101
+}
102
+
103
+// merge merges src into dst assuming they are both of type *mi.typ.
104
+func (mi *mergeInfo) merge(dst, src pointer) {
105
+	if dst.isNil() {
106
+		panic("proto: nil destination")
107
+	}
108
+	if src.isNil() {
109
+		return // Nothing to do.
110
+	}
111
+
112
+	if atomic.LoadInt32(&mi.initialized) == 0 {
113
+		mi.computeMergeInfo()
114
+	}
115
+
116
+	for _, fi := range mi.fields {
117
+		sfp := src.offset(fi.field)
118
+
119
+		// As an optimization, we can avoid the merge function call cost
120
+		// if we know for sure that the source will have no effect
121
+		// by checking if it is the zero value.
122
+		if unsafeAllowed {
123
+			if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string
124
+				continue
125
+			}
126
+			if fi.basicWidth > 0 {
127
+				switch {
128
+				case fi.basicWidth == 1 && !*sfp.toBool():
129
+					continue
130
+				case fi.basicWidth == 4 && *sfp.toUint32() == 0:
131
+					continue
132
+				case fi.basicWidth == 8 && *sfp.toUint64() == 0:
133
+					continue
134
+				}
135
+			}
136
+		}
137
+
138
+		dfp := dst.offset(fi.field)
139
+		fi.merge(dfp, sfp)
140
+	}
141
+
142
+	// TODO: Make this faster?
143
+	out := dst.asPointerTo(mi.typ).Elem()
144
+	in := src.asPointerTo(mi.typ).Elem()
145
+	if emIn, err := extendable(in.Addr().Interface()); err == nil {
146
+		emOut, _ := extendable(out.Addr().Interface())
147
+		mIn, muIn := emIn.extensionsRead()
148
+		if mIn != nil {
149
+			mOut := emOut.extensionsWrite()
150
+			muIn.Lock()
151
+			mergeExtension(mOut, mIn)
152
+			muIn.Unlock()
153
+		}
154
+	}
155
+
156
+	if mi.unrecognized.IsValid() {
157
+		if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 {
158
+			*dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...)
159
+		}
160
+	}
161
+}
162
+
163
+func (mi *mergeInfo) computeMergeInfo() {
164
+	mi.lock.Lock()
165
+	defer mi.lock.Unlock()
166
+	if mi.initialized != 0 {
167
+		return
168
+	}
169
+	t := mi.typ
170
+	n := t.NumField()
171
+
172
+	props := GetProperties(t)
173
+	for i := 0; i < n; i++ {
174
+		f := t.Field(i)
175
+		if strings.HasPrefix(f.Name, "XXX_") {
176
+			continue
177
+		}
178
+
179
+		mfi := mergeFieldInfo{field: toField(&f)}
180
+		tf := f.Type
181
+
182
+		// As an optimization, we can avoid the merge function call cost
183
+		// if we know for sure that the source will have no effect
184
+		// by checking if it is the zero value.
185
+		if unsafeAllowed {
186
+			switch tf.Kind() {
187
+			case reflect.Ptr, reflect.Slice, reflect.String:
188
+				// As a special case, we assume slices and strings are pointers
189
+				// since we know that the first field in the SliceSlice or
190
+				// StringHeader is a data pointer.
191
+				mfi.isPointer = true
192
+			case reflect.Bool:
193
+				mfi.basicWidth = 1
194
+			case reflect.Int32, reflect.Uint32, reflect.Float32:
195
+				mfi.basicWidth = 4
196
+			case reflect.Int64, reflect.Uint64, reflect.Float64:
197
+				mfi.basicWidth = 8
198
+			}
199
+		}
200
+
201
+		// Unwrap tf to get at its most basic type.
202
+		var isPointer, isSlice bool
203
+		if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
204
+			isSlice = true
205
+			tf = tf.Elem()
206
+		}
207
+		if tf.Kind() == reflect.Ptr {
208
+			isPointer = true
209
+			tf = tf.Elem()
210
+		}
211
+		if isPointer && isSlice && tf.Kind() != reflect.Struct {
212
+			panic("both pointer and slice for basic type in " + tf.Name())
213
+		}
214
+
215
+		switch tf.Kind() {
216
+		case reflect.Int32:
217
+			switch {
218
+			case isSlice: // E.g., []int32
219
+				mfi.merge = func(dst, src pointer) {
220
+					// NOTE: toInt32Slice is not defined (see pointer_reflect.go).
221
+					/*
222
+						sfsp := src.toInt32Slice()
223
+						if *sfsp != nil {
224
+							dfsp := dst.toInt32Slice()
225
+							*dfsp = append(*dfsp, *sfsp...)
226
+							if *dfsp == nil {
227
+								*dfsp = []int64{}
228
+							}
229
+						}
230
+					*/
231
+					sfs := src.getInt32Slice()
232
+					if sfs != nil {
233
+						dfs := dst.getInt32Slice()
234
+						dfs = append(dfs, sfs...)
235
+						if dfs == nil {
236
+							dfs = []int32{}
237
+						}
238
+						dst.setInt32Slice(dfs)
239
+					}
240
+				}
241
+			case isPointer: // E.g., *int32
242
+				mfi.merge = func(dst, src pointer) {
243
+					// NOTE: toInt32Ptr is not defined (see pointer_reflect.go).
244
+					/*
245
+						sfpp := src.toInt32Ptr()
246
+						if *sfpp != nil {
247
+							dfpp := dst.toInt32Ptr()
248
+							if *dfpp == nil {
249
+								*dfpp = Int32(**sfpp)
250
+							} else {
251
+								**dfpp = **sfpp
252
+							}
253
+						}
254
+					*/
255
+					sfp := src.getInt32Ptr()
256
+					if sfp != nil {
257
+						dfp := dst.getInt32Ptr()
258
+						if dfp == nil {
259
+							dst.setInt32Ptr(*sfp)
260
+						} else {
261
+							*dfp = *sfp
262
+						}
263
+					}
264
+				}
265
+			default: // E.g., int32
266
+				mfi.merge = func(dst, src pointer) {
267
+					if v := *src.toInt32(); v != 0 {
268
+						*dst.toInt32() = v
269
+					}
270
+				}
271
+			}
272
+		case reflect.Int64:
273
+			switch {
274
+			case isSlice: // E.g., []int64
275
+				mfi.merge = func(dst, src pointer) {
276
+					sfsp := src.toInt64Slice()
277
+					if *sfsp != nil {
278
+						dfsp := dst.toInt64Slice()
279
+						*dfsp = append(*dfsp, *sfsp...)
280
+						if *dfsp == nil {
281
+							*dfsp = []int64{}
282
+						}
283
+					}
284
+				}
285
+			case isPointer: // E.g., *int64
286
+				mfi.merge = func(dst, src pointer) {
287
+					sfpp := src.toInt64Ptr()
288
+					if *sfpp != nil {
289
+						dfpp := dst.toInt64Ptr()
290
+						if *dfpp == nil {
291
+							*dfpp = Int64(**sfpp)
292
+						} else {
293
+							**dfpp = **sfpp
294
+						}
295
+					}
296
+				}
297
+			default: // E.g., int64
298
+				mfi.merge = func(dst, src pointer) {
299
+					if v := *src.toInt64(); v != 0 {
300
+						*dst.toInt64() = v
301
+					}
302
+				}
303
+			}
304
+		case reflect.Uint32:
305
+			switch {
306
+			case isSlice: // E.g., []uint32
307
+				mfi.merge = func(dst, src pointer) {
308
+					sfsp := src.toUint32Slice()
309
+					if *sfsp != nil {
310
+						dfsp := dst.toUint32Slice()
311
+						*dfsp = append(*dfsp, *sfsp...)
312
+						if *dfsp == nil {
313
+							*dfsp = []uint32{}
314
+						}
315
+					}
316
+				}
317
+			case isPointer: // E.g., *uint32
318
+				mfi.merge = func(dst, src pointer) {
319
+					sfpp := src.toUint32Ptr()
320
+					if *sfpp != nil {
321
+						dfpp := dst.toUint32Ptr()
322
+						if *dfpp == nil {
323
+							*dfpp = Uint32(**sfpp)
324
+						} else {
325
+							**dfpp = **sfpp
326
+						}
327
+					}
328
+				}
329
+			default: // E.g., uint32
330
+				mfi.merge = func(dst, src pointer) {
331
+					if v := *src.toUint32(); v != 0 {
332
+						*dst.toUint32() = v
333
+					}
334
+				}
335
+			}
336
+		case reflect.Uint64:
337
+			switch {
338
+			case isSlice: // E.g., []uint64
339
+				mfi.merge = func(dst, src pointer) {
340
+					sfsp := src.toUint64Slice()
341
+					if *sfsp != nil {
342
+						dfsp := dst.toUint64Slice()
343
+						*dfsp = append(*dfsp, *sfsp...)
344
+						if *dfsp == nil {
345
+							*dfsp = []uint64{}
346
+						}
347
+					}
348
+				}
349
+			case isPointer: // E.g., *uint64
350
+				mfi.merge = func(dst, src pointer) {
351
+					sfpp := src.toUint64Ptr()
352
+					if *sfpp != nil {
353
+						dfpp := dst.toUint64Ptr()
354
+						if *dfpp == nil {
355
+							*dfpp = Uint64(**sfpp)
356
+						} else {
357
+							**dfpp = **sfpp
358
+						}
359
+					}
360
+				}
361
+			default: // E.g., uint64
362
+				mfi.merge = func(dst, src pointer) {
363
+					if v := *src.toUint64(); v != 0 {
364
+						*dst.toUint64() = v
365
+					}
366
+				}
367
+			}
368
+		case reflect.Float32:
369
+			switch {
370
+			case isSlice: // E.g., []float32
371
+				mfi.merge = func(dst, src pointer) {
372
+					sfsp := src.toFloat32Slice()
373
+					if *sfsp != nil {
374
+						dfsp := dst.toFloat32Slice()
375
+						*dfsp = append(*dfsp, *sfsp...)
376
+						if *dfsp == nil {
377
+							*dfsp = []float32{}
378
+						}
379
+					}
380
+				}
381
+			case isPointer: // E.g., *float32
382
+				mfi.merge = func(dst, src pointer) {
383
+					sfpp := src.toFloat32Ptr()
384
+					if *sfpp != nil {
385
+						dfpp := dst.toFloat32Ptr()
386
+						if *dfpp == nil {
387
+							*dfpp = Float32(**sfpp)
388
+						} else {
389
+							**dfpp = **sfpp
390
+						}
391
+					}
392
+				}
393
+			default: // E.g., float32
394
+				mfi.merge = func(dst, src pointer) {
395
+					if v := *src.toFloat32(); v != 0 {
396
+						*dst.toFloat32() = v
397
+					}
398
+				}
399
+			}
400
+		case reflect.Float64:
401
+			switch {
402
+			case isSlice: // E.g., []float64
403
+				mfi.merge = func(dst, src pointer) {
404
+					sfsp := src.toFloat64Slice()
405
+					if *sfsp != nil {
406
+						dfsp := dst.toFloat64Slice()
407
+						*dfsp = append(*dfsp, *sfsp...)
408
+						if *dfsp == nil {
409
+							*dfsp = []float64{}
410
+						}
411
+					}
412
+				}
413
+			case isPointer: // E.g., *float64
414
+				mfi.merge = func(dst, src pointer) {
415
+					sfpp := src.toFloat64Ptr()
416
+					if *sfpp != nil {
417
+						dfpp := dst.toFloat64Ptr()
418
+						if *dfpp == nil {
419
+							*dfpp = Float64(**sfpp)
420
+						} else {
421
+							**dfpp = **sfpp
422
+						}
423
+					}
424
+				}
425
+			default: // E.g., float64
426
+				mfi.merge = func(dst, src pointer) {
427
+					if v := *src.toFloat64(); v != 0 {
428
+						*dst.toFloat64() = v
429
+					}
430
+				}
431
+			}
432
+		case reflect.Bool:
433
+			switch {
434
+			case isSlice: // E.g., []bool
435
+				mfi.merge = func(dst, src pointer) {
436
+					sfsp := src.toBoolSlice()
437
+					if *sfsp != nil {
438
+						dfsp := dst.toBoolSlice()
439
+						*dfsp = append(*dfsp, *sfsp...)
440
+						if *dfsp == nil {
441
+							*dfsp = []bool{}
442
+						}
443
+					}
444
+				}
445
+			case isPointer: // E.g., *bool
446
+				mfi.merge = func(dst, src pointer) {
447
+					sfpp := src.toBoolPtr()
448
+					if *sfpp != nil {
449
+						dfpp := dst.toBoolPtr()
450
+						if *dfpp == nil {
451
+							*dfpp = Bool(**sfpp)
452
+						} else {
453
+							**dfpp = **sfpp
454
+						}
455
+					}
456
+				}
457
+			default: // E.g., bool
458
+				mfi.merge = func(dst, src pointer) {
459
+					if v := *src.toBool(); v {
460
+						*dst.toBool() = v
461
+					}
462
+				}
463
+			}
464
+		case reflect.String:
465
+			switch {
466
+			case isSlice: // E.g., []string
467
+				mfi.merge = func(dst, src pointer) {
468
+					sfsp := src.toStringSlice()
469
+					if *sfsp != nil {
470
+						dfsp := dst.toStringSlice()
471
+						*dfsp = append(*dfsp, *sfsp...)
472
+						if *dfsp == nil {
473
+							*dfsp = []string{}
474
+						}
475
+					}
476
+				}
477
+			case isPointer: // E.g., *string
478
+				mfi.merge = func(dst, src pointer) {
479
+					sfpp := src.toStringPtr()
480
+					if *sfpp != nil {
481
+						dfpp := dst.toStringPtr()
482
+						if *dfpp == nil {
483
+							*dfpp = String(**sfpp)
484
+						} else {
485
+							**dfpp = **sfpp
486
+						}
487
+					}
488
+				}
489
+			default: // E.g., string
490
+				mfi.merge = func(dst, src pointer) {
491
+					if v := *src.toString(); v != "" {
492
+						*dst.toString() = v
493
+					}
494
+				}
495
+			}
496
+		case reflect.Slice:
497
+			isProto3 := props.Prop[i].proto3
498
+			switch {
499
+			case isPointer:
500
+				panic("bad pointer in byte slice case in " + tf.Name())
501
+			case tf.Elem().Kind() != reflect.Uint8:
502
+				panic("bad element kind in byte slice case in " + tf.Name())
503
+			case isSlice: // E.g., [][]byte
504
+				mfi.merge = func(dst, src pointer) {
505
+					sbsp := src.toBytesSlice()
506
+					if *sbsp != nil {
507
+						dbsp := dst.toBytesSlice()
508
+						for _, sb := range *sbsp {
509
+							if sb == nil {
510
+								*dbsp = append(*dbsp, nil)
511
+							} else {
512
+								*dbsp = append(*dbsp, append([]byte{}, sb...))
513
+							}
514
+						}
515
+						if *dbsp == nil {
516
+							*dbsp = [][]byte{}
517
+						}
518
+					}
519
+				}
520
+			default: // E.g., []byte
521
+				mfi.merge = func(dst, src pointer) {
522
+					sbp := src.toBytes()
523
+					if *sbp != nil {
524
+						dbp := dst.toBytes()
525
+						if !isProto3 || len(*sbp) > 0 {
526
+							*dbp = append([]byte{}, *sbp...)
527
+						}
528
+					}
529
+				}
530
+			}
531
+		case reflect.Struct:
532
+			switch {
533
+			case !isPointer:
534
+				panic(fmt.Sprintf("message field %s without pointer", tf))
535
+			case isSlice: // E.g., []*pb.T
536
+				mi := getMergeInfo(tf)
537
+				mfi.merge = func(dst, src pointer) {
538
+					sps := src.getPointerSlice()
539
+					if sps != nil {
540
+						dps := dst.getPointerSlice()
541
+						for _, sp := range sps {
542
+							var dp pointer
543
+							if !sp.isNil() {
544
+								dp = valToPointer(reflect.New(tf))
545
+								mi.merge(dp, sp)
546
+							}
547
+							dps = append(dps, dp)
548
+						}
549
+						if dps == nil {
550
+							dps = []pointer{}
551
+						}
552
+						dst.setPointerSlice(dps)
553
+					}
554
+				}
555
+			default: // E.g., *pb.T
556
+				mi := getMergeInfo(tf)
557
+				mfi.merge = func(dst, src pointer) {
558
+					sp := src.getPointer()
559
+					if !sp.isNil() {
560
+						dp := dst.getPointer()
561
+						if dp.isNil() {
562
+							dp = valToPointer(reflect.New(tf))
563
+							dst.setPointer(dp)
564
+						}
565
+						mi.merge(dp, sp)
566
+					}
567
+				}
568
+			}
569
+		case reflect.Map:
570
+			switch {
571
+			case isPointer || isSlice:
572
+				panic("bad pointer or slice in map case in " + tf.Name())
573
+			default: // E.g., map[K]V
574
+				mfi.merge = func(dst, src pointer) {
575
+					sm := src.asPointerTo(tf).Elem()
576
+					if sm.Len() == 0 {
577
+						return
578
+					}
579
+					dm := dst.asPointerTo(tf).Elem()
580
+					if dm.IsNil() {
581
+						dm.Set(reflect.MakeMap(tf))
582
+					}
583
+
584
+					switch tf.Elem().Kind() {
585
+					case reflect.Ptr: // Proto struct (e.g., *T)
586
+						for _, key := range sm.MapKeys() {
587
+							val := sm.MapIndex(key)
588
+							val = reflect.ValueOf(Clone(val.Interface().(Message)))
589
+							dm.SetMapIndex(key, val)
590
+						}
591
+					case reflect.Slice: // E.g. Bytes type (e.g., []byte)
592
+						for _, key := range sm.MapKeys() {
593
+							val := sm.MapIndex(key)
594
+							val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
595
+							dm.SetMapIndex(key, val)
596
+						}
597
+					default: // Basic type (e.g., string)
598
+						for _, key := range sm.MapKeys() {
599
+							val := sm.MapIndex(key)
600
+							dm.SetMapIndex(key, val)
601
+						}
602
+					}
603
+				}
604
+			}
605
+		case reflect.Interface:
606
+			// Must be oneof field.
607
+			switch {
608
+			case isPointer || isSlice:
609
+				panic("bad pointer or slice in interface case in " + tf.Name())
610
+			default: // E.g., interface{}
611
+				// TODO: Make this faster?
612
+				mfi.merge = func(dst, src pointer) {
613
+					su := src.asPointerTo(tf).Elem()
614
+					if !su.IsNil() {
615
+						du := dst.asPointerTo(tf).Elem()
616
+						typ := su.Elem().Type()
617
+						if du.IsNil() || du.Elem().Type() != typ {
618
+							du.Set(reflect.New(typ.Elem())) // Initialize interface if empty
619
+						}
620
+						sv := su.Elem().Elem().Field(0)
621
+						if sv.Kind() == reflect.Ptr && sv.IsNil() {
622
+							return
623
+						}
624
+						dv := du.Elem().Elem().Field(0)
625
+						if dv.Kind() == reflect.Ptr && dv.IsNil() {
626
+							dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty
627
+						}
628
+						switch sv.Type().Kind() {
629
+						case reflect.Ptr: // Proto struct (e.g., *T)
630
+							Merge(dv.Interface().(Message), sv.Interface().(Message))
631
+						case reflect.Slice: // E.g. Bytes type (e.g., []byte)
632
+							dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...)))
633
+						default: // Basic type (e.g., string)
634
+							dv.Set(sv)
635
+						}
636
+					}
637
+				}
638
+			}
639
+		default:
640
+			panic(fmt.Sprintf("merger not found for type:%s", tf))
641
+		}
642
+		mi.fields = append(mi.fields, mfi)
643
+	}
644
+
645
+	mi.unrecognized = invalidField
646
+	if f, ok := t.FieldByName("XXX_unrecognized"); ok {
647
+		if f.Type != reflect.TypeOf([]byte{}) {
648
+			panic("expected XXX_unrecognized to be of type []byte")
649
+		}
650
+		mi.unrecognized = toField(&f)
651
+	}
652
+
653
+	atomic.StoreInt32(&mi.initialized, 1)
654
+}

+ 2053
- 0
log/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
File diff suppressed because it is too large
View File


+ 843
- 0
log/vendor/github.com/golang/protobuf/proto/text.go View File

@@ -0,0 +1,843 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+// Functions for writing the text protocol buffer format.
35
+
36
+import (
37
+	"bufio"
38
+	"bytes"
39
+	"encoding"
40
+	"errors"
41
+	"fmt"
42
+	"io"
43
+	"log"
44
+	"math"
45
+	"reflect"
46
+	"sort"
47
+	"strings"
48
+)
49
+
50
+var (
51
+	newline         = []byte("\n")
52
+	spaces          = []byte("                                        ")
53
+	endBraceNewline = []byte("}\n")
54
+	backslashN      = []byte{'\\', 'n'}
55
+	backslashR      = []byte{'\\', 'r'}
56
+	backslashT      = []byte{'\\', 't'}
57
+	backslashDQ     = []byte{'\\', '"'}
58
+	backslashBS     = []byte{'\\', '\\'}
59
+	posInf          = []byte("inf")
60
+	negInf          = []byte("-inf")
61
+	nan             = []byte("nan")
62
+)
63
+
64
+type writer interface {
65
+	io.Writer
66
+	WriteByte(byte) error
67
+}
68
+
69
+// textWriter is an io.Writer that tracks its indentation level.
70
+type textWriter struct {
71
+	ind      int
72
+	complete bool // if the current position is a complete line
73
+	compact  bool // whether to write out as a one-liner
74
+	w        writer
75
+}
76
+
77
+func (w *textWriter) WriteString(s string) (n int, err error) {
78
+	if !strings.Contains(s, "\n") {
79
+		if !w.compact && w.complete {
80
+			w.writeIndent()
81
+		}
82
+		w.complete = false
83
+		return io.WriteString(w.w, s)
84
+	}
85
+	// WriteString is typically called without newlines, so this
86
+	// codepath and its copy are rare.  We copy to avoid
87
+	// duplicating all of Write's logic here.
88
+	return w.Write([]byte(s))
89
+}
90
+
91
+func (w *textWriter) Write(p []byte) (n int, err error) {
92
+	newlines := bytes.Count(p, newline)
93
+	if newlines == 0 {
94
+		if !w.compact && w.complete {
95
+			w.writeIndent()
96
+		}
97
+		n, err = w.w.Write(p)
98
+		w.complete = false
99
+		return n, err
100
+	}
101
+
102
+	frags := bytes.SplitN(p, newline, newlines+1)
103
+	if w.compact {
104
+		for i, frag := range frags {
105
+			if i > 0 {
106
+				if err := w.w.WriteByte(' '); err != nil {
107
+					return n, err
108
+				}
109
+				n++
110
+			}
111
+			nn, err := w.w.Write(frag)
112
+			n += nn
113
+			if err != nil {
114
+				return n, err
115
+			}
116
+		}
117
+		return n, nil
118
+	}
119
+
120
+	for i, frag := range frags {
121
+		if w.complete {
122
+			w.writeIndent()
123
+		}
124
+		nn, err := w.w.Write(frag)
125
+		n += nn
126
+		if err != nil {
127
+			return n, err
128
+		}
129
+		if i+1 < len(frags) {
130
+			if err := w.w.WriteByte('\n'); err != nil {
131
+				return n, err
132
+			}
133
+			n++
134
+		}
135
+	}
136
+	w.complete = len(frags[len(frags)-1]) == 0
137
+	return n, nil
138
+}
139
+
140
+func (w *textWriter) WriteByte(c byte) error {
141
+	if w.compact && c == '\n' {
142
+		c = ' '
143
+	}
144
+	if !w.compact && w.complete {
145
+		w.writeIndent()
146
+	}
147
+	err := w.w.WriteByte(c)
148
+	w.complete = c == '\n'
149
+	return err
150
+}
151
+
152
+func (w *textWriter) indent() { w.ind++ }
153
+
154
+func (w *textWriter) unindent() {
155
+	if w.ind == 0 {
156
+		log.Print("proto: textWriter unindented too far")
157
+		return
158
+	}
159
+	w.ind--
160
+}
161
+
162
+func writeName(w *textWriter, props *Properties) error {
163
+	if _, err := w.WriteString(props.OrigName); err != nil {
164
+		return err
165
+	}
166
+	if props.Wire != "group" {
167
+		return w.WriteByte(':')
168
+	}
169
+	return nil
170
+}
171
+
172
+func requiresQuotes(u string) bool {
173
+	// When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
174
+	for _, ch := range u {
175
+		switch {
176
+		case ch == '.' || ch == '/' || ch == '_':
177
+			continue
178
+		case '0' <= ch && ch <= '9':
179
+			continue
180
+		case 'A' <= ch && ch <= 'Z':
181
+			continue
182
+		case 'a' <= ch && ch <= 'z':
183
+			continue
184
+		default:
185
+			return true
186
+		}
187
+	}
188
+	return false
189
+}
190
+
191
+// isAny reports whether sv is a google.protobuf.Any message
192
+func isAny(sv reflect.Value) bool {
193
+	type wkt interface {
194
+		XXX_WellKnownType() string
195
+	}
196
+	t, ok := sv.Addr().Interface().(wkt)
197
+	return ok && t.XXX_WellKnownType() == "Any"
198
+}
199
+
200
+// writeProto3Any writes an expanded google.protobuf.Any message.
201
+//
202
+// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
203
+// required messages are not linked in).
204
+//
205
+// It returns (true, error) when sv was written in expanded format or an error
206
+// was encountered.
207
+func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
208
+	turl := sv.FieldByName("TypeUrl")
209
+	val := sv.FieldByName("Value")
210
+	if !turl.IsValid() || !val.IsValid() {
211
+		return true, errors.New("proto: invalid google.protobuf.Any message")
212
+	}
213
+
214
+	b, ok := val.Interface().([]byte)
215
+	if !ok {
216
+		return true, errors.New("proto: invalid google.protobuf.Any message")
217
+	}
218
+
219
+	parts := strings.Split(turl.String(), "/")
220
+	mt := MessageType(parts[len(parts)-1])
221
+	if mt == nil {
222
+		return false, nil
223
+	}
224
+	m := reflect.New(mt.Elem())
225
+	if err := Unmarshal(b, m.Interface().(Message)); err != nil {
226
+		return false, nil
227
+	}
228
+	w.Write([]byte("["))
229
+	u := turl.String()
230
+	if requiresQuotes(u) {
231
+		writeString(w, u)
232
+	} else {
233
+		w.Write([]byte(u))
234
+	}
235
+	if w.compact {
236
+		w.Write([]byte("]:<"))
237
+	} else {
238
+		w.Write([]byte("]: <\n"))
239
+		w.ind++
240
+	}
241
+	if err := tm.writeStruct(w, m.Elem()); err != nil {
242
+		return true, err
243
+	}
244
+	if w.compact {
245
+		w.Write([]byte("> "))
246
+	} else {
247
+		w.ind--
248
+		w.Write([]byte(">\n"))
249
+	}
250
+	return true, nil
251
+}
252
+
253
+func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
254
+	if tm.ExpandAny && isAny(sv) {
255
+		if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
256
+			return err
257
+		}
258
+	}
259
+	st := sv.Type()
260
+	sprops := GetProperties(st)
261
+	for i := 0; i < sv.NumField(); i++ {
262
+		fv := sv.Field(i)
263
+		props := sprops.Prop[i]
264
+		name := st.Field(i).Name
265
+
266
+		if name == "XXX_NoUnkeyedLiteral" {
267
+			continue
268
+		}
269
+
270
+		if strings.HasPrefix(name, "XXX_") {
271
+			// There are two XXX_ fields:
272
+			//   XXX_unrecognized []byte
273
+			//   XXX_extensions   map[int32]proto.Extension
274
+			// The first is handled here;
275
+			// the second is handled at the bottom of this function.
276
+			if name == "XXX_unrecognized" && !fv.IsNil() {
277
+				if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
278
+					return err
279
+				}
280
+			}
281
+			continue
282
+		}
283
+		if fv.Kind() == reflect.Ptr && fv.IsNil() {
284
+			// Field not filled in. This could be an optional field or
285
+			// a required field that wasn't filled in. Either way, there
286
+			// isn't anything we can show for it.
287
+			continue
288
+		}
289
+		if fv.Kind() == reflect.Slice && fv.IsNil() {
290
+			// Repeated field that is empty, or a bytes field that is unused.
291
+			continue
292
+		}
293
+
294
+		if props.Repeated && fv.Kind() == reflect.Slice {
295
+			// Repeated field.
296
+			for j := 0; j < fv.Len(); j++ {
297
+				if err := writeName(w, props); err != nil {
298
+					return err
299
+				}
300
+				if !w.compact {
301
+					if err := w.WriteByte(' '); err != nil {
302
+						return err
303
+					}
304
+				}
305
+				v := fv.Index(j)
306
+				if v.Kind() == reflect.Ptr && v.IsNil() {
307
+					// A nil message in a repeated field is not valid,
308
+					// but we can handle that more gracefully than panicking.
309
+					if _, err := w.Write([]byte("<nil>\n")); err != nil {
310
+						return err
311
+					}
312
+					continue
313
+				}
314
+				if err := tm.writeAny(w, v, props); err != nil {
315
+					return err
316
+				}
317
+				if err := w.WriteByte('\n'); err != nil {
318
+					return err
319
+				}
320
+			}
321
+			continue
322
+		}
323
+		if fv.Kind() == reflect.Map {
324
+			// Map fields are rendered as a repeated struct with key/value fields.
325
+			keys := fv.MapKeys()
326
+			sort.Sort(mapKeys(keys))
327
+			for _, key := range keys {
328
+				val := fv.MapIndex(key)
329
+				if err := writeName(w, props); err != nil {
330
+					return err
331
+				}
332
+				if !w.compact {
333
+					if err := w.WriteByte(' '); err != nil {
334
+						return err
335
+					}
336
+				}
337
+				// open struct
338
+				if err := w.WriteByte('<'); err != nil {
339
+					return err
340
+				}
341
+				if !w.compact {
342
+					if err := w.WriteByte('\n'); err != nil {
343
+						return err
344
+					}
345
+				}
346
+				w.indent()
347
+				// key
348
+				if _, err := w.WriteString("key:"); err != nil {
349
+					return err
350
+				}
351
+				if !w.compact {
352
+					if err := w.WriteByte(' '); err != nil {
353
+						return err
354
+					}
355
+				}
356
+				if err := tm.writeAny(w, key, props.MapKeyProp); err != nil {
357
+					return err
358
+				}
359
+				if err := w.WriteByte('\n'); err != nil {
360
+					return err
361
+				}
362
+				// nil values aren't legal, but we can avoid panicking because of them.
363
+				if val.Kind() != reflect.Ptr || !val.IsNil() {
364
+					// value
365
+					if _, err := w.WriteString("value:"); err != nil {
366
+						return err
367
+					}
368
+					if !w.compact {
369
+						if err := w.WriteByte(' '); err != nil {
370
+							return err
371
+						}
372
+					}
373
+					if err := tm.writeAny(w, val, props.MapValProp); err != nil {
374
+						return err
375
+					}
376
+					if err := w.WriteByte('\n'); err != nil {
377
+						return err
378
+					}
379
+				}
380
+				// close struct
381
+				w.unindent()
382
+				if err := w.WriteByte('>'); err != nil {
383
+					return err
384
+				}
385
+				if err := w.WriteByte('\n'); err != nil {
386
+					return err
387
+				}
388
+			}
389
+			continue
390
+		}
391
+		if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
392
+			// empty bytes field
393
+			continue
394
+		}
395
+		if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
396
+			// proto3 non-repeated scalar field; skip if zero value
397
+			if isProto3Zero(fv) {
398
+				continue
399
+			}
400
+		}
401
+
402
+		if fv.Kind() == reflect.Interface {
403
+			// Check if it is a oneof.
404
+			if st.Field(i).Tag.Get("protobuf_oneof") != "" {
405
+				// fv is nil, or holds a pointer to generated struct.
406
+				// That generated struct has exactly one field,
407
+				// which has a protobuf struct tag.
408
+				if fv.IsNil() {
409
+					continue
410
+				}
411
+				inner := fv.Elem().Elem() // interface -> *T -> T
412
+				tag := inner.Type().Field(0).Tag.Get("protobuf")
413
+				props = new(Properties) // Overwrite the outer props var, but not its pointee.
414
+				props.Parse(tag)
415
+				// Write the value in the oneof, not the oneof itself.
416
+				fv = inner.Field(0)
417
+
418
+				// Special case to cope with malformed messages gracefully:
419
+				// If the value in the oneof is a nil pointer, don't panic
420
+				// in writeAny.
421
+				if fv.Kind() == reflect.Ptr && fv.IsNil() {
422
+					// Use errors.New so writeAny won't render quotes.
423
+					msg := errors.New("/* nil */")
424
+					fv = reflect.ValueOf(&msg).Elem()
425
+				}
426
+			}
427
+		}
428
+
429
+		if err := writeName(w, props); err != nil {
430
+			return err
431
+		}
432
+		if !w.compact {
433
+			if err := w.WriteByte(' '); err != nil {
434
+				return err
435
+			}
436
+		}
437
+
438
+		// Enums have a String method, so writeAny will work fine.
439
+		if err := tm.writeAny(w, fv, props); err != nil {
440
+			return err
441
+		}
442
+
443
+		if err := w.WriteByte('\n'); err != nil {
444
+			return err
445
+		}
446
+	}
447
+
448
+	// Extensions (the XXX_extensions field).
449
+	pv := sv.Addr()
450
+	if _, err := extendable(pv.Interface()); err == nil {
451
+		if err := tm.writeExtensions(w, pv); err != nil {
452
+			return err
453
+		}
454
+	}
455
+
456
+	return nil
457
+}
458
+
459
+// writeAny writes an arbitrary field.
460
+func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
461
+	v = reflect.Indirect(v)
462
+
463
+	// Floats have special cases.
464
+	if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
465
+		x := v.Float()
466
+		var b []byte
467
+		switch {
468
+		case math.IsInf(x, 1):
469
+			b = posInf
470
+		case math.IsInf(x, -1):
471
+			b = negInf
472
+		case math.IsNaN(x):
473
+			b = nan
474
+		}
475
+		if b != nil {
476
+			_, err := w.Write(b)
477
+			return err
478
+		}
479
+		// Other values are handled below.
480
+	}
481
+
482
+	// We don't attempt to serialise every possible value type; only those
483
+	// that can occur in protocol buffers.
484
+	switch v.Kind() {
485
+	case reflect.Slice:
486
+		// Should only be a []byte; repeated fields are handled in writeStruct.
487
+		if err := writeString(w, string(v.Bytes())); err != nil {
488
+			return err
489
+		}
490
+	case reflect.String:
491
+		if err := writeString(w, v.String()); err != nil {
492
+			return err
493
+		}
494
+	case reflect.Struct:
495
+		// Required/optional group/message.
496
+		var bra, ket byte = '<', '>'
497
+		if props != nil && props.Wire == "group" {
498
+			bra, ket = '{', '}'
499
+		}
500
+		if err := w.WriteByte(bra); err != nil {
501
+			return err
502
+		}
503
+		if !w.compact {
504
+			if err := w.WriteByte('\n'); err != nil {
505
+				return err
506
+			}
507
+		}
508
+		w.indent()
509
+		if v.CanAddr() {
510
+			// Calling v.Interface on a struct causes the reflect package to
511
+			// copy the entire struct. This is racy with the new Marshaler
512
+			// since we atomically update the XXX_sizecache.
513
+			//
514
+			// Thus, we retrieve a pointer to the struct if possible to avoid
515
+			// a race since v.Interface on the pointer doesn't copy the struct.
516
+			//
517
+			// If v is not addressable, then we are not worried about a race
518
+			// since it implies that the binary Marshaler cannot possibly be
519
+			// mutating this value.
520
+			v = v.Addr()
521
+		}
522
+		if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
523
+			text, err := etm.MarshalText()
524
+			if err != nil {
525
+				return err
526
+			}
527
+			if _, err = w.Write(text); err != nil {
528
+				return err
529
+			}
530
+		} else {
531
+			if v.Kind() == reflect.Ptr {
532
+				v = v.Elem()
533
+			}
534
+			if err := tm.writeStruct(w, v); err != nil {
535
+				return err
536
+			}
537
+		}
538
+		w.unindent()
539
+		if err := w.WriteByte(ket); err != nil {
540
+			return err
541
+		}
542
+	default:
543
+		_, err := fmt.Fprint(w, v.Interface())
544
+		return err
545
+	}
546
+	return nil
547
+}
548
+
549
+// equivalent to C's isprint.
550
+func isprint(c byte) bool {
551
+	return c >= 0x20 && c < 0x7f
552
+}
553
+
554
+// writeString writes a string in the protocol buffer text format.
555
+// It is similar to strconv.Quote except we don't use Go escape sequences,
556
+// we treat the string as a byte sequence, and we use octal escapes.
557
+// These differences are to maintain interoperability with the other
558
+// languages' implementations of the text format.
559
+func writeString(w *textWriter, s string) error {
560
+	// use WriteByte here to get any needed indent
561
+	if err := w.WriteByte('"'); err != nil {
562
+		return err
563
+	}
564
+	// Loop over the bytes, not the runes.
565
+	for i := 0; i < len(s); i++ {
566
+		var err error
567
+		// Divergence from C++: we don't escape apostrophes.
568
+		// There's no need to escape them, and the C++ parser
569
+		// copes with a naked apostrophe.
570
+		switch c := s[i]; c {
571
+		case '\n':
572
+			_, err = w.w.Write(backslashN)
573
+		case '\r':
574
+			_, err = w.w.Write(backslashR)
575
+		case '\t':
576
+			_, err = w.w.Write(backslashT)
577
+		case '"':
578
+			_, err = w.w.Write(backslashDQ)
579
+		case '\\':
580
+			_, err = w.w.Write(backslashBS)
581
+		default:
582
+			if isprint(c) {
583
+				err = w.w.WriteByte(c)
584
+			} else {
585
+				_, err = fmt.Fprintf(w.w, "\\%03o", c)
586
+			}
587
+		}
588
+		if err != nil {
589
+			return err
590
+		}
591
+	}
592
+	return w.WriteByte('"')
593
+}
594
+
595
+func writeUnknownStruct(w *textWriter, data []byte) (err error) {
596
+	if !w.compact {
597
+		if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
598
+			return err
599
+		}
600
+	}
601
+	b := NewBuffer(data)
602
+	for b.index < len(b.buf) {
603
+		x, err := b.DecodeVarint()
604
+		if err != nil {
605
+			_, err := fmt.Fprintf(w, "/* %v */\n", err)
606
+			return err
607
+		}
608
+		wire, tag := x&7, x>>3
609
+		if wire == WireEndGroup {
610
+			w.unindent()
611
+			if _, err := w.Write(endBraceNewline); err != nil {
612
+				return err
613
+			}
614
+			continue
615
+		}
616
+		if _, err := fmt.Fprint(w, tag); err != nil {
617
+			return err
618
+		}
619
+		if wire != WireStartGroup {
620
+			if err := w.WriteByte(':'); err != nil {
621
+				return err
622
+			}
623
+		}
624
+		if !w.compact || wire == WireStartGroup {
625
+			if err := w.WriteByte(' '); err != nil {
626
+				return err
627
+			}
628
+		}
629
+		switch wire {
630
+		case WireBytes:
631
+			buf, e := b.DecodeRawBytes(false)
632
+			if e == nil {
633
+				_, err = fmt.Fprintf(w, "%q", buf)
634
+			} else {
635
+				_, err = fmt.Fprintf(w, "/* %v */", e)
636
+			}
637
+		case WireFixed32:
638
+			x, err = b.DecodeFixed32()
639
+			err = writeUnknownInt(w, x, err)
640
+		case WireFixed64:
641
+			x, err = b.DecodeFixed64()
642
+			err = writeUnknownInt(w, x, err)
643
+		case WireStartGroup:
644
+			err = w.WriteByte('{')
645
+			w.indent()
646
+		case WireVarint:
647
+			x, err = b.DecodeVarint()
648
+			err = writeUnknownInt(w, x, err)
649
+		default:
650
+			_, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
651
+		}
652
+		if err != nil {
653
+			return err
654
+		}
655
+		if err = w.WriteByte('\n'); err != nil {
656
+			return err
657
+		}
658
+	}
659
+	return nil
660
+}
661
+
662
+func writeUnknownInt(w *textWriter, x uint64, err error) error {
663
+	if err == nil {
664
+		_, err = fmt.Fprint(w, x)
665
+	} else {
666
+		_, err = fmt.Fprintf(w, "/* %v */", err)
667
+	}
668
+	return err
669
+}
670
+
671
+type int32Slice []int32
672
+
673
+func (s int32Slice) Len() int           { return len(s) }
674
+func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
675
+func (s int32Slice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
676
+
677
+// writeExtensions writes all the extensions in pv.
678
+// pv is assumed to be a pointer to a protocol message struct that is extendable.
679
+func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
680
+	emap := extensionMaps[pv.Type().Elem()]
681
+	ep, _ := extendable(pv.Interface())
682
+
683
+	// Order the extensions by ID.
684
+	// This isn't strictly necessary, but it will give us
685
+	// canonical output, which will also make testing easier.
686
+	m, mu := ep.extensionsRead()
687
+	if m == nil {
688
+		return nil
689
+	}
690
+	mu.Lock()
691
+	ids := make([]int32, 0, len(m))
692
+	for id := range m {
693
+		ids = append(ids, id)
694
+	}
695
+	sort.Sort(int32Slice(ids))
696
+	mu.Unlock()
697
+
698
+	for _, extNum := range ids {
699
+		ext := m[extNum]
700
+		var desc *ExtensionDesc
701
+		if emap != nil {
702
+			desc = emap[extNum]
703
+		}
704
+		if desc == nil {
705
+			// Unknown extension.
706
+			if err := writeUnknownStruct(w, ext.enc); err != nil {
707
+				return err
708
+			}
709
+			continue
710
+		}
711
+
712
+		pb, err := GetExtension(ep, desc)
713
+		if err != nil {
714
+			return fmt.Errorf("failed getting extension: %v", err)
715
+		}
716
+
717
+		// Repeated extensions will appear as a slice.
718
+		if !desc.repeated() {
719
+			if err := tm.writeExtension(w, desc.Name, pb); err != nil {
720
+				return err
721
+			}
722
+		} else {
723
+			v := reflect.ValueOf(pb)
724
+			for i := 0; i < v.Len(); i++ {
725
+				if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
726
+					return err
727
+				}
728
+			}
729
+		}
730
+	}
731
+	return nil
732
+}
733
+
734
+func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
735
+	if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
736
+		return err
737
+	}
738
+	if !w.compact {
739
+		if err := w.WriteByte(' '); err != nil {
740
+			return err
741
+		}
742
+	}
743
+	if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
744
+		return err
745
+	}
746
+	if err := w.WriteByte('\n'); err != nil {
747
+		return err
748
+	}
749
+	return nil
750
+}
751
+
752
+func (w *textWriter) writeIndent() {
753
+	if !w.complete {
754
+		return
755
+	}
756
+	remain := w.ind * 2
757
+	for remain > 0 {
758
+		n := remain
759
+		if n > len(spaces) {
760
+			n = len(spaces)
761
+		}
762
+		w.w.Write(spaces[:n])
763
+		remain -= n
764
+	}
765
+	w.complete = false
766
+}
767
+
768
+// TextMarshaler is a configurable text format marshaler.
769
+type TextMarshaler struct {
770
+	Compact   bool // use compact text format (one line).
771
+	ExpandAny bool // expand google.protobuf.Any messages of known types
772
+}
773
+
774
+// Marshal writes a given protocol buffer in text format.
775
+// The only errors returned are from w.
776
+func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
777
+	val := reflect.ValueOf(pb)
778
+	if pb == nil || val.IsNil() {
779
+		w.Write([]byte("<nil>"))
780
+		return nil
781
+	}
782
+	var bw *bufio.Writer
783
+	ww, ok := w.(writer)
784
+	if !ok {
785
+		bw = bufio.NewWriter(w)
786
+		ww = bw
787
+	}
788
+	aw := &textWriter{
789
+		w:        ww,
790
+		complete: true,
791
+		compact:  tm.Compact,
792
+	}
793
+
794
+	if etm, ok := pb.(encoding.TextMarshaler); ok {
795
+		text, err := etm.MarshalText()
796
+		if err != nil {
797
+			return err
798
+		}
799
+		if _, err = aw.Write(text); err != nil {
800
+			return err
801
+		}
802
+		if bw != nil {
803
+			return bw.Flush()
804
+		}
805
+		return nil
806
+	}
807
+	// Dereference the received pointer so we don't have outer < and >.
808
+	v := reflect.Indirect(val)
809
+	if err := tm.writeStruct(aw, v); err != nil {
810
+		return err
811
+	}
812
+	if bw != nil {
813
+		return bw.Flush()
814
+	}
815
+	return nil
816
+}
817
+
818
+// Text is the same as Marshal, but returns the string directly.
819
+func (tm *TextMarshaler) Text(pb Message) string {
820
+	var buf bytes.Buffer
821
+	tm.Marshal(&buf, pb)
822
+	return buf.String()
823
+}
824
+
825
+var (
826
+	defaultTextMarshaler = TextMarshaler{}
827
+	compactTextMarshaler = TextMarshaler{Compact: true}
828
+)
829
+
830
+// TODO: consider removing some of the Marshal functions below.
831
+
832
+// MarshalText writes a given protocol buffer in text format.
833
+// The only errors returned are from w.
834
+func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
835
+
836
+// MarshalTextString is the same as MarshalText, but returns the string directly.
837
+func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
838
+
839
+// CompactText writes a given protocol buffer in compact text format (one line).
840
+func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
841
+
842
+// CompactTextString is the same as CompactText, but returns the string directly.
843
+func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }

+ 880
- 0
log/vendor/github.com/golang/protobuf/proto/text_parser.go View File

@@ -0,0 +1,880 @@
1
+// Go support for Protocol Buffers - Google's data interchange format
2
+//
3
+// Copyright 2010 The Go Authors.  All rights reserved.
4
+// https://github.com/golang/protobuf
5
+//
6
+// Redistribution and use in source and binary forms, with or without
7
+// modification, are permitted provided that the following conditions are
8
+// met:
9
+//
10
+//     * Redistributions of source code must retain the above copyright
11
+// notice, this list of conditions and the following disclaimer.
12
+//     * Redistributions in binary form must reproduce the above
13
+// copyright notice, this list of conditions and the following disclaimer
14
+// in the documentation and/or other materials provided with the
15
+// distribution.
16
+//     * Neither the name of Google Inc. nor the names of its
17
+// contributors may be used to endorse or promote products derived from
18
+// this software without specific prior written permission.
19
+//
20
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+package proto
33
+
34
+// Functions for parsing the Text protocol buffer format.
35
+// TODO: message sets.
36
+
37
+import (
38
+	"encoding"
39
+	"errors"
40
+	"fmt"
41
+	"reflect"
42
+	"strconv"
43
+	"strings"
44
+	"unicode/utf8"
45
+)
46
+
47
+// Error string emitted when deserializing Any and fields are already set
48
+const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
49
+
50
+type ParseError struct {
51
+	Message string
52
+	Line    int // 1-based line number
53
+	Offset  int // 0-based byte offset from start of input
54
+}
55
+
56
+func (p *ParseError) Error() string {
57
+	if p.Line == 1 {
58
+		// show offset only for first line
59
+		return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
60
+	}
61
+	return fmt.Sprintf("line %d: %v", p.Line, p.Message)
62
+}
63
+
64
+type token struct {
65
+	value    string
66
+	err      *ParseError
67
+	line     int    // line number
68
+	offset   int    // byte number from start of input, not start of line
69
+	unquoted string // the unquoted version of value, if it was a quoted string
70
+}
71
+
72
+func (t *token) String() string {
73
+	if t.err == nil {
74
+		return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
75
+	}
76
+	return fmt.Sprintf("parse error: %v", t.err)
77
+}
78
+
79
+type textParser struct {
80
+	s            string // remaining input
81
+	done         bool   // whether the parsing is finished (success or error)
82
+	backed       bool   // whether back() was called
83
+	offset, line int
84
+	cur          token
85
+}
86
+
87
+func newTextParser(s string) *textParser {
88
+	p := new(textParser)
89
+	p.s = s
90
+	p.line = 1
91
+	p.cur.line = 1
92
+	return p
93
+}
94
+
95
+func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
96
+	pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
97
+	p.cur.err = pe
98
+	p.done = true
99
+	return pe
100
+}
101
+
102
+// Numbers and identifiers are matched by [-+._A-Za-z0-9]
103
+func isIdentOrNumberChar(c byte) bool {
104
+	switch {
105
+	case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
106
+		return true
107
+	case '0' <= c && c <= '9':
108
+		return true
109
+	}
110
+	switch c {
111
+	case '-', '+', '.', '_':
112
+		return true
113
+	}
114
+	return false
115
+}
116
+
117
+func isWhitespace(c byte) bool {
118
+	switch c {
119
+	case ' ', '\t', '\n', '\r':
120
+		return true
121
+	}
122
+	return false
123
+}
124
+
125
+func isQuote(c byte) bool {
126
+	switch c {
127
+	case '"', '\'':
128
+		return true
129
+	}
130
+	return false
131
+}
132
+
133
+func (p *textParser) skipWhitespace() {
134
+	i := 0
135
+	for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
136
+		if p.s[i] == '#' {
137
+			// comment; skip to end of line or input
138
+			for i < len(p.s) && p.s[i] != '\n' {
139
+				i++
140
+			}
141
+			if i == len(p.s) {
142
+				break
143
+			}
144
+		}
145
+		if p.s[i] == '\n' {
146
+			p.line++
147
+		}
148
+		i++
149
+	}
150
+	p.offset += i
151
+	p.s = p.s[i:len(p.s)]
152
+	if len(p.s) == 0 {
153
+		p.done = true
154
+	}
155
+}
156
+
157
+func (p *textParser) advance() {
158
+	// Skip whitespace
159
+	p.skipWhitespace()
160
+	if p.done {
161
+		return
162
+	}
163
+
164
+	// Start of non-whitespace
165
+	p.cur.err = nil
166
+	p.cur.offset, p.cur.line = p.offset, p.line
167
+	p.cur.unquoted = ""
168
+	switch p.s[0] {
169
+	case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
170
+		// Single symbol
171
+		p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
172
+	case '"', '\'':
173
+		// Quoted string
174
+		i := 1
175
+		for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
176
+			if p.s[i] == '\\' && i+1 < len(p.s) {
177
+				// skip escaped char
178
+				i++
179
+			}
180
+			i++
181
+		}
182
+		if i >= len(p.s) || p.s[i] != p.s[0] {
183
+			p.errorf("unmatched quote")
184
+			return
185
+		}
186
+		unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
187
+		if err != nil {
188
+			p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
189
+			return
190
+		}
191
+		p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
192
+		p.cur.unquoted = unq
193
+	default:
194
+		i := 0
195
+		for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
196
+			i++
197
+		}
198
+		if i == 0 {
199
+			p.errorf("unexpected byte %#x", p.s[0])
200
+			return
201
+		}
202
+		p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
203
+	}
204
+	p.offset += len(p.cur.value)
205
+}
206
+
207
+var (
208
+	errBadUTF8 = errors.New("proto: bad UTF-8")
209
+)
210
+
211
+func unquoteC(s string, quote rune) (string, error) {
212
+	// This is based on C++'s tokenizer.cc.
213
+	// Despite its name, this is *not* parsing C syntax.
214
+	// For instance, "\0" is an invalid quoted string.
215
+
216
+	// Avoid allocation in trivial cases.
217
+	simple := true
218
+	for _, r := range s {
219
+		if r == '\\' || r == quote {
220
+			simple = false
221
+			break
222
+		}
223
+	}
224
+	if simple {
225
+		return s, nil
226
+	}
227
+
228
+	buf := make([]byte, 0, 3*len(s)/2)
229
+	for len(s) > 0 {
230
+		r, n := utf8.DecodeRuneInString(s)
231
+		if r == utf8.RuneError && n == 1 {
232
+			return "", errBadUTF8
233
+		}
234
+		s = s[n:]
235
+		if r != '\\' {
236
+			if r < utf8.RuneSelf {
237
+				buf = append(buf, byte(r))
238
+			} else {
239
+				buf = append(buf, string(r)...)
240
+			}
241
+			continue
242
+		}
243
+
244
+		ch, tail, err := unescape(s)
245
+		if err != nil {
246
+			return "", err
247
+		}
248
+		buf = append(buf, ch...)
249
+		s = tail
250
+	}
251
+	return string(buf), nil
252
+}
253
+
254
+func unescape(s string) (ch string, tail string, err error) {
255
+	r, n := utf8.DecodeRuneInString(s)
256
+	if r == utf8.RuneError && n == 1 {
257
+		return "", "", errBadUTF8
258
+	}
259
+	s = s[n:]
260
+	switch r {
261
+	case 'a':
262
+		return "\a", s, nil
263
+	case 'b':
264
+		return "\b", s, nil
265
+	case 'f':
266
+		return "\f", s, nil
267
+	case 'n':
268
+		return "\n", s, nil
269
+	case 'r':
270
+		return "\r", s, nil
271
+	case 't':
272
+		return "\t", s, nil
273
+	case 'v':
274
+		return "\v", s, nil
275
+	case '?':
276
+		return "?", s, nil // trigraph workaround
277
+	case '\'', '"', '\\':
278
+		return string(r), s, nil
279
+	case '0', '1', '2', '3', '4', '5', '6', '7':
280
+		if len(s) < 2 {
281
+			return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
282
+		}
283
+		ss := string(r) + s[:2]
284
+		s = s[2:]
285
+		i, err := strconv.ParseUint(ss, 8, 8)
286
+		if err != nil {
287
+			return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss)
288
+		}
289
+		return string([]byte{byte(i)}), s, nil
290
+	case 'x', 'X', 'u', 'U':
291
+		var n int
292
+		switch r {
293
+		case 'x', 'X':
294
+			n = 2
295
+		case 'u':
296
+			n = 4
297
+		case 'U':
298
+			n = 8
299
+		}
300
+		if len(s) < n {
301
+			return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n)
302
+		}
303
+		ss := s[:n]
304
+		s = s[n:]
305
+		i, err := strconv.ParseUint(ss, 16, 64)
306
+		if err != nil {
307
+			return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss)
308
+		}
309
+		if r == 'x' || r == 'X' {
310
+			return string([]byte{byte(i)}), s, nil
311
+		}
312
+		if i > utf8.MaxRune {
313
+			return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
314
+		}
315
+		return string(i), s, nil
316
+	}
317
+	return "", "", fmt.Errorf(`unknown escape \%c`, r)
318
+}
319
+
320
+// Back off the parser by one token. Can only be done between calls to next().
321
+// It makes the next advance() a no-op.
322
+func (p *textParser) back() { p.backed = true }
323
+
324
+// Advances the parser and returns the new current token.
325
+func (p *textParser) next() *token {
326
+	if p.backed || p.done {
327
+		p.backed = false
328
+		return &p.cur
329
+	}
330
+	p.advance()
331
+	if p.done {
332
+		p.cur.value = ""
333
+	} else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
334
+		// Look for multiple quoted strings separated by whitespace,
335
+		// and concatenate them.
336
+		cat := p.cur
337
+		for {
338
+			p.skipWhitespace()
339
+			if p.done || !isQuote(p.s[0]) {
340
+				break
341
+			}
342
+			p.advance()
343
+			if p.cur.err != nil {
344
+				return &p.cur
345
+			}
346
+			cat.value += " " + p.cur.value
347
+			cat.unquoted += p.cur.unquoted
348
+		}
349
+		p.done = false // parser may have seen EOF, but we want to return cat
350
+		p.cur = cat
351
+	}
352
+	return &p.cur
353
+}
354
+
355
+func (p *textParser) consumeToken(s string) error {
356
+	tok := p.next()
357
+	if tok.err != nil {
358
+		return tok.err
359
+	}
360
+	if tok.value != s {
361
+		p.back()
362
+		return p.errorf("expected %q, found %q", s, tok.value)
363
+	}
364
+	return nil
365
+}
366
+
367
+// Return a RequiredNotSetError indicating which required field was not set.
368
+func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
369
+	st := sv.Type()
370
+	sprops := GetProperties(st)
371
+	for i := 0; i < st.NumField(); i++ {
372
+		if !isNil(sv.Field(i)) {
373
+			continue
374
+		}
375
+
376
+		props := sprops.Prop[i]
377
+		if props.Required {
378
+			return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
379
+		}
380
+	}
381
+	return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
382
+}
383
+
384
+// Returns the index in the struct for the named field, as well as the parsed tag properties.
385
+func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
386
+	i, ok := sprops.decoderOrigNames[name]
387
+	if ok {
388
+		return i, sprops.Prop[i], true
389
+	}
390
+	return -1, nil, false
391
+}
392
+
393
+// Consume a ':' from the input stream (if the next token is a colon),
394
+// returning an error if a colon is needed but not present.
395
+func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
396
+	tok := p.next()
397
+	if tok.err != nil {
398
+		return tok.err
399
+	}
400
+	if tok.value != ":" {
401
+		// Colon is optional when the field is a group or message.
402
+		needColon := true
403
+		switch props.Wire {
404
+		case "group":
405
+			needColon = false
406
+		case "bytes":
407
+			// A "bytes" field is either a message, a string, or a repeated field;
408
+			// those three become *T, *string and []T respectively, so we can check for
409
+			// this field being a pointer to a non-string.
410
+			if typ.Kind() == reflect.Ptr {
411
+				// *T or *string
412
+				if typ.Elem().Kind() == reflect.String {
413
+					break
414
+				}
415
+			} else if typ.Kind() == reflect.Slice {
416
+				// []T or []*T
417
+				if typ.Elem().Kind() != reflect.Ptr {
418
+					break
419
+				}
420
+			} else if typ.Kind() == reflect.String {
421
+				// The proto3 exception is for a string field,
422
+				// which requires a colon.
423
+				break
424
+			}
425
+			needColon = false
426
+		}
427
+		if needColon {
428
+			return p.errorf("expected ':', found %q", tok.value)
429
+		}
430
+		p.back()
431
+	}
432
+	return nil
433
+}
434
+
435
+func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
436
+	st := sv.Type()
437
+	sprops := GetProperties(st)
438
+	reqCount := sprops.reqCount
439
+	var reqFieldErr error
440
+	fieldSet := make(map[string]bool)
441
+	// A struct is a sequence of "name: value", terminated by one of
442
+	// '>' or '}', or the end of the input.  A name may also be
443
+	// "[extension]" or "[type/url]".
444
+	//
445
+	// The whole struct can also be an expanded Any message, like:
446
+	// [type/url] < ... struct contents ... >
447
+	for {
448
+		tok := p.next()
449
+		if tok.err != nil {
450
+			return tok.err
451
+		}
452
+		if tok.value == terminator {
453
+			break
454
+		}
455
+		if tok.value == "[" {
456
+			// Looks like an extension or an Any.
457
+			//
458
+			// TODO: Check whether we need to handle
459
+			// namespace rooted names (e.g. ".something.Foo").
460
+			extName, err := p.consumeExtName()
461
+			if err != nil {
462
+				return err
463
+			}
464
+
465
+			if s := strings.LastIndex(extName, "/"); s >= 0 {
466
+				// If it contains a slash, it's an Any type URL.
467
+				messageName := extName[s+1:]
468
+				mt := MessageType(messageName)
469
+				if mt == nil {
470
+					return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
471
+				}
472
+				tok = p.next()
473
+				if tok.err != nil {
474
+					return tok.err
475
+				}
476
+				// consume an optional colon
477
+				if tok.value == ":" {
478
+					tok = p.next()
479
+					if tok.err != nil {
480
+						return tok.err
481
+					}
482
+				}
483
+				var terminator string
484
+				switch tok.value {
485
+				case "<":
486
+					terminator = ">"
487
+				case "{":
488
+					terminator = "}"
489
+				default:
490
+					return p.errorf("expected '{' or '<', found %q", tok.value)
491
+				}
492
+				v := reflect.New(mt.Elem())
493
+				if pe := p.readStruct(v.Elem(), terminator); pe != nil {
494
+					return pe
495
+				}
496
+				b, err := Marshal(v.Interface().(Message))
497
+				if err != nil {
498
+					return p.errorf("failed to marshal message of type %q: %v", messageName, err)
499
+				}
500
+				if fieldSet["type_url"] {
501
+					return p.errorf(anyRepeatedlyUnpacked, "type_url")
502
+				}
503
+				if fieldSet["value"] {
504
+					return p.errorf(anyRepeatedlyUnpacked, "value")
505
+				}
506
+				sv.FieldByName("TypeUrl").SetString(extName)
507
+				sv.FieldByName("Value").SetBytes(b)
508
+				fieldSet["type_url"] = true
509
+				fieldSet["value"] = true
510
+				continue
511
+			}
512
+
513
+			var desc *ExtensionDesc
514
+			// This could be faster, but it's functional.
515
+			// TODO: Do something smarter than a linear scan.
516
+			for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
517
+				if d.Name == extName {
518
+					desc = d
519
+					break
520
+				}
521
+			}
522
+			if desc == nil {
523
+				return p.errorf("unrecognized extension %q", extName)
524
+			}
525
+
526
+			props := &Properties{}
527
+			props.Parse(desc.Tag)
528
+
529
+			typ := reflect.TypeOf(desc.ExtensionType)
530
+			if err := p.checkForColon(props, typ); err != nil {
531
+				return err
532
+			}
533
+
534
+			rep := desc.repeated()
535
+
536
+			// Read the extension structure, and set it in
537
+			// the value we're constructing.
538
+			var ext reflect.Value
539
+			if !rep {
540
+				ext = reflect.New(typ).Elem()
541
+			} else {
542
+				ext = reflect.New(typ.Elem()).Elem()
543
+			}
544
+			if err := p.readAny(ext, props); err != nil {
545
+				if _, ok := err.(*RequiredNotSetError); !ok {
546
+					return err
547
+				}
548
+				reqFieldErr = err
549
+			}
550
+			ep := sv.Addr().Interface().(Message)
551
+			if !rep {
552
+				SetExtension(ep, desc, ext.Interface())
553
+			} else {
554
+				old, err := GetExtension(ep, desc)
555
+				var sl reflect.Value
556
+				if err == nil {
557
+					sl = reflect.ValueOf(old) // existing slice
558
+				} else {
559
+					sl = reflect.MakeSlice(typ, 0, 1)
560
+				}
561
+				sl = reflect.Append(sl, ext)
562
+				SetExtension(ep, desc, sl.Interface())
563
+			}
564
+			if err := p.consumeOptionalSeparator(); err != nil {
565
+				return err
566
+			}
567
+			continue
568
+		}
569
+
570
+		// This is a normal, non-extension field.
571
+		name := tok.value
572
+		var dst reflect.Value
573
+		fi, props, ok := structFieldByName(sprops, name)
574
+		if ok {
575
+			dst = sv.Field(fi)
576
+		} else if oop, ok := sprops.OneofTypes[name]; ok {
577
+			// It is a oneof.
578
+			props = oop.Prop
579
+			nv := reflect.New(oop.Type.Elem())
580
+			dst = nv.Elem().Field(0)
581
+			field := sv.Field(oop.Field)
582
+			if !field.IsNil() {
583
+				return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
584
+			}
585
+			field.Set(nv)
586
+		}
587
+		if !dst.IsValid() {
588
+			return p.errorf("unknown field name %q in %v", name, st)
589
+		}
590
+
591
+		if dst.Kind() == reflect.Map {
592
+			// Consume any colon.
593
+			if err := p.checkForColon(props, dst.Type()); err != nil {
594
+				return err
595
+			}
596
+
597
+			// Construct the map if it doesn't already exist.
598
+			if dst.IsNil() {
599
+				dst.Set(reflect.MakeMap(dst.Type()))
600
+			}
601
+			key := reflect.New(dst.Type().Key()).Elem()
602
+			val := reflect.New(dst.Type().Elem()).Elem()
603
+
604
+			// The map entry should be this sequence of tokens:
605
+			//	< key : KEY value : VALUE >
606
+			// However, implementations may omit key or value, and technically
607
+			// we should support them in any order.  See b/28924776 for a time
608
+			// this went wrong.
609
+
610
+			tok := p.next()
611
+			var terminator string
612
+			switch tok.value {
613
+			case "<":
614
+				terminator = ">"
615
+			case "{":
616
+				terminator = "}"
617
+			default:
618
+				return p.errorf("expected '{' or '<', found %q", tok.value)
619
+			}
620
+			for {
621
+				tok := p.next()
622
+				if tok.err != nil {
623
+					return tok.err
624
+				}
625
+				if tok.value == terminator {
626
+					break
627
+				}
628
+				switch tok.value {
629
+				case "key":
630
+					if err := p.consumeToken(":"); err != nil {
631
+						return err
632
+					}
633
+					if err := p.readAny(key, props.MapKeyProp); err != nil {
634
+						return err
635
+					}
636
+					if err := p.consumeOptionalSeparator(); err != nil {
637
+						return err
638
+					}
639
+				case "value":
640
+					if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil {
641
+						return err
642
+					}
643
+					if err := p.readAny(val, props.MapValProp); err != nil {
644
+						return err
645
+					}
646
+					if err := p.consumeOptionalSeparator(); err != nil {
647
+						return err
648
+					}
649
+				default:
650
+					p.back()
651
+					return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
652
+				}
653
+			}
654
+
655
+			dst.SetMapIndex(key, val)
656
+			continue
657
+		}
658
+
659
+		// Check that it's not already set if it's not a repeated field.
660
+		if !props.Repeated && fieldSet[name] {
661
+			return p.errorf("non-repeated field %q was repeated", name)
662
+		}
663
+
664
+		if err := p.checkForColon(props, dst.Type()); err != nil {
665
+			return err
666
+		}
667
+
668
+		// Parse into the field.
669
+		fieldSet[name] = true
670
+		if err := p.readAny(dst, props); err != nil {
671
+			if _, ok := err.(*RequiredNotSetError); !ok {
672
+				return err
673
+			}
674
+			reqFieldErr = err
675
+		}
676
+		if props.Required {
677
+			reqCount--
678
+		}
679
+
680
+		if err := p.consumeOptionalSeparator(); err != nil {
681
+			return err
682
+		}
683
+
684
+	}
685
+
686
+	if reqCount > 0 {
687
+		return p.missingRequiredFieldError(sv)
688
+	}
689
+	return reqFieldErr
690
+}
691
+
692
+// consumeExtName consumes extension name or expanded Any type URL and the
693
+// following ']'. It returns the name or URL consumed.
694
+func (p *textParser) consumeExtName() (string, error) {
695
+	tok := p.next()
696
+	if tok.err != nil {
697
+		return "", tok.err
698
+	}
699
+
700
+	// If extension name or type url is quoted, it's a single token.
701
+	if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
702
+		name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
703
+		if err != nil {
704
+			return "", err
705
+		}
706
+		return name, p.consumeToken("]")
707
+	}
708
+
709
+	// Consume everything up to "]"
710
+	var parts []string
711
+	for tok.value != "]" {
712
+		parts = append(parts, tok.value)
713
+		tok = p.next()
714
+		if tok.err != nil {
715
+			return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
716
+		}
717
+		if p.done && tok.value != "]" {
718
+			return "", p.errorf("unclosed type_url or extension name")
719
+		}
720
+	}
721
+	return strings.Join(parts, ""), nil
722
+}
723
+
724
+// consumeOptionalSeparator consumes an optional semicolon or comma.
725
+// It is used in readStruct to provide backward compatibility.
726
+func (p *textParser) consumeOptionalSeparator() error {
727
+	tok := p.next()
728
+	if tok.err != nil {
729
+		return tok.err
730
+	}
731
+	if tok.value != ";" && tok.value != "," {
732
+		p.back()
733
+	}
734
+	return nil
735
+}
736
+
737
+func (p *textParser) readAny(v reflect.Value, props *Properties) error {
738
+	tok := p.next()
739
+	if tok.err != nil {
740
+		return tok.err
741
+	}
742
+	if tok.value == "" {
743
+		return p.errorf("unexpected EOF")
744
+	}
745
+
746
+	switch fv := v; fv.Kind() {
747
+	case reflect.Slice:
748
+		at := v.Type()
749
+		if at.Elem().Kind() == reflect.Uint8 {
750
+			// Special case for []byte
751
+			if tok.value[0] != '"' && tok.value[0] != '\'' {
752
+				// Deliberately written out here, as the error after
753
+				// this switch statement would write "invalid []byte: ...",
754
+				// which is not as user-friendly.
755
+				return p.errorf("invalid string: %v", tok.value)
756
+			}
757
+			bytes := []byte(tok.unquoted)
758
+			fv.Set(reflect.ValueOf(bytes))
759
+			return nil
760
+		}
761
+		// Repeated field.
762
+		if tok.value == "[" {
763
+			// Repeated field with list notation, like [1,2,3].
764
+			for {
765
+				fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
766
+				err := p.readAny(fv.Index(fv.Len()-1), props)
767
+				if err != nil {
768
+					return err
769
+				}
770
+				tok := p.next()
771
+				if tok.err != nil {
772
+					return tok.err
773
+				}
774
+				if tok.value == "]" {
775
+					break
776
+				}
777
+				if tok.value != "," {
778
+					return p.errorf("Expected ']' or ',' found %q", tok.value)
779
+				}
780
+			}
781
+			return nil
782
+		}
783
+		// One value of the repeated field.
784
+		p.back()
785
+		fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
786
+		return p.readAny(fv.Index(fv.Len()-1), props)
787
+	case reflect.Bool:
788
+		// true/1/t/True or false/f/0/False.
789
+		switch tok.value {
790
+		case "true", "1", "t", "True":
791
+			fv.SetBool(true)
792
+			return nil
793
+		case "false", "0", "f", "False":
794
+			fv.SetBool(false)
795
+			return nil
796
+		}
797
+	case reflect.Float32, reflect.Float64:
798
+		v := tok.value
799
+		// Ignore 'f' for compatibility with output generated by C++, but don't
800
+		// remove 'f' when the value is "-inf" or "inf".
801
+		if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
802
+			v = v[:len(v)-1]
803
+		}
804
+		if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
805
+			fv.SetFloat(f)
806
+			return nil
807
+		}
808
+	case reflect.Int32:
809
+		if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
810
+			fv.SetInt(x)
811
+			return nil
812
+		}
813
+
814
+		if len(props.Enum) == 0 {
815
+			break
816
+		}
817
+		m, ok := enumValueMaps[props.Enum]
818
+		if !ok {
819
+			break
820
+		}
821
+		x, ok := m[tok.value]
822
+		if !ok {
823
+			break
824
+		}
825
+		fv.SetInt(int64(x))
826
+		return nil
827
+	case reflect.Int64:
828
+		if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
829
+			fv.SetInt(x)
830
+			return nil
831
+		}
832
+
833
+	case reflect.Ptr:
834
+		// A basic field (indirected through pointer), or a repeated message/group
835
+		p.back()
836
+		fv.Set(reflect.New(fv.Type().Elem()))
837
+		return p.readAny(fv.Elem(), props)
838
+	case reflect.String:
839
+		if tok.value[0] == '"' || tok.value[0] == '\'' {
840
+			fv.SetString(tok.unquoted)
841
+			return nil
842
+		}
843
+	case reflect.Struct:
844
+		var terminator string
845
+		switch tok.value {
846
+		case "{":
847
+			terminator = "}"
848
+		case "<":
849
+			terminator = ">"
850
+		default:
851
+			return p.errorf("expected '{' or '<', found %q", tok.value)
852
+		}
853
+		// TODO: Handle nested messages which implement encoding.TextUnmarshaler.
854
+		return p.readStruct(fv, terminator)
855
+	case reflect.Uint32:
856
+		if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
857
+			fv.SetUint(uint64(x))
858
+			return nil
859
+		}
860
+	case reflect.Uint64:
861
+		if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
862
+			fv.SetUint(x)
863
+			return nil
864
+		}
865
+	}
866
+	return p.errorf("invalid %v: %v", v.Type(), tok.value)
867
+}
868
+
869
+// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
870
+// before starting to unmarshal, so any existing data in pb is always removed.
871
+// If a required field is not set and no other error occurs,
872
+// UnmarshalText returns *RequiredNotSetError.
873
+func UnmarshalText(s string, pb Message) error {
874
+	if um, ok := pb.(encoding.TextUnmarshaler); ok {
875
+		return um.UnmarshalText([]byte(s))
876
+	}
877
+	pb.Reset()
878
+	v := reflect.ValueOf(pb)
879
+	return newTextParser(s).readStruct(v.Elem(), "")
880
+}

+ 25
- 0
log/vendor/github.com/gorilla/websocket/.gitignore View File

@@ -0,0 +1,25 @@
1
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
2
+*.o
3
+*.a
4
+*.so
5
+
6
+# Folders
7
+_obj
8
+_test
9
+
10
+# Architecture specific extensions/prefixes
11
+*.[568vq]
12
+[568vq].out
13
+
14
+*.cgo1.go
15
+*.cgo2.c
16
+_cgo_defun.c
17
+_cgo_gotypes.go
18
+_cgo_export.*
19
+
20
+_testmain.go
21
+
22
+*.exe
23
+
24
+.idea/
25
+*.iml

+ 19
- 0
log/vendor/github.com/gorilla/websocket/.travis.yml View File

@@ -0,0 +1,19 @@
1
+language: go
2
+sudo: false
3
+
4
+matrix:
5
+  include:
6
+    - go: 1.4
7
+    - go: 1.5
8
+    - go: 1.6
9
+    - go: 1.7
10
+    - go: 1.8
11
+    - go: tip
12
+  allow_failures:
13
+    - go: tip
14
+
15
+script:
16
+  - go get -t -v ./...
17
+  - diff -u <(echo -n) <(gofmt -d .)
18
+  - go vet $(go list ./... | grep -v /vendor/)
19
+  - go test -v -race ./...

+ 8
- 0
log/vendor/github.com/gorilla/websocket/AUTHORS View File

@@ -0,0 +1,8 @@
1
+# This is the official list of Gorilla WebSocket authors for copyright
2
+# purposes.
3
+#
4
+# Please keep the list sorted.
5
+
6
+Gary Burd <gary@beagledreams.com>
7
+Joachim Bauch <mail@joachim-bauch.de>
8
+

+ 22
- 0
log/vendor/github.com/gorilla/websocket/LICENSE View File

@@ -0,0 +1,22 @@
1
+Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved.
2
+
3
+Redistribution and use in source and binary forms, with or without
4
+modification, are permitted provided that the following conditions are met:
5
+
6
+  Redistributions of source code must retain the above copyright notice, this
7
+  list of conditions and the following disclaimer.
8
+
9
+  Redistributions in binary form must reproduce the above copyright notice,
10
+  this list of conditions and the following disclaimer in the documentation
11
+  and/or other materials provided with the distribution.
12
+
13
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
17
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
20
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
21
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
22
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 64
- 0
log/vendor/github.com/gorilla/websocket/README.md View File

@@ -0,0 +1,64 @@
1
+# Gorilla WebSocket
2
+
3
+Gorilla WebSocket is a [Go](http://golang.org/) implementation of the
4
+[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol.
5
+
6
+[![Build Status](https://travis-ci.org/gorilla/websocket.svg?branch=master)](https://travis-ci.org/gorilla/websocket)
7
+[![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket)
8
+
9
+### Documentation
10
+
11
+* [API Reference](http://godoc.org/github.com/gorilla/websocket)
12
+* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat)
13
+* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command)
14
+* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo)
15
+* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch)
16
+
17
+### Status
18
+
19
+The Gorilla WebSocket package provides a complete and tested implementation of
20
+the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The
21
+package API is stable.
22
+
23
+### Installation
24
+
25
+    go get github.com/gorilla/websocket
26
+
27
+### Protocol Compliance
28
+
29
+The Gorilla WebSocket package passes the server tests in the [Autobahn Test
30
+Suite](http://autobahn.ws/testsuite) using the application in the [examples/autobahn
31
+subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn).
32
+
33
+### Gorilla WebSocket compared with other packages
34
+
35
+<table>
36
+<tr>
37
+<th></th>
38
+<th><a href="http://godoc.org/github.com/gorilla/websocket">github.com/gorilla</a></th>
39
+<th><a href="http://godoc.org/golang.org/x/net/websocket">golang.org/x/net</a></th>
40
+</tr>
41
+<tr>
42
+<tr><td colspan="3"><a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a> Features</td></tr>
43
+<tr><td>Passes <a href="http://autobahn.ws/testsuite/">Autobahn Test Suite</a></td><td><a href="https://github.com/gorilla/websocket/tree/master/examples/autobahn">Yes</a></td><td>No</td></tr>
44
+<tr><td>Receive <a href="https://tools.ietf.org/html/rfc6455#section-5.4">fragmented</a> message<td>Yes</td><td><a href="https://code.google.com/p/go/issues/detail?id=7632">No</a>, see note 1</td></tr>
45
+<tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1">close</a> message</td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td><a href="https://code.google.com/p/go/issues/detail?id=4588">No</a></td></tr>
46
+<tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.2">pings</a> and receive <a href="https://tools.ietf.org/html/rfc6455#section-5.5.3">pongs</a></td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td>No</td></tr>
47
+<tr><td>Get the <a href="https://tools.ietf.org/html/rfc6455#section-5.6">type</a> of a received data message</td><td>Yes</td><td>Yes, see note 2</td></tr>
48
+<tr><td colspan="3">Other Features</tr></td>
49
+<tr><td><a href="https://tools.ietf.org/html/rfc7692">Compression Extensions</a></td><td>Experimental</td><td>No</td></tr>
50
+<tr><td>Read message using io.Reader</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextReader">Yes</a></td><td>No, see note 3</td></tr>
51
+<tr><td>Write message using io.WriteCloser</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextWriter">Yes</a></td><td>No, see note 3</td></tr>
52
+</table>
53
+
54
+Notes: 
55
+
56
+1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html).
57
+2. The application can get the type of a received data message by implementing
58
+   a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal)
59
+   function.
60
+3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries.
61
+  Read returns when the input buffer is full or a frame boundary is
62
+  encountered. Each call to Write sends a single frame message. The Gorilla
63
+  io.Reader and io.WriteCloser operate on a single WebSocket message.
64
+

+ 392
- 0
log/vendor/github.com/gorilla/websocket/client.go View File

@@ -0,0 +1,392 @@
1
+// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+package websocket
6
+
7
+import (
8
+	"bufio"
9
+	"bytes"
10
+	"crypto/tls"
11
+	"encoding/base64"
12
+	"errors"
13
+	"io"
14
+	"io/ioutil"
15
+	"net"
16
+	"net/http"
17
+	"net/url"
18
+	"strings"
19
+	"time"
20
+)
21
+
22
+// ErrBadHandshake is returned when the server response to opening handshake is
23
+// invalid.
24
+var ErrBadHandshake = errors.New("websocket: bad handshake")
25
+
26
+var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
27
+
28
+// NewClient creates a new client connection using the given net connection.
29
+// The URL u specifies the host and request URI. Use requestHeader to specify
30
+// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
31
+// (Cookie). Use the response.Header to get the selected subprotocol
32
+// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
33
+//
34
+// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
35
+// non-nil *http.Response so that callers can handle redirects, authentication,
36
+// etc.
37
+//
38
+// Deprecated: Use Dialer instead.
39
+func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
40
+	d := Dialer{
41
+		ReadBufferSize:  readBufSize,
42
+		WriteBufferSize: writeBufSize,
43
+		NetDial: func(net, addr string) (net.Conn, error) {
44
+			return netConn, nil
45
+		},
46
+	}
47
+	return d.Dial(u.String(), requestHeader)
48
+}
49
+
50
+// A Dialer contains options for connecting to WebSocket server.
51
+type Dialer struct {
52
+	// NetDial specifies the dial function for creating TCP connections. If
53
+	// NetDial is nil, net.Dial is used.
54
+	NetDial func(network, addr string) (net.Conn, error)
55
+
56
+	// Proxy specifies a function to return a proxy for a given
57
+	// Request. If the function returns a non-nil error, the
58
+	// request is aborted with the provided error.
59
+	// If Proxy is nil or returns a nil *URL, no proxy is used.
60
+	Proxy func(*http.Request) (*url.URL, error)
61
+
62
+	// TLSClientConfig specifies the TLS configuration to use with tls.Client.
63
+	// If nil, the default configuration is used.
64
+	TLSClientConfig *tls.Config
65
+
66
+	// HandshakeTimeout specifies the duration for the handshake to complete.
67
+	HandshakeTimeout time.Duration
68
+
69
+	// ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
70
+	// size is zero, then a useful default size is used. The I/O buffer sizes
71
+	// do not limit the size of the messages that can be sent or received.
72
+	ReadBufferSize, WriteBufferSize int
73
+
74
+	// Subprotocols specifies the client's requested subprotocols.
75
+	Subprotocols []string
76
+
77
+	// EnableCompression specifies if the client should attempt to negotiate
78
+	// per message compression (RFC 7692). Setting this value to true does not
79
+	// guarantee that compression will be supported. Currently only "no context
80
+	// takeover" modes are supported.
81
+	EnableCompression bool
82
+
83
+	// Jar specifies the cookie jar.
84
+	// If Jar is nil, cookies are not sent in requests and ignored
85
+	// in responses.
86
+	Jar http.CookieJar
87
+}
88
+
89
+var errMalformedURL = errors.New("malformed ws or wss URL")
90
+
91
+// parseURL parses the URL.
92
+//
93
+// This function is a replacement for the standard library url.Parse function.
94
+// In Go 1.4 and earlier, url.Parse loses information from the path.
95
+func parseURL(s string) (*url.URL, error) {
96
+	// From the RFC:
97
+	//
98
+	// ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
99
+	// wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
100
+	var u url.URL
101
+	switch {
102
+	case strings.HasPrefix(s, "ws://"):
103
+		u.Scheme = "ws"
104
+		s = s[len("ws://"):]
105
+	case strings.HasPrefix(s, "wss://"):
106
+		u.Scheme = "wss"
107
+		s = s[len("wss://"):]
108
+	default:
109
+		return nil, errMalformedURL
110
+	}
111
+
112
+	if i := strings.Index(s, "?"); i >= 0 {
113
+		u.RawQuery = s[i+1:]
114
+		s = s[:i]
115
+	}
116
+
117
+	if i := strings.Index(s, "/"); i >= 0 {
118
+		u.Opaque = s[i:]
119
+		s = s[:i]
120
+	} else {
121
+		u.Opaque = "/"
122
+	}
123
+
124
+	u.Host = s
125
+
126
+	if strings.Contains(u.Host, "@") {
127
+		// Don't bother parsing user information because user information is
128
+		// not allowed in websocket URIs.
129
+		return nil, errMalformedURL
130
+	}
131
+
132
+	return &u, nil
133
+}
134
+
135
+func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
136
+	hostPort = u.Host
137
+	hostNoPort = u.Host
138
+	if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
139
+		hostNoPort = hostNoPort[:i]
140
+	} else {
141
+		switch u.Scheme {
142
+		case "wss":
143
+			hostPort += ":443"
144
+		case "https":
145
+			hostPort += ":443"
146
+		default:
147
+			hostPort += ":80"
148
+		}
149
+	}
150
+	return hostPort, hostNoPort
151
+}
152
+
153
+// DefaultDialer is a dialer with all fields set to the default zero values.
154
+var DefaultDialer = &Dialer{
155
+	Proxy: http.ProxyFromEnvironment,
156
+}
157
+
158
+// Dial creates a new client connection. Use requestHeader to specify the
159
+// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
160
+// Use the response.Header to get the selected subprotocol
161
+// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
162
+//
163
+// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
164
+// non-nil *http.Response so that callers can handle redirects, authentication,
165
+// etcetera. The response body may not contain the entire response and does not
166
+// need to be closed by the application.
167
+func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
168
+
169
+	if d == nil {
170
+		d = &Dialer{
171
+			Proxy: http.ProxyFromEnvironment,
172
+		}
173
+	}
174
+
175
+	challengeKey, err := generateChallengeKey()
176
+	if err != nil {
177
+		return nil, nil, err
178
+	}
179
+
180
+	u, err := parseURL(urlStr)
181
+	if err != nil {
182
+		return nil, nil, err
183
+	}
184
+
185
+	switch u.Scheme {
186
+	case "ws":
187
+		u.Scheme = "http"
188
+	case "wss":
189
+		u.Scheme = "https"
190
+	default:
191
+		return nil, nil, errMalformedURL
192
+	}
193
+
194
+	if u.User != nil {
195
+		// User name and password are not allowed in websocket URIs.
196
+		return nil, nil, errMalformedURL
197
+	}
198
+
199
+	req := &http.Request{
200
+		Method:     "GET",
201
+		URL:        u,
202
+		Proto:      "HTTP/1.1",
203
+		ProtoMajor: 1,
204
+		ProtoMinor: 1,
205
+		Header:     make(http.Header),
206
+		Host:       u.Host,
207
+	}
208
+
209
+	// Set the cookies present in the cookie jar of the dialer
210
+	if d.Jar != nil {
211
+		for _, cookie := range d.Jar.Cookies(u) {
212
+			req.AddCookie(cookie)
213
+		}
214
+	}
215
+
216
+	// Set the request headers using the capitalization for names and values in
217
+	// RFC examples. Although the capitalization shouldn't matter, there are
218
+	// servers that depend on it. The Header.Set method is not used because the
219
+	// method canonicalizes the header names.
220
+	req.Header["Upgrade"] = []string{"websocket"}
221
+	req.Header["Connection"] = []string{"Upgrade"}
222
+	req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
223
+	req.Header["Sec-WebSocket-Version"] = []string{"13"}
224
+	if len(d.Subprotocols) > 0 {
225
+		req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
226
+	}
227
+	for k, vs := range requestHeader {
228
+		switch {
229
+		case k == "Host":
230
+			if len(vs) > 0 {
231
+				req.Host = vs[0]
232
+			}
233
+		case k == "Upgrade" ||
234
+			k == "Connection" ||
235
+			k == "Sec-Websocket-Key" ||
236
+			k == "Sec-Websocket-Version" ||
237
+			k == "Sec-Websocket-Extensions" ||
238
+			(k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
239
+			return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
240
+		default:
241
+			req.Header[k] = vs
242
+		}
243
+	}
244
+
245
+	if d.EnableCompression {
246
+		req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover")
247
+	}
248
+
249
+	hostPort, hostNoPort := hostPortNoPort(u)
250
+
251
+	var proxyURL *url.URL
252
+	// Check wether the proxy method has been configured
253
+	if d.Proxy != nil {
254
+		proxyURL, err = d.Proxy(req)
255
+	}
256
+	if err != nil {
257
+		return nil, nil, err
258
+	}
259
+
260
+	var targetHostPort string
261
+	if proxyURL != nil {
262
+		targetHostPort, _ = hostPortNoPort(proxyURL)
263
+	} else {
264
+		targetHostPort = hostPort
265
+	}
266
+
267
+	var deadline time.Time
268
+	if d.HandshakeTimeout != 0 {
269
+		deadline = time.Now().Add(d.HandshakeTimeout)
270
+	}
271
+
272
+	netDial := d.NetDial
273
+	if netDial == nil {
274
+		netDialer := &net.Dialer{Deadline: deadline}
275
+		netDial = netDialer.Dial
276
+	}
277
+
278
+	netConn, err := netDial("tcp", targetHostPort)
279
+	if err != nil {
280
+		return nil, nil, err
281
+	}
282
+
283
+	defer func() {
284
+		if netConn != nil {
285
+			netConn.Close()
286
+		}
287
+	}()
288
+
289
+	if err := netConn.SetDeadline(deadline); err != nil {
290
+		return nil, nil, err
291
+	}
292
+
293
+	if proxyURL != nil {
294
+		connectHeader := make(http.Header)
295
+		if user := proxyURL.User; user != nil {
296
+			proxyUser := user.Username()
297
+			if proxyPassword, passwordSet := user.Password(); passwordSet {
298
+				credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword))
299
+				connectHeader.Set("Proxy-Authorization", "Basic "+credential)
300
+			}
301
+		}
302
+		connectReq := &http.Request{
303
+			Method: "CONNECT",
304
+			URL:    &url.URL{Opaque: hostPort},
305
+			Host:   hostPort,
306
+			Header: connectHeader,
307
+		}
308
+
309
+		connectReq.Write(netConn)
310
+
311
+		// Read response.
312
+		// Okay to use and discard buffered reader here, because
313
+		// TLS server will not speak until spoken to.
314
+		br := bufio.NewReader(netConn)
315
+		resp, err := http.ReadResponse(br, connectReq)
316
+		if err != nil {
317
+			return nil, nil, err
318
+		}
319
+		if resp.StatusCode != 200 {
320
+			f := strings.SplitN(resp.Status, " ", 2)
321
+			return nil, nil, errors.New(f[1])
322
+		}
323
+	}
324
+
325
+	if u.Scheme == "https" {
326
+		cfg := cloneTLSConfig(d.TLSClientConfig)
327
+		if cfg.ServerName == "" {
328
+			cfg.ServerName = hostNoPort
329
+		}
330
+		tlsConn := tls.Client(netConn, cfg)
331
+		netConn = tlsConn
332
+		if err := tlsConn.Handshake(); err != nil {
333
+			return nil, nil, err
334
+		}
335
+		if !cfg.InsecureSkipVerify {
336
+			if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
337
+				return nil, nil, err
338
+			}
339
+		}
340
+	}
341
+
342
+	conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize)
343
+
344
+	if err := req.Write(netConn); err != nil {
345
+		return nil, nil, err
346
+	}
347
+
348
+	resp, err := http.ReadResponse(conn.br, req)
349
+	if err != nil {
350
+		return nil, nil, err
351
+	}
352
+
353
+	if d.Jar != nil {
354
+		if rc := resp.Cookies(); len(rc) > 0 {
355
+			d.Jar.SetCookies(u, rc)
356
+		}
357
+	}
358
+
359
+	if resp.StatusCode != 101 ||
360
+		!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
361
+		!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
362
+		resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
363
+		// Before closing the network connection on return from this
364
+		// function, slurp up some of the response to aid application
365
+		// debugging.
366
+		buf := make([]byte, 1024)
367
+		n, _ := io.ReadFull(resp.Body, buf)
368
+		resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
369
+		return nil, resp, ErrBadHandshake
370
+	}
371
+
372
+	for _, ext := range parseExtensions(resp.Header) {
373
+		if ext[""] != "permessage-deflate" {
374
+			continue
375
+		}
376
+		_, snct := ext["server_no_context_takeover"]
377
+		_, cnct := ext["client_no_context_takeover"]
378
+		if !snct || !cnct {
379
+			return nil, resp, errInvalidCompression
380
+		}
381
+		conn.newCompressionWriter = compressNoContextTakeover
382
+		conn.newDecompressionReader = decompressNoContextTakeover
383
+		break
384
+	}
385
+
386
+	resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
387
+	conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
388
+
389
+	netConn.SetDeadline(time.Time{})
390
+	netConn = nil // to avoid close in defer.
391
+	return conn, resp, nil
392
+}

+ 16
- 0
log/vendor/github.com/gorilla/websocket/client_clone.go View File

@@ -0,0 +1,16 @@
1
+// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+// +build go1.8
6
+
7
+package websocket
8
+
9
+import "crypto/tls"
10
+
11
+func cloneTLSConfig(cfg *tls.Config) *tls.Config {
12
+	if cfg == nil {
13
+		return &tls.Config{}
14
+	}
15
+	return cfg.Clone()
16
+}

+ 38
- 0
log/vendor/github.com/gorilla/websocket/client_clone_legacy.go View File

@@ -0,0 +1,38 @@
1
+// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+// +build !go1.8
6
+
7
+package websocket
8
+
9
+import "crypto/tls"
10
+
11
+// cloneTLSConfig clones all public fields except the fields
12
+// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
13
+// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
14
+// config in active use.
15
+func cloneTLSConfig(cfg *tls.Config) *tls.Config {
16
+	if cfg == nil {
17
+		return &tls.Config{}
18
+	}
19
+	return &tls.Config{
20
+		Rand:                     cfg.Rand,
21
+		Time:                     cfg.Time,
22
+		Certificates:             cfg.Certificates,
23
+		NameToCertificate:        cfg.NameToCertificate,
24
+		GetCertificate:           cfg.GetCertificate,
25
+		RootCAs:                  cfg.RootCAs,
26
+		NextProtos:               cfg.NextProtos,
27
+		ServerName:               cfg.ServerName,
28
+		ClientAuth:               cfg.ClientAuth,
29
+		ClientCAs:                cfg.ClientCAs,
30
+		InsecureSkipVerify:       cfg.InsecureSkipVerify,
31
+		CipherSuites:             cfg.CipherSuites,
32
+		PreferServerCipherSuites: cfg.PreferServerCipherSuites,
33
+		ClientSessionCache:       cfg.ClientSessionCache,
34
+		MinVersion:               cfg.MinVersion,
35
+		MaxVersion:               cfg.MaxVersion,
36
+		CurvePreferences:         cfg.CurvePreferences,
37
+	}
38
+}

+ 148
- 0
log/vendor/github.com/gorilla/websocket/compression.go View File

@@ -0,0 +1,148 @@
1
+// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+package websocket
6
+
7
+import (
8
+	"compress/flate"
9
+	"errors"
10
+	"io"
11
+	"strings"
12
+	"sync"
13
+)
14
+
15
+const (
16
+	minCompressionLevel     = -2 // flate.HuffmanOnly not defined in Go < 1.6
17
+	maxCompressionLevel     = flate.BestCompression
18
+	defaultCompressionLevel = 1
19
+)
20
+
21
+var (
22
+	flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
23
+	flateReaderPool  = sync.Pool{New: func() interface{} {
24
+		return flate.NewReader(nil)
25
+	}}
26
+)
27
+
28
+func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
29
+	const tail =
30
+	// Add four bytes as specified in RFC
31
+	"\x00\x00\xff\xff" +
32
+		// Add final block to squelch unexpected EOF error from flate reader.
33
+		"\x01\x00\x00\xff\xff"
34
+
35
+	fr, _ := flateReaderPool.Get().(io.ReadCloser)
36
+	fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil)
37
+	return &flateReadWrapper{fr}
38
+}
39
+
40
+func isValidCompressionLevel(level int) bool {
41
+	return minCompressionLevel <= level && level <= maxCompressionLevel
42
+}
43
+
44
+func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
45
+	p := &flateWriterPools[level-minCompressionLevel]
46
+	tw := &truncWriter{w: w}
47
+	fw, _ := p.Get().(*flate.Writer)
48
+	if fw == nil {
49
+		fw, _ = flate.NewWriter(tw, level)
50
+	} else {
51
+		fw.Reset(tw)
52
+	}
53
+	return &flateWriteWrapper{fw: fw, tw: tw, p: p}
54
+}
55
+
56
+// truncWriter is an io.Writer that writes all but the last four bytes of the
57
+// stream to another io.Writer.
58
+type truncWriter struct {
59
+	w io.WriteCloser
60
+	n int
61
+	p [4]byte
62
+}
63
+
64
+func (w *truncWriter) Write(p []byte) (int, error) {
65
+	n := 0
66
+
67
+	// fill buffer first for simplicity.
68
+	if w.n < len(w.p) {
69
+		n = copy(w.p[w.n:], p)
70
+		p = p[n:]
71
+		w.n += n
72
+		if len(p) == 0 {
73
+			return n, nil
74
+		}
75
+	}
76
+
77
+	m := len(p)
78
+	if m > len(w.p) {
79
+		m = len(w.p)
80
+	}
81
+
82
+	if nn, err := w.w.Write(w.p[:m]); err != nil {
83
+		return n + nn, err
84
+	}
85
+
86
+	copy(w.p[:], w.p[m:])
87
+	copy(w.p[len(w.p)-m:], p[len(p)-m:])
88
+	nn, err := w.w.Write(p[:len(p)-m])
89
+	return n + nn, err
90
+}
91
+
92
+type flateWriteWrapper struct {
93
+	fw *flate.Writer
94
+	tw *truncWriter
95
+	p  *sync.Pool
96
+}
97
+
98
+func (w *flateWriteWrapper) Write(p []byte) (int, error) {
99
+	if w.fw == nil {
100
+		return 0, errWriteClosed
101
+	}
102
+	return w.fw.Write(p)
103
+}
104
+
105
+func (w *flateWriteWrapper) Close() error {
106
+	if w.fw == nil {
107
+		return errWriteClosed
108
+	}
109
+	err1 := w.fw.Flush()
110
+	w.p.Put(w.fw)
111
+	w.fw = nil
112
+	if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
113
+		return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
114
+	}
115
+	err2 := w.tw.w.Close()
116
+	if err1 != nil {
117
+		return err1
118
+	}
119
+	return err2
120
+}
121
+
122
+type flateReadWrapper struct {
123
+	fr io.ReadCloser
124
+}
125
+
126
+func (r *flateReadWrapper) Read(p []byte) (int, error) {
127
+	if r.fr == nil {
128
+		return 0, io.ErrClosedPipe
129
+	}
130
+	n, err := r.fr.Read(p)
131
+	if err == io.EOF {
132
+		// Preemptively place the reader back in the pool. This helps with
133
+		// scenarios where the application does not call NextReader() soon after
134
+		// this final read.
135
+		r.Close()
136
+	}
137
+	return n, err
138
+}
139
+
140
+func (r *flateReadWrapper) Close() error {
141
+	if r.fr == nil {
142
+		return io.ErrClosedPipe
143
+	}
144
+	err := r.fr.Close()
145
+	flateReaderPool.Put(r.fr)
146
+	r.fr = nil
147
+	return err
148
+}

+ 1149
- 0
log/vendor/github.com/gorilla/websocket/conn.go
File diff suppressed because it is too large
View File


+ 18
- 0
log/vendor/github.com/gorilla/websocket/conn_read.go View File

@@ -0,0 +1,18 @@
1
+// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+// +build go1.5
6
+
7
+package websocket
8
+
9
+import "io"
10
+
11
+func (c *Conn) read(n int) ([]byte, error) {
12
+	p, err := c.br.Peek(n)
13
+	if err == io.EOF {
14
+		err = errUnexpectedEOF
15
+	}
16
+	c.br.Discard(len(p))
17
+	return p, err
18
+}

+ 21
- 0
log/vendor/github.com/gorilla/websocket/conn_read_legacy.go View File

@@ -0,0 +1,21 @@
1
+// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+// +build !go1.5
6
+
7
+package websocket
8
+
9
+import "io"
10
+
11
+func (c *Conn) read(n int) ([]byte, error) {
12
+	p, err := c.br.Peek(n)
13
+	if err == io.EOF {
14
+		err = errUnexpectedEOF
15
+	}
16
+	if len(p) > 0 {
17
+		// advance over the bytes just read
18
+		io.ReadFull(c.br, p)
19
+	}
20
+	return p, err
21
+}

+ 180
- 0
log/vendor/github.com/gorilla/websocket/doc.go View File

@@ -0,0 +1,180 @@
1
+// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+// Package websocket implements the WebSocket protocol defined in RFC 6455.
6
+//
7
+// Overview
8
+//
9
+// The Conn type represents a WebSocket connection. A server application uses
10
+// the Upgrade function from an Upgrader object with a HTTP request handler
11
+// to get a pointer to a Conn:
12
+//
13
+//  var upgrader = websocket.Upgrader{
14
+//      ReadBufferSize:  1024,
15
+//      WriteBufferSize: 1024,
16
+//  }
17
+//
18
+//  func handler(w http.ResponseWriter, r *http.Request) {
19
+//      conn, err := upgrader.Upgrade(w, r, nil)
20
+//      if err != nil {
21
+//          log.Println(err)
22
+//          return
23
+//      }
24
+//      ... Use conn to send and receive messages.
25
+//  }
26
+//
27
+// Call the connection's WriteMessage and ReadMessage methods to send and
28
+// receive messages as a slice of bytes. This snippet of code shows how to echo
29
+// messages using these methods:
30
+//
31
+//  for {
32
+//      messageType, p, err := conn.ReadMessage()
33
+//      if err != nil {
34
+//          return
35
+//      }
36
+//      if err = conn.WriteMessage(messageType, p); err != nil {
37
+//          return err
38
+//      }
39
+//  }
40
+//
41
+// In above snippet of code, p is a []byte and messageType is an int with value
42
+// websocket.BinaryMessage or websocket.TextMessage.
43
+//
44
+// An application can also send and receive messages using the io.WriteCloser
45
+// and io.Reader interfaces. To send a message, call the connection NextWriter
46
+// method to get an io.WriteCloser, write the message to the writer and close
47
+// the writer when done. To receive a message, call the connection NextReader
48
+// method to get an io.Reader and read until io.EOF is returned. This snippet
49
+// shows how to echo messages using the NextWriter and NextReader methods:
50
+//
51
+//  for {
52
+//      messageType, r, err := conn.NextReader()
53
+//      if err != nil {
54
+//          return
55
+//      }
56
+//      w, err := conn.NextWriter(messageType)
57
+//      if err != nil {
58
+//          return err
59
+//      }
60
+//      if _, err := io.Copy(w, r); err != nil {
61
+//          return err
62
+//      }
63
+//      if err := w.Close(); err != nil {
64
+//          return err
65
+//      }
66
+//  }
67
+//
68
+// Data Messages
69
+//
70
+// The WebSocket protocol distinguishes between text and binary data messages.
71
+// Text messages are interpreted as UTF-8 encoded text. The interpretation of
72
+// binary messages is left to the application.
73
+//
74
+// This package uses the TextMessage and BinaryMessage integer constants to
75
+// identify the two data message types. The ReadMessage and NextReader methods
76
+// return the type of the received message. The messageType argument to the
77
+// WriteMessage and NextWriter methods specifies the type of a sent message.
78
+//
79
+// It is the application's responsibility to ensure that text messages are
80
+// valid UTF-8 encoded text.
81
+//
82
+// Control Messages
83
+//
84
+// The WebSocket protocol defines three types of control messages: close, ping
85
+// and pong. Call the connection WriteControl, WriteMessage or NextWriter
86
+// methods to send a control message to the peer.
87
+//
88
+// Connections handle received close messages by sending a close message to the
89
+// peer and returning a *CloseError from the the NextReader, ReadMessage or the
90
+// message Read method.
91
+//
92
+// Connections handle received ping and pong messages by invoking callback
93
+// functions set with SetPingHandler and SetPongHandler methods. The callback
94
+// functions are called from the NextReader, ReadMessage and the message Read
95
+// methods.
96
+//
97
+// The default ping handler sends a pong to the peer. The application's reading
98
+// goroutine can block for a short time while the handler writes the pong data
99
+// to the connection.
100
+//
101
+// The application must read the connection to process ping, pong and close
102
+// messages sent from the peer. If the application is not otherwise interested
103
+// in messages from the peer, then the application should start a goroutine to
104
+// read and discard messages from the peer. A simple example is:
105
+//
106
+//  func readLoop(c *websocket.Conn) {
107
+//      for {
108
+//          if _, _, err := c.NextReader(); err != nil {
109
+//              c.Close()
110
+//              break
111
+//          }
112
+//      }
113
+//  }
114
+//
115
+// Concurrency
116
+//
117
+// Connections support one concurrent reader and one concurrent writer.
118
+//
119
+// Applications are responsible for ensuring that no more than one goroutine
120
+// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage,
121
+// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and
122
+// that no more than one goroutine calls the read methods (NextReader,
123
+// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler)
124
+// concurrently.
125
+//
126
+// The Close and WriteControl methods can be called concurrently with all other
127
+// methods.
128
+//
129
+// Origin Considerations
130
+//
131
+// Web browsers allow Javascript applications to open a WebSocket connection to
132
+// any host. It's up to the server to enforce an origin policy using the Origin
133
+// request header sent by the browser.
134
+//
135
+// The Upgrader calls the function specified in the CheckOrigin field to check
136
+// the origin. If the CheckOrigin function returns false, then the Upgrade
137
+// method fails the WebSocket handshake with HTTP status 403.
138
+//
139
+// If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail
140
+// the handshake if the Origin request header is present and not equal to the
141
+// Host request header.
142
+//
143
+// An application can allow connections from any origin by specifying a
144
+// function that always returns true:
145
+//
146
+//  var upgrader = websocket.Upgrader{
147
+//      CheckOrigin: func(r *http.Request) bool { return true },
148
+//  }
149
+//
150
+// The deprecated Upgrade function does not enforce an origin policy. It's the
151
+// application's responsibility to check the Origin header before calling
152
+// Upgrade.
153
+//
154
+// Compression EXPERIMENTAL
155
+//
156
+// Per message compression extensions (RFC 7692) are experimentally supported
157
+// by this package in a limited capacity. Setting the EnableCompression option
158
+// to true in Dialer or Upgrader will attempt to negotiate per message deflate
159
+// support.
160
+//
161
+//  var upgrader = websocket.Upgrader{
162
+//      EnableCompression: true,
163
+//  }
164
+//
165
+// If compression was successfully negotiated with the connection's peer, any
166
+// message received in compressed form will be automatically decompressed.
167
+// All Read methods will return uncompressed bytes.
168
+//
169
+// Per message compression of messages written to a connection can be enabled
170
+// or disabled by calling the corresponding Conn method:
171
+//
172
+//  conn.EnableWriteCompression(false)
173
+//
174
+// Currently this package does not support compression with "context takeover".
175
+// This means that messages must be compressed and decompressed in isolation,
176
+// without retaining sliding window or dictionary state across messages. For
177
+// more details refer to RFC 7692.
178
+//
179
+// Use of compression is experimental and may result in decreased performance.
180
+package websocket

+ 55
- 0
log/vendor/github.com/gorilla/websocket/json.go View File

@@ -0,0 +1,55 @@
1
+// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2
+// Use of this source code is governed by a BSD-style
3
+// license that can be found in the LICENSE file.
4
+
5
+package websocket
6
+
7
+import (
8
+	"encoding/json"
9
+	"io"
10
+)
11
+
12
+// WriteJSON is deprecated, use c.WriteJSON instead.
13
+func WriteJSON(c *Conn, v interface{}) error {
14
+	return c.WriteJSON(v)
15
+}
16
+
17
+// WriteJSON writes the JSON encoding of v to the connection.
18
+//
19
+// See the documentation for encoding/json Marshal for details about the
20
+// conversion of Go values to JSON.
21
+func (c *Conn) WriteJSON(v interface{}) error {
22
+	w, err := c.NextWriter(TextMessage)
23
+	if err != nil {
24
+		return err
25
+	}
26
+	err1 := json.NewEncoder(w).Encode(v)
27
+	err2 := w.Close()
28
+	if err1 != nil {
29
+		return err1
30
+	}
31
+	return err2
32
+}
33
+
34
+// ReadJSON is deprecated, use c.ReadJSON instead.
35
+func ReadJSON(c *Conn, v interface{}) error {
36
+	return c.ReadJSON(v)
37
+}
38
+
39
+// ReadJSON reads the next JSON-encoded message from the connection and stores
40
+// it in the value pointed to by v.
41
+//
42
+// See the documentation for the encoding/json Unmarshal function for details
43
+// about the conversion of JSON to a Go value.
44
+func (c *Conn) ReadJSON(v interface{}) error {
45
+	_, r, err := c.NextReader()
46
+	if err != nil {
47
+		return err
48
+	}
49
+	err = json.NewDecoder(r).Decode(v)
50
+	if err == io.EOF {
51
+		// One value is expected in the message.
52
+		err = io.ErrUnexpectedEOF
53
+	}
54
+	return err
55
+}

+ 0
- 0
log/vendor/github.com/gorilla/websocket/mask.go View File


Some files were not shown because too many files changed in this diff