vendor: update grpc

This commit is contained in:
Cadey Ratio 2017-09-30 09:47:47 -07:00
parent 1883feaacc
commit db341f4c0d
No known key found for this signature in database
GPG Key ID: D607EE27C2E7F89A
794 changed files with 407794 additions and 6497 deletions

View File

@ -0,0 +1,58 @@
package server
import (
"git.xeserv.us/xena/route/lib/tun2"
proto "git.xeserv.us/xena/route/proto"
"golang.org/x/net/context"
)
// Backend implements proto.BackendsServer for gRPC.
type Backend struct {
*Server
}
// List returns a list of backends given filtering parameters.
func (b *Backend) List(ctx context.Context, sel *proto.BackendSelector) (*proto.BackendList, error) {
bl := map[string]tun2.Backend{}
switch {
case sel.Domain != "":
for _, bk := range b.ts.GetBackendsForDomain(sel.Domain) {
bl[bk.ID] = bk
}
case sel.User != "":
for _, bk := range b.ts.GetBackendsForUser(sel.User) {
bl[bk.ID] = bk
}
default:
for _, bk := range b.ts.GetAllBackends() {
bl[bk.ID] = bk
}
}
resp := &proto.BackendList{
Bs: sel,
}
for _, bk := range bl {
resp.Backends = append(resp.Backends, &proto.Backend{
Id: bk.ID,
Proto: bk.Proto,
User: bk.User,
Domain: bk.Domain,
Phi: bk.Phi,
Host: bk.Host,
})
}
return resp, nil
}
// Kill removes a backend's connection by ID.
func (b *Backend) Kill(ctx context.Context, bid *proto.BackendID) (*proto.Nil, error) {
if err := b.ts.KillBackend(bid.Id); err != nil {
return nil, err
}
return &proto.Nil{}, nil
}

View File

@ -19,7 +19,7 @@ var (
func (s *Server) getAuth(ctx context.Context, scope string) (database.Token, error) {
var err error
md, ok := metadata.FromContext(ctx)
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
}

View File

@ -96,6 +96,7 @@ func New(cfg Config) (*Server, error) {
InsecureSkipVerify: true,
})))
proto.RegisterBackendsServer(gs, &Backend{Server: s})
proto.RegisterRoutesServer(gs, &Route{Server: s})
proto.RegisterTokensServer(gs, &Token{Server: s})

11
lib/tun2/backend.go Normal file
View File

@ -0,0 +1,11 @@
package tun2
// Backend is the public state of an individual Connection.
type Backend struct {
ID string
Proto string
User string
Domain string
Phi float32
Host string
}

View File

@ -77,6 +77,67 @@ func NewServer(cfg *ServerConfig) (*Server, error) {
return server, nil
}
type backendMatcher func(*Connection) bool
func (s *Server) getBackendsForMatcher(bm backendMatcher) []Backend {
s.connlock.Lock()
defer s.connlock.Unlock()
var result []Backend
for _, c := range s.conns {
if !bm(c) {
continue
}
protocol := "tcp"
if c.isKCP {
protocol = "kcp"
}
result = append(result, Backend{
ID: c.id,
Proto: protocol,
User: c.user,
Domain: c.domain,
Phi: float32(c.detector.Phi(time.Now())),
Host: c.conn.RemoteAddr().String(),
})
}
return result
}
func (s *Server) KillBackend(id string) error {
s.connlock.Lock()
defer s.connlock.Unlock()
for _, c := range s.conns {
if c.id == id {
c.cancel()
return nil
}
}
return ErrNoSuchBackend
}
func (s *Server) GetBackendsForDomain(domain string) []Backend {
return s.getBackendsForMatcher(func(c *Connection) bool {
return c.domain == domain
})
}
func (s *Server) GetBackendsForUser(uname string) []Backend {
return s.getBackendsForMatcher(func(c *Connection) bool {
return c.user == uname
})
}
func (s *Server) GetAllBackends() []Backend {
return s.getBackendsForMatcher(func(*Connection) bool { return true })
}
// ListenAndServe starts the backend TCP/KCP listeners and relays backend
// traffic to and from them.
func (s *Server) ListenAndServe() error {

View File

@ -6,14 +6,14 @@ protoc -I/usr/local/include -I. \
--go_out=Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api,plugins=grpc:. \
route.proto
protoc -I/usr/local/include -I. \
-I$GOPATH/src \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--grpc-gateway_out=logtostderr=true:. \
route.proto
# protoc -I/usr/local/include -I. \
# -I$GOPATH/src \
# -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
# --grpc-gateway_out=logtostderr=true:. \
# route.proto
protoc -I/usr/local/include -I. \
-I$GOPATH/src \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--swagger_out=logtostderr=true:. \
route.proto
# protoc -I/usr/local/include -I. \
# -I$GOPATH/src \
# -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
# --swagger_out=logtostderr=true:. \
# route.proto

View File

@ -27,7 +27,6 @@ package route
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"
import (
context "golang.org/x/net/context"
@ -815,48 +814,40 @@ var _Backends_serviceDesc = grpc.ServiceDesc{
func init() { proto.RegisterFile("route.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 674 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0xcd, 0x6e, 0xd3, 0x4c,
0x14, 0x95, 0xed, 0xd8, 0x4d, 0x6e, 0xaa, 0xb4, 0xbd, 0x5f, 0xbe, 0x60, 0xd2, 0x82, 0xa2, 0x11,
0xa0, 0xa8, 0x8b, 0x1a, 0x82, 0x00, 0x81, 0x60, 0x01, 0xb8, 0x94, 0x0a, 0x54, 0x21, 0x97, 0x1d,
0x2b, 0x27, 0x1e, 0xb5, 0xa3, 0x1a, 0x4f, 0xc8, 0x4c, 0x2a, 0xa1, 0xaa, 0x0b, 0x78, 0x05, 0x56,
0xf0, 0x30, 0xbc, 0x04, 0xaf, 0xc0, 0x83, 0x20, 0xcf, 0x8c, 0x13, 0x3b, 0xe6, 0x67, 0x37, 0x77,
0xe6, 0x9e, 0xeb, 0x73, 0xce, 0x9c, 0x31, 0xb4, 0x67, 0x7c, 0x2e, 0xe9, 0xde, 0x74, 0xc6, 0x25,
0x47, 0x57, 0x15, 0xfd, 0x9d, 0x13, 0xce, 0x4f, 0x52, 0x1a, 0xc4, 0x53, 0x16, 0xc4, 0x59, 0xc6,
0x65, 0x2c, 0x19, 0xcf, 0x84, 0x6e, 0x22, 0x2e, 0x38, 0x47, 0x2c, 0x25, 0x37, 0x61, 0xe3, 0x80,
0xca, 0x28, 0x07, 0x44, 0xf4, 0xc3, 0x9c, 0x0a, 0x89, 0x08, 0x8d, 0x53, 0x2e, 0xa4, 0x6f, 0x0d,
0xac, 0x61, 0x2b, 0x52, 0x6b, 0xb2, 0x0f, 0xae, 0xea, 0xc1, 0x0e, 0xd8, 0x2c, 0x31, 0x47, 0x36,
0x4b, 0xd0, 0x87, 0xb5, 0xc9, 0x8c, 0xc6, 0x92, 0xcf, 0x7c, 0x5b, 0x6d, 0x16, 0xe5, 0x62, 0x8c,
0x53, 0x1a, 0xf3, 0x18, 0xba, 0x07, 0x54, 0x3e, 0x4d, 0x53, 0x35, 0x4c, 0x44, 0x54, 0x4c, 0x79,
0x26, 0x28, 0xde, 0x00, 0x4f, 0x71, 0x16, 0xbe, 0x35, 0x70, 0x86, 0xed, 0xd1, 0xfa, 0x9e, 0xd6,
0xa3, 0x79, 0x99, 0x33, 0xb2, 0x03, 0x70, 0x18, 0x2e, 0x30, 0x2b, 0x4c, 0xc8, 0x3b, 0x70, 0xdf,
0xf2, 0x33, 0x9a, 0xd5, 0x28, 0x22, 0x34, 0xc6, 0x3c, 0xf9, 0x68, 0xf8, 0xa9, 0x35, 0xf6, 0xc0,
0x13, 0x13, 0x3e, 0xa5, 0xc2, 0x77, 0x06, 0xce, 0xb0, 0x15, 0x99, 0x2a, 0xdf, 0x8f, 0x27, 0x92,
0x9d, 0x53, 0xbf, 0x31, 0xb0, 0x86, 0xcd, 0xc8, 0x54, 0xe4, 0x36, 0x34, 0xd5, 0xf0, 0x63, 0x2a,
0x73, 0xb2, 0x32, 0x5f, 0xaf, 0x92, 0x55, 0x0d, 0x91, 0x39, 0x23, 0x0f, 0x94, 0xb1, 0x7a, 0xcf,
0x18, 0xdb, 0x05, 0x57, 0x1d, 0x1a, 0x6e, 0xba, 0x30, 0x74, 0xed, 0x85, 0x8e, 0x4f, 0x16, 0xac,
0x3d, 0x8b, 0x27, 0x67, 0x34, 0x4b, 0x6a, 0x52, 0xba, 0xe0, 0xaa, 0xdb, 0x33, 0xed, 0xba, 0xc8,
0x05, 0xce, 0x05, 0x9d, 0x15, 0x4e, 0xe7, 0xeb, 0x5c, 0x48, 0xc2, 0xdf, 0xc7, 0x2c, 0x53, 0x42,
0x5a, 0x91, 0xa9, 0x70, 0x13, 0x9c, 0xe9, 0x29, 0xf3, 0xdd, 0x81, 0x35, 0xb4, 0xa3, 0x7c, 0xb9,
0xb8, 0x27, 0xaf, 0x74, 0x4f, 0x31, 0xb4, 0x0d, 0x85, 0xd7, 0x4c, 0x48, 0xbc, 0x05, 0xf6, 0x58,
0x28, 0x1a, 0xed, 0x51, 0xcf, 0xa8, 0x35, 0xe7, 0xc7, 0x34, 0xa5, 0x13, 0xc9, 0x67, 0x91, 0x3d,
0x16, 0xb8, 0x0b, 0xcd, 0xb1, 0xde, 0x16, 0xbe, 0xad, 0xbc, 0xe9, 0x54, 0xbb, 0xa3, 0xc5, 0x39,
0x79, 0x02, 0x1b, 0x2b, 0x23, 0x4a, 0x9c, 0xad, 0x0a, 0xe7, 0x42, 0x9f, 0xbd, 0xd4, 0x47, 0xb6,
0xa1, 0x65, 0xe0, 0x87, 0xe1, 0xaa, 0x4d, 0xa3, 0xaf, 0x36, 0x78, 0x3a, 0x61, 0xf8, 0x02, 0x9c,
0x03, 0x2a, 0xb1, 0x60, 0xbd, 0x92, 0xf5, 0x7e, 0x25, 0x68, 0xe4, 0xea, 0xe7, 0x1f, 0x3f, 0xbf,
0xd8, 0xff, 0xe1, 0x56, 0x70, 0x7e, 0x27, 0xd0, 0xa1, 0x0b, 0x2e, 0x72, 0x43, 0x2e, 0x71, 0x1f,
0x3c, 0x9d, 0x5c, 0x04, 0x03, 0x39, 0x62, 0x69, 0x7f, 0x7b, 0x39, 0xb6, 0x16, 0x6a, 0x82, 0x6a,
0xda, 0x3a, 0xc2, 0x72, 0x1a, 0x3e, 0x02, 0xe7, 0xcd, 0x5c, 0x62, 0xe5, 0xb3, 0xfd, 0x2d, 0x53,
0x2d, 0xc3, 0x5d, 0x60, 0x49, 0x19, 0x1b, 0x82, 0x17, 0xd2, 0x94, 0x4a, 0xfa, 0x6f, 0xb8, 0x11,
0xb2, 0x5b, 0x17, 0x32, 0xfa, 0x6e, 0x83, 0xa7, 0x52, 0x29, 0xf0, 0x79, 0xcd, 0x9b, 0x72, 0x5c,
0xfb, 0x95, 0x5c, 0x93, 0x9e, 0x1a, 0xb9, 0x89, 0x9d, 0x7c, 0xa4, 0xce, 0x78, 0xc0, 0x33, 0x8a,
0x0f, 0x7f, 0x6b, 0xcc, 0x46, 0x19, 0x7b, 0x4c, 0x65, 0xd5, 0x0c, 0x0d, 0xc7, 0x7b, 0x55, 0x33,
0x54, 0xef, 0xca, 0x57, 0x2b, 0x3e, 0x18, 0xd8, 0xfd, 0x9a, 0x0f, 0x1a, 0x59, 0xfa, 0x7e, 0x81,
0xdb, 0x2d, 0xe3, 0xf6, 0x01, 0x42, 0xaa, 0xde, 0x73, 0xfc, 0x57, 0xec, 0x35, 0x85, 0xbd, 0x42,
0xfe, 0x2f, 0x29, 0x4d, 0x16, 0xc0, 0xd1, 0x37, 0x0b, 0x9a, 0x26, 0x7a, 0x02, 0x5f, 0x42, 0x43,
0xbd, 0x90, 0x3f, 0xbc, 0x8a, 0x3e, 0x56, 0xf7, 0xf3, 0x5e, 0xd2, 0x55, 0xf3, 0x3b, 0xb8, 0x9e,
0xcf, 0x2f, 0xde, 0x03, 0x86, 0xd0, 0x78, 0xc5, 0xd2, 0x14, 0x37, 0xab, 0x88, 0xc3, 0xb0, 0xc2,
0xed, 0xba, 0xc2, 0xfa, 0xa4, 0x57, 0xc6, 0x06, 0x17, 0x2c, 0xb9, 0x0c, 0xce, 0x58, 0x9a, 0x8e,
0x3d, 0xf5, 0x47, 0xb8, 0xfb, 0x2b, 0x00, 0x00, 0xff, 0xff, 0xaf, 0x50, 0x50, 0x47, 0x10, 0x06,
0x00, 0x00,
// 553 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x53, 0x4f, 0x6f, 0xd3, 0x4e,
0x10, 0xf5, 0x9f, 0xd8, 0x4d, 0x26, 0x3f, 0x35, 0xfd, 0x8d, 0xa2, 0xca, 0x4a, 0x39, 0x44, 0x4b,
0x29, 0x16, 0x88, 0x0a, 0xa5, 0x48, 0x5c, 0xe0, 0x00, 0x0a, 0x8a, 0x22, 0x50, 0x85, 0x36, 0xdc,
0x38, 0x39, 0xc9, 0x48, 0xb1, 0x6a, 0xb2, 0xc1, 0xbb, 0x41, 0xe2, 0xc8, 0x67, 0xe3, 0x33, 0xf0,
0x7d, 0x90, 0xc7, 0x9b, 0xc4, 0x8e, 0x0b, 0xe2, 0xb6, 0x33, 0xef, 0xed, 0xf8, 0xbd, 0xd9, 0x67,
0xe8, 0xe6, 0x6a, 0x6b, 0xe8, 0x7a, 0x93, 0x2b, 0xa3, 0x30, 0xe0, 0x42, 0x04, 0xe0, 0xdf, 0xa6,
0x99, 0x78, 0x04, 0xbd, 0x09, 0x19, 0x59, 0xb4, 0x24, 0x7d, 0xdd, 0x92, 0x36, 0x88, 0xd0, 0x5a,
0x29, 0x6d, 0x22, 0x77, 0xe8, 0xc6, 0x1d, 0xc9, 0x67, 0xf1, 0x0e, 0x02, 0xe6, 0xe0, 0x29, 0x78,
0xe9, 0xd2, 0x42, 0x5e, 0xba, 0xc4, 0x08, 0x4e, 0x16, 0x39, 0x25, 0x46, 0xe5, 0x91, 0xc7, 0xcd,
0x5d, 0xb9, 0x1f, 0xe3, 0x57, 0xc6, 0xbc, 0x82, 0xfe, 0x84, 0xcc, 0x9b, 0x2c, 0xe3, 0x61, 0x5a,
0x92, 0xde, 0xa8, 0xb5, 0x26, 0xbc, 0x84, 0x90, 0x55, 0xe9, 0xc8, 0x1d, 0xfa, 0x71, 0x77, 0xf4,
0xdf, 0x75, 0xa9, 0xb8, 0xd4, 0x65, 0x31, 0xf1, 0x00, 0x60, 0x3a, 0xde, 0xdf, 0x39, 0x52, 0x22,
0x3e, 0x43, 0xf0, 0x49, 0xdd, 0xd1, 0xba, 0x21, 0x11, 0xa1, 0x35, 0x57, 0xcb, 0xef, 0x56, 0x1f,
0x9f, 0xf1, 0x1c, 0x42, 0xbd, 0x50, 0x1b, 0xd2, 0x91, 0x3f, 0xf4, 0xe3, 0x8e, 0xb4, 0x55, 0xd1,
0x4f, 0x16, 0x26, 0xfd, 0x46, 0x51, 0x6b, 0xe8, 0xc6, 0x6d, 0x69, 0x2b, 0xf1, 0x1c, 0xda, 0x3c,
0x7c, 0x46, 0xa6, 0x10, 0x6b, 0x8a, 0xf3, 0xb1, 0x58, 0x26, 0x48, 0x8b, 0x89, 0x97, 0xbc, 0xd8,
0xb2, 0x67, 0x17, 0xdb, 0x87, 0x80, 0x41, 0xab, 0xad, 0x2c, 0xac, 0x5c, 0x6f, 0xef, 0xe3, 0x87,
0x0b, 0x27, 0x6f, 0x93, 0xc5, 0x1d, 0xad, 0x97, 0x0d, 0x2b, 0x7d, 0x08, 0xf8, 0x11, 0x2d, 0xbd,
0x2c, 0x0a, 0x83, 0x5b, 0x4d, 0xf9, 0x6e, 0xd3, 0xc5, 0xb9, 0x30, 0xb2, 0x54, 0x5f, 0x92, 0x74,
0xcd, 0x46, 0x3a, 0xd2, 0x56, 0x78, 0x06, 0xfe, 0x66, 0x95, 0x46, 0xc1, 0xd0, 0x8d, 0x3d, 0x59,
0x1c, 0xf7, 0xef, 0x14, 0x56, 0xde, 0x29, 0x81, 0xae, 0x95, 0xf0, 0x21, 0xd5, 0x06, 0xaf, 0xc0,
0x9b, 0x6b, 0x96, 0xd1, 0x1d, 0x9d, 0x5b, 0xb7, 0x16, 0x9f, 0x51, 0x46, 0x0b, 0xa3, 0x72, 0xe9,
0xcd, 0x35, 0x3e, 0x81, 0xf6, 0xbc, 0x6c, 0xeb, 0xc8, 0xe3, 0xdd, 0x9c, 0xd6, 0xd9, 0x72, 0x8f,
0x8b, 0xd7, 0xd0, 0x3b, 0x1a, 0x51, 0xd1, 0xec, 0xd6, 0x34, 0xef, 0xfc, 0x79, 0x07, 0x7f, 0xe2,
0x02, 0x3a, 0xf6, 0xfa, 0x74, 0x7c, 0xbc, 0xa6, 0xd1, 0x4f, 0x17, 0xc2, 0x32, 0x61, 0xf8, 0x0c,
0xfc, 0x09, 0x19, 0xdc, 0xa9, 0x3e, 0xca, 0xfa, 0xa0, 0x16, 0x34, 0xe1, 0xe0, 0x0d, 0x84, 0x65,
0x40, 0x11, 0x2c, 0x72, 0x9b, 0x66, 0x83, 0x8b, 0xc3, 0xed, 0x46, 0x76, 0x85, 0x83, 0x31, 0xf8,
0x1f, 0xb7, 0x06, 0x6b, 0xb3, 0x06, 0xff, 0xdb, 0xea, 0x90, 0x58, 0xe1, 0xe0, 0x53, 0x08, 0xc7,
0x94, 0x91, 0xa1, 0x7f, 0x20, 0x8f, 0x7e, 0xb9, 0x10, 0x72, 0x7e, 0xee, 0x73, 0x51, 0x0d, 0xd6,
0xa0, 0x96, 0x40, 0xe1, 0xe0, 0xe3, 0x7b, 0x5d, 0xf4, 0xaa, 0xac, 0x19, 0x19, 0xe1, 0xe0, 0xc3,
0xba, 0x72, 0x46, 0x1a, 0xd3, 0x2e, 0x1b, 0xa2, 0x4b, 0x5e, 0x65, 0x36, 0x2f, 0x01, 0xc6, 0xc4,
0x7f, 0x4b, 0xf2, 0x77, 0xe6, 0x68, 0x05, 0x6d, 0xfb, 0x74, 0x1a, 0x5f, 0x40, 0x8b, 0x13, 0xf6,
0x87, 0x54, 0x0d, 0xb0, 0xde, 0x2f, 0xb8, 0xc2, 0xc1, 0x2b, 0x68, 0xbd, 0x4f, 0xb3, 0x0c, 0xcf,
0xea, 0xe8, 0x74, 0x5c, 0xff, 0xd2, 0x3c, 0xe4, 0xff, 0xe3, 0xe6, 0x77, 0x00, 0x00, 0x00, 0xff,
0xff, 0x11, 0x4c, 0x9d, 0x1a, 0x00, 0x05, 0x00, 0x00,
}

View File

@ -1,712 +0,0 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: route.proto
/*
Package route is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package route
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
func request_Routes_Get_0(ctx context.Context, marshaler runtime.Marshaler, client RoutesClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetRouteRequest
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["host"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "host")
}
protoReq.Host, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "host", err)
}
msg, err := client.Get(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_Routes_GetAll_0(ctx context.Context, marshaler runtime.Marshaler, client RoutesClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Nil
var metadata runtime.ServerMetadata
msg, err := client.GetAll(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_Routes_Put_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_Routes_Put_0(ctx context.Context, marshaler runtime.Marshaler, client RoutesClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Route
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_Routes_Put_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Put(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_Routes_Delete_0 = &utilities.DoubleArray{Encoding: map[string]int{"host": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}}
)
func request_Routes_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client RoutesClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Route
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["host"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "host")
}
protoReq.Host, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "host", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_Routes_Delete_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_Tokens_Get_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_Tokens_Get_0(ctx context.Context, marshaler runtime.Marshaler, client TokensClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetTokenRequest
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_Tokens_Get_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Get(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_Tokens_GetAll_0(ctx context.Context, marshaler runtime.Marshaler, client TokensClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Nil
var metadata runtime.ServerMetadata
msg, err := client.GetAll(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_Tokens_Put_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_Tokens_Put_0(ctx context.Context, marshaler runtime.Marshaler, client TokensClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Token
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_Tokens_Put_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Put(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_Tokens_Delete_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_Tokens_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client TokensClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Token
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_Tokens_Delete_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_Tokens_Deactivate_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_Tokens_Deactivate_0(ctx context.Context, marshaler runtime.Marshaler, client TokensClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq Token
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_Tokens_Deactivate_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Deactivate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_Backends_List_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_Backends_List_0(ctx context.Context, marshaler runtime.Marshaler, client BackendsClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BackendSelector
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_Backends_List_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.List(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_Backends_Kill_0(ctx context.Context, marshaler runtime.Marshaler, client BackendsClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BackendID
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["id"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id")
}
protoReq.Id, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err)
}
msg, err := client.Kill(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
// RegisterRoutesHandlerFromEndpoint is same as RegisterRoutesHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterRoutesHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterRoutesHandler(ctx, mux, conn)
}
// RegisterRoutesHandler registers the http handlers for service Routes to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterRoutesHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
client := NewRoutesClient(conn)
mux.Handle("GET", pattern_Routes_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Routes_Get_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Routes_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Routes_GetAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Routes_GetAll_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Routes_GetAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Routes_Put_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Routes_Put_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Routes_Put_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("DELETE", pattern_Routes_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Routes_Delete_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Routes_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_Routes_Get_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"v1", "routes", "host"}, ""))
pattern_Routes_GetAll_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "routes"}, ""))
pattern_Routes_Put_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "routes"}, ""))
pattern_Routes_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"v1", "routes", "host"}, ""))
)
var (
forward_Routes_Get_0 = runtime.ForwardResponseMessage
forward_Routes_GetAll_0 = runtime.ForwardResponseMessage
forward_Routes_Put_0 = runtime.ForwardResponseMessage
forward_Routes_Delete_0 = runtime.ForwardResponseMessage
)
// RegisterTokensHandlerFromEndpoint is same as RegisterTokensHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterTokensHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterTokensHandler(ctx, mux, conn)
}
// RegisterTokensHandler registers the http handlers for service Tokens to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterTokensHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
client := NewTokensClient(conn)
mux.Handle("GET", pattern_Tokens_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Tokens_Get_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Tokens_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Tokens_GetAll_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Tokens_GetAll_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Tokens_GetAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Tokens_Put_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Tokens_Put_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Tokens_Put_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("DELETE", pattern_Tokens_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Tokens_Delete_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Tokens_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Tokens_Deactivate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Tokens_Deactivate_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Tokens_Deactivate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_Tokens_Get_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "tokens", "one"}, ""))
pattern_Tokens_GetAll_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "tokens"}, ""))
pattern_Tokens_Put_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "tokens"}, ""))
pattern_Tokens_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "tokens"}, ""))
pattern_Tokens_Deactivate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "tokens", "deactivate"}, ""))
)
var (
forward_Tokens_Get_0 = runtime.ForwardResponseMessage
forward_Tokens_GetAll_0 = runtime.ForwardResponseMessage
forward_Tokens_Put_0 = runtime.ForwardResponseMessage
forward_Tokens_Delete_0 = runtime.ForwardResponseMessage
forward_Tokens_Deactivate_0 = runtime.ForwardResponseMessage
)
// RegisterBackendsHandlerFromEndpoint is same as RegisterBackendsHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterBackendsHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterBackendsHandler(ctx, mux, conn)
}
// RegisterBackendsHandler registers the http handlers for service Backends to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterBackendsHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
client := NewBackendsClient(conn)
mux.Handle("GET", pattern_Backends_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Backends_List_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Backends_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_Backends_Kill_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_Backends_Kill_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Backends_Kill_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_Backends_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "backends"}, ""))
pattern_Backends_Kill_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"v1", "backends", "id", "kill"}, ""))
)
var (
forward_Backends_List_0 = runtime.ForwardResponseMessage
forward_Backends_Kill_0 = runtime.ForwardResponseMessage
)

View File

@ -4,33 +4,33 @@ syntax = "proto3";
package route;
import "google/api/annotations.proto";
// import "google/api/annotations.proto";
message Nil {}
service Routes {
rpc Get(GetRouteRequest) returns (Route) {
option (google.api.http) = {
get: "/v1/routes/{host}"
};
// option (google.api.http) = {
// get: "/v1/routes/{host}"
// };
}
rpc GetAll(Nil) returns (GetAllRoutesResponse) {
option (google.api.http) = {
get: "/v1/routes"
};
// option (google.api.http) = {
// get: "/v1/routes"
// };
}
rpc Put(Route) returns (IDResponse) {
option (google.api.http) = {
post: "/v1/routes"
};
// option (google.api.http) = {
// post: "/v1/routes"
// };
}
rpc Delete(Route) returns (IDResponse) {
option (google.api.http) = {
delete: "/v1/routes/{host}"
};
// option (google.api.http) = {
// delete: "/v1/routes/{host}"
// };
}
}
@ -54,33 +54,33 @@ message IDResponse {
service Tokens {
rpc Get(GetTokenRequest) returns (Token) {
option (google.api.http) = {
get: "/v1/tokens/one"
};
// option (google.api.http) = {
// get: "/v1/tokens/one"
// };
}
rpc GetAll(Nil) returns (TokenSet) {
option (google.api.http) = {
get: "/v1/tokens"
};
// option (google.api.http) = {
// get: "/v1/tokens"
// };
}
rpc Put(Token) returns (Token) {
option (google.api.http) = {
post: "/v1/tokens"
};
// option (google.api.http) = {
// post: "/v1/tokens"
// };
}
rpc Delete(Token) returns (Nil) {
option (google.api.http) = {
delete: "/v1/tokens"
};
// option (google.api.http) = {
// delete: "/v1/tokens"
// };
}
rpc Deactivate(Token) returns (Nil) {
option (google.api.http) = {
post: "/v1/tokens/deactivate"
};
// option (google.api.http) = {
// post: "/v1/tokens/deactivate"
// };
}
}
@ -102,15 +102,15 @@ message GetTokenRequest {
service Backends {
rpc List(BackendSelector) returns (BackendList) {
option (google.api.http) = {
get: "/v1/backends"
};
// option (google.api.http) = {
// get: "/v1/backends"
// };
}
rpc Kill(BackendID) returns (Nil) {
option (google.api.http) = {
post: "/v1/backends/{id}/kill"
};
// option (google.api.http) = {
// post: "/v1/backends/{id}/kill"
// };
}
}

View File

@ -1,358 +0,0 @@
{
"swagger": "2.0",
"info": {
"title": "route.proto",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/v1/backends": {
"get": {
"operationId": "List",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeBackendList"
}
}
},
"parameters": [
{
"name": "domain",
"in": "query",
"required": false,
"type": "string"
},
{
"name": "user",
"in": "query",
"required": false,
"type": "string"
}
],
"tags": [
"Backends"
]
}
},
"/v1/backends/{id}/kill": {
"post": {
"operationId": "Kill",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeNil"
}
}
},
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"Backends"
]
}
},
"/v1/routes": {
"get": {
"operationId": "GetAll",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeGetAllRoutesResponse"
}
}
},
"tags": [
"Routes"
]
},
"post": {
"operationId": "Put",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeIDResponse"
}
}
},
"tags": [
"Routes"
]
}
},
"/v1/routes/{host}": {
"get": {
"operationId": "Get",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeRoute"
}
}
},
"parameters": [
{
"name": "host",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"Routes"
]
},
"delete": {
"operationId": "Delete",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeIDResponse"
}
}
},
"parameters": [
{
"name": "host",
"in": "path",
"required": true,
"type": "string"
}
],
"tags": [
"Routes"
]
}
},
"/v1/tokens": {
"get": {
"operationId": "GetAll",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeTokenSet"
}
}
},
"tags": [
"Tokens"
]
},
"delete": {
"operationId": "Delete",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeNil"
}
}
},
"tags": [
"Tokens"
]
},
"post": {
"operationId": "Put",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeToken"
}
}
},
"tags": [
"Tokens"
]
}
},
"/v1/tokens/deactivate": {
"post": {
"operationId": "Deactivate",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeNil"
}
}
},
"tags": [
"Tokens"
]
}
},
"/v1/tokens/one": {
"get": {
"operationId": "Get",
"responses": {
"200": {
"description": "",
"schema": {
"$ref": "#/definitions/routeToken"
}
}
},
"parameters": [
{
"name": "token",
"in": "query",
"required": false,
"type": "string"
},
{
"name": "id",
"in": "query",
"required": false,
"type": "string"
}
],
"tags": [
"Tokens"
]
}
}
},
"definitions": {
"routeBackend": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"proto": {
"type": "string"
},
"user": {
"type": "string"
},
"domain": {
"type": "string"
},
"phi": {
"type": "number",
"format": "float"
},
"host": {
"type": "string"
}
}
},
"routeBackendList": {
"type": "object",
"properties": {
"bs": {
"$ref": "#/definitions/routeBackendSelector"
},
"backends": {
"type": "array",
"items": {
"$ref": "#/definitions/routeBackend"
}
}
}
},
"routeBackendSelector": {
"type": "object",
"properties": {
"domain": {
"type": "string"
},
"user": {
"type": "string"
}
}
},
"routeGetAllRoutesResponse": {
"type": "object",
"properties": {
"routes": {
"type": "array",
"items": {
"$ref": "#/definitions/routeRoute"
}
}
}
},
"routeIDResponse": {
"type": "object",
"properties": {
"id": {
"type": "string"
}
}
},
"routeNil": {
"type": "object"
},
"routeRoute": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"creator": {
"type": "string"
},
"host": {
"type": "string"
}
}
},
"routeToken": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"body": {
"type": "string"
},
"scopes": {
"type": "array",
"items": {
"type": "string"
}
},
"active": {
"type": "boolean",
"format": "boolean"
}
}
},
"routeTokenSet": {
"type": "object",
"properties": {
"tokens": {
"type": "array",
"items": {
"$ref": "#/definitions/routeToken"
}
}
}
}
}
}

View File

@ -137,3 +137,189 @@ da118f7b8e5954f39d0d2130ab35d4bf0e3cb344 golang.org/x/net/context
a3b3ca73af22dd09dfac218f586a8f42c681298d github.com/Xe/ln
c605e284fe17294bda444b34710735b29d1a9d90 github.com/pkg/errors
3abb44dfc7ba8b5cdfdb634786f57e78c7004e1c github.com/jtolds/qod
8351a756f30f1297fe94bbf4b767ec589c6ea6d0 golang.org/x/net/context
8351a756f30f1297fe94bbf4b767ec589c6ea6d0 golang.org/x/net/context/ctxhttp
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/proto
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/any
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/duration
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/timestamp
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/context
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2/hpack
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/idna
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/internal/timeseries
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/lex/httplex
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/trace
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/secure/bidirule
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/transform
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/bidi
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/norm
1e559d0a00eef8a9a43151db4665280bd8dd5886 google.golang.org/genproto/googleapis/rpc/status
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/balancer
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/codes
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/connectivity
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/credentials
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/grpclb/grpc_lb_v1/messages
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/grpclog
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/internal
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/keepalive
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/metadata
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/naming
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/peer
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/resolver
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/stats
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/status
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/tap
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/transport
9ac9c42358f7c3c69ac9f8610e8790d7c338e85d github.com/go-resty/resty
23def4e6c14b4da8ac2ed8007337bc5eb5007998 github.com/golang/glog
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/jsonpb
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/proto
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/protoc-gen-go/descriptor
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/protoc-gen-go/generator
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/protoc-gen-go/plugin
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/any
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/duration
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/empty
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/struct
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/timestamp
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples/examplepb
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples/server
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples/server/cmd/example-server
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples/sub
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/examples/sub2
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/runtime
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/runtime/internal
8bec008bd140852468324fdd069ed8e38d37a963 github.com/grpc-ecosystem/grpc-gateway/utilities
6724a57986aff9bff1a1770e9347036def7c89f6 github.com/rogpeppe/fastuuid
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/context
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2/hpack
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/idna
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/internal/timeseries
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/lex/httplex
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/publicsuffix
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/trace
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/secure/bidirule
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/transform
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/bidi
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/norm
1e559d0a00eef8a9a43151db4665280bd8dd5886 google.golang.org/genproto/googleapis/api/annotations
1e559d0a00eef8a9a43151db4665280bd8dd5886 google.golang.org/genproto/googleapis/rpc/status
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/balancer
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/codes
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/connectivity
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/credentials
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/grpclb/grpc_lb_v1/messages
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/grpclog
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/internal
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/keepalive
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/metadata
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/naming
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/peer
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/resolver
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/stats
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/status
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/tap
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/transport
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/context
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/context/ctxhttp
7d9177d70076375b9a59c8fde23d52d9c4a7ecd5 golang.org/x/crypto/ssh/terminal
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/bpf
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/context
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/context/ctxhttp
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/dict
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/dns/dnsmessage
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/html
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/html/atom
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/html/charset
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2/h2i
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2/hpack
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/icmp
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/idna
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/internal/iana
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/internal/nettest
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/internal/socket
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/internal/timeseries
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/ipv4
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/ipv6
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/lex/httplex
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/nettest
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/netutil
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/proxy
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/publicsuffix
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/route
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/trace
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/webdav
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/webdav/internal/xml
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/websocket
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/xsrftoken
b6e1ae21643682ce023deb8d152024597b0e9bb4 golang.org/x/sys/unix
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/charmap
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/htmlindex
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/internal
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/internal/identifier
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/japanese
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/korean
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/simplifiedchinese
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/traditionalchinese
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/encoding/unicode
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/internal/tag
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/internal/utf8internal
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/language
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/runes
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/secure/bidirule
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/transform
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/bidi
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/norm
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/grpclog
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/proto
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/any
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/duration
130e6b02ab059e7b717a096f397c5b60111cae74 github.com/golang/protobuf/ptypes/timestamp
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/context
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/http2/hpack
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/idna
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/internal/timeseries
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/lex/httplex
0a9397675ba34b2845f758fe3cd68828369c6517 golang.org/x/net/trace
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/secure/bidirule
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/transform
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/bidi
1cbadb444a806fd9430d14ad08967ed91da4fa0a golang.org/x/text/unicode/norm
1e559d0a00eef8a9a43151db4665280bd8dd5886 google.golang.org/genproto/googleapis/rpc/status
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/balancer
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/codes
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/connectivity
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/credentials
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/grpclb/grpc_lb_v1/messages
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/grpclog
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/internal
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/keepalive
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/metadata
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/naming
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/peer
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/resolver
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/stats
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/status
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/tap
8443e311d3925f5e20494496790670942ed48504 google.golang.org/grpc/transport

824
vendor/github.com/go-resty/resty/client.go generated vendored Normal file
View File

@ -0,0 +1,824 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"bytes"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"reflect"
"regexp"
"strings"
"sync"
"time"
)
const (
// MethodGet HTTP method
MethodGet = "GET"
// MethodPost HTTP method
MethodPost = "POST"
// MethodPut HTTP method
MethodPut = "PUT"
// MethodDelete HTTP method
MethodDelete = "DELETE"
// MethodPatch HTTP method
MethodPatch = "PATCH"
// MethodHead HTTP method
MethodHead = "HEAD"
// MethodOptions HTTP method
MethodOptions = "OPTIONS"
)
var (
hdrUserAgentKey = http.CanonicalHeaderKey("User-Agent")
hdrAcceptKey = http.CanonicalHeaderKey("Accept")
hdrContentTypeKey = http.CanonicalHeaderKey("Content-Type")
hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length")
hdrAuthorizationKey = http.CanonicalHeaderKey("Authorization")
plainTextType = "text/plain; charset=utf-8"
jsonContentType = "application/json; charset=utf-8"
formContentType = "application/x-www-form-urlencoded"
jsonCheck = regexp.MustCompile("(?i:[application|text]/json)")
xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)")
hdrUserAgentValue = "go-resty v%s - https://github.com/go-resty/resty"
bufPool = &sync.Pool{New: func() interface{} { return &bytes.Buffer{} }}
)
// Client type is used for HTTP/RESTful global values
// for all request raised from the client
type Client struct {
HostURL string
QueryParam url.Values
FormData url.Values
Header http.Header
UserInfo *User
Token string
Cookies []*http.Cookie
Error reflect.Type
Debug bool
DisableWarn bool
AllowGetMethodPayload bool
Log *log.Logger
RetryCount int
RetryWaitTime time.Duration
RetryMaxWaitTime time.Duration
RetryConditions []RetryConditionFunc
JSONMarshal func(v interface{}) ([]byte, error)
JSONUnmarshal func(data []byte, v interface{}) error
httpClient *http.Client
setContentLength bool
isHTTPMode bool
outputDirectory string
scheme string
proxyURL *url.URL
closeConnection bool
notParseResponse bool
beforeRequest []func(*Client, *Request) error
udBeforeRequest []func(*Client, *Request) error
preReqHook func(*Client, *Request) error
afterResponse []func(*Client, *Response) error
}
// User type is to hold an username and password information
type User struct {
Username, Password string
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Client methods
//___________________________________
// SetHostURL method is to set Host URL in the client instance. It will be used with request
// raised from this client with relative URL
// // Setting HTTP address
// resty.SetHostURL("http://myjeeva.com")
//
// // Setting HTTPS address
// resty.SetHostURL("https://myjeeva.com")
//
func (c *Client) SetHostURL(url string) *Client {
c.HostURL = strings.TrimRight(url, "/")
return c
}
// SetHeader method sets a single header field and its value in the client instance.
// These headers will be applied to all requests raised from this client instance.
// Also it can be overridden at request level header options, see `resty.R().SetHeader`
// or `resty.R().SetHeaders`.
//
// Example: To set `Content-Type` and `Accept` as `application/json`
//
// resty.
// SetHeader("Content-Type", "application/json").
// SetHeader("Accept", "application/json")
//
func (c *Client) SetHeader(header, value string) *Client {
c.Header.Set(header, value)
return c
}
// SetHeaders method sets multiple headers field and its values at one go in the client instance.
// These headers will be applied to all requests raised from this client instance. Also it can be
// overridden at request level headers options, see `resty.R().SetHeaders` or `resty.R().SetHeader`.
//
// Example: To set `Content-Type` and `Accept` as `application/json`
//
// resty.SetHeaders(map[string]string{
// "Content-Type": "application/json",
// "Accept": "application/json",
// })
//
func (c *Client) SetHeaders(headers map[string]string) *Client {
for h, v := range headers {
c.Header.Set(h, v)
}
return c
}
// SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default.
// Example: sometimes we don't want to save cookies in api contacting, we can remove the default
// CookieJar in resty client.
//
// resty.SetCookieJar(nil)
//
func (c *Client) SetCookieJar(jar http.CookieJar) *Client {
c.httpClient.Jar = jar
return c
}
// SetCookie method appends a single cookie in the client instance.
// These cookies will be added to all the request raised from this client instance.
// resty.SetCookie(&http.Cookie{
// Name:"go-resty",
// Value:"This is cookie value",
// Path: "/",
// Domain: "sample.com",
// MaxAge: 36000,
// HttpOnly: true,
// Secure: false,
// })
//
func (c *Client) SetCookie(hc *http.Cookie) *Client {
c.Cookies = append(c.Cookies, hc)
return c
}
// SetCookies method sets an array of cookies in the client instance.
// These cookies will be added to all the request raised from this client instance.
// cookies := make([]*http.Cookie, 0)
//
// cookies = append(cookies, &http.Cookie{
// Name:"go-resty-1",
// Value:"This is cookie 1 value",
// Path: "/",
// Domain: "sample.com",
// MaxAge: 36000,
// HttpOnly: true,
// Secure: false,
// })
//
// cookies = append(cookies, &http.Cookie{
// Name:"go-resty-2",
// Value:"This is cookie 2 value",
// Path: "/",
// Domain: "sample.com",
// MaxAge: 36000,
// HttpOnly: true,
// Secure: false,
// })
//
// // Setting a cookies into resty
// resty.SetCookies(cookies)
//
func (c *Client) SetCookies(cs []*http.Cookie) *Client {
c.Cookies = append(c.Cookies, cs...)
return c
}
// SetQueryParam method sets single parameter and its value in the client instance.
// It will be formed as query string for the request. For example: `search=kitchen%20papers&size=large`
// in the URL after `?` mark. These query params will be added to all the request raised from
// this client instance. Also it can be overridden at request level Query Param options,
// see `resty.R().SetQueryParam` or `resty.R().SetQueryParams`.
// resty.
// SetQueryParam("search", "kitchen papers").
// SetQueryParam("size", "large")
//
func (c *Client) SetQueryParam(param, value string) *Client {
c.QueryParam.Set(param, value)
return c
}
// SetQueryParams method sets multiple parameters and their values at one go in the client instance.
// It will be formed as query string for the request. For example: `search=kitchen%20papers&size=large`
// in the URL after `?` mark. These query params will be added to all the request raised from this
// client instance. Also it can be overridden at request level Query Param options,
// see `resty.R().SetQueryParams` or `resty.R().SetQueryParam`.
// resty.SetQueryParams(map[string]string{
// "search": "kitchen papers",
// "size": "large",
// })
//
func (c *Client) SetQueryParams(params map[string]string) *Client {
for p, v := range params {
c.SetQueryParam(p, v)
}
return c
}
// SetFormData method sets Form parameters and their values in the client instance.
// It's applicable only HTTP method `POST` and `PUT` and requets content type would be set as
// `application/x-www-form-urlencoded`. These form data will be added to all the request raised from
// this client instance. Also it can be overridden at request level form data, see `resty.R().SetFormData`.
// resty.SetFormData(map[string]string{
// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
// "user_id": "3455454545",
// })
//
func (c *Client) SetFormData(data map[string]string) *Client {
for k, v := range data {
c.FormData.Set(k, v)
}
return c
}
// SetBasicAuth method sets the basic authentication header in the HTTP request. Example:
// Authorization: Basic <base64-encoded-value>
//
// Example: To set the header for username "go-resty" and password "welcome"
// resty.SetBasicAuth("go-resty", "welcome")
//
// This basic auth information gets added to all the request rasied from this client instance.
// Also it can be overridden or set one at the request level is supported, see `resty.R().SetBasicAuth`.
//
func (c *Client) SetBasicAuth(username, password string) *Client {
c.UserInfo = &User{Username: username, Password: password}
return c
}
// SetAuthToken method sets bearer auth token header in the HTTP request. Example:
// Authorization: Bearer <auth-token-value-comes-here>
//
// Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
//
// resty.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
//
// This bearer auth token gets added to all the request rasied from this client instance.
// Also it can be overridden or set one at the request level is supported, see `resty.R().SetAuthToken`.
//
func (c *Client) SetAuthToken(token string) *Client {
c.Token = token
return c
}
// R method creates a request instance, its used for Get, Post, Put, Delete, Patch, Head and Options.
func (c *Client) R() *Request {
r := &Request{
URL: "",
Method: "",
QueryParam: url.Values{},
FormData: url.Values{},
Header: http.Header{},
Body: nil,
Result: nil,
Error: nil,
RawRequest: nil,
client: c,
bodyBuf: nil,
multipartFiles: []*File{},
}
return r
}
// NewRequest is an alias for R(). Creates a request instance, its used for
// Get, Post, Put, Delete, Patch, Head and Options.
func (c *Client) NewRequest() *Request {
return c.R()
}
// OnBeforeRequest method appends request middleware into the before request chain.
// Its gets applied after default `go-resty` request middlewares and before request
// been sent from `go-resty` to host server.
// resty.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error {
// // Now you have access to Client and Request instance
// // manipulate it as per your need
//
// return nil // if its success otherwise return error
// })
//
func (c *Client) OnBeforeRequest(m func(*Client, *Request) error) *Client {
c.udBeforeRequest = append(c.udBeforeRequest, m)
return c
}
// OnAfterResponse method appends response middleware into the after response chain.
// Once we receive response from host server, default `go-resty` response middleware
// gets applied and then user assigened response middlewares applied.
// resty.OnAfterResponse(func(c *resty.Client, r *resty.Response) error {
// // Now you have access to Client and Response instance
// // manipulate it as per your need
//
// return nil // if its success otherwise return error
// })
//
func (c *Client) OnAfterResponse(m func(*Client, *Response) error) *Client {
c.afterResponse = append(c.afterResponse, m)
return c
}
// SetPreRequestHook method sets the given pre-request function into resty client.
// It is called right before the request is fired.
//
// Note: Only one pre-request hook can be registered. Use `resty.OnBeforeRequest` for mutilple.
func (c *Client) SetPreRequestHook(h func(*Client, *Request) error) *Client {
if c.preReqHook != nil {
c.Log.Printf("Overwriting an existing pre-request hook: %s", functionName(h))
}
c.preReqHook = h
return c
}
// SetDebug method enables the debug mode on `go-resty` client. Client logs details of every request and response.
// For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one.
// For `Response` it logs information such as Status, Response Time, Headers, Body if it has one.
// resty.SetDebug(true)
//
func (c *Client) SetDebug(d bool) *Client {
c.Debug = d
return c
}
// SetDisableWarn method disables the warning message on `go-resty` client.
// For example: go-resty warns the user when BasicAuth used on HTTP mode.
// resty.SetDisableWarn(true)
//
func (c *Client) SetDisableWarn(d bool) *Client {
c.DisableWarn = d
return c
}
// SetAllowGetMethodPayload method allows the GET method with payload on `go-resty` client.
// For example: go-resty allows the user sends request with a payload on HTTP GET method.
// resty.SetAllowGetMethodPayload(true)
//
func (c *Client) SetAllowGetMethodPayload(a bool) *Client {
c.AllowGetMethodPayload = a
return c
}
// SetLogger method sets given writer for logging go-resty request and response details.
// Default is os.Stderr
// file, _ := os.OpenFile("/Users/jeeva/go-resty.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
//
// resty.SetLogger(file)
//
func (c *Client) SetLogger(w io.Writer) *Client {
c.Log = getLogger(w)
return c
}
// SetContentLength method enables the HTTP header `Content-Length` value for every request.
// By default go-resty won't set `Content-Length`.
// resty.SetContentLength(true)
//
// Also you have an option to enable for particular request. See `resty.R().SetContentLength`
//
func (c *Client) SetContentLength(l bool) *Client {
c.setContentLength = l
return c
}
// SetTimeout method sets timeout for request raised from client.
// resty.SetTimeout(time.Duration(1 * time.Minute))
//
func (c *Client) SetTimeout(timeout time.Duration) *Client {
c.httpClient.Timeout = timeout
return c
}
// SetError method is to register the global or client common `Error` object into go-resty.
// It is used for automatic unmarshalling if response status code is greater than 399 and
// content type either JSON or XML. Can be pointer or non-pointer.
// resty.SetError(&Error{})
// // OR
// resty.SetError(Error{})
//
func (c *Client) SetError(err interface{}) *Client {
c.Error = typeOf(err)
return c
}
// SetRedirectPolicy method sets the client redirect poilicy. go-resty provides ready to use
// redirect policies. Wanna create one for yourself refer `redirect.go`.
//
// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))
//
// // Need multiple redirect policies together
// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net"))
//
func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client {
for _, p := range policies {
if _, ok := p.(RedirectPolicy); !ok {
c.Log.Printf("ERORR: %v does not implement resty.RedirectPolicy (missing Apply method)",
functionName(p))
}
}
c.httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
for _, p := range policies {
if err := p.(RedirectPolicy).Apply(req, via); err != nil {
return err
}
}
return nil // looks good, go ahead
}
return c
}
// SetRetryCount method enables retry on `go-resty` client and allows you
// to set no. of retry count. Resty uses a Backoff mechanism.
func (c *Client) SetRetryCount(count int) *Client {
c.RetryCount = count
return c
}
// SetRetryWaitTime method sets default wait time to sleep before retrying
// request.
// Default is 100 milliseconds.
func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client {
c.RetryWaitTime = waitTime
return c
}
// SetRetryMaxWaitTime method sets max wait time to sleep before retrying
// request.
// Default is 2 seconds.
func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client {
c.RetryMaxWaitTime = maxWaitTime
return c
}
// AddRetryCondition method adds a retry condition function to array of functions
// that are checked to determine if the request is retried. The request will
// retry if any of the functions return true and error is nil.
func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client {
c.RetryConditions = append(c.RetryConditions, condition)
return c
}
// SetHTTPMode method sets go-resty mode into HTTP
func (c *Client) SetHTTPMode() *Client {
return c.SetMode("http")
}
// SetRESTMode method sets go-resty mode into RESTful
func (c *Client) SetRESTMode() *Client {
return c.SetMode("rest")
}
// SetMode method sets go-resty client mode to given value such as 'http' & 'rest'.
// RESTful:
// - No Redirect
// - Automatic response unmarshal if it is JSON or XML
// HTML:
// - Up to 10 Redirects
// - No automatic unmarshall. Response will be treated as `response.String()`
//
// If you want more redirects, use FlexibleRedirectPolicy
// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))
//
func (c *Client) SetMode(mode string) *Client {
// HTTP
if mode == "http" {
c.isHTTPMode = true
c.SetRedirectPolicy(FlexibleRedirectPolicy(10))
c.afterResponse = []func(*Client, *Response) error{
responseLogger,
saveResponseIntoFile,
}
return c
}
// RESTful
c.isHTTPMode = false
c.SetRedirectPolicy(NoRedirectPolicy())
c.afterResponse = []func(*Client, *Response) error{
responseLogger,
parseResponseBody,
saveResponseIntoFile,
}
return c
}
// Mode method returns the current client mode. Typically its a "http" or "rest".
// Default is "rest"
func (c *Client) Mode() string {
if c.isHTTPMode {
return "http"
}
return "rest"
}
// SetTLSClientConfig method sets TLSClientConfig for underling client Transport.
//
// Example:
// // One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial
// resty.SetTLSClientConfig(&tls.Config{ RootCAs: roots })
//
// // or One can disable security check (https)
// resty.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })
// Note: This method overwrites existing `TLSClientConfig`.
//
func (c *Client) SetTLSClientConfig(config *tls.Config) *Client {
transport, err := c.getTransport()
if err != nil {
c.Log.Printf("ERROR [%v]", err)
return c
}
transport.TLSClientConfig = config
return c
}
// SetProxy method sets the Proxy URL and Port for resty client.
// resty.SetProxy("http://proxyserver:8888")
//
// Alternatives: At request level proxy, see `Request.SetProxy`. OR Without this `SetProxy` method,
// you can also set Proxy via environment variable. By default `Go` uses setting from `HTTP_PROXY`.
//
func (c *Client) SetProxy(proxyURL string) *Client {
transport, err := c.getTransport()
if err != nil {
c.Log.Printf("ERROR [%v]", err)
return c
}
if pURL, err := url.Parse(proxyURL); err == nil {
c.proxyURL = pURL
transport.Proxy = http.ProxyURL(c.proxyURL)
} else {
c.Log.Printf("ERROR [%v]", err)
c.RemoveProxy()
}
return c
}
// RemoveProxy method removes the proxy configuration from resty client
// resty.RemoveProxy()
//
func (c *Client) RemoveProxy() *Client {
transport, err := c.getTransport()
if err != nil {
c.Log.Printf("ERROR [%v]", err)
return c
}
c.proxyURL = nil
transport.Proxy = nil
return c
}
// SetCertificates method helps to set client certificates into resty conveniently.
//
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client {
config, err := c.getTLSConfig()
if err != nil {
c.Log.Printf("ERROR [%v]", err)
return c
}
config.Certificates = append(config.Certificates, certs...)
return c
}
// SetRootCertificate method helps to add one or more root certificates into resty client
// resty.SetRootCertificate("/path/to/root/pemFile.pem")
//
func (c *Client) SetRootCertificate(pemFilePath string) *Client {
rootPemData, err := ioutil.ReadFile(pemFilePath)
if err != nil {
c.Log.Printf("ERROR [%v]", err)
return c
}
config, err := c.getTLSConfig()
if err != nil {
c.Log.Printf("ERROR [%v]", err)
return c
}
if config.RootCAs == nil {
config.RootCAs = x509.NewCertPool()
}
config.RootCAs.AppendCertsFromPEM(rootPemData)
return c
}
// SetOutputDirectory method sets output directory for saving HTTP response into file.
// If the output directory not exists then resty creates one. This setting is optional one,
// if you're planning using absoule path in `Request.SetOutput` and can used together.
// resty.SetOutputDirectory("/save/http/response/here")
//
func (c *Client) SetOutputDirectory(dirPath string) *Client {
c.outputDirectory = dirPath
return c
}
// SetTransport method sets custom `*http.Transport` or any `http.RoundTripper`
// compatible interface implementation in the resty client.
//
// Please Note:
//
// - If transport is not type of `*http.Transport` then you may not be able to
// take advantage of some of the `resty` client settings.
//
// - It overwrites the resty client transport instance and it's configurations.
//
// transport := &http.Transport{
// // somthing like Proxying to httptest.Server, etc...
// Proxy: func(req *http.Request) (*url.URL, error) {
// return url.Parse(server.URL)
// },
// }
//
// resty.SetTransport(transport)
//
func (c *Client) SetTransport(transport http.RoundTripper) *Client {
if transport != nil {
c.httpClient.Transport = transport
}
return c
}
// SetScheme method sets custom scheme in the resty client. It's way to override default.
// resty.SetScheme("http")
//
func (c *Client) SetScheme(scheme string) *Client {
if !IsStringEmpty(scheme) {
c.scheme = scheme
}
return c
}
// SetCloseConnection method sets variable `Close` in http request struct with the given
// value. More info: https://golang.org/src/net/http/request.go
func (c *Client) SetCloseConnection(close bool) *Client {
c.closeConnection = close
return c
}
// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically.
// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body,
// otherwise you might get into connection leaks, no connection reuse.
//
// Please Note: Response middlewares are not applicable, if you use this option. Basically you have
// taken over the control of response parsing from `Resty`.
func (c *Client) SetDoNotParseResponse(parse bool) *Client {
c.notParseResponse = parse
return c
}
// IsProxySet method returns the true if proxy is set on client otherwise false.
func (c *Client) IsProxySet() bool {
return c.proxyURL != nil
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Client Unexported methods
//___________________________________
// executes the given `Request` object and returns response
func (c *Client) execute(req *Request) (*Response, error) {
defer releaseBuffer(req.bodyBuf)
// Apply Request middleware
var err error
// user defined on before request methods
// to modify the *resty.Request object
for _, f := range c.udBeforeRequest {
if err = f(c, req); err != nil {
return nil, err
}
}
// resty middlewares
for _, f := range c.beforeRequest {
if err = f(c, req); err != nil {
return nil, err
}
}
// call pre-request if defined
if c.preReqHook != nil {
if err = c.preReqHook(c, req); err != nil {
return nil, err
}
}
req.Time = time.Now()
resp, err := c.httpClient.Do(req.RawRequest)
response := &Response{
Request: req,
RawResponse: resp,
receivedAt: time.Now(),
}
if err != nil || req.notParseResponse || c.notParseResponse {
return response, err
}
if !req.isSaveResponse {
defer func() {
_ = resp.Body.Close()
}()
if response.body, err = ioutil.ReadAll(resp.Body); err != nil {
return response, err
}
response.size = int64(len(response.body))
}
// Apply Response middleware
for _, f := range c.afterResponse {
if err = f(c, response); err != nil {
break
}
}
return response, err
}
// enables a log prefix
func (c *Client) enableLogPrefix() {
c.Log.SetFlags(log.LstdFlags)
c.Log.SetPrefix("RESTY ")
}
// disables a log prefix
func (c *Client) disableLogPrefix() {
c.Log.SetFlags(0)
c.Log.SetPrefix("")
}
// getting TLS client config if not exists then create one
func (c *Client) getTLSConfig() (*tls.Config, error) {
transport, err := c.getTransport()
if err != nil {
return nil, err
}
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{}
}
return transport.TLSClientConfig, nil
}
// returns `*http.Transport` currently in use or error
// in case currently used `transport` is not an `*http.Transport`
func (c *Client) getTransport() (*http.Transport, error) {
if transport, ok := c.httpClient.Transport.(*http.Transport); ok {
return transport, nil
}
return nil, errors.New("current transport is not an *http.Transport instance")
}
//
// File
//
// File represent file information for multipart request
type File struct {
Name string
ParamName string
io.Reader
}
// String returns string value of current file details
func (f *File) String() string {
return fmt.Sprintf("ParamName: %v; FileName: %v", f.ParamName, f.Name)
}

15
vendor/github.com/go-resty/resty/context17_test.go generated vendored Normal file
View File

@ -0,0 +1,15 @@
// +build !go1.8
// Copyright (c) 2015-2016 Jeevanandam M (jeeva@myjeeva.com)
// 2016 Andrew Grigorev (https://github.com/ei-grad)
// All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import "strings"
func errIsContextCanceled(err error) bool {
return strings.Contains(err.Error(), "request canceled")
}

296
vendor/github.com/go-resty/resty/default.go generated vendored Normal file
View File

@ -0,0 +1,296 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"crypto/tls"
"encoding/json"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"time"
"golang.org/x/net/publicsuffix"
)
// DefaultClient of resty
var DefaultClient *Client
// New method creates a new go-resty client
func New() *Client {
cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
c := &Client{
HostURL: "",
QueryParam: url.Values{},
FormData: url.Values{},
Header: http.Header{},
UserInfo: nil,
Token: "",
Cookies: make([]*http.Cookie, 0),
Debug: false,
Log: getLogger(os.Stderr),
RetryCount: 0,
RetryWaitTime: defaultWaitTime,
RetryMaxWaitTime: defaultMaxWaitTime,
JSONMarshal: json.Marshal,
JSONUnmarshal: json.Unmarshal,
httpClient: &http.Client{Jar: cookieJar},
}
// Default transport
c.SetTransport(&http.Transport{})
// Default redirect policy
c.SetRedirectPolicy(NoRedirectPolicy())
// default before request middlewares
c.beforeRequest = []func(*Client, *Request) error{
parseRequestURL,
parseRequestHeader,
parseRequestBody,
createHTTPRequest,
addCredentials,
requestLogger,
}
// user defined request middlewares
c.udBeforeRequest = []func(*Client, *Request) error{}
// default after response middlewares
c.afterResponse = []func(*Client, *Response) error{
responseLogger,
parseResponseBody,
saveResponseIntoFile,
}
return c
}
// R creates a new resty request object, it is used form a HTTP/RESTful request
// such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.
func R() *Request {
return DefaultClient.R()
}
// NewRequest is an alias for R(). Creates a new resty request object, it is used form a HTTP/RESTful request
// such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.
func NewRequest() *Request {
return R()
}
// SetHostURL sets Host URL. See `Client.SetHostURL for more information.
func SetHostURL(url string) *Client {
return DefaultClient.SetHostURL(url)
}
// SetHeader sets single header. See `Client.SetHeader` for more information.
func SetHeader(header, value string) *Client {
return DefaultClient.SetHeader(header, value)
}
// SetHeaders sets multiple headers. See `Client.SetHeaders` for more information.
func SetHeaders(headers map[string]string) *Client {
return DefaultClient.SetHeaders(headers)
}
// SetCookieJar sets custom http.CookieJar. See `Client.SetCookieJar` for more information.
func SetCookieJar(jar http.CookieJar) *Client {
return DefaultClient.SetCookieJar(jar)
}
// SetCookie sets single cookie object. See `Client.SetCookie` for more information.
func SetCookie(hc *http.Cookie) *Client {
return DefaultClient.SetCookie(hc)
}
// SetCookies sets multiple cookie object. See `Client.SetCookies` for more information.
func SetCookies(cs []*http.Cookie) *Client {
return DefaultClient.SetCookies(cs)
}
// SetQueryParam method sets single parameter and its value. See `Client.SetQueryParam` for more information.
func SetQueryParam(param, value string) *Client {
return DefaultClient.SetQueryParam(param, value)
}
// SetQueryParams method sets multiple parameters and its value. See `Client.SetQueryParams` for more information.
func SetQueryParams(params map[string]string) *Client {
return DefaultClient.SetQueryParams(params)
}
// SetFormData method sets Form parameters and its values. See `Client.SetFormData` for more information.
func SetFormData(data map[string]string) *Client {
return DefaultClient.SetFormData(data)
}
// SetBasicAuth method sets the basic authentication header. See `Client.SetBasicAuth` for more information.
func SetBasicAuth(username, password string) *Client {
return DefaultClient.SetBasicAuth(username, password)
}
// SetAuthToken method sets bearer auth token header. See `Client.SetAuthToken` for more information.
func SetAuthToken(token string) *Client {
return DefaultClient.SetAuthToken(token)
}
// OnBeforeRequest method sets request middleware. See `Client.OnBeforeRequest` for more information.
func OnBeforeRequest(m func(*Client, *Request) error) *Client {
return DefaultClient.OnBeforeRequest(m)
}
// OnAfterResponse method sets response middleware. See `Client.OnAfterResponse` for more information.
func OnAfterResponse(m func(*Client, *Response) error) *Client {
return DefaultClient.OnAfterResponse(m)
}
// SetPreRequestHook method sets the pre-request hook. See `Client.SetPreRequestHook` for more information.
func SetPreRequestHook(h func(*Client, *Request) error) *Client {
return DefaultClient.SetPreRequestHook(h)
}
// SetDebug method enables the debug mode. See `Client.SetDebug` for more information.
func SetDebug(d bool) *Client {
return DefaultClient.SetDebug(d)
}
// SetAllowGetMethodPayload method allows the GET method with payload. See `Client.SetAllowGetMethodPayload` for more information.
func SetAllowGetMethodPayload(a bool) *Client {
return DefaultClient.SetAllowGetMethodPayload(a)
}
// SetRetryCount method sets the retry count. See `Client.SetRetryCount` for more information.
func SetRetryCount(count int) *Client {
return DefaultClient.SetRetryCount(count)
}
// SetRetryWaitTime method sets the retry wait time. See `Client.SetRetryWaitTime` for more information.
func SetRetryWaitTime(waitTime time.Duration) *Client {
return DefaultClient.SetRetryWaitTime(waitTime)
}
// SetRetryMaxWaitTime method sets the retry max wait time. See `Client.SetRetryMaxWaitTime` for more information.
func SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client {
return DefaultClient.SetRetryMaxWaitTime(maxWaitTime)
}
// AddRetryCondition method appends check function for retry. See `Client.AddRetryCondition` for more information.
func AddRetryCondition(condition RetryConditionFunc) *Client {
return DefaultClient.AddRetryCondition(condition)
}
// SetDisableWarn method disables warning comes from `go-resty` client. See `Client.SetDisableWarn` for more information.
func SetDisableWarn(d bool) *Client {
return DefaultClient.SetDisableWarn(d)
}
// SetLogger method sets given writer for logging. See `Client.SetLogger` for more information.
func SetLogger(w io.Writer) *Client {
return DefaultClient.SetLogger(w)
}
// SetContentLength method enables `Content-Length` value. See `Client.SetContentLength` for more information.
func SetContentLength(l bool) *Client {
return DefaultClient.SetContentLength(l)
}
// SetError method is to register the global or client common `Error` object. See `Client.SetError` for more information.
func SetError(err interface{}) *Client {
return DefaultClient.SetError(err)
}
// SetRedirectPolicy method sets the client redirect poilicy. See `Client.SetRedirectPolicy` for more information.
func SetRedirectPolicy(policies ...interface{}) *Client {
return DefaultClient.SetRedirectPolicy(policies...)
}
// SetHTTPMode method sets go-resty mode into HTTP. See `Client.SetMode` for more information.
func SetHTTPMode() *Client {
return DefaultClient.SetHTTPMode()
}
// SetRESTMode method sets go-resty mode into RESTful. See `Client.SetMode` for more information.
func SetRESTMode() *Client {
return DefaultClient.SetRESTMode()
}
// Mode method returns the current client mode. See `Client.Mode` for more information.
func Mode() string {
return DefaultClient.Mode()
}
// SetTLSClientConfig method sets TLSClientConfig for underling client Transport. See `Client.SetTLSClientConfig` for more information.
func SetTLSClientConfig(config *tls.Config) *Client {
return DefaultClient.SetTLSClientConfig(config)
}
// SetTimeout method sets timeout for request. See `Client.SetTimeout` for more information.
func SetTimeout(timeout time.Duration) *Client {
return DefaultClient.SetTimeout(timeout)
}
// SetProxy method sets Proxy for request. See `Client.SetProxy` for more information.
func SetProxy(proxyURL string) *Client {
return DefaultClient.SetProxy(proxyURL)
}
// RemoveProxy method removes the proxy configuration. See `Client.RemoveProxy` for more information.
func RemoveProxy() *Client {
return DefaultClient.RemoveProxy()
}
// SetCertificates method helps to set client certificates into resty conveniently.
// See `Client.SetCertificates` for more information and example.
func SetCertificates(certs ...tls.Certificate) *Client {
return DefaultClient.SetCertificates(certs...)
}
// SetRootCertificate method helps to add one or more root certificates into resty client.
// See `Client.SetRootCertificate` for more information.
func SetRootCertificate(pemFilePath string) *Client {
return DefaultClient.SetRootCertificate(pemFilePath)
}
// SetOutputDirectory method sets output directory. See `Client.SetOutputDirectory` for more information.
func SetOutputDirectory(dirPath string) *Client {
return DefaultClient.SetOutputDirectory(dirPath)
}
// SetTransport method sets custom `*http.Transport` or any `http.RoundTripper`
// compatible interface implementation in the resty client.
// See `Client.SetTransport` for more information.
func SetTransport(transport http.RoundTripper) *Client {
return DefaultClient.SetTransport(transport)
}
// SetScheme method sets custom scheme in the resty client.
// See `Client.SetScheme` for more information.
func SetScheme(scheme string) *Client {
return DefaultClient.SetScheme(scheme)
}
// SetCloseConnection method sets close connection value in the resty client.
// See `Client.SetCloseConnection` for more information.
func SetCloseConnection(close bool) *Client {
return DefaultClient.SetCloseConnection(close)
}
// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically.
// See `Client.SetDoNotParseResponse` for more information.
func SetDoNotParseResponse(parse bool) *Client {
return DefaultClient.SetDoNotParseResponse(parse)
}
// IsProxySet method returns the true if proxy is set on client otherwise false.
// See `Client.IsProxySet` for more information.
func IsProxySet() bool {
return DefaultClient.IsProxySet()
}
func init() {
DefaultClient = New()
}

414
vendor/github.com/go-resty/resty/middleware.go generated vendored Normal file
View File

@ -0,0 +1,414 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"time"
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Request Middleware(s)
//___________________________________
func parseRequestURL(c *Client, r *Request) error {
// Parsing request URL
reqURL, err := url.Parse(r.URL)
if err != nil {
return err
}
// If Request.Url is relative path then added c.HostUrl into
// the request URL otherwise Request.Url will be used as-is
if !reqURL.IsAbs() {
if !strings.HasPrefix(r.URL, "/") {
r.URL = "/" + r.URL
}
reqURL, err = url.Parse(c.HostURL + r.URL)
if err != nil {
return err
}
}
// Adding Query Param
query := reqURL.Query()
for k, v := range c.QueryParam {
for _, iv := range v {
query.Add(k, iv)
}
}
for k, v := range r.QueryParam {
// remove query param from client level by key
// since overrides happens for that key in the request
query.Del(k)
for _, iv := range v {
query.Add(k, iv)
}
}
reqURL.RawQuery = query.Encode()
r.URL = reqURL.String()
return nil
}
func parseRequestHeader(c *Client, r *Request) error {
hdr := http.Header{}
for k := range c.Header {
hdr[k] = append(hdr[k], c.Header[k]...)
}
for k := range r.Header {
hdr[k] = append(hdr[k], r.Header[k]...)
}
if IsStringEmpty(hdr.Get(hdrUserAgentKey)) {
hdr.Set(hdrUserAgentKey, fmt.Sprintf(hdrUserAgentValue, Version))
}
if IsStringEmpty(hdr.Get(hdrAcceptKey)) && !IsStringEmpty(hdr.Get(hdrContentTypeKey)) {
hdr.Set(hdrAcceptKey, hdr.Get(hdrContentTypeKey))
}
r.Header = hdr
return nil
}
func parseRequestBody(c *Client, r *Request) (err error) {
if isPayloadSupported(r.Method, c.AllowGetMethodPayload) {
// Handling Multipart
if r.isMultiPart && !(r.Method == MethodPatch) {
if err = handleMultipart(c, r); err != nil {
return
}
goto CL
}
// Handling Form Data
if len(c.FormData) > 0 || len(r.FormData) > 0 {
handleFormData(c, r)
goto CL
}
// Handling Request body
if r.Body != nil {
handleContentType(c, r)
if err = handleRequestBody(c, r); err != nil {
return
}
}
}
CL:
// by default resty won't set content length, you can if you want to :)
if (c.setContentLength || r.setContentLength) && r.bodyBuf != nil {
r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len()))
}
return
}
func createHTTPRequest(c *Client, r *Request) (err error) {
if r.bodyBuf == nil {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil)
} else {
r.RawRequest, err = http.NewRequest(r.Method, r.URL, r.bodyBuf)
}
if err != nil {
return
}
// Assign close connection option
r.RawRequest.Close = c.closeConnection
// Add headers into http request
r.RawRequest.Header = r.Header
// Add cookies into http request
for _, cookie := range c.Cookies {
r.RawRequest.AddCookie(cookie)
}
// it's for non-http scheme option
if r.RawRequest.URL != nil && r.RawRequest.URL.Scheme == "" {
r.RawRequest.URL.Scheme = c.scheme
r.RawRequest.URL.Host = r.URL
}
// Use context if it was specified
r.addContextIfAvailable()
return
}
func addCredentials(c *Client, r *Request) error {
var isBasicAuth bool
// Basic Auth
if r.UserInfo != nil { // takes precedence
r.RawRequest.SetBasicAuth(r.UserInfo.Username, r.UserInfo.Password)
isBasicAuth = true
} else if c.UserInfo != nil {
r.RawRequest.SetBasicAuth(c.UserInfo.Username, c.UserInfo.Password)
isBasicAuth = true
}
if !c.DisableWarn {
if isBasicAuth && !strings.HasPrefix(r.URL, "https") {
c.Log.Println("WARNING - Using Basic Auth in HTTP mode is not secure.")
}
}
// Token Auth
if !IsStringEmpty(r.Token) { // takes precedence
r.RawRequest.Header.Set(hdrAuthorizationKey, "Bearer "+r.Token)
} else if !IsStringEmpty(c.Token) {
r.RawRequest.Header.Set(hdrAuthorizationKey, "Bearer "+c.Token)
}
return nil
}
func requestLogger(c *Client, r *Request) error {
if c.Debug {
rr := r.RawRequest
c.Log.Println()
c.disableLogPrefix()
c.Log.Println("---------------------- REQUEST LOG -----------------------")
c.Log.Printf("%s %s %s\n", r.Method, rr.URL.RequestURI(), rr.Proto)
c.Log.Printf("HOST : %s", rr.URL.Host)
c.Log.Println("HEADERS:")
for h, v := range rr.Header {
c.Log.Printf("%25s: %v", h, strings.Join(v, ", "))
}
c.Log.Printf("BODY :\n%v", r.fmtBodyString())
c.Log.Println("----------------------------------------------------------")
c.enableLogPrefix()
}
return nil
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Response Middleware(s)
//___________________________________
func responseLogger(c *Client, res *Response) error {
if c.Debug {
c.Log.Println()
c.disableLogPrefix()
c.Log.Println("---------------------- RESPONSE LOG -----------------------")
c.Log.Printf("STATUS : %s", res.Status())
c.Log.Printf("RECEIVED AT : %v", res.ReceivedAt().Format(time.RFC3339Nano))
c.Log.Printf("RESPONSE TIME : %v", res.Time())
c.Log.Println("HEADERS:")
for h, v := range res.Header() {
c.Log.Printf("%30s: %v", h, strings.Join(v, ", "))
}
if res.Request.isSaveResponse {
c.Log.Printf("BODY :\n***** RESPONSE WRITTEN INTO FILE *****")
} else {
c.Log.Printf("BODY :\n%v", res.fmtBodyString())
}
c.Log.Println("----------------------------------------------------------")
c.enableLogPrefix()
}
return nil
}
func parseResponseBody(c *Client, res *Response) (err error) {
// Handles only JSON or XML content type
ct := firstNonEmpty(res.Header().Get(hdrContentTypeKey), res.Request.fallbackContentType)
if IsJSONType(ct) || IsXMLType(ct) {
// Considered as Result
if res.StatusCode() > 199 && res.StatusCode() < 300 {
if res.Request.Result != nil {
err = Unmarshalc(c, ct, res.body, res.Request.Result)
return
}
}
// Considered as Error
if res.StatusCode() > 399 {
// global error interface
if res.Request.Error == nil && c.Error != nil {
res.Request.Error = reflect.New(c.Error).Interface()
}
if res.Request.Error != nil {
err = Unmarshalc(c, ct, res.body, res.Request.Error)
}
}
}
return
}
func handleMultipart(c *Client, r *Request) (err error) {
r.bodyBuf = acquireBuffer()
w := multipart.NewWriter(r.bodyBuf)
for k, v := range c.FormData {
for _, iv := range v {
if err = w.WriteField(k, iv); err != nil {
return err
}
}
}
for k, v := range r.FormData {
for _, iv := range v {
if strings.HasPrefix(k, "@") { // file
err = addFile(w, k[1:], iv)
if err != nil {
return
}
} else { // form value
if err = w.WriteField(k, iv); err != nil {
return err
}
}
}
}
// #21 - adding io.Reader support
if len(r.multipartFiles) > 0 {
for _, f := range r.multipartFiles {
err = addFileReader(w, f)
if err != nil {
return
}
}
}
r.Header.Set(hdrContentTypeKey, w.FormDataContentType())
err = w.Close()
return
}
func handleFormData(c *Client, r *Request) {
formData := url.Values{}
for k, v := range c.FormData {
for _, iv := range v {
formData.Add(k, iv)
}
}
for k, v := range r.FormData {
// remove form data field from client level by key
// since overrides happens for that key in the request
formData.Del(k)
for _, iv := range v {
formData.Add(k, iv)
}
}
r.bodyBuf = bytes.NewBuffer([]byte(formData.Encode()))
r.Header.Set(hdrContentTypeKey, formContentType)
r.isFormData = true
}
func handleContentType(c *Client, r *Request) {
contentType := r.Header.Get(hdrContentTypeKey)
if IsStringEmpty(contentType) {
contentType = DetectContentType(r.Body)
r.Header.Set(hdrContentTypeKey, contentType)
}
}
func handleRequestBody(c *Client, r *Request) (err error) {
var bodyBytes []byte
contentType := r.Header.Get(hdrContentTypeKey)
kind := kindOf(r.Body)
r.bodyBuf = nil
if reader, ok := r.Body.(io.Reader); ok {
r.bodyBuf = acquireBuffer()
_, err = r.bodyBuf.ReadFrom(reader)
} else if b, ok := r.Body.([]byte); ok {
bodyBytes = b
} else if s, ok := r.Body.(string); ok {
bodyBytes = []byte(s)
} else if IsJSONType(contentType) &&
(kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) {
bodyBytes, err = c.JSONMarshal(r.Body)
} else if IsXMLType(contentType) && (kind == reflect.Struct) {
bodyBytes, err = xml.Marshal(r.Body)
}
if bodyBytes == nil && r.bodyBuf == nil {
err = errors.New("Unsupported 'Body' type/value")
}
// if any errors during body bytes handling, return it
if err != nil {
return
}
// []byte into Buffer
if bodyBytes != nil && r.bodyBuf == nil {
r.bodyBuf = acquireBuffer()
_, _ = r.bodyBuf.Write(bodyBytes)
}
return
}
func saveResponseIntoFile(c *Client, res *Response) error {
if res.Request.isSaveResponse {
file := ""
if len(c.outputDirectory) > 0 && !filepath.IsAbs(res.Request.outputFile) {
file += c.outputDirectory + string(filepath.Separator)
}
file = filepath.Clean(file + res.Request.outputFile)
if err := createDirectory(filepath.Dir(file)); err != nil {
return err
}
outFile, err := os.Create(file)
if err != nil {
return err
}
defer func() {
_ = outFile.Close()
}()
// io.Copy reads maximum 32kb size, it is perfect for large file download too
defer func() {
_ = res.RawResponse.Body.Close()
}()
written, err := io.Copy(outFile, res.RawResponse.Body)
if err != nil {
return err
}
res.size = written
}
return nil
}

99
vendor/github.com/go-resty/resty/redirect.go generated vendored Normal file
View File

@ -0,0 +1,99 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"errors"
"fmt"
"net"
"net/http"
"strings"
)
type (
// RedirectPolicy to regulate the redirects in the resty client.
// Objects implementing the RedirectPolicy interface can be registered as
//
// Apply function should return nil to continue the redirect jounery, otherwise
// return error to stop the redirect.
RedirectPolicy interface {
Apply(req *http.Request, via []*http.Request) error
}
// The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy.
// If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f.
RedirectPolicyFunc func(*http.Request, []*http.Request) error
)
// Apply calls f(req, via).
func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error {
return f(req, via)
}
// NoRedirectPolicy is used to disable redirects in the HTTP client
// resty.SetRedirectPolicy(NoRedirectPolicy())
func NoRedirectPolicy() RedirectPolicy {
return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
return errors.New("Auto redirect is disabled")
})
}
// FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client.
// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))
func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy {
return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
if len(via) >= noOfRedirect {
return fmt.Errorf("Stopped after %d redirects", noOfRedirect)
}
checkHostAndAddHeaders(req, via[0])
return nil
})
}
// DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client.
// Redirect is allowed for only mentioned host in the policy.
// resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))
func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy {
hosts := make(map[string]bool)
for _, h := range hostnames {
hosts[strings.ToLower(h)] = true
}
fn := RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
if ok := hosts[getHostname(req.URL.Host)]; !ok {
return errors.New("Redirect is not allowed as per DomainCheckRedirectPolicy")
}
return nil
})
return fn
}
func getHostname(host string) (hostname string) {
if strings.Index(host, ":") > 0 {
host, _, _ = net.SplitHostPort(host)
}
hostname = strings.ToLower(host)
return
}
// By default Golang will not redirect request headers
// after go throughing various discussion commments from thread
// https://github.com/golang/go/issues/4800
// go-resty will add all the headers during a redirect for the same host
func checkHostAndAddHeaders(cur *http.Request, pre *http.Request) {
curHostname := getHostname(cur.URL.Host)
preHostname := getHostname(pre.URL.Host)
if strings.EqualFold(curHostname, preHostname) {
for key, val := range pre.Header {
cur.Header[key] = val
}
} else { // only library User-Agent header is added
cur.Header.Set(hdrUserAgentKey, fmt.Sprintf(hdrUserAgentValue, Version))
}
}

518
vendor/github.com/go-resty/resty/request.go generated vendored Normal file
View File

@ -0,0 +1,518 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net"
"net/url"
"reflect"
"strings"
)
// SRVRecord holds the data to query the SRV record for the following service
type SRVRecord struct {
Service string
Domain string
}
// SetHeader method is to set a single header field and its value in the current request.
// Example: To set `Content-Type` and `Accept` as `application/json`.
// resty.R().
// SetHeader("Content-Type", "application/json").
// SetHeader("Accept", "application/json")
//
// Also you can override header value, which was set at client instance level.
//
func (r *Request) SetHeader(header, value string) *Request {
r.Header.Set(header, value)
return r
}
// SetHeaders method sets multiple headers field and its values at one go in the current request.
// Example: To set `Content-Type` and `Accept` as `application/json`
//
// resty.R().
// SetHeaders(map[string]string{
// "Content-Type": "application/json",
// "Accept": "application/json",
// })
// Also you can override header value, which was set at client instance level.
//
func (r *Request) SetHeaders(headers map[string]string) *Request {
for h, v := range headers {
r.SetHeader(h, v)
}
return r
}
// SetQueryParam method sets single parameter and its value in the current request.
// It will be formed as query string for the request.
// Example: `search=kitchen%20papers&size=large` in the URL after `?` mark.
// resty.R().
// SetQueryParam("search", "kitchen papers").
// SetQueryParam("size", "large")
// Also you can override query params value, which was set at client instance level
//
func (r *Request) SetQueryParam(param, value string) *Request {
r.QueryParam.Set(param, value)
return r
}
// SetQueryParams method sets multiple parameters and its values at one go in the current request.
// It will be formed as query string for the request.
// Example: `search=kitchen%20papers&size=large` in the URL after `?` mark.
// resty.R().
// SetQueryParams(map[string]string{
// "search": "kitchen papers",
// "size": "large",
// })
// Also you can override query params value, which was set at client instance level
//
func (r *Request) SetQueryParams(params map[string]string) *Request {
for p, v := range params {
r.SetQueryParam(p, v)
}
return r
}
// SetMultiValueQueryParams method appends multiple parameters with multi-value
// at one go in the current request. It will be formed as query string for the request.
// Example: `status=pending&status=approved&status=open` in the URL after `?` mark.
// resty.R().
// SetMultiValueQueryParams(url.Values{
// "status": []string{"pending", "approved", "open"},
// })
// Also you can override query params value, which was set at client instance level
//
func (r *Request) SetMultiValueQueryParams(params url.Values) *Request {
for p, v := range params {
for _, pv := range v {
r.QueryParam.Add(p, pv)
}
}
return r
}
// SetQueryString method provides ability to use string as an input to set URL query string for the request.
//
// Using String as an input
// resty.R().
// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")
//
func (r *Request) SetQueryString(query string) *Request {
values, err := url.ParseQuery(strings.TrimSpace(query))
if err == nil {
for k := range values {
r.QueryParam.Add(k, values.Get(k))
}
} else {
r.client.Log.Printf("ERROR [%v]", err)
}
return r
}
// SetFormData method sets Form parameters and their values in the current request.
// It's applicable only HTTP method `POST` and `PUT` and requests content type would be set as
// `application/x-www-form-urlencoded`.
// resty.R().
// SetFormData(map[string]string{
// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
// "user_id": "3455454545",
// })
// Also you can override form data value, which was set at client instance level
//
func (r *Request) SetFormData(data map[string]string) *Request {
for k, v := range data {
r.FormData.Set(k, v)
}
return r
}
// SetMultiValueFormData method appends multiple form parameters with multi-value
// at one go in the current request.
// resty.R().
// SetMultiValueFormData(url.Values{
// "search_criteria": []string{"book", "glass", "pencil"},
// })
// Also you can override form data value, which was set at client instance level
//
func (r *Request) SetMultiValueFormData(params url.Values) *Request {
for k, v := range params {
for _, kv := range v {
r.FormData.Add(k, kv)
}
}
return r
}
// SetBody method sets the request body for the request. It supports various realtime need easy.
// We can say its quite handy or powerful. Supported request body data types is `string`, `[]byte`,
// `struct` and `map`. Body value can be pointer or non-pointer. Automatic marshalling
// for JSON and XML content type, if it is `struct` or `map`.
//
// Example:
//
// Struct as a body input, based on content type, it will be marshalled.
// resty.R().
// SetBody(User{
// Username: "jeeva@myjeeva.com",
// Password: "welcome2resty",
// })
//
// Map as a body input, based on content type, it will be marshalled.
// resty.R().
// SetBody(map[string]interface{}{
// "username": "jeeva@myjeeva.com",
// "password": "welcome2resty",
// "address": &Address{
// Address1: "1111 This is my street",
// Address2: "Apt 201",
// City: "My City",
// State: "My State",
// ZipCode: 00000,
// },
// })
//
// String as a body input. Suitable for any need as a string input.
// resty.R().
// SetBody(`{
// "username": "jeeva@getrightcare.com",
// "password": "admin"
// }`)
//
// []byte as a body input. Suitable for raw request such as file upload, serialize & deserialize, etc.
// resty.R().
// SetBody([]byte("This is my raw request, sent as-is"))
//
func (r *Request) SetBody(body interface{}) *Request {
r.Body = body
return r
}
// SetResult method is to register the response `Result` object for automatic unmarshalling in the RESTful mode
// if response status code is between 200 and 299 and content type either JSON or XML.
//
// Note: Result object can be pointer or non-pointer.
// resty.R().SetResult(&AuthToken{})
// // OR
// resty.R().SetResult(AuthToken{})
//
// Accessing a result value
// response.Result().(*AuthToken)
//
func (r *Request) SetResult(res interface{}) *Request {
r.Result = getPointer(res)
return r
}
// SetError method is to register the request `Error` object for automatic unmarshalling in the RESTful mode
// if response status code is greater than 399 and content type either JSON or XML.
//
// Note: Error object can be pointer or non-pointer.
// resty.R().SetError(&AuthError{})
// // OR
// resty.R().SetError(AuthError{})
//
// Accessing a error value
// response.Error().(*AuthError)
//
func (r *Request) SetError(err interface{}) *Request {
r.Error = getPointer(err)
return r
}
// SetFile method is to set single file field name and its path for multipart upload.
// resty.R().
// SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf")
//
func (r *Request) SetFile(param, filePath string) *Request {
r.isMultiPart = true
r.FormData.Set("@"+param, filePath)
return r
}
// SetFiles method is to set multiple file field name and its path for multipart upload.
// resty.R().
// SetFiles(map[string]string{
// "my_file1": "/Users/jeeva/Gas Bill - Sep.pdf",
// "my_file2": "/Users/jeeva/Electricity Bill - Sep.pdf",
// "my_file3": "/Users/jeeva/Water Bill - Sep.pdf",
// })
//
func (r *Request) SetFiles(files map[string]string) *Request {
r.isMultiPart = true
for f, fp := range files {
r.FormData.Set("@"+f, fp)
}
return r
}
// SetFileReader method is to set single file using io.Reader for multipart upload.
// resty.R().
// SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)).
// SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes))
//
func (r *Request) SetFileReader(param, fileName string, reader io.Reader) *Request {
r.isMultiPart = true
r.multipartFiles = append(r.multipartFiles, &File{
Name: fileName,
ParamName: param,
Reader: reader,
})
return r
}
// SetContentLength method sets the HTTP header `Content-Length` value for current request.
// By default go-resty won't set `Content-Length`. Also you have an option to enable for every
// request. See `resty.SetContentLength`
// resty.R().SetContentLength(true)
//
func (r *Request) SetContentLength(l bool) *Request {
r.setContentLength = true
return r
}
// SetBasicAuth method sets the basic authentication header in the current HTTP request.
// For Header example:
// Authorization: Basic <base64-encoded-value>
//
// To set the header for username "go-resty" and password "welcome"
// resty.R().SetBasicAuth("go-resty", "welcome")
//
// This method overrides the credentials set by method `resty.SetBasicAuth`.
//
func (r *Request) SetBasicAuth(username, password string) *Request {
r.UserInfo = &User{Username: username, Password: password}
return r
}
// SetAuthToken method sets bearer auth token header in the current HTTP request. Header example:
// Authorization: Bearer <auth-token-value-comes-here>
//
// Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
//
// resty.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
//
// This method overrides the Auth token set by method `resty.SetAuthToken`.
//
func (r *Request) SetAuthToken(token string) *Request {
r.Token = token
return r
}
// SetOutput method sets the output file for current HTTP request. Current HTTP response will be
// saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used.
// If is it relative path then output file goes under the output directory, as mentioned
// in the `Client.SetOutputDirectory`.
// resty.R().
// SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip").
// Get("http://bit.ly/1LouEKr")
//
// Note: In this scenario `Response.Body` might be nil.
func (r *Request) SetOutput(file string) *Request {
r.outputFile = file
r.isSaveResponse = true
return r
}
// SetSRV method sets the details to query the service SRV record and execute the
// request.
// resty.R().
// SetSRV(SRVRecord{"web", "testservice.com"}).
// Get("/get")
func (r *Request) SetSRV(srv *SRVRecord) *Request {
r.SRV = srv
return r
}
// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically.
// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body,
// otherwise you might get into connection leaks, no connection reuse.
//
// Please Note: Response middlewares are not applicable, if you use this option. Basically you have
// taken over the control of response parsing from `Resty`.
func (r *Request) SetDoNotParseResponse(parse bool) *Request {
r.notParseResponse = parse
return r
}
// ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling
// when `Content-Type` response header is unavailable.
func (r *Request) ExpectContentType(contentType string) *Request {
r.fallbackContentType = contentType
return r
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// HTTP verb method starts here
//___________________________________
// Get method does GET HTTP request. It's defined in section 4.3.1 of RFC7231.
func (r *Request) Get(url string) (*Response, error) {
return r.Execute(MethodGet, url)
}
// Head method does HEAD HTTP request. It's defined in section 4.3.2 of RFC7231.
func (r *Request) Head(url string) (*Response, error) {
return r.Execute(MethodHead, url)
}
// Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231.
func (r *Request) Post(url string) (*Response, error) {
return r.Execute(MethodPost, url)
}
// Put method does PUT HTTP request. It's defined in section 4.3.4 of RFC7231.
func (r *Request) Put(url string) (*Response, error) {
return r.Execute(MethodPut, url)
}
// Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231.
func (r *Request) Delete(url string) (*Response, error) {
return r.Execute(MethodDelete, url)
}
// Options method does OPTIONS HTTP request. It's defined in section 4.3.7 of RFC7231.
func (r *Request) Options(url string) (*Response, error) {
return r.Execute(MethodOptions, url)
}
// Patch method does PATCH HTTP request. It's defined in section 2 of RFC5789.
func (r *Request) Patch(url string) (*Response, error) {
return r.Execute(MethodPatch, url)
}
// Execute method performs the HTTP request with given HTTP method and URL
// for current `Request`.
// resp, err := resty.R().Execute(resty.GET, "http://httpbin.org/get")
//
func (r *Request) Execute(method, url string) (*Response, error) {
var addrs []*net.SRV
var err error
if r.isMultiPart && !(method == MethodPost || method == MethodPut) {
return nil, fmt.Errorf("Multipart content is not allowed in HTTP verb [%v]", method)
}
if r.SRV != nil {
_, addrs, err = net.LookupSRV(r.SRV.Service, "tcp", r.SRV.Domain)
if err != nil {
return nil, err
}
}
r.Method = method
r.URL = r.selectAddr(addrs, url, 0)
if r.client.RetryCount == 0 {
return r.client.execute(r)
}
var resp *Response
attempt := 0
_ = Backoff(
func() (*Response, error) {
attempt++
r.URL = r.selectAddr(addrs, url, attempt)
resp, err = r.client.execute(r)
if err != nil {
r.client.Log.Printf("ERROR [%v] Attempt [%v]", err, attempt)
if r.isContextCancelledIfAvailable() {
// stop Backoff from retrying request if request has been
// canceled by context
return resp, nil
}
}
return resp, err
},
Retries(r.client.RetryCount),
WaitTime(r.client.RetryWaitTime),
MaxWaitTime(r.client.RetryMaxWaitTime),
RetryConditions(r.client.RetryConditions),
)
return resp, err
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Request Unexported methods
//___________________________________
func (r *Request) fmtBodyString() (body string) {
body = "***** NO CONTENT *****"
if isPayloadSupported(r.Method, r.client.AllowGetMethodPayload) {
// multipart or form-data
if r.isMultiPart || r.isFormData {
body = string(r.bodyBuf.Bytes())
return
}
// request body data
if r.Body == nil {
return
}
var prtBodyBytes []byte
var err error
contentType := r.Header.Get(hdrContentTypeKey)
kind := kindOf(r.Body)
if canJSONMarshal(contentType, kind) {
prtBodyBytes, err = json.MarshalIndent(&r.Body, "", " ")
} else if IsXMLType(contentType) && (kind == reflect.Struct) {
prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ")
} else if b, ok := r.Body.(string); ok {
if IsJSONType(contentType) {
bodyBytes := []byte(b)
out := acquireBuffer()
defer releaseBuffer(out)
if err = json.Indent(out, bodyBytes, "", " "); err == nil {
prtBodyBytes = out.Bytes()
}
} else {
body = b
return
}
} else if b, ok := r.Body.([]byte); ok {
body = base64.StdEncoding.EncodeToString(b)
}
if prtBodyBytes != nil && err == nil {
body = string(prtBodyBytes)
}
}
return
}
func (r *Request) selectAddr(addrs []*net.SRV, path string, attempt int) string {
if addrs == nil {
return path
}
idx := attempt % len(addrs)
domain := strings.TrimRight(addrs[idx].Target, ".")
path = strings.TrimLeft(path, "/")
return fmt.Sprintf("%s://%s:%d/%s", r.client.scheme, domain, addrs[idx].Port, path)
}

57
vendor/github.com/go-resty/resty/request16.go generated vendored Normal file
View File

@ -0,0 +1,57 @@
// +build !go1.7
// Copyright (c) 2015-2016 Jeevanandam M (jeeva@myjeeva.com)
// 2016 Andrew Grigorev (https://github.com/ei-grad)
// All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"bytes"
"net/http"
"net/url"
"time"
)
// Request type is used to compose and send individual request from client
// go-resty is provide option override client level settings such as
// Auth Token, Basic Auth credentials, Header, Query Param, Form Data, Error object
// and also you can add more options for that particular request
//
type Request struct {
URL string
Method string
QueryParam url.Values
FormData url.Values
Header http.Header
UserInfo *User
Token string
Body interface{}
Result interface{}
Error interface{}
Time time.Time
RawRequest *http.Request
SRV *SRVRecord
client *Client
bodyBuf *bytes.Buffer
isMultiPart bool
isFormData bool
setContentLength bool
isSaveResponse bool
outputFile string
multipartFiles []*File
notParseResponse bool
fallbackContentType string
}
func (r *Request) addContextIfAvailable() {
// nothing to do for golang<1.7
}
func (r *Request) isContextCancelledIfAvailable() bool {
// just always return false golang<1.7
return false
}

74
vendor/github.com/go-resty/resty/request17.go generated vendored Normal file
View File

@ -0,0 +1,74 @@
// +build go1.7 go1.8
// Copyright (c) 2015-2016 Jeevanandam M (jeeva@myjeeva.com)
// 2016 Andrew Grigorev (https://github.com/ei-grad)
// All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"bytes"
"context"
"net/http"
"net/url"
"time"
)
// Request type is used to compose and send individual request from client
// go-resty is provide option override client level settings such as
// Auth Token, Basic Auth credentials, Header, Query Param, Form Data, Error object
// and also you can add more options for that particular request
//
type Request struct {
URL string
Method string
QueryParam url.Values
FormData url.Values
Header http.Header
UserInfo *User
Token string
Body interface{}
Result interface{}
Error interface{}
Time time.Time
RawRequest *http.Request
SRV *SRVRecord
client *Client
bodyBuf *bytes.Buffer
isMultiPart bool
isFormData bool
setContentLength bool
isSaveResponse bool
outputFile string
multipartFiles []*File
notParseResponse bool
ctx context.Context
fallbackContentType string
}
// SetContext method sets the context.Context for current Request. It allows
// to interrupt the request execution if ctx.Done() channel is closed.
// See https://blog.golang.org/context article and the "context" package
// documentation.
func (r *Request) SetContext(ctx context.Context) *Request {
r.ctx = ctx
return r
}
func (r *Request) addContextIfAvailable() {
if r.ctx != nil {
r.RawRequest = r.RawRequest.WithContext(r.ctx)
}
}
func (r *Request) isContextCancelledIfAvailable() bool {
if r.ctx != nil {
if r.ctx.Err() != nil {
return true
}
}
return false
}

138
vendor/github.com/go-resty/resty/response.go generated vendored Normal file
View File

@ -0,0 +1,138 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"encoding/json"
"io"
"net/http"
"strings"
"time"
)
// Response is an object represents executed request and its values.
type Response struct {
Request *Request
RawResponse *http.Response
body []byte
size int64
receivedAt time.Time
}
// Body method returns HTTP response as []byte array for the executed request.
// Note: `Response.Body` might be nil, if `Request.SetOutput` is used.
func (r *Response) Body() []byte {
if r.RawResponse == nil {
return []byte{}
}
return r.body
}
// Status method returns the HTTP status string for the executed request.
// Example: 200 OK
func (r *Response) Status() string {
if r.RawResponse == nil {
return ""
}
return r.RawResponse.Status
}
// StatusCode method returns the HTTP status code for the executed request.
// Example: 200
func (r *Response) StatusCode() int {
if r.RawResponse == nil {
return 0
}
return r.RawResponse.StatusCode
}
// Result method returns the response value as an object if it has one
func (r *Response) Result() interface{} {
return r.Request.Result
}
// Error method returns the error object if it has one
func (r *Response) Error() interface{} {
return r.Request.Error
}
// Header method returns the response headers
func (r *Response) Header() http.Header {
if r.RawResponse == nil {
return http.Header{}
}
return r.RawResponse.Header
}
// Cookies method to access all the response cookies
func (r *Response) Cookies() []*http.Cookie {
if r.RawResponse == nil {
return make([]*http.Cookie, 0)
}
return r.RawResponse.Cookies()
}
// String method returns the body of the server response as String.
func (r *Response) String() string {
if r.body == nil {
return ""
}
return strings.TrimSpace(string(r.body))
}
// Time method returns the time of HTTP response time that from request we sent and received a request.
// See `response.ReceivedAt` to know when client recevied response and see `response.Request.Time` to know
// when client sent a request.
func (r *Response) Time() time.Duration {
return r.receivedAt.Sub(r.Request.Time)
}
// ReceivedAt method returns when response got recevied from server for the request.
func (r *Response) ReceivedAt() time.Time {
return r.receivedAt
}
// Size method returns the HTTP response size in bytes. Ya, you can relay on HTTP `Content-Length` header,
// however it won't be good for chucked transfer/compressed response. Since Resty calculates response size
// at the client end. You will get actual size of the http response.
func (r *Response) Size() int64 {
return r.size
}
// RawBody method exposes the HTTP raw response body. Use this method in-conjunction with `SetDoNotParseResponse`
// option otherwise you get an error as `read err: http: read on closed response body`.
//
// Do not forget to close the body, otherwise you might get into connection leaks, no connection reuse.
// Basically you have taken over the control of response parsing from `Resty`.
func (r *Response) RawBody() io.ReadCloser {
if r.RawResponse == nil {
return nil
}
return r.RawResponse.Body
}
func (r *Response) fmtBodyString() string {
bodyStr := "***** NO CONTENT *****"
if r.body != nil {
ct := r.Header().Get(hdrContentTypeKey)
if IsJSONType(ct) {
out := acquireBuffer()
defer releaseBuffer(out)
if err := json.Indent(out, r.body, "", " "); err == nil {
bodyStr = string(out.Bytes())
}
} else {
bodyStr = r.String()
}
}
return bodyStr
}

9
vendor/github.com/go-resty/resty/resty.go generated vendored Normal file
View File

@ -0,0 +1,9 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
// Package resty provides simple HTTP and REST client for Go inspired by Ruby rest-client.
package resty
// Version # of resty
const Version = "1.0"

114
vendor/github.com/go-resty/resty/retry.go generated vendored Normal file
View File

@ -0,0 +1,114 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"math"
"math/rand"
"time"
)
const (
defaultMaxRetries = 3
defaultWaitTime = time.Duration(100) * time.Millisecond
defaultMaxWaitTime = time.Duration(2000) * time.Millisecond
)
type (
// Option is to create convenient retry options like wait time, max retries, etc.
Option func(*Options)
// RetryConditionFunc type is for retry condition function
RetryConditionFunc func(*Response) (bool, error)
// Options to hold go-resty retry values
Options struct {
maxRetries int
waitTime time.Duration
maxWaitTime time.Duration
retryConditions []RetryConditionFunc
}
)
// Retries sets the max number of retries
func Retries(value int) Option {
return func(o *Options) {
o.maxRetries = value
}
}
// WaitTime sets the default wait time to sleep between requests
func WaitTime(value time.Duration) Option {
return func(o *Options) {
o.waitTime = value
}
}
// MaxWaitTime sets the max wait time to sleep between requests
func MaxWaitTime(value time.Duration) Option {
return func(o *Options) {
o.maxWaitTime = value
}
}
// RetryConditions sets the conditions that will be checked for retry.
func RetryConditions(conditions []RetryConditionFunc) Option {
return func(o *Options) {
o.retryConditions = conditions
}
}
// Backoff retries with increasing timeout duration up until X amount of retries
// (Default is 3 attempts, Override with option Retries(n))
func Backoff(operation func() (*Response, error), options ...Option) error {
// Defaults
opts := Options{
maxRetries: defaultMaxRetries,
waitTime: defaultWaitTime,
maxWaitTime: defaultMaxWaitTime,
retryConditions: []RetryConditionFunc{},
}
for _, o := range options {
o(&opts)
}
var (
resp *Response
err error
)
base := float64(opts.waitTime) // Time to wait between each attempt
capLevel := float64(opts.maxWaitTime) // Maximum amount of wait time for the retry
for attempt := 0; attempt < opts.maxRetries; attempt++ {
resp, err = operation()
var needsRetry bool
var conditionErr error
for _, condition := range opts.retryConditions {
needsRetry, conditionErr = condition(resp)
if needsRetry || conditionErr != nil {
break
}
}
// If the operation returned no error, there was no condition satisfied and
// there was no error caused by the conditional functions.
if err == nil && !needsRetry && conditionErr == nil {
return nil
}
// Adding capped exponential backup with jitter
// See the following article...
// http://www.awsarchitectureblog.com/2015/03/backoff.html
temp := math.Min(capLevel, base*math.Exp2(float64(attempt)))
sleepDuration := time.Duration(int(temp/2) + rand.Intn(int(temp/2)))
if sleepDuration < opts.waitTime {
sleepDuration = opts.waitTime
}
time.Sleep(sleepDuration)
}
return err
}

185
vendor/github.com/go-resty/resty/util.go generated vendored Normal file
View File

@ -0,0 +1,185 @@
// Copyright (c) 2015-2017 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
// resty source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package resty
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Package Helper methods
//___________________________________
// IsStringEmpty method tells whether given string is empty or not
func IsStringEmpty(str string) bool {
return (len(strings.TrimSpace(str)) == 0)
}
// DetectContentType method is used to figure out `Request.Body` content type for request header
func DetectContentType(body interface{}) string {
contentType := plainTextType
kind := kindOf(body)
switch kind {
case reflect.Struct, reflect.Map:
contentType = jsonContentType
case reflect.String:
contentType = plainTextType
default:
if b, ok := body.([]byte); ok {
contentType = http.DetectContentType(b)
} else if kind == reflect.Slice {
contentType = jsonContentType
}
}
return contentType
}
// IsJSONType method is to check JSON content type or not
func IsJSONType(ct string) bool {
return jsonCheck.MatchString(ct)
}
// IsXMLType method is to check XML content type or not
func IsXMLType(ct string) bool {
return xmlCheck.MatchString(ct)
}
// Unmarshal content into object from JSON or XML
// Deprecated: kept for backward compatibility
func Unmarshal(ct string, b []byte, d interface{}) (err error) {
if IsJSONType(ct) {
err = json.Unmarshal(b, d)
} else if IsXMLType(ct) {
err = xml.Unmarshal(b, d)
}
return
}
// Unmarshalc content into object from JSON or XML
func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error) {
if IsJSONType(ct) {
err = c.JSONUnmarshal(b, d)
} else if IsXMLType(ct) {
err = xml.Unmarshal(b, d)
}
return
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Package Unexported methods
//___________________________________
func firstNonEmpty(v ...string) string {
for _, s := range v {
if !IsStringEmpty(s) {
return s
}
}
return ""
}
func getLogger(w io.Writer) *log.Logger {
return log.New(w, "RESTY ", log.LstdFlags)
}
func addFile(w *multipart.Writer, fieldName, path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()
part, err := w.CreateFormFile(fieldName, filepath.Base(path))
if err != nil {
return err
}
_, err = io.Copy(part, file)
return err
}
func addFileReader(w *multipart.Writer, f *File) error {
part, err := w.CreateFormFile(f.ParamName, f.Name)
if err != nil {
return err
}
_, err = io.Copy(part, f.Reader)
return err
}
func getPointer(v interface{}) interface{} {
vv := valueOf(v)
if vv.Kind() == reflect.Ptr {
return v
}
return reflect.New(vv.Type()).Interface()
}
func isPayloadSupported(m string, allowMethodGet bool) bool {
return (m == MethodPost || m == MethodPut || m == MethodDelete || m == MethodPatch || (allowMethodGet && m == MethodGet))
}
func typeOf(i interface{}) reflect.Type {
return indirect(valueOf(i)).Type()
}
func valueOf(i interface{}) reflect.Value {
return reflect.ValueOf(i)
}
func indirect(v reflect.Value) reflect.Value {
return reflect.Indirect(v)
}
func kindOf(v interface{}) reflect.Kind {
return typeOf(v).Kind()
}
func createDirectory(dir string) (err error) {
if _, err = os.Stat(dir); err != nil {
if os.IsNotExist(err) {
if err = os.MkdirAll(dir, 0755); err != nil {
return
}
}
}
return
}
func canJSONMarshal(contentType string, kind reflect.Kind) bool {
return IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map)
}
func functionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}
func acquireBuffer() *bytes.Buffer {
return bufPool.Get().(*bytes.Buffer)
}
func releaseBuffer(buf *bytes.Buffer) {
if buf != nil {
buf.Reset()
bufPool.Put(buf)
}
}

1180
vendor/github.com/golang/glog/glog.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

124
vendor/github.com/golang/glog/glog_file.go generated vendored Normal file
View File

@ -0,0 +1,124 @@
// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/
//
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// File I/O for logs.
package glog
import (
"errors"
"flag"
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"sync"
"time"
)
// MaxSize is the maximum size of a log file in bytes.
var MaxSize uint64 = 1024 * 1024 * 1800
// logDirs lists the candidate directories for new log files.
var logDirs []string
// If non-empty, overrides the choice of directory in which to write logs.
// See createLogDirs for the full list of possible destinations.
var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory")
func createLogDirs() {
if *logDir != "" {
logDirs = append(logDirs, *logDir)
}
logDirs = append(logDirs, os.TempDir())
}
var (
pid = os.Getpid()
program = filepath.Base(os.Args[0])
host = "unknownhost"
userName = "unknownuser"
)
func init() {
h, err := os.Hostname()
if err == nil {
host = shortHostname(h)
}
current, err := user.Current()
if err == nil {
userName = current.Username
}
// Sanitize userName since it may contain filepath separators on Windows.
userName = strings.Replace(userName, `\`, "_", -1)
}
// shortHostname returns its argument, truncating at the first period.
// For instance, given "www.google.com" it returns "www".
func shortHostname(hostname string) string {
if i := strings.Index(hostname, "."); i >= 0 {
return hostname[:i]
}
return hostname
}
// logName returns a new log file name containing tag, with start time t, and
// the name for the symlink for tag.
func logName(tag string, t time.Time) (name, link string) {
name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d",
program,
host,
userName,
tag,
t.Year(),
t.Month(),
t.Day(),
t.Hour(),
t.Minute(),
t.Second(),
pid)
return name, program + "." + tag
}
var onceLogDirs sync.Once
// create creates a new log file and returns the file and its filename, which
// contains tag ("INFO", "FATAL", etc.) and t. If the file is created
// successfully, create also attempts to update the symlink for that tag, ignoring
// errors.
func create(tag string, t time.Time) (f *os.File, filename string, err error) {
onceLogDirs.Do(createLogDirs)
if len(logDirs) == 0 {
return nil, "", errors.New("log: no log dirs")
}
name, link := logName(tag, t)
var lastErr error
for _, dir := range logDirs {
fname := filepath.Join(dir, name)
f, err := os.Create(fname)
if err == nil {
symlink := filepath.Join(dir, link)
os.Remove(symlink) // ignore err
os.Symlink(name, symlink) // ignore err
return f, fname, nil
}
lastErr = err
}
return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr)
}

View File

@ -174,11 +174,11 @@ func sizeFixed32(x uint64) int {
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) EncodeZigzag64(x uint64) error {
// use signed number to get arithmetic right shift.
return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63)))
}
func sizeZigzag64(x uint64) int {
return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
return sizeVarint((x << 1) ^ uint64((int64(x) >> 63)))
}
// EncodeZigzag32 writes a zigzag-encoded 32-bit integer

View File

@ -73,7 +73,6 @@ for a protocol buffer variable v:
When the .proto file specifies `syntax="proto3"`, there are some differences:
- Non-repeated fields of non-message type are values instead of pointers.
- Getters are only generated for message and oneof fields.
- Enum types do not get an Enum method.
The simplest way to describe this is to see an example.

View File

@ -865,7 +865,7 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error {
return p.readStruct(fv, terminator)
case reflect.Uint32:
if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
fv.SetUint(uint64(x))
fv.SetUint(x)
return nil
}
case reflect.Uint64:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,293 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/compiler/plugin.proto
/*
Package plugin_go is a generated protocol buffer package.
It is generated from these files:
google/protobuf/compiler/plugin.proto
It has these top-level messages:
Version
CodeGeneratorRequest
CodeGeneratorResponse
*/
package plugin_go
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// The version number of protocol compiler.
type Version struct {
Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"`
// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
// be empty for mainline stable releases.
Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *Version) Reset() { *m = Version{} }
func (m *Version) String() string { return proto.CompactTextString(m) }
func (*Version) ProtoMessage() {}
func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *Version) GetMajor() int32 {
if m != nil && m.Major != nil {
return *m.Major
}
return 0
}
func (m *Version) GetMinor() int32 {
if m != nil && m.Minor != nil {
return *m.Minor
}
return 0
}
func (m *Version) GetPatch() int32 {
if m != nil && m.Patch != nil {
return *m.Patch
}
return 0
}
func (m *Version) GetSuffix() string {
if m != nil && m.Suffix != nil {
return *m.Suffix
}
return ""
}
// An encoded CodeGeneratorRequest is written to the plugin's stdin.
type CodeGeneratorRequest struct {
// The .proto files that were explicitly listed on the command-line. The
// code generator should generate code only for these files. Each file's
// descriptor will be included in proto_file, below.
FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"`
// The generator parameter passed on the command-line.
Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"`
// FileDescriptorProtos for all files in files_to_generate and everything
// they import. The files will appear in topological order, so each file
// appears before any file that imports it.
//
// protoc guarantees that all proto_files will be written after
// the fields above, even though this is not technically guaranteed by the
// protobuf wire format. This theoretically could allow a plugin to stream
// in the FileDescriptorProtos and handle them one by one rather than read
// the entire set into memory at once. However, as of this writing, this
// is not similarly optimized on protoc's end -- it will store all fields in
// memory at once before sending them to the plugin.
//
// Type names of fields and extensions in the FileDescriptorProto are always
// fully qualified.
ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"`
// The version number of protocol compiler.
CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *CodeGeneratorRequest) Reset() { *m = CodeGeneratorRequest{} }
func (m *CodeGeneratorRequest) String() string { return proto.CompactTextString(m) }
func (*CodeGeneratorRequest) ProtoMessage() {}
func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *CodeGeneratorRequest) GetFileToGenerate() []string {
if m != nil {
return m.FileToGenerate
}
return nil
}
func (m *CodeGeneratorRequest) GetParameter() string {
if m != nil && m.Parameter != nil {
return *m.Parameter
}
return ""
}
func (m *CodeGeneratorRequest) GetProtoFile() []*google_protobuf.FileDescriptorProto {
if m != nil {
return m.ProtoFile
}
return nil
}
func (m *CodeGeneratorRequest) GetCompilerVersion() *Version {
if m != nil {
return m.CompilerVersion
}
return nil
}
// The plugin writes an encoded CodeGeneratorResponse to stdout.
type CodeGeneratorResponse struct {
// Error message. If non-empty, code generation failed. The plugin process
// should exit with status code zero even if it reports an error in this way.
//
// This should be used to indicate errors in .proto files which prevent the
// code generator from generating correct code. Errors which indicate a
// problem in protoc itself -- such as the input CodeGeneratorRequest being
// unparseable -- should be reported by writing a message to stderr and
// exiting with a non-zero status code.
Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"`
File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *CodeGeneratorResponse) Reset() { *m = CodeGeneratorResponse{} }
func (m *CodeGeneratorResponse) String() string { return proto.CompactTextString(m) }
func (*CodeGeneratorResponse) ProtoMessage() {}
func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
func (m *CodeGeneratorResponse) GetError() string {
if m != nil && m.Error != nil {
return *m.Error
}
return ""
}
func (m *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File {
if m != nil {
return m.File
}
return nil
}
// Represents a single generated file.
type CodeGeneratorResponse_File struct {
// The file name, relative to the output directory. The name must not
// contain "." or ".." components and must be relative, not be absolute (so,
// the file cannot lie outside the output directory). "/" must be used as
// the path separator, not "\".
//
// If the name is omitted, the content will be appended to the previous
// file. This allows the generator to break large files into small chunks,
// and allows the generated text to be streamed back to protoc so that large
// files need not reside completely in memory at one time. Note that as of
// this writing protoc does not optimize for this -- it will read the entire
// CodeGeneratorResponse before writing files to disk.
Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
// If non-empty, indicates that the named file should already exist, and the
// content here is to be inserted into that file at a defined insertion
// point. This feature allows a code generator to extend the output
// produced by another code generator. The original generator may provide
// insertion points by placing special annotations in the file that look
// like:
// @@protoc_insertion_point(NAME)
// The annotation can have arbitrary text before and after it on the line,
// which allows it to be placed in a comment. NAME should be replaced with
// an identifier naming the point -- this is what other generators will use
// as the insertion_point. Code inserted at this point will be placed
// immediately above the line containing the insertion point (thus multiple
// insertions to the same point will come out in the order they were added).
// The double-@ is intended to make it unlikely that the generated code
// could contain things that look like insertion points by accident.
//
// For example, the C++ code generator places the following line in the
// .pb.h files that it generates:
// // @@protoc_insertion_point(namespace_scope)
// This line appears within the scope of the file's package namespace, but
// outside of any particular class. Another plugin can then specify the
// insertion_point "namespace_scope" to generate additional classes or
// other declarations that should be placed in this scope.
//
// Note that if the line containing the insertion point begins with
// whitespace, the same whitespace will be added to every line of the
// inserted text. This is useful for languages like Python, where
// indentation matters. In these languages, the insertion point comment
// should be indented the same amount as any inserted code will need to be
// in order to work correctly in that context.
//
// The code generator that generates the initial file and the one which
// inserts into it must both run as part of a single invocation of protoc.
// Code generators are executed in the order in which they appear on the
// command line.
//
// If |insertion_point| is present, |name| must also be present.
InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"`
// The file contents.
Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *CodeGeneratorResponse_File) Reset() { *m = CodeGeneratorResponse_File{} }
func (m *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(m) }
func (*CodeGeneratorResponse_File) ProtoMessage() {}
func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
func (m *CodeGeneratorResponse_File) GetName() string {
if m != nil && m.Name != nil {
return *m.Name
}
return ""
}
func (m *CodeGeneratorResponse_File) GetInsertionPoint() string {
if m != nil && m.InsertionPoint != nil {
return *m.InsertionPoint
}
return ""
}
func (m *CodeGeneratorResponse_File) GetContent() string {
if m != nil && m.Content != nil {
return *m.Content
}
return ""
}
func init() {
proto.RegisterType((*Version)(nil), "google.protobuf.compiler.Version")
proto.RegisterType((*CodeGeneratorRequest)(nil), "google.protobuf.compiler.CodeGeneratorRequest")
proto.RegisterType((*CodeGeneratorResponse)(nil), "google.protobuf.compiler.CodeGeneratorResponse")
proto.RegisterType((*CodeGeneratorResponse_File)(nil), "google.protobuf.compiler.CodeGeneratorResponse.File")
}
func init() { proto.RegisterFile("google/protobuf/compiler/plugin.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 417 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xcf, 0x6a, 0x14, 0x41,
0x10, 0xc6, 0x19, 0x77, 0x63, 0x98, 0x8a, 0x64, 0x43, 0x13, 0xa5, 0x09, 0x39, 0x8c, 0x8b, 0xe2,
0x5c, 0x32, 0x0b, 0xc1, 0x8b, 0x78, 0x4b, 0x44, 0x3d, 0x78, 0x58, 0x1a, 0xf1, 0x20, 0xc8, 0x30,
0x99, 0xd4, 0x74, 0x5a, 0x66, 0xba, 0xc6, 0xee, 0x1e, 0xf1, 0x49, 0x7d, 0x0f, 0xdf, 0x40, 0xfa,
0xcf, 0x24, 0xb2, 0xb8, 0xa7, 0xee, 0xef, 0x57, 0xd5, 0xd5, 0x55, 0x1f, 0x05, 0x2f, 0x25, 0x91,
0xec, 0x71, 0x33, 0x1a, 0x72, 0x74, 0x33, 0x75, 0x9b, 0x96, 0x86, 0x51, 0xf5, 0x68, 0x36, 0x63,
0x3f, 0x49, 0xa5, 0xab, 0x10, 0x60, 0x3c, 0xa6, 0x55, 0x73, 0x5a, 0x35, 0xa7, 0x9d, 0x15, 0xbb,
0x05, 0x6e, 0xd1, 0xb6, 0x46, 0x8d, 0x8e, 0x4c, 0xcc, 0x5e, 0xb7, 0x70, 0xf8, 0x05, 0x8d, 0x55,
0xa4, 0xd9, 0x29, 0x1c, 0x0c, 0xcd, 0x77, 0x32, 0x3c, 0x2b, 0xb2, 0xf2, 0x40, 0x44, 0x11, 0xa8,
0xd2, 0x64, 0xf8, 0xa3, 0x44, 0xbd, 0xf0, 0x74, 0x6c, 0x5c, 0x7b, 0xc7, 0x17, 0x91, 0x06, 0xc1,
0x9e, 0xc1, 0x63, 0x3b, 0x75, 0x9d, 0xfa, 0xc5, 0x97, 0x45, 0x56, 0xe6, 0x22, 0xa9, 0xf5, 0x9f,
0x0c, 0x4e, 0xaf, 0xe9, 0x16, 0x3f, 0xa0, 0x46, 0xd3, 0x38, 0x32, 0x02, 0x7f, 0x4c, 0x68, 0x1d,
0x2b, 0xe1, 0xa4, 0x53, 0x3d, 0xd6, 0x8e, 0x6a, 0x19, 0x63, 0xc8, 0xb3, 0x62, 0x51, 0xe6, 0xe2,
0xd8, 0xf3, 0xcf, 0x94, 0x5e, 0x20, 0x3b, 0x87, 0x7c, 0x6c, 0x4c, 0x33, 0xa0, 0xc3, 0xd8, 0x4a,
0x2e, 0x1e, 0x00, 0xbb, 0x06, 0x08, 0xe3, 0xd4, 0xfe, 0x15, 0x5f, 0x15, 0x8b, 0xf2, 0xe8, 0xf2,
0x45, 0xb5, 0x6b, 0xcb, 0x7b, 0xd5, 0xe3, 0xbb, 0x7b, 0x03, 0xb6, 0x1e, 0x8b, 0x3c, 0x44, 0x7d,
0x84, 0x7d, 0x82, 0x93, 0xd9, 0xb8, 0xfa, 0x67, 0xf4, 0x24, 0x8c, 0x77, 0x74, 0xf9, 0xbc, 0xda,
0xe7, 0x70, 0x95, 0xcc, 0x13, 0xab, 0x99, 0x24, 0xb0, 0xfe, 0x9d, 0xc1, 0xd3, 0x9d, 0x99, 0xed,
0x48, 0xda, 0xa2, 0xf7, 0x0e, 0x8d, 0x49, 0x3e, 0xe7, 0x22, 0x0a, 0xf6, 0x11, 0x96, 0xff, 0x34,
0xff, 0x7a, 0xff, 0x8f, 0xff, 0x2d, 0x1a, 0x66, 0x13, 0xa1, 0xc2, 0xd9, 0x37, 0x58, 0x86, 0x79,
0x18, 0x2c, 0x75, 0x33, 0x60, 0xfa, 0x26, 0xdc, 0xd9, 0x2b, 0x58, 0x29, 0x6d, 0xd1, 0x38, 0x45,
0xba, 0x1e, 0x49, 0x69, 0x97, 0xcc, 0x3c, 0xbe, 0xc7, 0x5b, 0x4f, 0x19, 0x87, 0xc3, 0x96, 0xb4,
0x43, 0xed, 0xf8, 0x2a, 0x24, 0xcc, 0xf2, 0x4a, 0xc2, 0x79, 0x4b, 0xc3, 0xde, 0xfe, 0xae, 0x9e,
0x6c, 0xc3, 0x6e, 0x06, 0x7b, 0xed, 0xd7, 0x37, 0x52, 0xb9, 0xbb, 0xe9, 0xc6, 0x87, 0x37, 0x92,
0xfa, 0x46, 0xcb, 0x87, 0x65, 0x0c, 0x97, 0xf6, 0x42, 0xa2, 0xbe, 0x90, 0x94, 0x56, 0xfa, 0x6d,
0x3c, 0x6a, 0x49, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x15, 0x40, 0xc5, 0xfe, 0x02, 0x00,
0x00,
}

139
vendor/github.com/golang/protobuf/ptypes/any.go generated vendored Normal file
View File

@ -0,0 +1,139 @@
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package ptypes
// This file implements functions to marshal proto.Message to/from
// google.protobuf.Any message.
import (
"fmt"
"reflect"
"strings"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/any"
)
const googleApis = "type.googleapis.com/"
// AnyMessageName returns the name of the message contained in a google.protobuf.Any message.
//
// Note that regular type assertions should be done using the Is
// function. AnyMessageName is provided for less common use cases like filtering a
// sequence of Any messages based on a set of allowed message type names.
func AnyMessageName(any *any.Any) (string, error) {
if any == nil {
return "", fmt.Errorf("message is nil")
}
slash := strings.LastIndex(any.TypeUrl, "/")
if slash < 0 {
return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
}
return any.TypeUrl[slash+1:], nil
}
// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any.
func MarshalAny(pb proto.Message) (*any.Any, error) {
value, err := proto.Marshal(pb)
if err != nil {
return nil, err
}
return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil
}
// DynamicAny is a value that can be passed to UnmarshalAny to automatically
// allocate a proto.Message for the type specified in a google.protobuf.Any
// message. The allocated message is stored in the embedded proto.Message.
//
// Example:
//
// var x ptypes.DynamicAny
// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
// fmt.Printf("unmarshaled message: %v", x.Message)
type DynamicAny struct {
proto.Message
}
// Empty returns a new proto.Message of the type specified in a
// google.protobuf.Any message. It returns an error if corresponding message
// type isn't linked in.
func Empty(any *any.Any) (proto.Message, error) {
aname, err := AnyMessageName(any)
if err != nil {
return nil, err
}
t := proto.MessageType(aname)
if t == nil {
return nil, fmt.Errorf("any: message type %q isn't linked in", aname)
}
return reflect.New(t.Elem()).Interface().(proto.Message), nil
}
// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any
// message and places the decoded result in pb. It returns an error if type of
// contents of Any message does not match type of pb message.
//
// pb can be a proto.Message, or a *DynamicAny.
func UnmarshalAny(any *any.Any, pb proto.Message) error {
if d, ok := pb.(*DynamicAny); ok {
if d.Message == nil {
var err error
d.Message, err = Empty(any)
if err != nil {
return err
}
}
return UnmarshalAny(any, d.Message)
}
aname, err := AnyMessageName(any)
if err != nil {
return err
}
mname := proto.MessageName(pb)
if aname != mname {
return fmt.Errorf("mismatched message type: got %q want %q", aname, mname)
}
return proto.Unmarshal(any.Value, pb)
}
// Is returns true if any value contains a given message type.
func Is(any *any.Any, pb proto.Message) bool {
aname, err := AnyMessageName(any)
if err != nil {
return false
}
return aname == proto.MessageName(pb)
}

View File

@ -1,12 +1,11 @@
// Code generated by protoc-gen-go.
// source: github.com/golang/protobuf/ptypes/any/any.proto
// DO NOT EDIT!
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/any.proto
/*
Package any is a generated protocol buffer package.
It is generated from these files:
github.com/golang/protobuf/ptypes/any/any.proto
google/protobuf/any.proto
It has these top-level messages:
Any
@ -63,6 +62,16 @@ const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// any.Unpack(foo)
// ...
//
// Example 4: Pack and unpack a message in Go
//
// foo := &pb.Foo{...}
// any, err := ptypes.MarshalAny(foo)
// ...
// foo := &pb.Foo{}
// if err := ptypes.UnmarshalAny(any, foo); err != nil {
// ...
// }
//
// The pack methods provided by protobuf library will by default use
// 'type.googleapis.com/full.type.name' as the type URL and the unpack
// methods only use the fully qualified type name after the last '/'
@ -132,24 +141,38 @@ func (*Any) ProtoMessage() {}
func (*Any) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (*Any) XXX_WellKnownType() string { return "Any" }
func (m *Any) GetTypeUrl() string {
if m != nil {
return m.TypeUrl
}
return ""
}
func (m *Any) GetValue() []byte {
if m != nil {
return m.Value
}
return nil
}
func init() {
proto.RegisterType((*Any)(nil), "google.protobuf.Any")
}
func init() { proto.RegisterFile("github.com/golang/protobuf/ptypes/any/any.proto", fileDescriptor0) }
func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 187 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xd2, 0x4f, 0xcf, 0x2c, 0xc9,
0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x2f, 0x28,
0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x28, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0xcc,
0xab, 0x04, 0x61, 0x3d, 0xb0, 0xb8, 0x10, 0x7f, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0xaa, 0x1e, 0x4c,
0x95, 0x92, 0x19, 0x17, 0xb3, 0x63, 0x5e, 0xa5, 0x90, 0x24, 0x17, 0x07, 0x48, 0x79, 0x7c, 0x69,
0x51, 0x8e, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x3b, 0x88, 0x1f, 0x5a, 0x94, 0x23, 0x24,
0xc2, 0xc5, 0x5a, 0x96, 0x98, 0x53, 0x9a, 0x2a, 0xc1, 0xa4, 0xc0, 0xa8, 0xc1, 0x13, 0x04, 0xe1,
0x38, 0x15, 0x71, 0x09, 0x27, 0xe7, 0xe7, 0xea, 0xa1, 0x19, 0xe7, 0xc4, 0xe1, 0x98, 0x57, 0x19,
0x00, 0xe2, 0x04, 0x30, 0x46, 0xa9, 0x12, 0xe5, 0xb8, 0x05, 0x8c, 0x8c, 0x8b, 0x98, 0x98, 0xdd,
0x03, 0x9c, 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x4c, 0x0b, 0x80, 0xaa, 0xd2, 0x0b, 0x4f, 0xcd, 0xc9,
0xf1, 0xce, 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0xa9, 0x4e, 0x62, 0x03, 0x6b, 0x37, 0x06, 0x04, 0x00,
0x00, 0xff, 0xff, 0xc6, 0x4d, 0x03, 0x23, 0xf6, 0x00, 0x00, 0x00,
// 185 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f,
0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4,
0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a,
0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46,
0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7,
0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce,
0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52,
0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc,
0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c,
0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce,
0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff,
0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00,
}

35
vendor/github.com/golang/protobuf/ptypes/doc.go generated vendored Normal file
View File

@ -0,0 +1,35 @@
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Package ptypes contains code for interacting with well-known types.
*/
package ptypes

102
vendor/github.com/golang/protobuf/ptypes/duration.go generated vendored Normal file
View File

@ -0,0 +1,102 @@
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package ptypes
// This file implements conversions between google.protobuf.Duration
// and time.Duration.
import (
"errors"
"fmt"
"time"
durpb "github.com/golang/protobuf/ptypes/duration"
)
const (
// Range of a durpb.Duration in seconds, as specified in
// google/protobuf/duration.proto. This is about 10,000 years in seconds.
maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
minSeconds = -maxSeconds
)
// validateDuration determines whether the durpb.Duration is valid according to the
// definition in google/protobuf/duration.proto. A valid durpb.Duration
// may still be too large to fit into a time.Duration (the range of durpb.Duration
// is about 10,000 years, and the range of time.Duration is about 290).
func validateDuration(d *durpb.Duration) error {
if d == nil {
return errors.New("duration: nil Duration")
}
if d.Seconds < minSeconds || d.Seconds > maxSeconds {
return fmt.Errorf("duration: %v: seconds out of range", d)
}
if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
return fmt.Errorf("duration: %v: nanos out of range", d)
}
// Seconds and Nanos must have the same sign, unless d.Nanos is zero.
if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
return fmt.Errorf("duration: %v: seconds and nanos have different signs", d)
}
return nil
}
// Duration converts a durpb.Duration to a time.Duration. Duration
// returns an error if the durpb.Duration is invalid or is too large to be
// represented in a time.Duration.
func Duration(p *durpb.Duration) (time.Duration, error) {
if err := validateDuration(p); err != nil {
return 0, err
}
d := time.Duration(p.Seconds) * time.Second
if int64(d/time.Second) != p.Seconds {
return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
}
if p.Nanos != 0 {
d += time.Duration(p.Nanos)
if (d < 0) != (p.Nanos < 0) {
return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
}
}
return d, nil
}
// DurationProto converts a time.Duration to a durpb.Duration.
func DurationProto(d time.Duration) *durpb.Duration {
nanos := d.Nanoseconds()
secs := nanos / 1e9
nanos -= secs * 1e9
return &durpb.Duration{
Seconds: secs,
Nanos: int32(nanos),
}
}

View File

@ -0,0 +1,144 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/duration.proto
/*
Package duration is a generated protocol buffer package.
It is generated from these files:
google/protobuf/duration.proto
It has these top-level messages:
Duration
*/
package duration
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// A Duration represents a signed, fixed-length span of time represented
// as a count of seconds and fractions of seconds at nanosecond
// resolution. It is independent of any calendar and concepts like "day"
// or "month". It is related to Timestamp in that the difference between
// two Timestamp values is a Duration and it can be added or subtracted
// from a Timestamp. Range is approximately +-10,000 years.
//
// # Examples
//
// Example 1: Compute Duration from two Timestamps in pseudo code.
//
// Timestamp start = ...;
// Timestamp end = ...;
// Duration duration = ...;
//
// duration.seconds = end.seconds - start.seconds;
// duration.nanos = end.nanos - start.nanos;
//
// if (duration.seconds < 0 && duration.nanos > 0) {
// duration.seconds += 1;
// duration.nanos -= 1000000000;
// } else if (durations.seconds > 0 && duration.nanos < 0) {
// duration.seconds -= 1;
// duration.nanos += 1000000000;
// }
//
// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
//
// Timestamp start = ...;
// Duration duration = ...;
// Timestamp end = ...;
//
// end.seconds = start.seconds + duration.seconds;
// end.nanos = start.nanos + duration.nanos;
//
// if (end.nanos < 0) {
// end.seconds -= 1;
// end.nanos += 1000000000;
// } else if (end.nanos >= 1000000000) {
// end.seconds += 1;
// end.nanos -= 1000000000;
// }
//
// Example 3: Compute Duration from datetime.timedelta in Python.
//
// td = datetime.timedelta(days=3, minutes=10)
// duration = Duration()
// duration.FromTimedelta(td)
//
// # JSON Mapping
//
// In JSON format, the Duration type is encoded as a string rather than an
// object, where the string ends in the suffix "s" (indicating seconds) and
// is preceded by the number of seconds, with nanoseconds expressed as
// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
// microsecond should be expressed in JSON format as "3.000001s".
//
//
type Duration struct {
// Signed seconds of the span of time. Must be from -315,576,000,000
// to +315,576,000,000 inclusive. Note: these bounds are computed from:
// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
// Signed fractions of a second at nanosecond resolution of the span
// of time. Durations less than one second are represented with a 0
// `seconds` field and a positive or negative `nanos` field. For durations
// of one second or more, a non-zero value for the `nanos` field must be
// of the same sign as the `seconds` field. Must be from -999,999,999
// to +999,999,999 inclusive.
Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
}
func (m *Duration) Reset() { *m = Duration{} }
func (m *Duration) String() string { return proto.CompactTextString(m) }
func (*Duration) ProtoMessage() {}
func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (*Duration) XXX_WellKnownType() string { return "Duration" }
func (m *Duration) GetSeconds() int64 {
if m != nil {
return m.Seconds
}
return 0
}
func (m *Duration) GetNanos() int32 {
if m != nil {
return m.Nanos
}
return 0
}
func init() {
proto.RegisterType((*Duration)(nil), "google.protobuf.Duration")
}
func init() { proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 190 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f,
0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a,
0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56,
0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5,
0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e,
0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c,
0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56,
0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e,
0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4,
0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78,
0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63,
0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00,
}

View File

@ -0,0 +1,66 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/empty.proto
/*
Package empty is a generated protocol buffer package.
It is generated from these files:
google/protobuf/empty.proto
It has these top-level messages:
Empty
*/
package empty
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// A generic empty message that you can re-use to avoid defining duplicated
// empty messages in your APIs. A typical example is to use it as the request
// or the response type of an API method. For instance:
//
// service Foo {
// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
// }
//
// The JSON representation for `Empty` is empty JSON object `{}`.
type Empty struct {
}
func (m *Empty) Reset() { *m = Empty{} }
func (m *Empty) String() string { return proto.CompactTextString(m) }
func (*Empty) ProtoMessage() {}
func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (*Empty) XXX_WellKnownType() string { return "Empty" }
func init() {
proto.RegisterType((*Empty)(nil), "google.protobuf.Empty")
}
func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 148 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f,
0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28,
0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57,
0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36,
0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf,
0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0x58, 0x53, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x0c,
0xb1, 0xed, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10,
0x13, 0x03, 0xa0, 0xea, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40,
0xea, 0x93, 0xd8, 0xc0, 0x06, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd4, 0xb3, 0xa6,
0xb7, 0x00, 0x00, 0x00,
}

View File

@ -0,0 +1,380 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/struct.proto
/*
Package structpb is a generated protocol buffer package.
It is generated from these files:
google/protobuf/struct.proto
It has these top-level messages:
Struct
Value
ListValue
*/
package structpb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// `NullValue` is a singleton enumeration to represent the null value for the
// `Value` type union.
//
// The JSON representation for `NullValue` is JSON `null`.
type NullValue int32
const (
// Null value.
NullValue_NULL_VALUE NullValue = 0
)
var NullValue_name = map[int32]string{
0: "NULL_VALUE",
}
var NullValue_value = map[string]int32{
"NULL_VALUE": 0,
}
func (x NullValue) String() string {
return proto.EnumName(NullValue_name, int32(x))
}
func (NullValue) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (NullValue) XXX_WellKnownType() string { return "NullValue" }
// `Struct` represents a structured data value, consisting of fields
// which map to dynamically typed values. In some languages, `Struct`
// might be supported by a native representation. For example, in
// scripting languages like JS a struct is represented as an
// object. The details of that representation are described together
// with the proto support for the language.
//
// The JSON representation for `Struct` is JSON object.
type Struct struct {
// Unordered map of dynamically typed values.
Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
}
func (m *Struct) Reset() { *m = Struct{} }
func (m *Struct) String() string { return proto.CompactTextString(m) }
func (*Struct) ProtoMessage() {}
func (*Struct) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (*Struct) XXX_WellKnownType() string { return "Struct" }
func (m *Struct) GetFields() map[string]*Value {
if m != nil {
return m.Fields
}
return nil
}
// `Value` represents a dynamically typed value which can be either
// null, a number, a string, a boolean, a recursive struct value, or a
// list of values. A producer of value is expected to set one of that
// variants, absence of any variant indicates an error.
//
// The JSON representation for `Value` is JSON value.
type Value struct {
// The kind of value.
//
// Types that are valid to be assigned to Kind:
// *Value_NullValue
// *Value_NumberValue
// *Value_StringValue
// *Value_BoolValue
// *Value_StructValue
// *Value_ListValue
Kind isValue_Kind `protobuf_oneof:"kind"`
}
func (m *Value) Reset() { *m = Value{} }
func (m *Value) String() string { return proto.CompactTextString(m) }
func (*Value) ProtoMessage() {}
func (*Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (*Value) XXX_WellKnownType() string { return "Value" }
type isValue_Kind interface {
isValue_Kind()
}
type Value_NullValue struct {
NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"`
}
type Value_NumberValue struct {
NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"`
}
type Value_StringValue struct {
StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"`
}
type Value_BoolValue struct {
BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"`
}
type Value_StructValue struct {
StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"`
}
type Value_ListValue struct {
ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"`
}
func (*Value_NullValue) isValue_Kind() {}
func (*Value_NumberValue) isValue_Kind() {}
func (*Value_StringValue) isValue_Kind() {}
func (*Value_BoolValue) isValue_Kind() {}
func (*Value_StructValue) isValue_Kind() {}
func (*Value_ListValue) isValue_Kind() {}
func (m *Value) GetKind() isValue_Kind {
if m != nil {
return m.Kind
}
return nil
}
func (m *Value) GetNullValue() NullValue {
if x, ok := m.GetKind().(*Value_NullValue); ok {
return x.NullValue
}
return NullValue_NULL_VALUE
}
func (m *Value) GetNumberValue() float64 {
if x, ok := m.GetKind().(*Value_NumberValue); ok {
return x.NumberValue
}
return 0
}
func (m *Value) GetStringValue() string {
if x, ok := m.GetKind().(*Value_StringValue); ok {
return x.StringValue
}
return ""
}
func (m *Value) GetBoolValue() bool {
if x, ok := m.GetKind().(*Value_BoolValue); ok {
return x.BoolValue
}
return false
}
func (m *Value) GetStructValue() *Struct {
if x, ok := m.GetKind().(*Value_StructValue); ok {
return x.StructValue
}
return nil
}
func (m *Value) GetListValue() *ListValue {
if x, ok := m.GetKind().(*Value_ListValue); ok {
return x.ListValue
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{
(*Value_NullValue)(nil),
(*Value_NumberValue)(nil),
(*Value_StringValue)(nil),
(*Value_BoolValue)(nil),
(*Value_StructValue)(nil),
(*Value_ListValue)(nil),
}
}
func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*Value)
// kind
switch x := m.Kind.(type) {
case *Value_NullValue:
b.EncodeVarint(1<<3 | proto.WireVarint)
b.EncodeVarint(uint64(x.NullValue))
case *Value_NumberValue:
b.EncodeVarint(2<<3 | proto.WireFixed64)
b.EncodeFixed64(math.Float64bits(x.NumberValue))
case *Value_StringValue:
b.EncodeVarint(3<<3 | proto.WireBytes)
b.EncodeStringBytes(x.StringValue)
case *Value_BoolValue:
t := uint64(0)
if x.BoolValue {
t = 1
}
b.EncodeVarint(4<<3 | proto.WireVarint)
b.EncodeVarint(t)
case *Value_StructValue:
b.EncodeVarint(5<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.StructValue); err != nil {
return err
}
case *Value_ListValue:
b.EncodeVarint(6<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.ListValue); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("Value.Kind has unexpected type %T", x)
}
return nil
}
func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*Value)
switch tag {
case 1: // kind.null_value
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Kind = &Value_NullValue{NullValue(x)}
return true, err
case 2: // kind.number_value
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.Kind = &Value_NumberValue{math.Float64frombits(x)}
return true, err
case 3: // kind.string_value
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Kind = &Value_StringValue{x}
return true, err
case 4: // kind.bool_value
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.Kind = &Value_BoolValue{x != 0}
return true, err
case 5: // kind.struct_value
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(Struct)
err := b.DecodeMessage(msg)
m.Kind = &Value_StructValue{msg}
return true, err
case 6: // kind.list_value
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(ListValue)
err := b.DecodeMessage(msg)
m.Kind = &Value_ListValue{msg}
return true, err
default:
return false, nil
}
}
func _Value_OneofSizer(msg proto.Message) (n int) {
m := msg.(*Value)
// kind
switch x := m.Kind.(type) {
case *Value_NullValue:
n += proto.SizeVarint(1<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.NullValue))
case *Value_NumberValue:
n += proto.SizeVarint(2<<3 | proto.WireFixed64)
n += 8
case *Value_StringValue:
n += proto.SizeVarint(3<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.StringValue)))
n += len(x.StringValue)
case *Value_BoolValue:
n += proto.SizeVarint(4<<3 | proto.WireVarint)
n += 1
case *Value_StructValue:
s := proto.Size(x.StructValue)
n += proto.SizeVarint(5<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *Value_ListValue:
s := proto.Size(x.ListValue)
n += proto.SizeVarint(6<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
// `ListValue` is a wrapper around a repeated field of values.
//
// The JSON representation for `ListValue` is JSON array.
type ListValue struct {
// Repeated field of dynamically typed values.
Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"`
}
func (m *ListValue) Reset() { *m = ListValue{} }
func (m *ListValue) String() string { return proto.CompactTextString(m) }
func (*ListValue) ProtoMessage() {}
func (*ListValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
func (*ListValue) XXX_WellKnownType() string { return "ListValue" }
func (m *ListValue) GetValues() []*Value {
if m != nil {
return m.Values
}
return nil
}
func init() {
proto.RegisterType((*Struct)(nil), "google.protobuf.Struct")
proto.RegisterType((*Value)(nil), "google.protobuf.Value")
proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue")
proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value)
}
func init() { proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 417 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40,
0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09,
0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94,
0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa,
0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff,
0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc,
0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15,
0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d,
0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce,
0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39,
0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab,
0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84,
0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48,
0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f,
0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59,
0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a,
0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64,
0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92,
0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25,
0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37,
0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6,
0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4,
0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda,
0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9,
0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53,
0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00,
0x00,
}

134
vendor/github.com/golang/protobuf/ptypes/timestamp.go generated vendored Normal file
View File

@ -0,0 +1,134 @@
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package ptypes
// This file implements operations on google.protobuf.Timestamp.
import (
"errors"
"fmt"
"time"
tspb "github.com/golang/protobuf/ptypes/timestamp"
)
const (
// Seconds field of the earliest valid Timestamp.
// This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
minValidSeconds = -62135596800
// Seconds field just after the latest valid Timestamp.
// This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
maxValidSeconds = 253402300800
)
// validateTimestamp determines whether a Timestamp is valid.
// A valid timestamp represents a time in the range
// [0001-01-01, 10000-01-01) and has a Nanos field
// in the range [0, 1e9).
//
// If the Timestamp is valid, validateTimestamp returns nil.
// Otherwise, it returns an error that describes
// the problem.
//
// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
func validateTimestamp(ts *tspb.Timestamp) error {
if ts == nil {
return errors.New("timestamp: nil Timestamp")
}
if ts.Seconds < minValidSeconds {
return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
}
if ts.Seconds >= maxValidSeconds {
return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
}
if ts.Nanos < 0 || ts.Nanos >= 1e9 {
return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
}
return nil
}
// Timestamp converts a google.protobuf.Timestamp proto to a time.Time.
// It returns an error if the argument is invalid.
//
// Unlike most Go functions, if Timestamp returns an error, the first return value
// is not the zero time.Time. Instead, it is the value obtained from the
// time.Unix function when passed the contents of the Timestamp, in the UTC
// locale. This may or may not be a meaningful time; many invalid Timestamps
// do map to valid time.Times.
//
// A nil Timestamp returns an error. The first return value in that case is
// undefined.
func Timestamp(ts *tspb.Timestamp) (time.Time, error) {
// Don't return the zero value on error, because corresponds to a valid
// timestamp. Instead return whatever time.Unix gives us.
var t time.Time
if ts == nil {
t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
} else {
t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
}
return t, validateTimestamp(ts)
}
// TimestampNow returns a google.protobuf.Timestamp for the current time.
func TimestampNow() *tspb.Timestamp {
ts, err := TimestampProto(time.Now())
if err != nil {
panic("ptypes: time.Now() out of Timestamp range")
}
return ts
}
// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
// It returns an error if the resulting Timestamp is invalid.
func TimestampProto(t time.Time) (*tspb.Timestamp, error) {
seconds := t.Unix()
nanos := int32(t.Sub(time.Unix(seconds, 0)))
ts := &tspb.Timestamp{
Seconds: seconds,
Nanos: nanos,
}
if err := validateTimestamp(ts); err != nil {
return nil, err
}
return ts, nil
}
// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid
// Timestamps, it returns an error message in parentheses.
func TimestampString(ts *tspb.Timestamp) string {
t, err := Timestamp(ts)
if err != nil {
return fmt.Sprintf("(%v)", err)
}
return t.Format(time.RFC3339Nano)
}

View File

@ -0,0 +1,160 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/timestamp.proto
/*
Package timestamp is a generated protocol buffer package.
It is generated from these files:
google/protobuf/timestamp.proto
It has these top-level messages:
Timestamp
*/
package timestamp
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// A Timestamp represents a point in time independent of any time zone
// or calendar, represented as seconds and fractions of seconds at
// nanosecond resolution in UTC Epoch time. It is encoded using the
// Proleptic Gregorian Calendar which extends the Gregorian calendar
// backwards to year one. It is encoded assuming all minutes are 60
// seconds long, i.e. leap seconds are "smeared" so that no leap second
// table is needed for interpretation. Range is from
// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
// By restricting to that range, we ensure that we can convert to
// and from RFC 3339 date strings.
// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
//
// # Examples
//
// Example 1: Compute Timestamp from POSIX `time()`.
//
// Timestamp timestamp;
// timestamp.set_seconds(time(NULL));
// timestamp.set_nanos(0);
//
// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
//
// struct timeval tv;
// gettimeofday(&tv, NULL);
//
// Timestamp timestamp;
// timestamp.set_seconds(tv.tv_sec);
// timestamp.set_nanos(tv.tv_usec * 1000);
//
// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
//
// FILETIME ft;
// GetSystemTimeAsFileTime(&ft);
// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
//
// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
// Timestamp timestamp;
// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
//
// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
//
// long millis = System.currentTimeMillis();
//
// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
// .setNanos((int) ((millis % 1000) * 1000000)).build();
//
//
// Example 5: Compute Timestamp from current time in Python.
//
// timestamp = Timestamp()
// timestamp.GetCurrentTime()
//
// # JSON Mapping
//
// In JSON format, the Timestamp type is encoded as a string in the
// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
// where {year} is always expressed using four digits while {month}, {day},
// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
// is required, though only UTC (as indicated by "Z") is presently supported.
//
// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
// 01:30 UTC on January 15, 2017.
//
// In JavaScript, one can convert a Date object to this format using the
// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
// method. In Python, a standard `datetime.datetime` object can be converted
// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime())
// to obtain a formatter capable of generating timestamps in this format.
//
//
type Timestamp struct {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive.
Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
}
func (m *Timestamp) Reset() { *m = Timestamp{} }
func (m *Timestamp) String() string { return proto.CompactTextString(m) }
func (*Timestamp) ProtoMessage() {}
func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" }
func (m *Timestamp) GetSeconds() int64 {
if m != nil {
return m.Seconds
}
return 0
}
func (m *Timestamp) GetNanos() int32 {
if m != nil {
return m.Nanos
}
return 0
}
func init() {
proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp")
}
func init() { proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 191 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f,
0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d,
0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28,
0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5,
0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89,
0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70,
0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51,
0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89,
0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71,
0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a,
0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43,
0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00,
}

View File

@ -0,0 +1,10 @@
package abe
import (
)
type ProtobufDuration struct {
Seconds string `json:"seconds,omitempty"`
Nanos int32 `json:"nanos,omitempty"`
}

View File

@ -0,0 +1,22 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
// Nested is nested type.
type ABitOfEverythingNested struct {
// name is nested field.
Name string `json:"name,omitempty"`
Amount int64 `json:"amount,omitempty"`
Ok NestedDeepEnum `json:"ok,omitempty"`
}

View File

@ -0,0 +1,784 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"net/url"
"strings"
"time"
"encoding/json"
"fmt"
)
type ABitOfEverythingServiceApi struct {
Configuration *Configuration
}
func NewABitOfEverythingServiceApi() *ABitOfEverythingServiceApi {
configuration := NewConfiguration()
return &ABitOfEverythingServiceApi{
Configuration: configuration,
}
}
func NewABitOfEverythingServiceApiWithBasePath(basePath string) *ABitOfEverythingServiceApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &ABitOfEverythingServiceApi{
Configuration: configuration,
}
}
/**
*
*
* @param floatValue
* @param doubleValue
* @param int64Value
* @param uint64Value
* @param int32Value
* @param fixed64Value
* @param fixed32Value
* @param boolValue
* @param stringValue
* @param uint32Value
* @param sfixed32Value
* @param sfixed64Value
* @param sint32Value
* @param sint64Value
* @param nonConventionalNameValue
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) Create(floatValue float32, doubleValue float64, int64Value string, uint64Value string, int32Value int32, fixed64Value string, fixed32Value int64, boolValue bool, stringValue string, uint32Value int64, sfixed32Value int32, sfixed64Value string, sint32Value int32, sint64Value string, nonConventionalNameValue string) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}"
localVarPath = strings.Replace(localVarPath, "{"+"float_value"+"}", fmt.Sprintf("%v", floatValue), -1)
localVarPath = strings.Replace(localVarPath, "{"+"double_value"+"}", fmt.Sprintf("%v", doubleValue), -1)
localVarPath = strings.Replace(localVarPath, "{"+"int64_value"+"}", fmt.Sprintf("%v", int64Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"uint64_value"+"}", fmt.Sprintf("%v", uint64Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"int32_value"+"}", fmt.Sprintf("%v", int32Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"fixed64_value"+"}", fmt.Sprintf("%v", fixed64Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"fixed32_value"+"}", fmt.Sprintf("%v", fixed32Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"bool_value"+"}", fmt.Sprintf("%v", boolValue), -1)
localVarPath = strings.Replace(localVarPath, "{"+"string_value"+"}", fmt.Sprintf("%v", stringValue), -1)
localVarPath = strings.Replace(localVarPath, "{"+"uint32_value"+"}", fmt.Sprintf("%v", uint32Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"sfixed32_value"+"}", fmt.Sprintf("%v", sfixed32Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"sfixed64_value"+"}", fmt.Sprintf("%v", sfixed64Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"sint32_value"+"}", fmt.Sprintf("%v", sint32Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"sint64_value"+"}", fmt.Sprintf("%v", sint64Value), -1)
localVarPath = strings.Replace(localVarPath, "{"+"nonConventionalNameValue"+"}", fmt.Sprintf("%v", nonConventionalNameValue), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Create", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param body
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) CreateBody(body ExamplepbABitOfEverything) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "CreateBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param singleNestedName
* @param body
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) DeepPathEcho(singleNestedName string, body ExamplepbABitOfEverything) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{single_nested.name}"
localVarPath = strings.Replace(localVarPath, "{"+"single_nested.name"+"}", fmt.Sprintf("%v", singleNestedName), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "DeepPathEcho", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @return *ProtobufEmpty
*/
func (a ABitOfEverythingServiceApi) Delete(uuid string) (*ProtobufEmpty, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Delete")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{uuid}"
localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ProtobufEmpty)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Delete", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param value
* @return *SubStringMessage
*/
func (a ABitOfEverythingServiceApi) Echo(value string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/echo/{value}"
localVarPath = strings.Replace(localVarPath, "{"+"value"+"}", fmt.Sprintf("%v", value), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param value
* @return *SubStringMessage
*/
func (a ABitOfEverythingServiceApi) Echo_1(value string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/echo"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("value", a.Configuration.APIClient.ParameterToString(value, ""))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo_0", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param body
* @return *SubStringMessage
*/
func (a ABitOfEverythingServiceApi) Echo_2(body string) (*SubStringMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/echo"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(SubStringMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo_1", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @param singleNestedName name is nested field.
* @param singleNestedAmount
* @param singleNestedOk - FALSE: FALSE is false. - TRUE: TRUE is true.
* @param floatValue
* @param doubleValue
* @param int64Value
* @param uint64Value
* @param int32Value
* @param fixed64Value
* @param fixed32Value
* @param boolValue
* @param stringValue
* @param uint32Value TODO(yugui) add bytes_value.
* @param enumValue - ZERO: ZERO means 0 - ONE: ONE means 1
* @param sfixed32Value
* @param sfixed64Value
* @param sint32Value
* @param sint64Value
* @param repeatedStringValue
* @param oneofString
* @param nonConventionalNameValue
* @param timestampValue
* @param repeatedEnumValue repeated enum value. it is comma-separated in query. - ZERO: ZERO means 0 - ONE: ONE means 1
* @return *ProtobufEmpty
*/
func (a ABitOfEverythingServiceApi) GetQuery(uuid string, singleNestedName string, singleNestedAmount int64, singleNestedOk string, floatValue float32, doubleValue float64, int64Value string, uint64Value string, int32Value int32, fixed64Value string, fixed32Value int64, boolValue bool, stringValue string, uint32Value int64, enumValue string, sfixed32Value int32, sfixed64Value string, sint32Value int32, sint64Value string, repeatedStringValue []string, oneofString string, nonConventionalNameValue string, timestampValue time.Time, repeatedEnumValue []string) (*ProtobufEmpty, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/query/{uuid}"
localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
localVarQueryParams.Add("single_nested.name", a.Configuration.APIClient.ParameterToString(singleNestedName, ""))
localVarQueryParams.Add("single_nested.amount", a.Configuration.APIClient.ParameterToString(singleNestedAmount, ""))
localVarQueryParams.Add("single_nested.ok", a.Configuration.APIClient.ParameterToString(singleNestedOk, ""))
localVarQueryParams.Add("float_value", a.Configuration.APIClient.ParameterToString(floatValue, ""))
localVarQueryParams.Add("double_value", a.Configuration.APIClient.ParameterToString(doubleValue, ""))
localVarQueryParams.Add("int64_value", a.Configuration.APIClient.ParameterToString(int64Value, ""))
localVarQueryParams.Add("uint64_value", a.Configuration.APIClient.ParameterToString(uint64Value, ""))
localVarQueryParams.Add("int32_value", a.Configuration.APIClient.ParameterToString(int32Value, ""))
localVarQueryParams.Add("fixed64_value", a.Configuration.APIClient.ParameterToString(fixed64Value, ""))
localVarQueryParams.Add("fixed32_value", a.Configuration.APIClient.ParameterToString(fixed32Value, ""))
localVarQueryParams.Add("bool_value", a.Configuration.APIClient.ParameterToString(boolValue, ""))
localVarQueryParams.Add("string_value", a.Configuration.APIClient.ParameterToString(stringValue, ""))
localVarQueryParams.Add("uint32_value", a.Configuration.APIClient.ParameterToString(uint32Value, ""))
localVarQueryParams.Add("enum_value", a.Configuration.APIClient.ParameterToString(enumValue, ""))
localVarQueryParams.Add("sfixed32_value", a.Configuration.APIClient.ParameterToString(sfixed32Value, ""))
localVarQueryParams.Add("sfixed64_value", a.Configuration.APIClient.ParameterToString(sfixed64Value, ""))
localVarQueryParams.Add("sint32_value", a.Configuration.APIClient.ParameterToString(sint32Value, ""))
localVarQueryParams.Add("sint64_value", a.Configuration.APIClient.ParameterToString(sint64Value, ""))
var repeatedStringValueCollectionFormat = "csv"
localVarQueryParams.Add("repeated_string_value", a.Configuration.APIClient.ParameterToString(repeatedStringValue, repeatedStringValueCollectionFormat))
localVarQueryParams.Add("oneof_string", a.Configuration.APIClient.ParameterToString(oneofString, ""))
localVarQueryParams.Add("nonConventionalNameValue", a.Configuration.APIClient.ParameterToString(nonConventionalNameValue, ""))
localVarQueryParams.Add("timestamp_value", a.Configuration.APIClient.ParameterToString(timestampValue, ""))
var repeatedEnumValueCollectionFormat = "csv"
localVarQueryParams.Add("repeated_enum_value", a.Configuration.APIClient.ParameterToString(repeatedEnumValue, repeatedEnumValueCollectionFormat))
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ProtobufEmpty)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "GetQuery", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @return *ExamplepbABitOfEverything
*/
func (a ABitOfEverythingServiceApi) Lookup(uuid string) (*ExamplepbABitOfEverything, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{uuid}"
localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbABitOfEverything)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Lookup", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @return *ProtobufEmpty
*/
func (a ABitOfEverythingServiceApi) Timeout() (*ProtobufEmpty, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v2/example/timeout"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ProtobufEmpty)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Timeout", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
*
*
* @param uuid
* @param body
* @return *ProtobufEmpty
*/
func (a ABitOfEverythingServiceApi) Update(uuid string, body ExamplepbABitOfEverything) (*ProtobufEmpty, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Put")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{uuid}"
localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ProtobufEmpty)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Update", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}

View File

@ -0,0 +1,164 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"bytes"
"fmt"
"path/filepath"
"reflect"
"strings"
"net/url"
"io/ioutil"
"github.com/go-resty/resty"
)
type APIClient struct {
config *Configuration
}
func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
if len(contentTypes) == 0 {
return ""
}
if contains(contentTypes, "application/json") {
return "application/json"
}
return contentTypes[0] // use the first content type specified in 'consumes'
}
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.ToLower(a) == strings.ToLower(needle) {
return true
}
}
return false
}
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
rClient := c.prepareClient()
request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
delimiter := ""
switch collectionFormat {
case "pipes":
delimiter = "|"
case "ssv":
delimiter = " "
case "tsv":
delimiter = "\t"
case "csv":
delimiter = ","
}
if reflect.TypeOf(obj).Kind() == reflect.Slice {
return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
}
return fmt.Sprintf("%v", obj)
}
func (c *APIClient) prepareClient() *resty.Client {
rClient := resty.New()
rClient.SetDebug(c.config.Debug)
if c.config.Transport != nil {
rClient.SetTransport(c.config.Transport)
}
if c.config.Timeout != nil {
rClient.SetTimeout(*c.config.Timeout)
}
rClient.SetLogger(ioutil.Discard)
return rClient
}
func (c *APIClient) prepareRequest(
rClient *resty.Client,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := rClient.R()
request.SetBody(postBody)
if c.config.UserAgent != "" {
request.SetHeader("User-Agent", c.config.UserAgent)
}
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetMultiValueQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}

View File

@ -0,0 +1,44 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"net/http"
)
type APIResponse struct {
*http.Response `json:"-"`
Message string `json:"message,omitempty"`
// Operation is the name of the swagger operation.
Operation string `json:"operation,omitempty"`
// RequestURL is the request URL. This value is always available, even if the
// embedded *http.Response is nil.
RequestURL string `json:"url,omitempty"`
// Method is the HTTP method used for the request. This value is always
// available, even if the embedded *http.Response is nil.
Method string `json:"method,omitempty"`
// Payload holds the contents of the response body (which may be nil or empty).
// This is provided here as the raw response.Body() reader will have already
// been drained.
Payload []byte `json:"-"`
}
func NewAPIResponse(r *http.Response) *APIResponse {
response := &APIResponse{Response: r}
return response
}
func NewAPIResponseWithError(errorMessage string) *APIResponse {
response := &APIResponse{Message: errorMessage}
return response
}

View File

@ -0,0 +1,67 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"encoding/base64"
"net/http"
"time"
)
type Configuration struct {
Username string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
APIKey map[string]string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
APIClient *APIClient
Transport *http.Transport
Timeout *time.Duration `json:"timeout,omitempty"`
}
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://localhost",
DefaultHeader: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
APIClient: &APIClient{},
}
cfg.APIClient.config = cfg
return cfg
}
func (c *Configuration) GetBasicAuthEncodedString() string {
return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
}
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[APIKeyIdentifier] != "" {
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
}
return c.APIKey[APIKeyIdentifier]
}

View File

@ -0,0 +1,72 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
import (
"time"
)
type ExamplepbABitOfEverything struct {
SingleNested ABitOfEverythingNested `json:"single_nested,omitempty"`
Uuid string `json:"uuid,omitempty"`
Nested []ABitOfEverythingNested `json:"nested,omitempty"`
FloatValue float32 `json:"float_value,omitempty"`
DoubleValue float64 `json:"double_value,omitempty"`
Int64Value string `json:"int64_value,omitempty"`
Uint64Value string `json:"uint64_value,omitempty"`
Int32Value int32 `json:"int32_value,omitempty"`
Fixed64Value string `json:"fixed64_value,omitempty"`
Fixed32Value int64 `json:"fixed32_value,omitempty"`
BoolValue bool `json:"bool_value,omitempty"`
StringValue string `json:"string_value,omitempty"`
Uint32Value int64 `json:"uint32_value,omitempty"`
EnumValue ExamplepbNumericEnum `json:"enum_value,omitempty"`
Sfixed32Value int32 `json:"sfixed32_value,omitempty"`
Sfixed64Value string `json:"sfixed64_value,omitempty"`
Sint32Value int32 `json:"sint32_value,omitempty"`
Sint64Value string `json:"sint64_value,omitempty"`
RepeatedStringValue []string `json:"repeated_string_value,omitempty"`
OneofEmpty ProtobufEmpty `json:"oneof_empty,omitempty"`
OneofString string `json:"oneof_string,omitempty"`
MapValue map[string]ExamplepbNumericEnum `json:"map_value,omitempty"`
MappedStringValue map[string]string `json:"mapped_string_value,omitempty"`
MappedNestedValue map[string]ABitOfEverythingNested `json:"mapped_nested_value,omitempty"`
NonConventionalNameValue string `json:"nonConventionalNameValue,omitempty"`
TimestampValue time.Time `json:"timestamp_value,omitempty"`
RepeatedEnumValue []ExamplepbNumericEnum `json:"repeated_enum_value,omitempty"`
}

View File

@ -0,0 +1,15 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
// NumericEnum is one or zero. - ZERO: ZERO means 0 - ONE: ONE means 1
type ExamplepbNumericEnum struct {
}

View File

@ -0,0 +1,15 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
// DeepEnum is one or zero. - FALSE: FALSE is false. - TRUE: TRUE is true.
type NestedDeepEnum struct {
}

View File

@ -0,0 +1,15 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`.
type ProtobufEmpty struct {
}

View File

@ -0,0 +1,16 @@
/*
* examples/examplepb/a_bit_of_everything.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package abe
type SubStringMessage struct {
Value string `json:"value,omitempty"`
}

View File

@ -0,0 +1,164 @@
/*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
import (
"bytes"
"fmt"
"path/filepath"
"reflect"
"strings"
"net/url"
"io/ioutil"
"github.com/go-resty/resty"
)
type APIClient struct {
config *Configuration
}
func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
if len(contentTypes) == 0 {
return ""
}
if contains(contentTypes, "application/json") {
return "application/json"
}
return contentTypes[0] // use the first content type specified in 'consumes'
}
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.ToLower(a) == strings.ToLower(needle) {
return true
}
}
return false
}
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) (*resty.Response, error) {
rClient := c.prepareClient()
request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
switch strings.ToUpper(method) {
case "GET":
response, err := request.Get(path)
return response, err
case "POST":
response, err := request.Post(path)
return response, err
case "PUT":
response, err := request.Put(path)
return response, err
case "PATCH":
response, err := request.Patch(path)
return response, err
case "DELETE":
response, err := request.Delete(path)
return response, err
}
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
delimiter := ""
switch collectionFormat {
case "pipes":
delimiter = "|"
case "ssv":
delimiter = " "
case "tsv":
delimiter = "\t"
case "csv":
delimiter = ","
}
if reflect.TypeOf(obj).Kind() == reflect.Slice {
return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
}
return fmt.Sprintf("%v", obj)
}
func (c *APIClient) prepareClient() *resty.Client {
rClient := resty.New()
rClient.SetDebug(c.config.Debug)
if c.config.Transport != nil {
rClient.SetTransport(c.config.Transport)
}
if c.config.Timeout != nil {
rClient.SetTimeout(*c.config.Timeout)
}
rClient.SetLogger(ioutil.Discard)
return rClient
}
func (c *APIClient) prepareRequest(
rClient *resty.Client,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams map[string]string,
fileName string,
fileBytes []byte) *resty.Request {
request := rClient.R()
request.SetBody(postBody)
if c.config.UserAgent != "" {
request.SetHeader("User-Agent", c.config.UserAgent)
}
// add header parameter, if any
if len(headerParams) > 0 {
request.SetHeaders(headerParams)
}
// add query parameter, if any
if len(queryParams) > 0 {
request.SetMultiValueQueryParams(queryParams)
}
// add form parameter, if any
if len(formParams) > 0 {
request.SetFormData(formParams)
}
if len(fileBytes) > 0 && fileName != "" {
_, fileNm := filepath.Split(fileName)
request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes))
}
return request
}

View File

@ -0,0 +1,44 @@
/*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
import (
"net/http"
)
type APIResponse struct {
*http.Response `json:"-"`
Message string `json:"message,omitempty"`
// Operation is the name of the swagger operation.
Operation string `json:"operation,omitempty"`
// RequestURL is the request URL. This value is always available, even if the
// embedded *http.Response is nil.
RequestURL string `json:"url,omitempty"`
// Method is the HTTP method used for the request. This value is always
// available, even if the embedded *http.Response is nil.
Method string `json:"method,omitempty"`
// Payload holds the contents of the response body (which may be nil or empty).
// This is provided here as the raw response.Body() reader will have already
// been drained.
Payload []byte `json:"-"`
}
func NewAPIResponse(r *http.Response) *APIResponse {
response := &APIResponse{Response: r}
return response
}
func NewAPIResponseWithError(errorMessage string) *APIResponse {
response := &APIResponse{Message: errorMessage}
return response
}

View File

@ -0,0 +1,67 @@
/*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
import (
"encoding/base64"
"net/http"
"time"
)
type Configuration struct {
Username string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
APIKey map[string]string `json:"APIKey,omitempty"`
Debug bool `json:"debug,omitempty"`
DebugFile string `json:"debugFile,omitempty"`
OAuthToken string `json:"oAuthToken,omitempty"`
BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
APIClient *APIClient
Transport *http.Transport
Timeout *time.Duration `json:"timeout,omitempty"`
}
func NewConfiguration() *Configuration {
cfg := &Configuration{
BasePath: "http://localhost",
DefaultHeader: make(map[string]string),
APIKey: make(map[string]string),
APIKeyPrefix: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
APIClient: &APIClient{},
}
cfg.APIClient.config = cfg
return cfg
}
func (c *Configuration) GetBasicAuthEncodedString() string {
return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
}
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string {
if c.APIKeyPrefix[APIKeyIdentifier] != "" {
return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier]
}
return c.APIKey[APIKeyIdentifier]
}

View File

@ -0,0 +1,224 @@
/*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
import (
"net/url"
"strings"
"encoding/json"
"fmt"
)
type EchoServiceApi struct {
Configuration *Configuration
}
func NewEchoServiceApi() *EchoServiceApi {
configuration := NewConfiguration()
return &EchoServiceApi{
Configuration: configuration,
}
}
func NewEchoServiceApiWithBasePath(basePath string) *EchoServiceApi {
configuration := NewConfiguration()
configuration.BasePath = basePath
return &EchoServiceApi{
Configuration: configuration,
}
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) Echo(id string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}"
localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* EchoBody method receives a simple message and returns it.
*
* @param body
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) EchoBody(body ExamplepbSimpleMessage) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Post")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo_body"
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "EchoBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}
/**
* Echo method receives a simple message and returns it.
* The message posted as the id parameter will also be returned.
*
* @param id
* @param num
* @return *ExamplepbSimpleMessage
*/
func (a EchoServiceApi) Echo_1(id string, num string) (*ExamplepbSimpleMessage, *APIResponse, error) {
var localVarHttpMethod = strings.ToUpper("Get")
// create path and map variables
localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}/{num}"
localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1)
localVarPath = strings.Replace(localVarPath, "{"+"num"+"}", fmt.Sprintf("%v", num), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := make(map[string]string)
var localVarPostBody interface{}
var localVarFileName string
var localVarFileBytes []byte
// add default headers if any
for key := range a.Configuration.DefaultHeader {
localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/json", }
// set Content-Type header
localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
var successPayload = new(ExamplepbSimpleMessage)
localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
var localVarURL, _ = url.Parse(localVarPath)
localVarURL.RawQuery = localVarQueryParams.Encode()
var localVarAPIResponse = &APIResponse{Operation: "Echo_0", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
if localVarHttpResponse != nil {
localVarAPIResponse.Response = localVarHttpResponse.RawResponse
localVarAPIResponse.Payload = localVarHttpResponse.Body()
}
if err != nil {
return successPayload, localVarAPIResponse, err
}
err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
return successPayload, localVarAPIResponse, err
}

View File

@ -0,0 +1,20 @@
/*
* Echo Service
*
* Echo Service API consists of a single service which returns a message.
*
* OpenAPI spec version: version not set
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package echo
// SimpleMessage represents a simple message sent to the Echo service.
type ExamplepbSimpleMessage struct {
// Id represents the message identifier.
Id string `json:"id,omitempty"`
Num string `json:"num,omitempty"`
}

View File

@ -0,0 +1,957 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/examplepb/a_bit_of_everything.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import google_protobuf1 "github.com/golang/protobuf/ptypes/empty"
import google_protobuf2 "github.com/golang/protobuf/ptypes/duration"
import grpc_gateway_examples_sub "github.com/grpc-ecosystem/grpc-gateway/examples/sub"
import sub2 "github.com/grpc-ecosystem/grpc-gateway/examples/sub2"
import google_protobuf3 "github.com/golang/protobuf/ptypes/timestamp"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// NumericEnum is one or zero.
type NumericEnum int32
const (
// ZERO means 0
NumericEnum_ZERO NumericEnum = 0
// ONE means 1
NumericEnum_ONE NumericEnum = 1
)
var NumericEnum_name = map[int32]string{
0: "ZERO",
1: "ONE",
}
var NumericEnum_value = map[string]int32{
"ZERO": 0,
"ONE": 1,
}
func (x NumericEnum) String() string {
return proto.EnumName(NumericEnum_name, int32(x))
}
func (NumericEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
// DeepEnum is one or zero.
type ABitOfEverything_Nested_DeepEnum int32
const (
// FALSE is false.
ABitOfEverything_Nested_FALSE ABitOfEverything_Nested_DeepEnum = 0
// TRUE is true.
ABitOfEverything_Nested_TRUE ABitOfEverything_Nested_DeepEnum = 1
)
var ABitOfEverything_Nested_DeepEnum_name = map[int32]string{
0: "FALSE",
1: "TRUE",
}
var ABitOfEverything_Nested_DeepEnum_value = map[string]int32{
"FALSE": 0,
"TRUE": 1,
}
func (x ABitOfEverything_Nested_DeepEnum) String() string {
return proto.EnumName(ABitOfEverything_Nested_DeepEnum_name, int32(x))
}
func (ABitOfEverything_Nested_DeepEnum) EnumDescriptor() ([]byte, []int) {
return fileDescriptor1, []int{0, 0, 0}
}
// Intentionaly complicated message type to cover much features of Protobuf.
// NEXT ID: 27
type ABitOfEverything struct {
SingleNested *ABitOfEverything_Nested `protobuf:"bytes,25,opt,name=single_nested,json=singleNested" json:"single_nested,omitempty"`
Uuid string `protobuf:"bytes,1,opt,name=uuid" json:"uuid,omitempty"`
Nested []*ABitOfEverything_Nested `protobuf:"bytes,2,rep,name=nested" json:"nested,omitempty"`
FloatValue float32 `protobuf:"fixed32,3,opt,name=float_value,json=floatValue" json:"float_value,omitempty"`
DoubleValue float64 `protobuf:"fixed64,4,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
Int64Value int64 `protobuf:"varint,5,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"`
Uint64Value uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"`
Int32Value int32 `protobuf:"varint,7,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"`
Fixed64Value uint64 `protobuf:"fixed64,8,opt,name=fixed64_value,json=fixed64Value" json:"fixed64_value,omitempty"`
Fixed32Value uint32 `protobuf:"fixed32,9,opt,name=fixed32_value,json=fixed32Value" json:"fixed32_value,omitempty"`
BoolValue bool `protobuf:"varint,10,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"`
StringValue string `protobuf:"bytes,11,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
// TODO(yugui) add bytes_value
Uint32Value uint32 `protobuf:"varint,13,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"`
EnumValue NumericEnum `protobuf:"varint,14,opt,name=enum_value,json=enumValue,enum=grpc.gateway.examples.examplepb.NumericEnum" json:"enum_value,omitempty"`
Sfixed32Value int32 `protobuf:"fixed32,15,opt,name=sfixed32_value,json=sfixed32Value" json:"sfixed32_value,omitempty"`
Sfixed64Value int64 `protobuf:"fixed64,16,opt,name=sfixed64_value,json=sfixed64Value" json:"sfixed64_value,omitempty"`
Sint32Value int32 `protobuf:"zigzag32,17,opt,name=sint32_value,json=sint32Value" json:"sint32_value,omitempty"`
Sint64Value int64 `protobuf:"zigzag64,18,opt,name=sint64_value,json=sint64Value" json:"sint64_value,omitempty"`
RepeatedStringValue []string `protobuf:"bytes,19,rep,name=repeated_string_value,json=repeatedStringValue" json:"repeated_string_value,omitempty"`
// Types that are valid to be assigned to OneofValue:
// *ABitOfEverything_OneofEmpty
// *ABitOfEverything_OneofString
OneofValue isABitOfEverything_OneofValue `protobuf_oneof:"oneof_value"`
MapValue map[string]NumericEnum `protobuf:"bytes,22,rep,name=map_value,json=mapValue" json:"map_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=grpc.gateway.examples.examplepb.NumericEnum"`
MappedStringValue map[string]string `protobuf:"bytes,23,rep,name=mapped_string_value,json=mappedStringValue" json:"mapped_string_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
MappedNestedValue map[string]*ABitOfEverything_Nested `protobuf:"bytes,24,rep,name=mapped_nested_value,json=mappedNestedValue" json:"mapped_nested_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
NonConventionalNameValue string `protobuf:"bytes,26,opt,name=nonConventionalNameValue" json:"nonConventionalNameValue,omitempty"`
TimestampValue *google_protobuf3.Timestamp `protobuf:"bytes,27,opt,name=timestamp_value,json=timestampValue" json:"timestamp_value,omitempty"`
// repeated enum value. it is comma-separated in query
RepeatedEnumValue []NumericEnum `protobuf:"varint,28,rep,packed,name=repeated_enum_value,json=repeatedEnumValue,enum=grpc.gateway.examples.examplepb.NumericEnum" json:"repeated_enum_value,omitempty"`
}
func (m *ABitOfEverything) Reset() { *m = ABitOfEverything{} }
func (m *ABitOfEverything) String() string { return proto.CompactTextString(m) }
func (*ABitOfEverything) ProtoMessage() {}
func (*ABitOfEverything) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
type isABitOfEverything_OneofValue interface {
isABitOfEverything_OneofValue()
}
type ABitOfEverything_OneofEmpty struct {
OneofEmpty *google_protobuf1.Empty `protobuf:"bytes,20,opt,name=oneof_empty,json=oneofEmpty,oneof"`
}
type ABitOfEverything_OneofString struct {
OneofString string `protobuf:"bytes,21,opt,name=oneof_string,json=oneofString,oneof"`
}
func (*ABitOfEverything_OneofEmpty) isABitOfEverything_OneofValue() {}
func (*ABitOfEverything_OneofString) isABitOfEverything_OneofValue() {}
func (m *ABitOfEverything) GetOneofValue() isABitOfEverything_OneofValue {
if m != nil {
return m.OneofValue
}
return nil
}
func (m *ABitOfEverything) GetSingleNested() *ABitOfEverything_Nested {
if m != nil {
return m.SingleNested
}
return nil
}
func (m *ABitOfEverything) GetUuid() string {
if m != nil {
return m.Uuid
}
return ""
}
func (m *ABitOfEverything) GetNested() []*ABitOfEverything_Nested {
if m != nil {
return m.Nested
}
return nil
}
func (m *ABitOfEverything) GetFloatValue() float32 {
if m != nil {
return m.FloatValue
}
return 0
}
func (m *ABitOfEverything) GetDoubleValue() float64 {
if m != nil {
return m.DoubleValue
}
return 0
}
func (m *ABitOfEverything) GetInt64Value() int64 {
if m != nil {
return m.Int64Value
}
return 0
}
func (m *ABitOfEverything) GetUint64Value() uint64 {
if m != nil {
return m.Uint64Value
}
return 0
}
func (m *ABitOfEverything) GetInt32Value() int32 {
if m != nil {
return m.Int32Value
}
return 0
}
func (m *ABitOfEverything) GetFixed64Value() uint64 {
if m != nil {
return m.Fixed64Value
}
return 0
}
func (m *ABitOfEverything) GetFixed32Value() uint32 {
if m != nil {
return m.Fixed32Value
}
return 0
}
func (m *ABitOfEverything) GetBoolValue() bool {
if m != nil {
return m.BoolValue
}
return false
}
func (m *ABitOfEverything) GetStringValue() string {
if m != nil {
return m.StringValue
}
return ""
}
func (m *ABitOfEverything) GetUint32Value() uint32 {
if m != nil {
return m.Uint32Value
}
return 0
}
func (m *ABitOfEverything) GetEnumValue() NumericEnum {
if m != nil {
return m.EnumValue
}
return NumericEnum_ZERO
}
func (m *ABitOfEverything) GetSfixed32Value() int32 {
if m != nil {
return m.Sfixed32Value
}
return 0
}
func (m *ABitOfEverything) GetSfixed64Value() int64 {
if m != nil {
return m.Sfixed64Value
}
return 0
}
func (m *ABitOfEverything) GetSint32Value() int32 {
if m != nil {
return m.Sint32Value
}
return 0
}
func (m *ABitOfEverything) GetSint64Value() int64 {
if m != nil {
return m.Sint64Value
}
return 0
}
func (m *ABitOfEverything) GetRepeatedStringValue() []string {
if m != nil {
return m.RepeatedStringValue
}
return nil
}
func (m *ABitOfEverything) GetOneofEmpty() *google_protobuf1.Empty {
if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofEmpty); ok {
return x.OneofEmpty
}
return nil
}
func (m *ABitOfEverything) GetOneofString() string {
if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofString); ok {
return x.OneofString
}
return ""
}
func (m *ABitOfEverything) GetMapValue() map[string]NumericEnum {
if m != nil {
return m.MapValue
}
return nil
}
func (m *ABitOfEverything) GetMappedStringValue() map[string]string {
if m != nil {
return m.MappedStringValue
}
return nil
}
func (m *ABitOfEverything) GetMappedNestedValue() map[string]*ABitOfEverything_Nested {
if m != nil {
return m.MappedNestedValue
}
return nil
}
func (m *ABitOfEverything) GetNonConventionalNameValue() string {
if m != nil {
return m.NonConventionalNameValue
}
return ""
}
func (m *ABitOfEverything) GetTimestampValue() *google_protobuf3.Timestamp {
if m != nil {
return m.TimestampValue
}
return nil
}
func (m *ABitOfEverything) GetRepeatedEnumValue() []NumericEnum {
if m != nil {
return m.RepeatedEnumValue
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*ABitOfEverything) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _ABitOfEverything_OneofMarshaler, _ABitOfEverything_OneofUnmarshaler, _ABitOfEverything_OneofSizer, []interface{}{
(*ABitOfEverything_OneofEmpty)(nil),
(*ABitOfEverything_OneofString)(nil),
}
}
func _ABitOfEverything_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*ABitOfEverything)
// oneof_value
switch x := m.OneofValue.(type) {
case *ABitOfEverything_OneofEmpty:
b.EncodeVarint(20<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.OneofEmpty); err != nil {
return err
}
case *ABitOfEverything_OneofString:
b.EncodeVarint(21<<3 | proto.WireBytes)
b.EncodeStringBytes(x.OneofString)
case nil:
default:
return fmt.Errorf("ABitOfEverything.OneofValue has unexpected type %T", x)
}
return nil
}
func _ABitOfEverything_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*ABitOfEverything)
switch tag {
case 20: // oneof_value.oneof_empty
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf1.Empty)
err := b.DecodeMessage(msg)
m.OneofValue = &ABitOfEverything_OneofEmpty{msg}
return true, err
case 21: // oneof_value.oneof_string
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.OneofValue = &ABitOfEverything_OneofString{x}
return true, err
default:
return false, nil
}
}
func _ABitOfEverything_OneofSizer(msg proto.Message) (n int) {
m := msg.(*ABitOfEverything)
// oneof_value
switch x := m.OneofValue.(type) {
case *ABitOfEverything_OneofEmpty:
s := proto.Size(x.OneofEmpty)
n += proto.SizeVarint(20<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *ABitOfEverything_OneofString:
n += proto.SizeVarint(21<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.OneofString)))
n += len(x.OneofString)
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
// Nested is nested type.
type ABitOfEverything_Nested struct {
// name is nested field.
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
Amount uint32 `protobuf:"varint,2,opt,name=amount" json:"amount,omitempty"`
Ok ABitOfEverything_Nested_DeepEnum `protobuf:"varint,3,opt,name=ok,enum=grpc.gateway.examples.examplepb.ABitOfEverything_Nested_DeepEnum" json:"ok,omitempty"`
}
func (m *ABitOfEverything_Nested) Reset() { *m = ABitOfEverything_Nested{} }
func (m *ABitOfEverything_Nested) String() string { return proto.CompactTextString(m) }
func (*ABitOfEverything_Nested) ProtoMessage() {}
func (*ABitOfEverything_Nested) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0, 0} }
func (m *ABitOfEverything_Nested) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *ABitOfEverything_Nested) GetAmount() uint32 {
if m != nil {
return m.Amount
}
return 0
}
func (m *ABitOfEverything_Nested) GetOk() ABitOfEverything_Nested_DeepEnum {
if m != nil {
return m.Ok
}
return ABitOfEverything_Nested_FALSE
}
func init() {
proto.RegisterType((*ABitOfEverything)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything")
proto.RegisterType((*ABitOfEverything_Nested)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.Nested")
proto.RegisterEnum("grpc.gateway.examples.examplepb.NumericEnum", NumericEnum_name, NumericEnum_value)
proto.RegisterEnum("grpc.gateway.examples.examplepb.ABitOfEverything_Nested_DeepEnum", ABitOfEverything_Nested_DeepEnum_name, ABitOfEverything_Nested_DeepEnum_value)
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for ABitOfEverythingService service
type ABitOfEverythingServiceClient interface {
Create(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error)
CreateBody(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error)
Lookup(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*ABitOfEverything, error)
Update(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*google_protobuf1.Empty, error)
Delete(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*google_protobuf1.Empty, error)
GetQuery(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*google_protobuf1.Empty, error)
Echo(ctx context.Context, in *grpc_gateway_examples_sub.StringMessage, opts ...grpc.CallOption) (*grpc_gateway_examples_sub.StringMessage, error)
DeepPathEcho(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error)
NoBindings(ctx context.Context, in *google_protobuf2.Duration, opts ...grpc.CallOption) (*google_protobuf1.Empty, error)
Timeout(ctx context.Context, in *google_protobuf1.Empty, opts ...grpc.CallOption) (*google_protobuf1.Empty, error)
}
type aBitOfEverythingServiceClient struct {
cc *grpc.ClientConn
}
func NewABitOfEverythingServiceClient(cc *grpc.ClientConn) ABitOfEverythingServiceClient {
return &aBitOfEverythingServiceClient{cc}
}
func (c *aBitOfEverythingServiceClient) Create(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) {
out := new(ABitOfEverything)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Create", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) CreateBody(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) {
out := new(ABitOfEverything)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/CreateBody", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) Lookup(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*ABitOfEverything, error) {
out := new(ABitOfEverything)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Lookup", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) Update(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) {
out := new(google_protobuf1.Empty)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Update", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) Delete(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) {
out := new(google_protobuf1.Empty)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Delete", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) GetQuery(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) {
out := new(google_protobuf1.Empty)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/GetQuery", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) Echo(ctx context.Context, in *grpc_gateway_examples_sub.StringMessage, opts ...grpc.CallOption) (*grpc_gateway_examples_sub.StringMessage, error) {
out := new(grpc_gateway_examples_sub.StringMessage)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Echo", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) DeepPathEcho(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) {
out := new(ABitOfEverything)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/DeepPathEcho", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) NoBindings(ctx context.Context, in *google_protobuf2.Duration, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) {
out := new(google_protobuf1.Empty)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/NoBindings", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aBitOfEverythingServiceClient) Timeout(ctx context.Context, in *google_protobuf1.Empty, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) {
out := new(google_protobuf1.Empty)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Timeout", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for ABitOfEverythingService service
type ABitOfEverythingServiceServer interface {
Create(context.Context, *ABitOfEverything) (*ABitOfEverything, error)
CreateBody(context.Context, *ABitOfEverything) (*ABitOfEverything, error)
Lookup(context.Context, *sub2.IdMessage) (*ABitOfEverything, error)
Update(context.Context, *ABitOfEverything) (*google_protobuf1.Empty, error)
Delete(context.Context, *sub2.IdMessage) (*google_protobuf1.Empty, error)
GetQuery(context.Context, *ABitOfEverything) (*google_protobuf1.Empty, error)
Echo(context.Context, *grpc_gateway_examples_sub.StringMessage) (*grpc_gateway_examples_sub.StringMessage, error)
DeepPathEcho(context.Context, *ABitOfEverything) (*ABitOfEverything, error)
NoBindings(context.Context, *google_protobuf2.Duration) (*google_protobuf1.Empty, error)
Timeout(context.Context, *google_protobuf1.Empty) (*google_protobuf1.Empty, error)
}
func RegisterABitOfEverythingServiceServer(s *grpc.Server, srv ABitOfEverythingServiceServer) {
s.RegisterService(&_ABitOfEverythingService_serviceDesc, srv)
}
func _ABitOfEverythingService_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ABitOfEverything)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).Create(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Create",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).Create(ctx, req.(*ABitOfEverything))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_CreateBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ABitOfEverything)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).CreateBody(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/CreateBody",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).CreateBody(ctx, req.(*ABitOfEverything))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_Lookup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sub2.IdMessage)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).Lookup(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Lookup",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).Lookup(ctx, req.(*sub2.IdMessage))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ABitOfEverything)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).Update(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Update",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).Update(ctx, req.(*ABitOfEverything))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sub2.IdMessage)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).Delete(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Delete",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).Delete(ctx, req.(*sub2.IdMessage))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_GetQuery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ABitOfEverything)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).GetQuery(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/GetQuery",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).GetQuery(ctx, req.(*ABitOfEverything))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(grpc_gateway_examples_sub.StringMessage)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).Echo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Echo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).Echo(ctx, req.(*grpc_gateway_examples_sub.StringMessage))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_DeepPathEcho_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ABitOfEverything)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).DeepPathEcho(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/DeepPathEcho",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).DeepPathEcho(ctx, req.(*ABitOfEverything))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_NoBindings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(google_protobuf2.Duration)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).NoBindings(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/NoBindings",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).NoBindings(ctx, req.(*google_protobuf2.Duration))
}
return interceptor(ctx, in, info, handler)
}
func _ABitOfEverythingService_Timeout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(google_protobuf1.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ABitOfEverythingServiceServer).Timeout(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Timeout",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ABitOfEverythingServiceServer).Timeout(ctx, req.(*google_protobuf1.Empty))
}
return interceptor(ctx, in, info, handler)
}
var _ABitOfEverythingService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.gateway.examples.examplepb.ABitOfEverythingService",
HandlerType: (*ABitOfEverythingServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Create",
Handler: _ABitOfEverythingService_Create_Handler,
},
{
MethodName: "CreateBody",
Handler: _ABitOfEverythingService_CreateBody_Handler,
},
{
MethodName: "Lookup",
Handler: _ABitOfEverythingService_Lookup_Handler,
},
{
MethodName: "Update",
Handler: _ABitOfEverythingService_Update_Handler,
},
{
MethodName: "Delete",
Handler: _ABitOfEverythingService_Delete_Handler,
},
{
MethodName: "GetQuery",
Handler: _ABitOfEverythingService_GetQuery_Handler,
},
{
MethodName: "Echo",
Handler: _ABitOfEverythingService_Echo_Handler,
},
{
MethodName: "DeepPathEcho",
Handler: _ABitOfEverythingService_DeepPathEcho_Handler,
},
{
MethodName: "NoBindings",
Handler: _ABitOfEverythingService_NoBindings_Handler,
},
{
MethodName: "Timeout",
Handler: _ABitOfEverythingService_Timeout_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/examplepb/a_bit_of_everything.proto",
}
// Client API for AnotherServiceWithNoBindings service
type AnotherServiceWithNoBindingsClient interface {
NoBindings(ctx context.Context, in *google_protobuf1.Empty, opts ...grpc.CallOption) (*google_protobuf1.Empty, error)
}
type anotherServiceWithNoBindingsClient struct {
cc *grpc.ClientConn
}
func NewAnotherServiceWithNoBindingsClient(cc *grpc.ClientConn) AnotherServiceWithNoBindingsClient {
return &anotherServiceWithNoBindingsClient{cc}
}
func (c *anotherServiceWithNoBindingsClient) NoBindings(ctx context.Context, in *google_protobuf1.Empty, opts ...grpc.CallOption) (*google_protobuf1.Empty, error) {
out := new(google_protobuf1.Empty)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.AnotherServiceWithNoBindings/NoBindings", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for AnotherServiceWithNoBindings service
type AnotherServiceWithNoBindingsServer interface {
NoBindings(context.Context, *google_protobuf1.Empty) (*google_protobuf1.Empty, error)
}
func RegisterAnotherServiceWithNoBindingsServer(s *grpc.Server, srv AnotherServiceWithNoBindingsServer) {
s.RegisterService(&_AnotherServiceWithNoBindings_serviceDesc, srv)
}
func _AnotherServiceWithNoBindings_NoBindings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(google_protobuf1.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AnotherServiceWithNoBindingsServer).NoBindings(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.AnotherServiceWithNoBindings/NoBindings",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AnotherServiceWithNoBindingsServer).NoBindings(ctx, req.(*google_protobuf1.Empty))
}
return interceptor(ctx, in, info, handler)
}
var _AnotherServiceWithNoBindings_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.gateway.examples.examplepb.AnotherServiceWithNoBindings",
HandlerType: (*AnotherServiceWithNoBindingsServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "NoBindings",
Handler: _AnotherServiceWithNoBindings_NoBindings_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/examplepb/a_bit_of_everything.proto",
}
func init() { proto.RegisterFile("examples/examplepb/a_bit_of_everything.proto", fileDescriptor1) }
var fileDescriptor1 = []byte{
// 1297 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x57, 0x4f, 0x6f, 0x1b, 0x45,
0x14, 0xcf, 0xd8, 0x89, 0x13, 0x3f, 0xc7, 0x89, 0x33, 0x69, 0x53, 0xd7, 0x2d, 0x64, 0x71, 0x01,
0xad, 0x42, 0xb5, 0xab, 0xba, 0x15, 0x6a, 0x23, 0x41, 0x95, 0x34, 0x86, 0x22, 0xda, 0xb4, 0xdd,
0xfe, 0x41, 0x8a, 0x5a, 0xac, 0xb5, 0x3d, 0xb6, 0x57, 0xf1, 0xee, 0x2c, 0xbb, 0xb3, 0x26, 0x96,
0x31, 0x07, 0x0e, 0x5c, 0x38, 0x72, 0xef, 0x05, 0x09, 0x71, 0xe1, 0xc8, 0x19, 0xbe, 0x03, 0x5f,
0x81, 0x03, 0x1f, 0x03, 0xed, 0xcc, 0xec, 0x76, 0xd7, 0x89, 0xe5, 0x26, 0x45, 0xbd, 0xed, 0xcc,
0x7b, 0xef, 0xf7, 0x7b, 0x7f, 0xe6, 0xbd, 0x99, 0x85, 0xab, 0xe4, 0xc8, 0xb4, 0xdd, 0x3e, 0xf1,
0x75, 0xf9, 0xe1, 0x36, 0x75, 0xb3, 0xd1, 0xb4, 0x58, 0x83, 0x76, 0x1a, 0x64, 0x40, 0xbc, 0x21,
0xeb, 0x59, 0x4e, 0x57, 0x73, 0x3d, 0xca, 0x28, 0xde, 0xec, 0x7a, 0x6e, 0x4b, 0xeb, 0x9a, 0x8c,
0x7c, 0x6b, 0x0e, 0xb5, 0xc8, 0x54, 0x8b, 0x4d, 0x2b, 0x97, 0xbb, 0x94, 0x76, 0xfb, 0x44, 0x37,
0x5d, 0x4b, 0x37, 0x1d, 0x87, 0x32, 0x93, 0x59, 0xd4, 0xf1, 0x85, 0x79, 0xe5, 0x92, 0x94, 0xf2,
0x55, 0x33, 0xe8, 0xe8, 0xc4, 0x76, 0xd9, 0x50, 0x0a, 0xdf, 0x9d, 0x14, 0xb6, 0x03, 0x8f, 0x5b,
0x4b, 0x79, 0x25, 0xf6, 0xd4, 0x0f, 0x9a, 0xba, 0x4d, 0x7c, 0xdf, 0xec, 0x92, 0x08, 0x38, 0x29,
0xab, 0x4d, 0x08, 0x37, 0x27, 0x81, 0x99, 0x65, 0x13, 0x9f, 0x99, 0xb6, 0x2b, 0x14, 0xaa, 0x7f,
0xad, 0x42, 0x69, 0x67, 0xd7, 0x62, 0x0f, 0x3a, 0xf5, 0x38, 0x60, 0xfc, 0x02, 0x8a, 0xbe, 0xe5,
0x74, 0xfb, 0xa4, 0xe1, 0x10, 0x9f, 0x91, 0x76, 0xf9, 0xa2, 0x82, 0xd4, 0x42, 0xed, 0xa6, 0x36,
0x23, 0x05, 0xda, 0x24, 0x92, 0xb6, 0xcf, 0xed, 0x8d, 0x65, 0x01, 0x27, 0x56, 0x18, 0xc3, 0x7c,
0x10, 0x58, 0xed, 0x32, 0x52, 0x90, 0x9a, 0x37, 0xf8, 0x37, 0x7e, 0x08, 0x39, 0xc9, 0x95, 0x51,
0xb2, 0x6f, 0xc4, 0x25, 0x71, 0xf0, 0x26, 0x14, 0x3a, 0x7d, 0x6a, 0xb2, 0xc6, 0xc0, 0xec, 0x07,
0xa4, 0x9c, 0x55, 0x90, 0x9a, 0x31, 0x80, 0x6f, 0x3d, 0x0b, 0x77, 0xf0, 0x7b, 0xb0, 0xdc, 0xa6,
0x41, 0xb3, 0x4f, 0xa4, 0xc6, 0xbc, 0x82, 0x54, 0x64, 0x14, 0xc4, 0x9e, 0x50, 0xd9, 0x84, 0x82,
0xe5, 0xb0, 0x8f, 0x6f, 0x48, 0x8d, 0x05, 0x05, 0xa9, 0x59, 0x03, 0xf8, 0x56, 0x8c, 0x11, 0x24,
0x35, 0x72, 0x0a, 0x52, 0xe7, 0x8d, 0x42, 0x90, 0x50, 0x11, 0x18, 0xd7, 0x6b, 0x52, 0x63, 0x51,
0x41, 0xea, 0x02, 0xc7, 0xb8, 0x5e, 0x13, 0x0a, 0x57, 0xa0, 0xd8, 0xb1, 0x8e, 0x48, 0x3b, 0x06,
0x59, 0x52, 0x90, 0x9a, 0x33, 0x96, 0xe5, 0x66, 0x5a, 0x29, 0xc6, 0xc9, 0x2b, 0x48, 0x5d, 0x94,
0x4a, 0x11, 0xd2, 0x3b, 0x00, 0x4d, 0x4a, 0xfb, 0x52, 0x03, 0x14, 0xa4, 0x2e, 0x19, 0xf9, 0x70,
0x27, 0x76, 0xd6, 0x67, 0x9e, 0xe5, 0x74, 0xa5, 0x42, 0x81, 0xe7, 0xbf, 0x20, 0xf6, 0x52, 0xf1,
0xc4, 0x2c, 0x45, 0x05, 0xa9, 0x45, 0x11, 0x4f, 0x44, 0xf2, 0x25, 0x00, 0x71, 0x02, 0x5b, 0x2a,
0xac, 0x28, 0x48, 0x5d, 0xa9, 0x5d, 0x9d, 0x59, 0xad, 0xfd, 0xc0, 0x26, 0x9e, 0xd5, 0xaa, 0x3b,
0x81, 0x6d, 0xe4, 0x43, 0x7b, 0x01, 0xf6, 0x01, 0xac, 0xf8, 0xe9, 0xb8, 0x56, 0x15, 0xa4, 0xae,
0x1a, 0x45, 0x3f, 0x15, 0x58, 0xac, 0x16, 0xe7, 0xa8, 0xa4, 0x20, 0xb5, 0x14, 0xa9, 0x25, 0xaa,
0xe1, 0x27, 0xbd, 0x5f, 0x53, 0x90, 0xba, 0x66, 0x14, 0xfc, 0x84, 0xf7, 0x52, 0x25, 0xc6, 0xc1,
0x0a, 0x52, 0xb1, 0x50, 0x89, 0x50, 0x6a, 0x70, 0xde, 0x23, 0x2e, 0x31, 0x19, 0x69, 0x37, 0x52,
0xf9, 0x5a, 0x57, 0xb2, 0x6a, 0xde, 0x58, 0x8f, 0x84, 0x8f, 0x13, 0x79, 0xbb, 0x05, 0x05, 0xea,
0x90, 0x70, 0x6c, 0x84, 0x5d, 0x5d, 0x3e, 0xc7, 0xfb, 0x65, 0x43, 0x13, 0xdd, 0xa7, 0x45, 0xdd,
0xa7, 0xd5, 0x43, 0xe9, 0xdd, 0x39, 0x03, 0xb8, 0x32, 0x5f, 0xe1, 0x2b, 0xb0, 0x2c, 0x4c, 0x05,
0x57, 0xf9, 0x7c, 0x58, 0x95, 0xbb, 0x73, 0x86, 0x00, 0x14, 0x24, 0xf8, 0x39, 0xe4, 0x6d, 0xd3,
0x95, 0x7e, 0x6c, 0xf0, 0x0e, 0xb9, 0x7d, 0xfa, 0x0e, 0xb9, 0x6f, 0xba, 0xdc, 0xdd, 0xba, 0xc3,
0xbc, 0xa1, 0xb1, 0x64, 0xcb, 0x25, 0x3e, 0x82, 0x75, 0xdb, 0x74, 0xdd, 0xc9, 0x78, 0x2f, 0x70,
0x9e, 0xbb, 0x67, 0xe2, 0x71, 0x53, 0xf9, 0x11, 0x84, 0x6b, 0xf6, 0xe4, 0x7e, 0x82, 0x59, 0x74,
0xad, 0x64, 0x2e, 0xbf, 0x19, 0xb3, 0x98, 0x04, 0xc7, 0x99, 0x13, 0xfb, 0x78, 0x1b, 0xca, 0x0e,
0x75, 0xee, 0x50, 0x67, 0x40, 0x9c, 0x70, 0xd2, 0x9a, 0xfd, 0x7d, 0xd3, 0x16, 0x6d, 0x5f, 0xae,
0xf0, 0xc6, 0x98, 0x2a, 0xc7, 0x77, 0x60, 0x35, 0x9e, 0xa3, 0xd2, 0xe3, 0x4b, 0xbc, 0xe2, 0x95,
0x63, 0x15, 0x7f, 0x12, 0xe9, 0x19, 0x2b, 0xb1, 0x89, 0x00, 0x79, 0x0e, 0xf1, 0x49, 0x6a, 0x24,
0x1a, 0xea, 0xb2, 0x92, 0x3d, 0x75, 0x43, 0xad, 0x45, 0x40, 0xf5, 0xa8, 0xb1, 0x2a, 0xbf, 0x21,
0xc8, 0xbd, 0x1a, 0xb7, 0x8e, 0x69, 0x93, 0x68, 0xdc, 0x86, 0xdf, 0x78, 0x03, 0x72, 0xa6, 0x4d,
0x03, 0x87, 0x95, 0x33, 0xbc, 0xc3, 0xe5, 0x0a, 0x3f, 0x82, 0x0c, 0x3d, 0xe4, 0xb3, 0x72, 0xa5,
0xb6, 0x73, 0xd6, 0x11, 0xac, 0xed, 0x11, 0xe2, 0x72, 0xc7, 0x32, 0xf4, 0xb0, 0xba, 0x09, 0x4b,
0xd1, 0x1a, 0xe7, 0x61, 0xe1, 0xb3, 0x9d, 0x7b, 0x8f, 0xeb, 0xa5, 0x39, 0xbc, 0x04, 0xf3, 0x4f,
0x8c, 0xa7, 0xf5, 0x12, 0xaa, 0x58, 0x50, 0x4c, 0x1d, 0x4c, 0x5c, 0x82, 0xec, 0x21, 0x19, 0x4a,
0x7f, 0xc3, 0x4f, 0xbc, 0x0b, 0x0b, 0x22, 0x3b, 0x99, 0x33, 0x8c, 0x1b, 0x61, 0xba, 0x9d, 0xb9,
0x89, 0x2a, 0x7b, 0xb0, 0x71, 0xf2, 0xd9, 0x3c, 0x81, 0xf3, 0x5c, 0x92, 0x33, 0x9f, 0x44, 0xf9,
0x3e, 0x42, 0x99, 0x3c, 0x67, 0x27, 0xa0, 0xec, 0x27, 0x51, 0xde, 0xe4, 0x5a, 0x7b, 0xc5, 0xbf,
0x5b, 0x8c, 0x86, 0x0d, 0xdf, 0xda, 0x52, 0xa0, 0x90, 0x08, 0x37, 0x4c, 0xec, 0x41, 0xdd, 0x78,
0x50, 0x9a, 0xc3, 0x8b, 0x90, 0x7d, 0xb0, 0x5f, 0x2f, 0xa1, 0xda, 0xbf, 0xcb, 0x70, 0x61, 0x12,
0xf7, 0x31, 0xf1, 0x06, 0x56, 0x8b, 0xe0, 0x97, 0x59, 0xc8, 0xdd, 0xf1, 0xc2, 0xd3, 0x83, 0xaf,
0x9d, 0xda, 0xb9, 0xca, 0xe9, 0x4d, 0xaa, 0xbf, 0x67, 0x7e, 0xf8, 0xfb, 0x9f, 0x9f, 0x33, 0xbf,
0x66, 0xaa, 0xbf, 0x64, 0xf4, 0xc1, 0xb5, 0xe8, 0xed, 0x75, 0xd2, 0xcb, 0x4b, 0x1f, 0x25, 0x6e,
0xf0, 0xb1, 0x3e, 0x4a, 0x5e, 0xd7, 0x63, 0x7d, 0x94, 0x98, 0xe3, 0x63, 0xdd, 0x27, 0xae, 0xe9,
0x99, 0x8c, 0x7a, 0xfa, 0x28, 0x48, 0x09, 0x46, 0x89, 0x1b, 0x61, 0xac, 0x8f, 0x52, 0xd7, 0x48,
0xb4, 0x4e, 0xc8, 0x5f, 0x5d, 0xa0, 0x63, 0x7d, 0x94, 0x1c, 0x87, 0x9f, 0xf8, 0xcc, 0x73, 0x3d,
0xd2, 0xb1, 0x8e, 0xf4, 0xad, 0xb1, 0x20, 0x49, 0x98, 0xf9, 0x93, 0x38, 0xfe, 0x24, 0x91, 0x3f,
0x61, 0x90, 0x76, 0x72, 0xda, 0xac, 0x19, 0xe3, 0x97, 0x08, 0x40, 0x14, 0x68, 0x97, 0xb6, 0x87,
0x6f, 0xa9, 0x48, 0x5b, 0xbc, 0x46, 0xef, 0x57, 0x37, 0x67, 0x54, 0x68, 0x1b, 0x6d, 0xe1, 0xef,
0x20, 0x77, 0x8f, 0xd2, 0xc3, 0xc0, 0xc5, 0xab, 0x5a, 0xf8, 0x04, 0xd5, 0xbe, 0x68, 0xdf, 0x17,
0x8f, 0xd0, 0xb3, 0x30, 0x6b, 0x9c, 0x59, 0xc5, 0x1f, 0xce, 0x3c, 0x1b, 0xe1, 0xbb, 0x71, 0x8c,
0x7f, 0x44, 0x90, 0x7b, 0xea, 0xb6, 0xcf, 0x78, 0x7e, 0xa7, 0x5c, 0xd1, 0xd5, 0x6b, 0xdc, 0x8b,
0x8f, 0x2a, 0xaf, 0xe9, 0x45, 0x98, 0x06, 0x13, 0x72, 0x7b, 0xa4, 0x4f, 0x18, 0x39, 0x9e, 0x86,
0x69, 0x2c, 0x32, 0xd6, 0xad, 0xd7, 0x8d, 0xf5, 0x27, 0x04, 0x4b, 0x9f, 0x13, 0xf6, 0x28, 0x20,
0xde, 0xf0, 0xff, 0x8c, 0xf6, 0x06, 0xf7, 0x43, 0xc3, 0x57, 0x67, 0xf9, 0xf1, 0x4d, 0xc8, 0x1c,
0x79, 0xf3, 0x27, 0x82, 0xf9, 0x7a, 0xab, 0x47, 0xb1, 0x3a, 0xc5, 0x13, 0x3f, 0x68, 0x6a, 0x62,
0xd0, 0x46, 0x89, 0x78, 0x6d, 0xcd, 0x6a, 0x8b, 0xbb, 0xf4, 0x62, 0xb6, 0x4b, 0xa4, 0xd5, 0xa3,
0xfa, 0x48, 0xb4, 0xd1, 0xc1, 0xc5, 0x6a, 0x49, 0x1f, 0xd4, 0x62, 0xfd, 0x50, 0xb6, 0x2d, 0x06,
0xe7, 0x01, 0xc6, 0xc7, 0x44, 0xf8, 0x0f, 0x04, 0xcb, 0xe1, 0xdd, 0xf4, 0xd0, 0x64, 0x3d, 0x1e,
0xc9, 0xdb, 0x69, 0xae, 0xdb, 0x3c, 0xb6, 0x5b, 0xd5, 0x1b, 0x33, 0xcb, 0x9e, 0xfa, 0x0b, 0xd3,
0xc2, 0x9b, 0x9b, 0x1f, 0xb5, 0x1d, 0x80, 0x7d, 0xba, 0x6b, 0x39, 0x6d, 0xcb, 0xe9, 0xfa, 0xf8,
0xe2, 0xb1, 0xaa, 0xee, 0xc9, 0xbf, 0xc7, 0xa9, 0x05, 0x9f, 0xc3, 0xcf, 0x60, 0x31, 0x7c, 0x9a,
0xd0, 0x80, 0xe1, 0x29, 0x4a, 0x53, 0x8d, 0x2f, 0x71, 0xf7, 0xcf, 0xe3, 0xf5, 0x64, 0x3e, 0x99,
0x00, 0xab, 0x7d, 0x0d, 0x97, 0x77, 0x1c, 0xca, 0x7a, 0xc4, 0x93, 0x17, 0xcc, 0x57, 0x16, 0xeb,
0x25, 0x9c, 0xfd, 0x34, 0xe5, 0xfa, 0x69, 0xa9, 0xe7, 0x76, 0x0b, 0x07, 0xf9, 0x38, 0xb3, 0xcd,
0x1c, 0x17, 0x5f, 0xff, 0x2f, 0x00, 0x00, 0xff, 0xff, 0xab, 0xe5, 0x92, 0x0d, 0xc9, 0x0f, 0x00,
0x00,
}

View File

@ -0,0 +1,851 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/examplepb/a_bit_of_everything.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
"github.com/grpc-ecosystem/grpc-gateway/examples/sub"
"github.com/grpc-ecosystem/grpc-gateway/examples/sub2"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var (
filter_ABitOfEverythingService_Create_0 = &utilities.DoubleArray{Encoding: map[string]int{"float_value": 0, "double_value": 1, "int64_value": 2, "uint64_value": 3, "int32_value": 4, "fixed64_value": 5, "fixed32_value": 6, "bool_value": 7, "string_value": 8, "uint32_value": 9, "sfixed32_value": 10, "sfixed64_value": 11, "sint32_value": 12, "sint64_value": 13, "nonConventionalNameValue": 14}, Base: []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Check: []int{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}}
)
func request_ABitOfEverythingService_Create_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ABitOfEverything
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["float_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "float_value")
}
protoReq.FloatValue, err = runtime.Float32(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "float_value", err)
}
val, ok = pathParams["double_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "double_value")
}
protoReq.DoubleValue, err = runtime.Float64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "double_value", err)
}
val, ok = pathParams["int64_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int64_value")
}
protoReq.Int64Value, err = runtime.Int64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int64_value", err)
}
val, ok = pathParams["uint64_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint64_value")
}
protoReq.Uint64Value, err = runtime.Uint64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint64_value", err)
}
val, ok = pathParams["int32_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int32_value")
}
protoReq.Int32Value, err = runtime.Int32(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int32_value", err)
}
val, ok = pathParams["fixed64_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed64_value")
}
protoReq.Fixed64Value, err = runtime.Uint64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed64_value", err)
}
val, ok = pathParams["fixed32_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed32_value")
}
protoReq.Fixed32Value, err = runtime.Uint32(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed32_value", err)
}
val, ok = pathParams["bool_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "bool_value")
}
protoReq.BoolValue, err = runtime.Bool(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "bool_value", err)
}
val, ok = pathParams["string_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "string_value")
}
protoReq.StringValue, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "string_value", err)
}
val, ok = pathParams["uint32_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint32_value")
}
protoReq.Uint32Value, err = runtime.Uint32(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint32_value", err)
}
val, ok = pathParams["sfixed32_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed32_value")
}
protoReq.Sfixed32Value, err = runtime.Int32(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed32_value", err)
}
val, ok = pathParams["sfixed64_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed64_value")
}
protoReq.Sfixed64Value, err = runtime.Int64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed64_value", err)
}
val, ok = pathParams["sint32_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint32_value")
}
protoReq.Sint32Value, err = runtime.Int32(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint32_value", err)
}
val, ok = pathParams["sint64_value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint64_value")
}
protoReq.Sint64Value, err = runtime.Int64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint64_value", err)
}
val, ok = pathParams["nonConventionalNameValue"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "nonConventionalNameValue")
}
protoReq.NonConventionalNameValue, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "nonConventionalNameValue", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_ABitOfEverythingService_Create_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Create(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_CreateBody_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ABitOfEverything
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.CreateBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_Lookup_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq sub2.IdMessage
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["uuid"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid")
}
protoReq.Uuid, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err)
}
msg, err := client.Lookup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_Update_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ABitOfEverything
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["uuid"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid")
}
protoReq.Uuid, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err)
}
msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq sub2.IdMessage
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["uuid"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid")
}
protoReq.Uuid, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err)
}
msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_ABitOfEverythingService_GetQuery_0 = &utilities.DoubleArray{Encoding: map[string]int{"uuid": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}}
)
func request_ABitOfEverythingService_GetQuery_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ABitOfEverything
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["uuid"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid")
}
protoReq.Uuid, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_ABitOfEverythingService_GetQuery_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.GetQuery(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq sub.StringMessage
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["value"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value")
}
protoReq.Value, err = runtime.StringP(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err)
}
msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq sub.StringMessage
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.Value); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
var (
filter_ABitOfEverythingService_Echo_2 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_ABitOfEverythingService_Echo_2(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq sub.StringMessage
var metadata runtime.ServerMetadata
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_ABitOfEverythingService_Echo_2); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_DeepPathEcho_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ABitOfEverything
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["single_nested.name"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.name")
}
err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.name", val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.name", err)
}
msg, err := client.DeepPathEcho(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_ABitOfEverythingService_Timeout_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq empty.Empty
var metadata runtime.ServerMetadata
msg, err := client.Timeout(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
// RegisterABitOfEverythingServiceHandlerFromEndpoint is same as RegisterABitOfEverythingServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterABitOfEverythingServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterABitOfEverythingServiceHandler(ctx, mux, conn)
}
// RegisterABitOfEverythingServiceHandler registers the http handlers for service ABitOfEverythingService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterABitOfEverythingServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
client := NewABitOfEverythingServiceClient(conn)
mux.Handle("POST", pattern_ABitOfEverythingService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Create_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_ABitOfEverythingService_CreateBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_CreateBody_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_CreateBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_ABitOfEverythingService_Lookup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Lookup_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Lookup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("PUT", pattern_ABitOfEverythingService_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Update_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("DELETE", pattern_ABitOfEverythingService_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Delete_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_ABitOfEverythingService_GetQuery_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_GetQuery_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_GetQuery_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_ABitOfEverythingService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Echo_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_ABitOfEverythingService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Echo_1(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_ABitOfEverythingService_Echo_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Echo_2(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Echo_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_ABitOfEverythingService_DeepPathEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_DeepPathEcho_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_DeepPathEcho_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_ABitOfEverythingService_Timeout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ABitOfEverythingService_Timeout_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ABitOfEverythingService_Timeout_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_ABitOfEverythingService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5, 2, 6, 1, 0, 4, 1, 5, 7, 1, 0, 4, 1, 5, 8, 1, 0, 4, 1, 5, 9, 1, 0, 4, 1, 5, 10, 1, 0, 4, 1, 5, 11, 2, 12, 1, 0, 4, 2, 5, 13, 1, 0, 4, 1, 5, 14, 1, 0, 4, 1, 5, 15, 1, 0, 4, 1, 5, 16, 1, 0, 4, 1, 5, 17, 1, 0, 4, 1, 5, 18, 1, 0, 4, 1, 5, 19}, []string{"v1", "example", "a_bit_of_everything", "float_value", "double_value", "int64_value", "separator", "uint64_value", "int32_value", "fixed64_value", "fixed32_value", "bool_value", "strprefix", "string_value", "uint32_value", "sfixed32_value", "sfixed64_value", "sint32_value", "sint64_value", "nonConventionalNameValue"}, ""))
pattern_ABitOfEverythingService_CreateBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, ""))
pattern_ABitOfEverythingService_Lookup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, ""))
pattern_ABitOfEverythingService_Update_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, ""))
pattern_ABitOfEverythingService_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, ""))
pattern_ABitOfEverythingService_GetQuery_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "a_bit_of_everything", "query", "uuid"}, ""))
pattern_ABitOfEverythingService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "a_bit_of_everything", "echo", "value"}, ""))
pattern_ABitOfEverythingService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, ""))
pattern_ABitOfEverythingService_Echo_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, ""))
pattern_ABitOfEverythingService_DeepPathEcho_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "single_nested.name"}, ""))
pattern_ABitOfEverythingService_Timeout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "timeout"}, ""))
)
var (
forward_ABitOfEverythingService_Create_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_CreateBody_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_Lookup_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_Update_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_Delete_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_GetQuery_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_Echo_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_Echo_1 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_Echo_2 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_DeepPathEcho_0 = runtime.ForwardResponseMessage
forward_ABitOfEverythingService_Timeout_0 = runtime.ForwardResponseMessage
)

View File

@ -0,0 +1,216 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/examplepb/echo_service.proto
/*
Package examplepb is a generated protocol buffer package.
Echo Service
Echo Service API consists of a single service which returns
a message.
It is generated from these files:
examples/examplepb/echo_service.proto
examples/examplepb/a_bit_of_everything.proto
examples/examplepb/stream.proto
examples/examplepb/flow_combination.proto
It has these top-level messages:
SimpleMessage
ABitOfEverything
EmptyProto
NonEmptyProto
UnaryProto
NestedProto
SingleNestedProto
*/
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// SimpleMessage represents a simple message sent to the Echo service.
type SimpleMessage struct {
// Id represents the message identifier.
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Num int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
}
func (m *SimpleMessage) Reset() { *m = SimpleMessage{} }
func (m *SimpleMessage) String() string { return proto.CompactTextString(m) }
func (*SimpleMessage) ProtoMessage() {}
func (*SimpleMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *SimpleMessage) GetId() string {
if m != nil {
return m.Id
}
return ""
}
func (m *SimpleMessage) GetNum() int64 {
if m != nil {
return m.Num
}
return 0
}
func init() {
proto.RegisterType((*SimpleMessage)(nil), "grpc.gateway.examples.examplepb.SimpleMessage")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for EchoService service
type EchoServiceClient interface {
// Echo method receives a simple message and returns it.
//
// The message posted as the id parameter will also be
// returned.
Echo(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error)
// EchoBody method receives a simple message and returns it.
EchoBody(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error)
}
type echoServiceClient struct {
cc *grpc.ClientConn
}
func NewEchoServiceClient(cc *grpc.ClientConn) EchoServiceClient {
return &echoServiceClient{cc}
}
func (c *echoServiceClient) Echo(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) {
out := new(SimpleMessage)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.EchoService/Echo", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *echoServiceClient) EchoBody(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) {
out := new(SimpleMessage)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.EchoService/EchoBody", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for EchoService service
type EchoServiceServer interface {
// Echo method receives a simple message and returns it.
//
// The message posted as the id parameter will also be
// returned.
Echo(context.Context, *SimpleMessage) (*SimpleMessage, error)
// EchoBody method receives a simple message and returns it.
EchoBody(context.Context, *SimpleMessage) (*SimpleMessage, error)
}
func RegisterEchoServiceServer(s *grpc.Server, srv EchoServiceServer) {
s.RegisterService(&_EchoService_serviceDesc, srv)
}
func _EchoService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimpleMessage)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EchoServiceServer).Echo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.EchoService/Echo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EchoServiceServer).Echo(ctx, req.(*SimpleMessage))
}
return interceptor(ctx, in, info, handler)
}
func _EchoService_EchoBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimpleMessage)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EchoServiceServer).EchoBody(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.EchoService/EchoBody",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EchoServiceServer).EchoBody(ctx, req.(*SimpleMessage))
}
return interceptor(ctx, in, info, handler)
}
var _EchoService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.gateway.examples.examplepb.EchoService",
HandlerType: (*EchoServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Echo",
Handler: _EchoService_Echo_Handler,
},
{
MethodName: "EchoBody",
Handler: _EchoService_EchoBody_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "examples/examplepb/echo_service.proto",
}
func init() { proto.RegisterFile("examples/examplepb/echo_service.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 257 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x87, 0x32, 0x0a, 0x92, 0xf4, 0x53, 0x93, 0x33, 0xf2, 0xe3, 0x8b,
0x53, 0x8b, 0xca, 0x32, 0x93, 0x53, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xe4, 0xd3, 0x8b,
0x0a, 0x92, 0xf5, 0xd2, 0x13, 0x4b, 0x52, 0xcb, 0x13, 0x2b, 0xf5, 0x60, 0x7a, 0xf4, 0xe0, 0x7a,
0xa4, 0x64, 0xd2, 0xf3, 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0x13, 0x0b, 0x32, 0xf5, 0x13, 0xf3, 0xf2,
0xf2, 0x4b, 0x12, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0x21, 0xda, 0x95, 0x0c, 0xb9, 0x78, 0x83, 0x33,
0x41, 0x2a, 0x7d, 0x53, 0x8b, 0x8b, 0x13, 0xd3, 0x53, 0x85, 0xf8, 0xb8, 0x98, 0x32, 0x53, 0x24,
0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0x98, 0x32, 0x53, 0x84, 0x04, 0xb8, 0x98, 0xf3, 0x4a, 0x73,
0x25, 0x98, 0x14, 0x18, 0x35, 0x98, 0x83, 0x40, 0x4c, 0xa3, 0xc3, 0x4c, 0x5c, 0xdc, 0xae, 0xc9,
0x19, 0xf9, 0xc1, 0x10, 0x77, 0x08, 0x2d, 0x61, 0xe4, 0x62, 0x01, 0xf1, 0x85, 0xf4, 0xf4, 0x08,
0xb8, 0x45, 0x0f, 0xc5, 0x2a, 0x29, 0x12, 0xd5, 0x2b, 0xd9, 0x34, 0x5d, 0x7e, 0x32, 0x99, 0xc9,
0x4c, 0x49, 0x54, 0xbf, 0xcc, 0x10, 0x16, 0x28, 0xe0, 0x20, 0xd1, 0xaf, 0xce, 0x4c, 0xa9, 0x8d,
0x92, 0x15, 0x92, 0xc6, 0x2a, 0xa1, 0x5f, 0x9d, 0x57, 0x9a, 0x5b, 0x2b, 0xd4, 0xc3, 0xc8, 0xc5,
0x01, 0x72, 0xa6, 0x53, 0x7e, 0x4a, 0x25, 0xcd, 0x9d, 0xaa, 0x00, 0x76, 0xaa, 0x14, 0xa6, 0x53,
0xe3, 0x93, 0xf2, 0x53, 0x2a, 0xad, 0x18, 0xb5, 0x9c, 0xb8, 0xa3, 0x38, 0xe1, 0x9a, 0x93, 0xd8,
0xc0, 0x91, 0x61, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xf8, 0x6e, 0x70, 0xce, 0xf4, 0x01, 0x00,
0x00,
}

View File

@ -0,0 +1,251 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/examplepb/echo_service.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var (
filter_EchoService_Echo_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}}
)
func request_EchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SimpleMessage
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["id"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id")
}
protoReq.Id, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_EchoService_Echo_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_EchoService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SimpleMessage
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["id"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id")
}
protoReq.Id, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err)
}
val, ok = pathParams["num"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num")
}
protoReq.Num, err = runtime.Int64(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err)
}
msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func request_EchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SimpleMessage
var metadata runtime.ServerMetadata
if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.EchoBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
// RegisterEchoServiceHandlerFromEndpoint is same as RegisterEchoServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterEchoServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterEchoServiceHandler(ctx, mux, conn)
}
// RegisterEchoServiceHandler registers the http handlers for service EchoService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
client := NewEchoServiceClient(conn)
mux.Handle("POST", pattern_EchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_EchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_EchoService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EchoService_Echo_1(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_EchoService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_EchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_EchoService_EchoBody_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_EchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_EchoService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "echo", "id"}, ""))
pattern_EchoService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "echo", "id", "num"}, ""))
pattern_EchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_body"}, ""))
)
var (
forward_EchoService_Echo_0 = runtime.ForwardResponseMessage
forward_EchoService_Echo_1 = runtime.ForwardResponseMessage
forward_EchoService_EchoBody_0 = runtime.ForwardResponseMessage
)

View File

@ -0,0 +1,722 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/examplepb/flow_combination.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
type EmptyProto struct {
}
func (m *EmptyProto) Reset() { *m = EmptyProto{} }
func (m *EmptyProto) String() string { return proto.CompactTextString(m) }
func (*EmptyProto) ProtoMessage() {}
func (*EmptyProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{0} }
type NonEmptyProto struct {
A string `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
B string `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"`
C string `protobuf:"bytes,3,opt,name=c" json:"c,omitempty"`
}
func (m *NonEmptyProto) Reset() { *m = NonEmptyProto{} }
func (m *NonEmptyProto) String() string { return proto.CompactTextString(m) }
func (*NonEmptyProto) ProtoMessage() {}
func (*NonEmptyProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} }
func (m *NonEmptyProto) GetA() string {
if m != nil {
return m.A
}
return ""
}
func (m *NonEmptyProto) GetB() string {
if m != nil {
return m.B
}
return ""
}
func (m *NonEmptyProto) GetC() string {
if m != nil {
return m.C
}
return ""
}
type UnaryProto struct {
Str string `protobuf:"bytes,1,opt,name=str" json:"str,omitempty"`
}
func (m *UnaryProto) Reset() { *m = UnaryProto{} }
func (m *UnaryProto) String() string { return proto.CompactTextString(m) }
func (*UnaryProto) ProtoMessage() {}
func (*UnaryProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{2} }
func (m *UnaryProto) GetStr() string {
if m != nil {
return m.Str
}
return ""
}
type NestedProto struct {
A *UnaryProto `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
B string `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"`
C string `protobuf:"bytes,3,opt,name=c" json:"c,omitempty"`
}
func (m *NestedProto) Reset() { *m = NestedProto{} }
func (m *NestedProto) String() string { return proto.CompactTextString(m) }
func (*NestedProto) ProtoMessage() {}
func (*NestedProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{3} }
func (m *NestedProto) GetA() *UnaryProto {
if m != nil {
return m.A
}
return nil
}
func (m *NestedProto) GetB() string {
if m != nil {
return m.B
}
return ""
}
func (m *NestedProto) GetC() string {
if m != nil {
return m.C
}
return ""
}
type SingleNestedProto struct {
A *UnaryProto `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
}
func (m *SingleNestedProto) Reset() { *m = SingleNestedProto{} }
func (m *SingleNestedProto) String() string { return proto.CompactTextString(m) }
func (*SingleNestedProto) ProtoMessage() {}
func (*SingleNestedProto) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{4} }
func (m *SingleNestedProto) GetA() *UnaryProto {
if m != nil {
return m.A
}
return nil
}
func init() {
proto.RegisterType((*EmptyProto)(nil), "grpc.gateway.examples.examplepb.EmptyProto")
proto.RegisterType((*NonEmptyProto)(nil), "grpc.gateway.examples.examplepb.NonEmptyProto")
proto.RegisterType((*UnaryProto)(nil), "grpc.gateway.examples.examplepb.UnaryProto")
proto.RegisterType((*NestedProto)(nil), "grpc.gateway.examples.examplepb.NestedProto")
proto.RegisterType((*SingleNestedProto)(nil), "grpc.gateway.examples.examplepb.SingleNestedProto")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for FlowCombination service
type FlowCombinationClient interface {
RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error)
RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error)
StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error)
StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error)
RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error)
RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error)
RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error)
RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error)
RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error)
RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error)
}
type flowCombinationClient struct {
cc *grpc.ClientConn
}
func NewFlowCombinationClient(cc *grpc.ClientConn) FlowCombinationClient {
return &flowCombinationClient{cc}
}
func (c *flowCombinationClient) RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) {
out := new(EmptyProto)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyRpc", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *flowCombinationClient) RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error) {
stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[0], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyStream", opts...)
if err != nil {
return nil, err
}
x := &flowCombinationRpcEmptyStreamClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlowCombination_RpcEmptyStreamClient interface {
Recv() (*EmptyProto, error)
grpc.ClientStream
}
type flowCombinationRpcEmptyStreamClient struct {
grpc.ClientStream
}
func (x *flowCombinationRpcEmptyStreamClient) Recv() (*EmptyProto, error) {
m := new(EmptyProto)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *flowCombinationClient) StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error) {
stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[1], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/StreamEmptyRpc", opts...)
if err != nil {
return nil, err
}
x := &flowCombinationStreamEmptyRpcClient{stream}
return x, nil
}
type FlowCombination_StreamEmptyRpcClient interface {
Send(*EmptyProto) error
CloseAndRecv() (*EmptyProto, error)
grpc.ClientStream
}
type flowCombinationStreamEmptyRpcClient struct {
grpc.ClientStream
}
func (x *flowCombinationStreamEmptyRpcClient) Send(m *EmptyProto) error {
return x.ClientStream.SendMsg(m)
}
func (x *flowCombinationStreamEmptyRpcClient) CloseAndRecv() (*EmptyProto, error) {
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
m := new(EmptyProto)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *flowCombinationClient) StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error) {
stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[2], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/StreamEmptyStream", opts...)
if err != nil {
return nil, err
}
x := &flowCombinationStreamEmptyStreamClient{stream}
return x, nil
}
type FlowCombination_StreamEmptyStreamClient interface {
Send(*EmptyProto) error
Recv() (*EmptyProto, error)
grpc.ClientStream
}
type flowCombinationStreamEmptyStreamClient struct {
grpc.ClientStream
}
func (x *flowCombinationStreamEmptyStreamClient) Send(m *EmptyProto) error {
return x.ClientStream.SendMsg(m)
}
func (x *flowCombinationStreamEmptyStreamClient) Recv() (*EmptyProto, error) {
m := new(EmptyProto)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *flowCombinationClient) RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) {
out := new(EmptyProto)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyRpc", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *flowCombinationClient) RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error) {
out := new(EmptyProto)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedRpc", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *flowCombinationClient) RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error) {
out := new(EmptyProto)
err := grpc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedRpc", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *flowCombinationClient) RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error) {
stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[3], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyStream", opts...)
if err != nil {
return nil, err
}
x := &flowCombinationRpcBodyStreamClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlowCombination_RpcBodyStreamClient interface {
Recv() (*EmptyProto, error)
grpc.ClientStream
}
type flowCombinationRpcBodyStreamClient struct {
grpc.ClientStream
}
func (x *flowCombinationRpcBodyStreamClient) Recv() (*EmptyProto, error) {
m := new(EmptyProto)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *flowCombinationClient) RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error) {
stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[4], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedStream", opts...)
if err != nil {
return nil, err
}
x := &flowCombinationRpcPathSingleNestedStreamClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlowCombination_RpcPathSingleNestedStreamClient interface {
Recv() (*EmptyProto, error)
grpc.ClientStream
}
type flowCombinationRpcPathSingleNestedStreamClient struct {
grpc.ClientStream
}
func (x *flowCombinationRpcPathSingleNestedStreamClient) Recv() (*EmptyProto, error) {
m := new(EmptyProto)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *flowCombinationClient) RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error) {
stream, err := grpc.NewClientStream(ctx, &_FlowCombination_serviceDesc.Streams[5], c.cc, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedStream", opts...)
if err != nil {
return nil, err
}
x := &flowCombinationRpcPathNestedStreamClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type FlowCombination_RpcPathNestedStreamClient interface {
Recv() (*EmptyProto, error)
grpc.ClientStream
}
type flowCombinationRpcPathNestedStreamClient struct {
grpc.ClientStream
}
func (x *flowCombinationRpcPathNestedStreamClient) Recv() (*EmptyProto, error) {
m := new(EmptyProto)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// Server API for FlowCombination service
type FlowCombinationServer interface {
RpcEmptyRpc(context.Context, *EmptyProto) (*EmptyProto, error)
RpcEmptyStream(*EmptyProto, FlowCombination_RpcEmptyStreamServer) error
StreamEmptyRpc(FlowCombination_StreamEmptyRpcServer) error
StreamEmptyStream(FlowCombination_StreamEmptyStreamServer) error
RpcBodyRpc(context.Context, *NonEmptyProto) (*EmptyProto, error)
RpcPathSingleNestedRpc(context.Context, *SingleNestedProto) (*EmptyProto, error)
RpcPathNestedRpc(context.Context, *NestedProto) (*EmptyProto, error)
RpcBodyStream(*NonEmptyProto, FlowCombination_RpcBodyStreamServer) error
RpcPathSingleNestedStream(*SingleNestedProto, FlowCombination_RpcPathSingleNestedStreamServer) error
RpcPathNestedStream(*NestedProto, FlowCombination_RpcPathNestedStreamServer) error
}
func RegisterFlowCombinationServer(s *grpc.Server, srv FlowCombinationServer) {
s.RegisterService(&_FlowCombination_serviceDesc, srv)
}
func _FlowCombination_RpcEmptyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EmptyProto)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyRpc",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, req.(*EmptyProto))
}
return interceptor(ctx, in, info, handler)
}
func _FlowCombination_RpcEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(EmptyProto)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(FlowCombinationServer).RpcEmptyStream(m, &flowCombinationRpcEmptyStreamServer{stream})
}
type FlowCombination_RpcEmptyStreamServer interface {
Send(*EmptyProto) error
grpc.ServerStream
}
type flowCombinationRpcEmptyStreamServer struct {
grpc.ServerStream
}
func (x *flowCombinationRpcEmptyStreamServer) Send(m *EmptyProto) error {
return x.ServerStream.SendMsg(m)
}
func _FlowCombination_StreamEmptyRpc_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(FlowCombinationServer).StreamEmptyRpc(&flowCombinationStreamEmptyRpcServer{stream})
}
type FlowCombination_StreamEmptyRpcServer interface {
SendAndClose(*EmptyProto) error
Recv() (*EmptyProto, error)
grpc.ServerStream
}
type flowCombinationStreamEmptyRpcServer struct {
grpc.ServerStream
}
func (x *flowCombinationStreamEmptyRpcServer) SendAndClose(m *EmptyProto) error {
return x.ServerStream.SendMsg(m)
}
func (x *flowCombinationStreamEmptyRpcServer) Recv() (*EmptyProto, error) {
m := new(EmptyProto)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func _FlowCombination_StreamEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(FlowCombinationServer).StreamEmptyStream(&flowCombinationStreamEmptyStreamServer{stream})
}
type FlowCombination_StreamEmptyStreamServer interface {
Send(*EmptyProto) error
Recv() (*EmptyProto, error)
grpc.ServerStream
}
type flowCombinationStreamEmptyStreamServer struct {
grpc.ServerStream
}
func (x *flowCombinationStreamEmptyStreamServer) Send(m *EmptyProto) error {
return x.ServerStream.SendMsg(m)
}
func (x *flowCombinationStreamEmptyStreamServer) Recv() (*EmptyProto, error) {
m := new(EmptyProto)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func _FlowCombination_RpcBodyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(NonEmptyProto)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FlowCombinationServer).RpcBodyRpc(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyRpc",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FlowCombinationServer).RpcBodyRpc(ctx, req.(*NonEmptyProto))
}
return interceptor(ctx, in, info, handler)
}
func _FlowCombination_RpcPathSingleNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SingleNestedProto)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedRpc",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, req.(*SingleNestedProto))
}
return interceptor(ctx, in, info, handler)
}
func _FlowCombination_RpcPathNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(NestedProto)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedRpc",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, req.(*NestedProto))
}
return interceptor(ctx, in, info, handler)
}
func _FlowCombination_RpcBodyStream_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(NonEmptyProto)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(FlowCombinationServer).RpcBodyStream(m, &flowCombinationRpcBodyStreamServer{stream})
}
type FlowCombination_RpcBodyStreamServer interface {
Send(*EmptyProto) error
grpc.ServerStream
}
type flowCombinationRpcBodyStreamServer struct {
grpc.ServerStream
}
func (x *flowCombinationRpcBodyStreamServer) Send(m *EmptyProto) error {
return x.ServerStream.SendMsg(m)
}
func _FlowCombination_RpcPathSingleNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(SingleNestedProto)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(FlowCombinationServer).RpcPathSingleNestedStream(m, &flowCombinationRpcPathSingleNestedStreamServer{stream})
}
type FlowCombination_RpcPathSingleNestedStreamServer interface {
Send(*EmptyProto) error
grpc.ServerStream
}
type flowCombinationRpcPathSingleNestedStreamServer struct {
grpc.ServerStream
}
func (x *flowCombinationRpcPathSingleNestedStreamServer) Send(m *EmptyProto) error {
return x.ServerStream.SendMsg(m)
}
func _FlowCombination_RpcPathNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(NestedProto)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(FlowCombinationServer).RpcPathNestedStream(m, &flowCombinationRpcPathNestedStreamServer{stream})
}
type FlowCombination_RpcPathNestedStreamServer interface {
Send(*EmptyProto) error
grpc.ServerStream
}
type flowCombinationRpcPathNestedStreamServer struct {
grpc.ServerStream
}
func (x *flowCombinationRpcPathNestedStreamServer) Send(m *EmptyProto) error {
return x.ServerStream.SendMsg(m)
}
var _FlowCombination_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.gateway.examples.examplepb.FlowCombination",
HandlerType: (*FlowCombinationServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RpcEmptyRpc",
Handler: _FlowCombination_RpcEmptyRpc_Handler,
},
{
MethodName: "RpcBodyRpc",
Handler: _FlowCombination_RpcBodyRpc_Handler,
},
{
MethodName: "RpcPathSingleNestedRpc",
Handler: _FlowCombination_RpcPathSingleNestedRpc_Handler,
},
{
MethodName: "RpcPathNestedRpc",
Handler: _FlowCombination_RpcPathNestedRpc_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "RpcEmptyStream",
Handler: _FlowCombination_RpcEmptyStream_Handler,
ServerStreams: true,
},
{
StreamName: "StreamEmptyRpc",
Handler: _FlowCombination_StreamEmptyRpc_Handler,
ClientStreams: true,
},
{
StreamName: "StreamEmptyStream",
Handler: _FlowCombination_StreamEmptyStream_Handler,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "RpcBodyStream",
Handler: _FlowCombination_RpcBodyStream_Handler,
ServerStreams: true,
},
{
StreamName: "RpcPathSingleNestedStream",
Handler: _FlowCombination_RpcPathSingleNestedStream_Handler,
ServerStreams: true,
},
{
StreamName: "RpcPathNestedStream",
Handler: _FlowCombination_RpcPathNestedStream_Handler,
ServerStreams: true,
},
},
Metadata: "examples/examplepb/flow_combination.proto",
}
func init() { proto.RegisterFile("examples/examplepb/flow_combination.proto", fileDescriptor3) }
var fileDescriptor3 = []byte{
// 656 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x96, 0x3f, 0x8f, 0x12, 0x4f,
0x18, 0xc7, 0xf3, 0x70, 0xc9, 0x2f, 0xb9, 0xe1, 0xfe, 0x70, 0xcb, 0x2f, 0x08, 0x1c, 0x1e, 0x77,
0xe3, 0x25, 0xe2, 0xbf, 0x5d, 0x82, 0xd5, 0x51, 0x9e, 0xd1, 0x92, 0x5c, 0xb8, 0xd8, 0x6c, 0x63,
0x66, 0x87, 0x15, 0x48, 0x60, 0x67, 0x6e, 0x77, 0x0d, 0x5e, 0x08, 0x31, 0xb1, 0xb1, 0xb4, 0xf0,
0x05, 0x58, 0x5a, 0xf9, 0x06, 0xec, 0xac, 0x6c, 0x4c, 0x2c, 0x4c, 0xec, 0xec, 0xec, 0x7c, 0x13,
0x66, 0x67, 0x66, 0x77, 0x58, 0x05, 0x37, 0x18, 0xb1, 0xdb, 0x99, 0x79, 0x9e, 0x67, 0x3e, 0xf3,
0x7d, 0xbe, 0x0f, 0x01, 0xdd, 0x70, 0x9f, 0x92, 0x31, 0x1f, 0xb9, 0x81, 0xa5, 0x3e, 0xb8, 0x63,
0x3d, 0x1e, 0xb1, 0xc9, 0x23, 0xca, 0xc6, 0xce, 0xd0, 0x23, 0xe1, 0x90, 0x79, 0x26, 0xf7, 0x59,
0xc8, 0x8c, 0x7a, 0xdf, 0xe7, 0xd4, 0xec, 0x93, 0xd0, 0x9d, 0x90, 0x4b, 0x33, 0xce, 0x33, 0x93,
0xbc, 0x6a, 0xad, 0xcf, 0x58, 0x7f, 0xe4, 0x5a, 0x84, 0x0f, 0x2d, 0xe2, 0x79, 0x2c, 0x14, 0xd9,
0x81, 0x4c, 0xc7, 0x5b, 0x08, 0xdd, 0x1f, 0xf3, 0xf0, 0xf2, 0x4c, 0xac, 0x4e, 0xd0, 0x76, 0x87,
0x79, 0x7a, 0xc3, 0xd8, 0x42, 0x40, 0xca, 0x70, 0x08, 0x8d, 0xcd, 0x2e, 0x90, 0x68, 0xe5, 0x94,
0x73, 0x72, 0xe5, 0x44, 0x2b, 0x5a, 0xde, 0x90, 0x2b, 0x8a, 0x0f, 0x10, 0x7a, 0xe8, 0x11, 0x5f,
0xe5, 0x15, 0xd0, 0x46, 0x10, 0xfa, 0x2a, 0x33, 0xfa, 0xc4, 0x3d, 0x94, 0xef, 0xb8, 0x41, 0xe8,
0xf6, 0x64, 0xc0, 0x49, 0x5c, 0x38, 0xdf, 0xba, 0x65, 0x66, 0x3c, 0xc1, 0xd4, 0x85, 0xb3, 0x28,
0x3a, 0x68, 0xef, 0x7c, 0xe8, 0xf5, 0x47, 0xee, 0xdf, 0xb9, 0xab, 0xf5, 0x71, 0x17, 0xed, 0x3e,
0x18, 0xb1, 0xc9, 0x3d, 0xad, 0xbb, 0xf1, 0x0c, 0xe5, 0xbb, 0x9c, 0x0a, 0x91, 0xba, 0x9c, 0x1a,
0xd9, 0x25, 0xb5, 0x9e, 0xd5, 0x55, 0x82, 0x71, 0xe9, 0xf9, 0xe7, 0x6f, 0xaf, 0x72, 0x05, 0xbc,
0x63, 0xf9, 0x9c, 0x5a, 0x6e, 0x74, 0x10, 0x7d, 0x19, 0x2f, 0x00, 0xed, 0xc4, 0x04, 0xe7, 0xa1,
0xef, 0x92, 0xf1, 0x1a, 0x21, 0x2a, 0x02, 0xa2, 0x88, 0xf7, 0xe6, 0x20, 0x02, 0x71, 0x69, 0x13,
0x04, 0x89, 0x24, 0xf8, 0x07, 0x72, 0x68, 0x12, 0x79, 0xbf, 0x56, 0xa4, 0x01, 0xc6, 0x4b, 0x40,
0x7b, 0x73, 0x24, 0x6b, 0x97, 0xa5, 0x26, 0x60, 0x4a, 0xf8, 0xff, 0x34, 0x8c, 0x5c, 0x34, 0xa0,
0x09, 0xc6, 0xdb, 0x1c, 0x42, 0x5d, 0x4e, 0x4f, 0x59, 0x4f, 0xe8, 0x62, 0x66, 0x56, 0x4f, 0x4d,
0xde, 0x6a, 0x34, 0xef, 0x41, 0xe0, 0xbc, 0x03, 0xbc, 0x2d, 0xda, 0xe4, 0xb0, 0x9e, 0x10, 0xa6,
0x0d, 0x37, 0xed, 0x7d, 0x5c, 0x11, 0x7b, 0x9c, 0x84, 0x03, 0x6b, 0x4a, 0x66, 0xd6, 0xd4, 0x99,
0x59, 0x53, 0x3a, 0x8b, 0x36, 0xed, 0xd8, 0x5c, 0x17, 0x4f, 0x5c, 0x5f, 0x64, 0xd8, 0x75, 0x5c,
0xd5, 0x25, 0x52, 0x39, 0xa2, 0x1e, 0xb5, 0xcb, 0xb8, 0xa8, 0x03, 0x92, 0xbc, 0xe8, 0xe4, 0x08,
0xd7, 0x16, 0xa4, 0xa6, 0x42, 0x2a, 0xf8, 0x4a, 0x1a, 0x26, 0x39, 0x35, 0x5e, 0x03, 0x2a, 0x75,
0x39, 0x3d, 0x23, 0xe1, 0x60, 0x7e, 0x84, 0x23, 0xed, 0x5a, 0x99, 0x5a, 0xfc, 0x32, 0xf4, 0xab,
0xe9, 0x77, 0x2c, 0xe4, 0x3b, 0x50, 0xfc, 0x11, 0xdc, 0x1d, 0x4f, 0xd4, 0xb2, 0xa6, 0xc4, 0x0c,
0x42, 0x5f, 0x3c, 0xde, 0xf8, 0x0a, 0xa8, 0xa0, 0x08, 0x35, 0xdb, 0xed, 0xec, 0xbe, 0xfe, 0x29,
0x95, 0x27, 0xa8, 0x06, 0xf8, 0x70, 0x29, 0xd5, 0x5c, 0x5b, 0x32, 0xe0, 0x93, 0xe6, 0x2c, 0x39,
0x6f, 0x03, 0x35, 0x3e, 0xe4, 0xd0, 0xb6, 0x72, 0xac, 0x9a, 0x9f, 0xb5, 0x9a, 0xf6, 0x8b, 0x34,
0xed, 0x27, 0xc0, 0x05, 0x6d, 0x1b, 0x39, 0x40, 0x91, 0x6f, 0xe7, 0x1f, 0x94, 0xf2, 0xad, 0x0c,
0xb1, 0xe3, 0x9f, 0x24, 0xe9, 0x20, 0xb5, 0x89, 0xf1, 0xd5, 0x25, 0xee, 0x8d, 0x0b, 0x53, 0x7b,
0x1f, 0x97, 0x7e, 0x36, 0xb0, 0x3e, 0x3c, 0xc6, 0xf5, 0xa5, 0x1e, 0xd6, 0x51, 0x35, 0x35, 0x24,
0x0b, 0x03, 0x9a, 0x60, 0xbc, 0x01, 0x54, 0x59, 0xe0, 0x65, 0xa5, 0xea, 0xda, 0xed, 0x7c, 0x5d,
0x08, 0x7b, 0xa4, 0x9e, 0xb2, 0xa8, 0xe3, 0x09, 0xe9, 0x77, 0x40, 0xc5, 0x94, 0xa7, 0x15, 0xe3,
0x1a, 0x6d, 0x3d, 0x11, 0x74, 0x17, 0xf8, 0xda, 0x6f, 0x6d, 0xad, 0xc5, 0xce, 0x7e, 0x47, 0xd2,
0xb5, 0xe5, 0x21, 0x6d, 0xa0, 0x4d, 0x38, 0xcd, 0xdb, 0x9b, 0x09, 0x92, 0xf3, 0x9f, 0xf8, 0x07,
0x74, 0xf7, 0x47, 0x00, 0x00, 0x00, 0xff, 0xff, 0xaf, 0x85, 0xaf, 0x3c, 0x6d, 0x09, 0x00, 0x00,
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,278 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/examplepb/stream.proto
package examplepb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import google_protobuf1 "github.com/golang/protobuf/ptypes/empty"
import grpc_gateway_examples_sub "github.com/grpc-ecosystem/grpc-gateway/examples/sub"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for StreamService service
type StreamServiceClient interface {
BulkCreate(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkCreateClient, error)
List(ctx context.Context, in *google_protobuf1.Empty, opts ...grpc.CallOption) (StreamService_ListClient, error)
BulkEcho(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkEchoClient, error)
}
type streamServiceClient struct {
cc *grpc.ClientConn
}
func NewStreamServiceClient(cc *grpc.ClientConn) StreamServiceClient {
return &streamServiceClient{cc}
}
func (c *streamServiceClient) BulkCreate(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkCreateClient, error) {
stream, err := grpc.NewClientStream(ctx, &_StreamService_serviceDesc.Streams[0], c.cc, "/grpc.gateway.examples.examplepb.StreamService/BulkCreate", opts...)
if err != nil {
return nil, err
}
x := &streamServiceBulkCreateClient{stream}
return x, nil
}
type StreamService_BulkCreateClient interface {
Send(*ABitOfEverything) error
CloseAndRecv() (*google_protobuf1.Empty, error)
grpc.ClientStream
}
type streamServiceBulkCreateClient struct {
grpc.ClientStream
}
func (x *streamServiceBulkCreateClient) Send(m *ABitOfEverything) error {
return x.ClientStream.SendMsg(m)
}
func (x *streamServiceBulkCreateClient) CloseAndRecv() (*google_protobuf1.Empty, error) {
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
m := new(google_protobuf1.Empty)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *streamServiceClient) List(ctx context.Context, in *google_protobuf1.Empty, opts ...grpc.CallOption) (StreamService_ListClient, error) {
stream, err := grpc.NewClientStream(ctx, &_StreamService_serviceDesc.Streams[1], c.cc, "/grpc.gateway.examples.examplepb.StreamService/List", opts...)
if err != nil {
return nil, err
}
x := &streamServiceListClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type StreamService_ListClient interface {
Recv() (*ABitOfEverything, error)
grpc.ClientStream
}
type streamServiceListClient struct {
grpc.ClientStream
}
func (x *streamServiceListClient) Recv() (*ABitOfEverything, error) {
m := new(ABitOfEverything)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *streamServiceClient) BulkEcho(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkEchoClient, error) {
stream, err := grpc.NewClientStream(ctx, &_StreamService_serviceDesc.Streams[2], c.cc, "/grpc.gateway.examples.examplepb.StreamService/BulkEcho", opts...)
if err != nil {
return nil, err
}
x := &streamServiceBulkEchoClient{stream}
return x, nil
}
type StreamService_BulkEchoClient interface {
Send(*grpc_gateway_examples_sub.StringMessage) error
Recv() (*grpc_gateway_examples_sub.StringMessage, error)
grpc.ClientStream
}
type streamServiceBulkEchoClient struct {
grpc.ClientStream
}
func (x *streamServiceBulkEchoClient) Send(m *grpc_gateway_examples_sub.StringMessage) error {
return x.ClientStream.SendMsg(m)
}
func (x *streamServiceBulkEchoClient) Recv() (*grpc_gateway_examples_sub.StringMessage, error) {
m := new(grpc_gateway_examples_sub.StringMessage)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// Server API for StreamService service
type StreamServiceServer interface {
BulkCreate(StreamService_BulkCreateServer) error
List(*google_protobuf1.Empty, StreamService_ListServer) error
BulkEcho(StreamService_BulkEchoServer) error
}
func RegisterStreamServiceServer(s *grpc.Server, srv StreamServiceServer) {
s.RegisterService(&_StreamService_serviceDesc, srv)
}
func _StreamService_BulkCreate_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(StreamServiceServer).BulkCreate(&streamServiceBulkCreateServer{stream})
}
type StreamService_BulkCreateServer interface {
SendAndClose(*google_protobuf1.Empty) error
Recv() (*ABitOfEverything, error)
grpc.ServerStream
}
type streamServiceBulkCreateServer struct {
grpc.ServerStream
}
func (x *streamServiceBulkCreateServer) SendAndClose(m *google_protobuf1.Empty) error {
return x.ServerStream.SendMsg(m)
}
func (x *streamServiceBulkCreateServer) Recv() (*ABitOfEverything, error) {
m := new(ABitOfEverything)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func _StreamService_List_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(google_protobuf1.Empty)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(StreamServiceServer).List(m, &streamServiceListServer{stream})
}
type StreamService_ListServer interface {
Send(*ABitOfEverything) error
grpc.ServerStream
}
type streamServiceListServer struct {
grpc.ServerStream
}
func (x *streamServiceListServer) Send(m *ABitOfEverything) error {
return x.ServerStream.SendMsg(m)
}
func _StreamService_BulkEcho_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(StreamServiceServer).BulkEcho(&streamServiceBulkEchoServer{stream})
}
type StreamService_BulkEchoServer interface {
Send(*grpc_gateway_examples_sub.StringMessage) error
Recv() (*grpc_gateway_examples_sub.StringMessage, error)
grpc.ServerStream
}
type streamServiceBulkEchoServer struct {
grpc.ServerStream
}
func (x *streamServiceBulkEchoServer) Send(m *grpc_gateway_examples_sub.StringMessage) error {
return x.ServerStream.SendMsg(m)
}
func (x *streamServiceBulkEchoServer) Recv() (*grpc_gateway_examples_sub.StringMessage, error) {
m := new(grpc_gateway_examples_sub.StringMessage)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var _StreamService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.gateway.examples.examplepb.StreamService",
HandlerType: (*StreamServiceServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "BulkCreate",
Handler: _StreamService_BulkCreate_Handler,
ClientStreams: true,
},
{
StreamName: "List",
Handler: _StreamService_List_Handler,
ServerStreams: true,
},
{
StreamName: "BulkEcho",
Handler: _StreamService_BulkEcho_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "examples/examplepb/stream.proto",
}
func init() { proto.RegisterFile("examples/examplepb/stream.proto", fileDescriptor2) }
var fileDescriptor2 = []byte{
// 314 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x90, 0xbf, 0x4a, 0x43, 0x31,
0x14, 0xc6, 0xb9, 0x2a, 0xa2, 0x11, 0x97, 0x0c, 0x0e, 0x51, 0x28, 0x16, 0xc1, 0x2a, 0x92, 0xb4,
0xba, 0xb9, 0x59, 0xe9, 0xa6, 0x38, 0x74, 0x73, 0x29, 0xc9, 0xe5, 0x34, 0x0d, 0xbd, 0xf7, 0x26,
0x24, 0xe7, 0x56, 0x0b, 0x4e, 0x8e, 0xae, 0x7d, 0x11, 0xdf, 0xc5, 0x57, 0xf0, 0x41, 0xa4, 0xf7,
0xdf, 0xd4, 0xd2, 0xba, 0x25, 0x9c, 0x2f, 0xf9, 0x7e, 0xe7, 0x47, 0x5a, 0xf0, 0x2e, 0x53, 0x97,
0x40, 0x10, 0xd5, 0xc1, 0x29, 0x11, 0xd0, 0x83, 0x4c, 0xb9, 0xf3, 0x16, 0x2d, 0x6d, 0x69, 0xef,
0x62, 0xae, 0x25, 0xc2, 0x9b, 0x9c, 0xf3, 0x3a, 0xcd, 0x9b, 0x34, 0x3b, 0xd3, 0xd6, 0xea, 0x04,
0x84, 0x74, 0x46, 0xc8, 0x2c, 0xb3, 0x28, 0xd1, 0xd8, 0x2c, 0x94, 0xcf, 0xd9, 0x69, 0x35, 0x2d,
0x6e, 0x2a, 0x1f, 0x0b, 0x48, 0x1d, 0xce, 0xab, 0xe1, 0xcd, 0x8a, 0x72, 0x39, 0x52, 0x06, 0x47,
0x76, 0x3c, 0x82, 0x19, 0xf8, 0x39, 0x4e, 0x4c, 0xa6, 0xab, 0x34, 0x6b, 0xd2, 0x21, 0x57, 0x22,
0x85, 0x10, 0xa4, 0x86, 0x72, 0x76, 0xfb, 0xbd, 0x4b, 0x8e, 0x87, 0x05, 0xf6, 0x10, 0xfc, 0xcc,
0xc4, 0x40, 0xbf, 0x22, 0x42, 0xfa, 0x79, 0x32, 0x7d, 0xf4, 0x20, 0x11, 0x68, 0x8f, 0x6f, 0xd8,
0x83, 0x3f, 0xf4, 0x0d, 0xbe, 0x8c, 0x07, 0x4d, 0x2b, 0x3b, 0xe1, 0x25, 0x3b, 0xaf, 0xd9, 0xf9,
0x60, 0xc9, 0xde, 0x16, 0x9f, 0x3f, 0xbf, 0x8b, 0x9d, 0xab, 0xf6, 0x85, 0x98, 0xf5, 0x6a, 0xf0,
0x55, 0xd8, 0x42, 0xe5, 0xc9, 0xf4, 0x3e, 0xba, 0xee, 0x44, 0xf4, 0x83, 0xec, 0x3d, 0x99, 0x80,
0x74, 0xcd, 0x97, 0xec, 0xff, 0x74, 0xed, 0xcb, 0x82, 0xe2, 0x9c, 0xb6, 0x36, 0x50, 0x74, 0x23,
0xba, 0x88, 0xc8, 0xc1, 0x52, 0xc5, 0x20, 0x9e, 0x58, 0xda, 0x59, 0x53, 0x15, 0x72, 0xc5, 0x87,
0xe8, 0x4d, 0xa6, 0x9f, 0x4b, 0xb3, 0x6c, 0xeb, 0xe4, 0xf6, 0x46, 0x20, 0x9e, 0xd8, 0xc2, 0x48,
0x37, 0xea, 0x1f, 0xbd, 0x1e, 0x36, 0xeb, 0xa9, 0xfd, 0x42, 0xc8, 0xdd, 0x5f, 0x00, 0x00, 0x00,
0xff, 0xff, 0xbc, 0x52, 0x49, 0x85, 0x8f, 0x02, 0x00, 0x00,
}

View File

@ -0,0 +1,277 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: examples/examplepb/stream.proto
/*
Package examplepb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package examplepb
import (
"io"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
"github.com/grpc-ecosystem/grpc-gateway/examples/sub"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
func request_StreamService_BulkCreate_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var metadata runtime.ServerMetadata
stream, err := client.BulkCreate(ctx)
if err != nil {
grpclog.Printf("Failed to start streaming: %v", err)
return nil, metadata, err
}
dec := marshaler.NewDecoder(req.Body)
for {
var protoReq ABitOfEverything
err = dec.Decode(&protoReq)
if err == io.EOF {
break
}
if err != nil {
grpclog.Printf("Failed to decode request: %v", err)
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err = stream.Send(&protoReq); err != nil {
grpclog.Printf("Failed to send request: %v", err)
return nil, metadata, err
}
}
if err := stream.CloseSend(); err != nil {
grpclog.Printf("Failed to terminate client stream: %v", err)
return nil, metadata, err
}
header, err := stream.Header()
if err != nil {
grpclog.Printf("Failed to get header from client: %v", err)
return nil, metadata, err
}
metadata.HeaderMD = header
msg, err := stream.CloseAndRecv()
metadata.TrailerMD = stream.Trailer()
return msg, metadata, err
}
func request_StreamService_List_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (StreamService_ListClient, runtime.ServerMetadata, error) {
var protoReq empty.Empty
var metadata runtime.ServerMetadata
stream, err := client.List(ctx, &protoReq)
if err != nil {
return nil, metadata, err
}
header, err := stream.Header()
if err != nil {
return nil, metadata, err
}
metadata.HeaderMD = header
return stream, metadata, nil
}
func request_StreamService_BulkEcho_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (StreamService_BulkEchoClient, runtime.ServerMetadata, error) {
var metadata runtime.ServerMetadata
stream, err := client.BulkEcho(ctx)
if err != nil {
grpclog.Printf("Failed to start streaming: %v", err)
return nil, metadata, err
}
dec := marshaler.NewDecoder(req.Body)
handleSend := func() error {
var protoReq sub.StringMessage
err = dec.Decode(&protoReq)
if err == io.EOF {
return err
}
if err != nil {
grpclog.Printf("Failed to decode request: %v", err)
return err
}
if err = stream.Send(&protoReq); err != nil {
grpclog.Printf("Failed to send request: %v", err)
return err
}
return nil
}
if err := handleSend(); err != nil {
if cerr := stream.CloseSend(); cerr != nil {
grpclog.Printf("Failed to terminate client stream: %v", cerr)
}
if err == io.EOF {
return stream, metadata, nil
}
return nil, metadata, err
}
go func() {
for {
if err := handleSend(); err != nil {
break
}
}
if err := stream.CloseSend(); err != nil {
grpclog.Printf("Failed to terminate client stream: %v", err)
}
}()
header, err := stream.Header()
if err != nil {
grpclog.Printf("Failed to get header from client: %v", err)
return nil, metadata, err
}
metadata.HeaderMD = header
return stream, metadata, nil
}
// RegisterStreamServiceHandlerFromEndpoint is same as RegisterStreamServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterStreamServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterStreamServiceHandler(ctx, mux, conn)
}
// RegisterStreamServiceHandler registers the http handlers for service StreamService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterStreamServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
client := NewStreamServiceClient(conn)
mux.Handle("POST", pattern_StreamService_BulkCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_StreamService_BulkCreate_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_StreamService_BulkCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_StreamService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_StreamService_List_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_StreamService_List_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_StreamService_BulkEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_StreamService_BulkEcho_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_StreamService_BulkEcho_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_StreamService_BulkCreate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "a_bit_of_everything", "bulk"}, ""))
pattern_StreamService_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, ""))
pattern_StreamService_BulkEcho_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "a_bit_of_everything", "echo"}, ""))
)
var (
forward_StreamService_BulkCreate_0 = runtime.ForwardResponseMessage
forward_StreamService_List_0 = runtime.ForwardResponseStream
forward_StreamService_BulkEcho_0 = runtime.ForwardResponseStream
)

View File

@ -0,0 +1,109 @@
package main
import (
"flag"
"net/http"
"path"
"strings"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/examples/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
var (
echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of EchoService")
abeEndpoint = flag.String("more_endpoint", "localhost:9090", "endpoint of ABitOfEverythingService")
flowEndpoint = flag.String("flow_endpoint", "localhost:9090", "endpoint of FlowCombination")
swaggerDir = flag.String("swagger_dir", "examples/examplepb", "path to the directory which contains swagger definitions")
)
// newGateway returns a new gateway server which translates HTTP into gRPC.
func newGateway(ctx context.Context, opts ...runtime.ServeMuxOption) (http.Handler, error) {
mux := runtime.NewServeMux(opts...)
dialOpts := []grpc.DialOption{grpc.WithInsecure()}
err := examplepb.RegisterEchoServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, dialOpts)
if err != nil {
return nil, err
}
err = examplepb.RegisterStreamServiceHandlerFromEndpoint(ctx, mux, *abeEndpoint, dialOpts)
if err != nil {
return nil, err
}
err = examplepb.RegisterABitOfEverythingServiceHandlerFromEndpoint(ctx, mux, *abeEndpoint, dialOpts)
if err != nil {
return nil, err
}
err = examplepb.RegisterFlowCombinationHandlerFromEndpoint(ctx, mux, *flowEndpoint, dialOpts)
if err != nil {
return nil, err
}
return mux, nil
}
func serveSwagger(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, ".swagger.json") {
glog.Errorf("Not Found: %s", r.URL.Path)
http.NotFound(w, r)
return
}
glog.Infof("Serving %s", r.URL.Path)
p := strings.TrimPrefix(r.URL.Path, "/swagger/")
p = path.Join(*swaggerDir, p)
http.ServeFile(w, r, p)
}
// allowCORS allows Cross Origin Resoruce Sharing from any origin.
// Don't do this without consideration in production systems.
func allowCORS(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
preflightHandler(w, r)
return
}
}
h.ServeHTTP(w, r)
})
}
func preflightHandler(w http.ResponseWriter, r *http.Request) {
headers := []string{"Content-Type", "Accept"}
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
glog.Infof("preflight request for %s", r.URL.Path)
return
}
// Run starts a HTTP server and blocks forever if successful.
func Run(address string, opts ...runtime.ServeMuxOption) error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
mux := http.NewServeMux()
mux.HandleFunc("/swagger/", serveSwagger)
gw, err := newGateway(ctx, opts...)
if err != nil {
return err
}
mux.Handle("/", gw)
return http.ListenAndServe(address, allowCORS(mux))
}
func main() {
flag.Parse()
defer glog.Flush()
if err := Run(":8080"); err != nil {
glog.Fatal(err)
}
}

View File

@ -0,0 +1,248 @@
package server
import (
"fmt"
"io"
"sync"
"github.com/golang/glog"
"github.com/golang/protobuf/ptypes/duration"
"github.com/golang/protobuf/ptypes/empty"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb"
sub "github.com/grpc-ecosystem/grpc-gateway/examples/sub"
sub2 "github.com/grpc-ecosystem/grpc-gateway/examples/sub2"
"github.com/rogpeppe/fastuuid"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// Implements of ABitOfEverythingServiceServer
var uuidgen = fastuuid.MustNewGenerator()
type _ABitOfEverythingServer struct {
v map[string]*examples.ABitOfEverything
m sync.Mutex
}
type ABitOfEverythingServer interface {
examples.ABitOfEverythingServiceServer
examples.StreamServiceServer
}
func newABitOfEverythingServer() ABitOfEverythingServer {
return &_ABitOfEverythingServer{
v: make(map[string]*examples.ABitOfEverything),
}
}
func (s *_ABitOfEverythingServer) Create(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) {
s.m.Lock()
defer s.m.Unlock()
glog.Info(msg)
var uuid string
for {
uuid = fmt.Sprintf("%x", uuidgen.Next())
if _, ok := s.v[uuid]; !ok {
break
}
}
s.v[uuid] = msg
s.v[uuid].Uuid = uuid
glog.Infof("%v", s.v[uuid])
return s.v[uuid], nil
}
func (s *_ABitOfEverythingServer) CreateBody(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) {
return s.Create(ctx, msg)
}
func (s *_ABitOfEverythingServer) BulkCreate(stream examples.StreamService_BulkCreateServer) error {
count := 0
ctx := stream.Context()
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
count++
glog.Error(msg)
if _, err = s.Create(ctx, msg); err != nil {
return err
}
}
err := stream.SendHeader(metadata.New(map[string]string{
"count": fmt.Sprintf("%d", count),
}))
if err != nil {
return nil
}
stream.SetTrailer(metadata.New(map[string]string{
"foo": "foo2",
"bar": "bar2",
}))
return stream.SendAndClose(new(empty.Empty))
}
func (s *_ABitOfEverythingServer) Lookup(ctx context.Context, msg *sub2.IdMessage) (*examples.ABitOfEverything, error) {
s.m.Lock()
defer s.m.Unlock()
glog.Info(msg)
err := grpc.SendHeader(ctx, metadata.New(map[string]string{
"uuid": msg.Uuid,
}))
if err != nil {
return nil, err
}
if a, ok := s.v[msg.Uuid]; ok {
return a, nil
}
grpc.SetTrailer(ctx, metadata.New(map[string]string{
"foo": "foo2",
"bar": "bar2",
}))
return nil, status.Errorf(codes.NotFound, "not found")
}
func (s *_ABitOfEverythingServer) List(_ *empty.Empty, stream examples.StreamService_ListServer) error {
s.m.Lock()
defer s.m.Unlock()
err := stream.SendHeader(metadata.New(map[string]string{
"count": fmt.Sprintf("%d", len(s.v)),
}))
if err != nil {
return nil
}
for _, msg := range s.v {
if err := stream.Send(msg); err != nil {
return err
}
}
// return error when metadata includes error header
if header, ok := metadata.FromIncomingContext(stream.Context()); ok {
if v, ok := header["error"]; ok {
stream.SetTrailer(metadata.New(map[string]string{
"foo": "foo2",
"bar": "bar2",
}))
return status.Errorf(codes.InvalidArgument, "error metadata: %v", v)
}
}
return nil
}
func (s *_ABitOfEverythingServer) Update(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) {
s.m.Lock()
defer s.m.Unlock()
glog.Info(msg)
if _, ok := s.v[msg.Uuid]; ok {
s.v[msg.Uuid] = msg
} else {
return nil, status.Errorf(codes.NotFound, "not found")
}
return new(empty.Empty), nil
}
func (s *_ABitOfEverythingServer) Delete(ctx context.Context, msg *sub2.IdMessage) (*empty.Empty, error) {
s.m.Lock()
defer s.m.Unlock()
glog.Info(msg)
if _, ok := s.v[msg.Uuid]; ok {
delete(s.v, msg.Uuid)
} else {
return nil, status.Errorf(codes.NotFound, "not found")
}
return new(empty.Empty), nil
}
func (s *_ABitOfEverythingServer) GetQuery(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) {
s.m.Lock()
defer s.m.Unlock()
glog.Info(msg)
if _, ok := s.v[msg.Uuid]; ok {
s.v[msg.Uuid] = msg
} else {
return nil, status.Errorf(codes.NotFound, "not found")
}
return new(empty.Empty), nil
}
func (s *_ABitOfEverythingServer) Echo(ctx context.Context, msg *sub.StringMessage) (*sub.StringMessage, error) {
s.m.Lock()
defer s.m.Unlock()
glog.Info(msg)
return msg, nil
}
func (s *_ABitOfEverythingServer) BulkEcho(stream examples.StreamService_BulkEchoServer) error {
var msgs []*sub.StringMessage
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
msgs = append(msgs, msg)
}
hmd := metadata.New(map[string]string{
"foo": "foo1",
"bar": "bar1",
})
if err := stream.SendHeader(hmd); err != nil {
return err
}
for _, msg := range msgs {
glog.Info(msg)
if err := stream.Send(msg); err != nil {
return err
}
}
stream.SetTrailer(metadata.New(map[string]string{
"foo": "foo2",
"bar": "bar2",
}))
return nil
}
func (s *_ABitOfEverythingServer) DeepPathEcho(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) {
s.m.Lock()
defer s.m.Unlock()
glog.Info(msg)
return msg, nil
}
func (s *_ABitOfEverythingServer) NoBindings(ctx context.Context, msg *duration.Duration) (*empty.Empty, error) {
return nil, nil
}
func (s *_ABitOfEverythingServer) Timeout(ctx context.Context, msg *empty.Empty) (*empty.Empty, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
}
}

View File

@ -0,0 +1,17 @@
package main
import (
"flag"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/examples/server"
)
func main() {
flag.Parse()
defer glog.Flush()
if err := server.Run(); err != nil {
glog.Fatal(err)
}
}

View File

@ -0,0 +1,35 @@
package server
import (
"github.com/golang/glog"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// Implements of EchoServiceServer
type echoServer struct{}
func newEchoServer() examples.EchoServiceServer {
return new(echoServer)
}
func (s *echoServer) Echo(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) {
glog.Info(msg)
return msg, nil
}
func (s *echoServer) EchoBody(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) {
glog.Info(msg)
grpc.SendHeader(ctx, metadata.New(map[string]string{
"foo": "foo1",
"bar": "bar1",
}))
grpc.SetTrailer(ctx, metadata.New(map[string]string{
"foo": "foo2",
"bar": "bar2",
}))
return msg, nil
}

View File

@ -0,0 +1,72 @@
package server
import (
"io"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb"
"golang.org/x/net/context"
)
type flowCombinationServer struct{}
func newFlowCombinationServer() examples.FlowCombinationServer {
return &flowCombinationServer{}
}
func (s flowCombinationServer) RpcEmptyRpc(ctx context.Context, req *examples.EmptyProto) (*examples.EmptyProto, error) {
return req, nil
}
func (s flowCombinationServer) RpcEmptyStream(req *examples.EmptyProto, stream examples.FlowCombination_RpcEmptyStreamServer) error {
return stream.Send(req)
}
func (s flowCombinationServer) StreamEmptyRpc(stream examples.FlowCombination_StreamEmptyRpcServer) error {
for {
_, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return stream.SendAndClose(new(examples.EmptyProto))
}
func (s flowCombinationServer) StreamEmptyStream(stream examples.FlowCombination_StreamEmptyStreamServer) error {
for {
_, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return stream.Send(new(examples.EmptyProto))
}
func (s flowCombinationServer) RpcBodyRpc(ctx context.Context, req *examples.NonEmptyProto) (*examples.EmptyProto, error) {
return new(examples.EmptyProto), nil
}
func (s flowCombinationServer) RpcPathSingleNestedRpc(ctx context.Context, req *examples.SingleNestedProto) (*examples.EmptyProto, error) {
return new(examples.EmptyProto), nil
}
func (s flowCombinationServer) RpcPathNestedRpc(ctx context.Context, req *examples.NestedProto) (*examples.EmptyProto, error) {
return new(examples.EmptyProto), nil
}
func (s flowCombinationServer) RpcBodyStream(req *examples.NonEmptyProto, stream examples.FlowCombination_RpcBodyStreamServer) error {
return stream.Send(new(examples.EmptyProto))
}
func (s flowCombinationServer) RpcPathSingleNestedStream(req *examples.SingleNestedProto, stream examples.FlowCombination_RpcPathSingleNestedStreamServer) error {
return stream.Send(new(examples.EmptyProto))
}
func (s flowCombinationServer) RpcPathNestedStream(req *examples.NestedProto, stream examples.FlowCombination_RpcPathNestedStreamServer) error {
return stream.Send(new(examples.EmptyProto))
}

View File

@ -0,0 +1,25 @@
package server
import (
"net"
examples "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb"
"google.golang.org/grpc"
)
func Run() error {
l, err := net.Listen("tcp", ":9090")
if err != nil {
return err
}
s := grpc.NewServer()
examples.RegisterEchoServiceServer(s, newEchoServer())
examples.RegisterFlowCombinationServer(s, newFlowCombinationServer())
abe := newABitOfEverythingServer()
examples.RegisterABitOfEverythingServiceServer(s, abe)
examples.RegisterStreamServiceServer(s, abe)
s.Serve(l)
return nil
}

View File

@ -0,0 +1,62 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/sub/message.proto
/*
Package sub is a generated protocol buffer package.
It is generated from these files:
examples/sub/message.proto
It has these top-level messages:
StringMessage
*/
package sub
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type StringMessage struct {
Value *string `protobuf:"bytes,1,req,name=value" json:"value,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *StringMessage) Reset() { *m = StringMessage{} }
func (m *StringMessage) String() string { return proto.CompactTextString(m) }
func (*StringMessage) ProtoMessage() {}
func (*StringMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *StringMessage) GetValue() string {
if m != nil && m.Value != nil {
return *m.Value
}
return ""
}
func init() {
proto.RegisterType((*StringMessage)(nil), "grpc.gateway.examples.sub.StringMessage")
}
func init() { proto.RegisterFile("examples/sub/message.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 111 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4a, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x2e, 0x4d, 0xd2, 0xcf, 0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f,
0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x4c, 0x2f, 0x2a, 0x48, 0xd6, 0x4b, 0x4f, 0x2c,
0x49, 0x2d, 0x4f, 0xac, 0xd4, 0x83, 0x29, 0xd4, 0x2b, 0x2e, 0x4d, 0x52, 0x52, 0xe5, 0xe2, 0x0d,
0x2e, 0x29, 0xca, 0xcc, 0x4b, 0xf7, 0x85, 0xe8, 0x10, 0x12, 0xe1, 0x62, 0x2d, 0x4b, 0xcc, 0x29,
0x4d, 0x95, 0x60, 0x54, 0x60, 0xd2, 0xe0, 0x0c, 0x82, 0x70, 0x9c, 0x58, 0xa3, 0x98, 0x8b, 0x4b,
0x93, 0x00, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x10, 0x60, 0xa9, 0x65, 0x00, 0x00, 0x00,
}

View File

@ -0,0 +1,62 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: examples/sub2/message.proto
/*
Package sub2 is a generated protocol buffer package.
It is generated from these files:
examples/sub2/message.proto
It has these top-level messages:
IdMessage
*/
package sub2
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type IdMessage struct {
Uuid string `protobuf:"bytes,1,opt,name=uuid" json:"uuid,omitempty"`
}
func (m *IdMessage) Reset() { *m = IdMessage{} }
func (m *IdMessage) String() string { return proto.CompactTextString(m) }
func (*IdMessage) ProtoMessage() {}
func (*IdMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *IdMessage) GetUuid() string {
if m != nil {
return m.Uuid
}
return ""
}
func init() {
proto.RegisterType((*IdMessage)(nil), "sub2.IdMessage")
}
func init() { proto.RegisterFile("examples/sub2/message.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 128 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xad, 0x48, 0xcc,
0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x2e, 0x4d, 0x32, 0xd2, 0xcf, 0x4d, 0x2d, 0x2e, 0x4e, 0x4c,
0x4f, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x89, 0x29, 0xc9, 0x73, 0x71, 0x7a,
0xa6, 0xf8, 0x42, 0x24, 0x84, 0x84, 0xb8, 0x58, 0x4a, 0x4b, 0x33, 0x53, 0x24, 0x18, 0x15, 0x18,
0x35, 0x38, 0x83, 0xc0, 0x6c, 0x27, 0xb3, 0x28, 0x93, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd,
0xe4, 0xfc, 0x5c, 0xfd, 0xf4, 0xa2, 0x82, 0x64, 0xdd, 0xd4, 0xe4, 0xfc, 0xe2, 0xca, 0xe2, 0x92,
0x54, 0x28, 0x37, 0x3d, 0xb1, 0x24, 0xb5, 0x3c, 0xb1, 0x52, 0x1f, 0xc5, 0xb2, 0x24, 0x36, 0xb0,
0x2d, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x53, 0x75, 0xef, 0xe0, 0x84, 0x00, 0x00, 0x00,
}

View File

@ -0,0 +1,318 @@
package descriptor
import (
"fmt"
"path"
"path/filepath"
"strings"
"github.com/golang/glog"
descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
// Registry is a registry of information extracted from plugin.CodeGeneratorRequest.
type Registry struct {
// msgs is a mapping from fully-qualified message name to descriptor
msgs map[string]*Message
// enums is a mapping from fully-qualified enum name to descriptor
enums map[string]*Enum
// files is a mapping from file path to descriptor
files map[string]*File
// prefix is a prefix to be inserted to golang package paths generated from proto package names.
prefix string
// pkgMap is a user-specified mapping from file path to proto package.
pkgMap map[string]string
// pkgAliases is a mapping from package aliases to package paths in go which are already taken.
pkgAliases map[string]string
// allowDeleteBody permits http delete methods to have a body
allowDeleteBody bool
}
// NewRegistry returns a new Registry.
func NewRegistry() *Registry {
return &Registry{
msgs: make(map[string]*Message),
enums: make(map[string]*Enum),
files: make(map[string]*File),
pkgMap: make(map[string]string),
pkgAliases: make(map[string]string),
}
}
// Load loads definitions of services, methods, messages, enumerations and fields from "req".
func (r *Registry) Load(req *plugin.CodeGeneratorRequest) error {
for _, file := range req.GetProtoFile() {
r.loadFile(file)
}
var targetPkg string
for _, name := range req.FileToGenerate {
target := r.files[name]
if target == nil {
return fmt.Errorf("no such file: %s", name)
}
name := packageIdentityName(target.FileDescriptorProto)
if targetPkg == "" {
targetPkg = name
} else {
if targetPkg != name {
return fmt.Errorf("inconsistent package names: %s %s", targetPkg, name)
}
}
if err := r.loadServices(target); err != nil {
return err
}
}
return nil
}
// loadFile loads messages, enumerations and fields from "file".
// It does not loads services and methods in "file". You need to call
// loadServices after loadFiles is called for all files to load services and methods.
func (r *Registry) loadFile(file *descriptor.FileDescriptorProto) {
pkg := GoPackage{
Path: r.goPackagePath(file),
Name: defaultGoPackageName(file),
}
if err := r.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil {
for i := 0; ; i++ {
alias := fmt.Sprintf("%s_%d", pkg.Name, i)
if err := r.ReserveGoPackageAlias(alias, pkg.Path); err == nil {
pkg.Alias = alias
break
}
}
}
f := &File{
FileDescriptorProto: file,
GoPkg: pkg,
}
r.files[file.GetName()] = f
r.registerMsg(f, nil, file.GetMessageType())
r.registerEnum(f, nil, file.GetEnumType())
}
func (r *Registry) registerMsg(file *File, outerPath []string, msgs []*descriptor.DescriptorProto) {
for i, md := range msgs {
m := &Message{
File: file,
Outers: outerPath,
DescriptorProto: md,
Index: i,
}
for _, fd := range md.GetField() {
m.Fields = append(m.Fields, &Field{
Message: m,
FieldDescriptorProto: fd,
})
}
file.Messages = append(file.Messages, m)
r.msgs[m.FQMN()] = m
glog.V(1).Infof("register name: %s", m.FQMN())
var outers []string
outers = append(outers, outerPath...)
outers = append(outers, m.GetName())
r.registerMsg(file, outers, m.GetNestedType())
r.registerEnum(file, outers, m.GetEnumType())
}
}
func (r *Registry) registerEnum(file *File, outerPath []string, enums []*descriptor.EnumDescriptorProto) {
for i, ed := range enums {
e := &Enum{
File: file,
Outers: outerPath,
EnumDescriptorProto: ed,
Index: i,
}
file.Enums = append(file.Enums, e)
r.enums[e.FQEN()] = e
glog.V(1).Infof("register enum name: %s", e.FQEN())
}
}
// LookupMsg looks up a message type by "name".
// It tries to resolve "name" from "location" if "name" is a relative message name.
func (r *Registry) LookupMsg(location, name string) (*Message, error) {
glog.V(1).Infof("lookup %s from %s", name, location)
if strings.HasPrefix(name, ".") {
m, ok := r.msgs[name]
if !ok {
return nil, fmt.Errorf("no message found: %s", name)
}
return m, nil
}
if !strings.HasPrefix(location, ".") {
location = fmt.Sprintf(".%s", location)
}
components := strings.Split(location, ".")
for len(components) > 0 {
fqmn := strings.Join(append(components, name), ".")
if m, ok := r.msgs[fqmn]; ok {
return m, nil
}
components = components[:len(components)-1]
}
return nil, fmt.Errorf("no message found: %s", name)
}
// LookupEnum looks up a enum type by "name".
// It tries to resolve "name" from "location" if "name" is a relative enum name.
func (r *Registry) LookupEnum(location, name string) (*Enum, error) {
glog.V(1).Infof("lookup enum %s from %s", name, location)
if strings.HasPrefix(name, ".") {
e, ok := r.enums[name]
if !ok {
return nil, fmt.Errorf("no enum found: %s", name)
}
return e, nil
}
if !strings.HasPrefix(location, ".") {
location = fmt.Sprintf(".%s", location)
}
components := strings.Split(location, ".")
for len(components) > 0 {
fqen := strings.Join(append(components, name), ".")
if e, ok := r.enums[fqen]; ok {
return e, nil
}
components = components[:len(components)-1]
}
return nil, fmt.Errorf("no enum found: %s", name)
}
// LookupFile looks up a file by name.
func (r *Registry) LookupFile(name string) (*File, error) {
f, ok := r.files[name]
if !ok {
return nil, fmt.Errorf("no such file given: %s", name)
}
return f, nil
}
// AddPkgMap adds a mapping from a .proto file to proto package name.
func (r *Registry) AddPkgMap(file, protoPkg string) {
r.pkgMap[file] = protoPkg
}
// SetPrefix registers the prefix to be added to go package paths generated from proto package names.
func (r *Registry) SetPrefix(prefix string) {
r.prefix = prefix
}
// ReserveGoPackageAlias reserves the unique alias of go package.
// If succeeded, the alias will be never used for other packages in generated go files.
// If failed, the alias is already taken by another package, so you need to use another
// alias for the package in your go files.
func (r *Registry) ReserveGoPackageAlias(alias, pkgpath string) error {
if taken, ok := r.pkgAliases[alias]; ok {
if taken == pkgpath {
return nil
}
return fmt.Errorf("package name %s is already taken. Use another alias", alias)
}
r.pkgAliases[alias] = pkgpath
return nil
}
// goPackagePath returns the go package path which go files generated from "f" should have.
// It respects the mapping registered by AddPkgMap if exists. Or use go_package as import path
// if it includes a slash, Otherwide, it generates a path from the file name of "f".
func (r *Registry) goPackagePath(f *descriptor.FileDescriptorProto) string {
name := f.GetName()
if pkg, ok := r.pkgMap[name]; ok {
return path.Join(r.prefix, pkg)
}
gopkg := f.Options.GetGoPackage()
idx := strings.LastIndex(gopkg, "/")
if idx >= 0 {
if sc := strings.LastIndex(gopkg, ";"); sc > 0 {
gopkg = gopkg[:sc+1-1]
}
return gopkg
}
return path.Join(r.prefix, path.Dir(name))
}
// GetAllFQMNs returns a list of all FQMNs
func (r *Registry) GetAllFQMNs() []string {
var keys []string
for k := range r.msgs {
keys = append(keys, k)
}
return keys
}
// GetAllFQENs returns a list of all FQENs
func (r *Registry) GetAllFQENs() []string {
var keys []string
for k := range r.enums {
keys = append(keys, k)
}
return keys
}
// SetAllowDeleteBody controls whether http delete methods may have a
// body or fail loading if encountered.
func (r *Registry) SetAllowDeleteBody(allow bool) {
r.allowDeleteBody = allow
}
// sanitizePackageName replaces unallowed character in package name
// with allowed character.
func sanitizePackageName(pkgName string) string {
pkgName = strings.Replace(pkgName, ".", "_", -1)
pkgName = strings.Replace(pkgName, "-", "_", -1)
return pkgName
}
// defaultGoPackageName returns the default go package name to be used for go files generated from "f".
// You might need to use an unique alias for the package when you import it. Use ReserveGoPackageAlias to get a unique alias.
func defaultGoPackageName(f *descriptor.FileDescriptorProto) string {
name := packageIdentityName(f)
return sanitizePackageName(name)
}
// packageIdentityName returns the identity of packages.
// protoc-gen-grpc-gateway rejects CodeGenerationRequests which contains more than one packages
// as protoc-gen-go does.
func packageIdentityName(f *descriptor.FileDescriptorProto) string {
if f.Options != nil && f.Options.GoPackage != nil {
gopkg := f.Options.GetGoPackage()
idx := strings.LastIndex(gopkg, "/")
if idx < 0 {
gopkg = gopkg[idx+1:]
}
gopkg = gopkg[idx+1:]
// package name is overrided with the string after the
// ';' character
sc := strings.IndexByte(gopkg, ';')
if sc < 0 {
return sanitizePackageName(gopkg)
}
return sanitizePackageName(gopkg[sc+1:])
}
if f.Package == nil {
base := filepath.Base(f.GetName())
ext := filepath.Ext(base)
return strings.TrimSuffix(base, ext)
}
return f.GetPackage()
}

View File

@ -0,0 +1,266 @@
package descriptor
import (
"fmt"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule"
options "google.golang.org/genproto/googleapis/api/annotations"
)
// loadServices registers services and their methods from "targetFile" to "r".
// It must be called after loadFile is called for all files so that loadServices
// can resolve names of message types and their fields.
func (r *Registry) loadServices(file *File) error {
glog.V(1).Infof("Loading services from %s", file.GetName())
var svcs []*Service
for _, sd := range file.GetService() {
glog.V(2).Infof("Registering %s", sd.GetName())
svc := &Service{
File: file,
ServiceDescriptorProto: sd,
}
for _, md := range sd.GetMethod() {
glog.V(2).Infof("Processing %s.%s", sd.GetName(), md.GetName())
opts, err := extractAPIOptions(md)
if err != nil {
glog.Errorf("Failed to extract ApiMethodOptions from %s.%s: %v", svc.GetName(), md.GetName(), err)
return err
}
if opts == nil {
glog.V(1).Infof("Found non-target method: %s.%s", svc.GetName(), md.GetName())
}
meth, err := r.newMethod(svc, md, opts)
if err != nil {
return err
}
svc.Methods = append(svc.Methods, meth)
}
if len(svc.Methods) == 0 {
continue
}
glog.V(2).Infof("Registered %s with %d method(s)", svc.GetName(), len(svc.Methods))
svcs = append(svcs, svc)
}
file.Services = svcs
return nil
}
func (r *Registry) newMethod(svc *Service, md *descriptor.MethodDescriptorProto, opts *options.HttpRule) (*Method, error) {
requestType, err := r.LookupMsg(svc.File.GetPackage(), md.GetInputType())
if err != nil {
return nil, err
}
responseType, err := r.LookupMsg(svc.File.GetPackage(), md.GetOutputType())
if err != nil {
return nil, err
}
meth := &Method{
Service: svc,
MethodDescriptorProto: md,
RequestType: requestType,
ResponseType: responseType,
}
newBinding := func(opts *options.HttpRule, idx int) (*Binding, error) {
var (
httpMethod string
pathTemplate string
)
switch {
case opts.GetGet() != "":
httpMethod = "GET"
pathTemplate = opts.GetGet()
if opts.Body != "" {
return nil, fmt.Errorf("needs request body even though http method is GET: %s", md.GetName())
}
case opts.GetPut() != "":
httpMethod = "PUT"
pathTemplate = opts.GetPut()
case opts.GetPost() != "":
httpMethod = "POST"
pathTemplate = opts.GetPost()
case opts.GetDelete() != "":
httpMethod = "DELETE"
pathTemplate = opts.GetDelete()
if opts.Body != "" && !r.allowDeleteBody {
return nil, fmt.Errorf("needs request body even though http method is DELETE: %s", md.GetName())
}
case opts.GetPatch() != "":
httpMethod = "PATCH"
pathTemplate = opts.GetPatch()
case opts.GetCustom() != nil:
custom := opts.GetCustom()
httpMethod = custom.Kind
pathTemplate = custom.Path
default:
glog.V(1).Infof("No pattern specified in google.api.HttpRule: %s", md.GetName())
return nil, nil
}
parsed, err := httprule.Parse(pathTemplate)
if err != nil {
return nil, err
}
tmpl := parsed.Compile()
if md.GetClientStreaming() && len(tmpl.Fields) > 0 {
return nil, fmt.Errorf("cannot use path parameter in client streaming")
}
b := &Binding{
Method: meth,
Index: idx,
PathTmpl: tmpl,
HTTPMethod: httpMethod,
}
for _, f := range tmpl.Fields {
param, err := r.newParam(meth, f)
if err != nil {
return nil, err
}
b.PathParams = append(b.PathParams, param)
}
// TODO(yugui) Handle query params
b.Body, err = r.newBody(meth, opts.Body)
if err != nil {
return nil, err
}
return b, nil
}
b, err := newBinding(opts, 0)
if err != nil {
return nil, err
}
if b != nil {
meth.Bindings = append(meth.Bindings, b)
}
for i, additional := range opts.GetAdditionalBindings() {
if len(additional.AdditionalBindings) > 0 {
return nil, fmt.Errorf("additional_binding in additional_binding not allowed: %s.%s", svc.GetName(), meth.GetName())
}
b, err := newBinding(additional, i+1)
if err != nil {
return nil, err
}
meth.Bindings = append(meth.Bindings, b)
}
return meth, nil
}
func extractAPIOptions(meth *descriptor.MethodDescriptorProto) (*options.HttpRule, error) {
if meth.Options == nil {
return nil, nil
}
if !proto.HasExtension(meth.Options, options.E_Http) {
return nil, nil
}
ext, err := proto.GetExtension(meth.Options, options.E_Http)
if err != nil {
return nil, err
}
opts, ok := ext.(*options.HttpRule)
if !ok {
return nil, fmt.Errorf("extension is %T; want an HttpRule", ext)
}
return opts, nil
}
func (r *Registry) newParam(meth *Method, path string) (Parameter, error) {
msg := meth.RequestType
fields, err := r.resolveFiledPath(msg, path)
if err != nil {
return Parameter{}, err
}
l := len(fields)
if l == 0 {
return Parameter{}, fmt.Errorf("invalid field access list for %s", path)
}
target := fields[l-1].Target
switch target.GetType() {
case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP:
return Parameter{}, fmt.Errorf("aggregate type %s in parameter of %s.%s: %s", target.Type, meth.Service.GetName(), meth.GetName(), path)
}
return Parameter{
FieldPath: FieldPath(fields),
Method: meth,
Target: fields[l-1].Target,
}, nil
}
func (r *Registry) newBody(meth *Method, path string) (*Body, error) {
msg := meth.RequestType
switch path {
case "":
return nil, nil
case "*":
return &Body{FieldPath: nil}, nil
}
fields, err := r.resolveFiledPath(msg, path)
if err != nil {
return nil, err
}
return &Body{FieldPath: FieldPath(fields)}, nil
}
// lookupField looks up a field named "name" within "msg".
// It returns nil if no such field found.
func lookupField(msg *Message, name string) *Field {
for _, f := range msg.Fields {
if f.GetName() == name {
return f
}
}
return nil
}
// resolveFieldPath resolves "path" into a list of fieldDescriptor, starting from "msg".
func (r *Registry) resolveFiledPath(msg *Message, path string) ([]FieldPathComponent, error) {
if path == "" {
return nil, nil
}
root := msg
var result []FieldPathComponent
for i, c := range strings.Split(path, ".") {
if i > 0 {
f := result[i-1].Target
switch f.GetType() {
case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP:
var err error
msg, err = r.LookupMsg(msg.FQMN(), f.GetTypeName())
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("not an aggregate type: %s in %s", f.GetName(), path)
}
}
glog.V(2).Infof("Lookup %s in %s", c, msg.FQMN())
f := lookupField(msg, c)
if f == nil {
return nil, fmt.Errorf("no field %q found in %s", path, root.GetName())
}
if f.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED {
return nil, fmt.Errorf("repeated field not allowed in field path: %s in %s", f.GetName(), path)
}
result = append(result, FieldPathComponent{Name: c, Target: f})
}
return result, nil
}

View File

@ -0,0 +1,322 @@
package descriptor
import (
"fmt"
"strings"
descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
gogen "github.com/golang/protobuf/protoc-gen-go/generator"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule"
)
// GoPackage represents a golang package
type GoPackage struct {
// Path is the package path to the package.
Path string
// Name is the package name of the package
Name string
// Alias is an alias of the package unique within the current invokation of grpc-gateway generator.
Alias string
}
// Standard returns whether the import is a golang standard package.
func (p GoPackage) Standard() bool {
return !strings.Contains(p.Path, ".")
}
// String returns a string representation of this package in the form of import line in golang.
func (p GoPackage) String() string {
if p.Alias == "" {
return fmt.Sprintf("%q", p.Path)
}
return fmt.Sprintf("%s %q", p.Alias, p.Path)
}
// File wraps descriptor.FileDescriptorProto for richer features.
type File struct {
*descriptor.FileDescriptorProto
// GoPkg is the go package of the go file generated from this file..
GoPkg GoPackage
// Messages is the list of messages defined in this file.
Messages []*Message
// Enums is the list of enums defined in this file.
Enums []*Enum
// Services is the list of services defined in this file.
Services []*Service
}
// proto2 determines if the syntax of the file is proto2.
func (f *File) proto2() bool {
return f.Syntax == nil || f.GetSyntax() == "proto2"
}
// Message describes a protocol buffer message types
type Message struct {
// File is the file where the message is defined
File *File
// Outers is a list of outer messages if this message is a nested type.
Outers []string
*descriptor.DescriptorProto
Fields []*Field
// Index is proto path index of this message in File.
Index int
}
// FQMN returns a fully qualified message name of this message.
func (m *Message) FQMN() string {
components := []string{""}
if m.File.Package != nil {
components = append(components, m.File.GetPackage())
}
components = append(components, m.Outers...)
components = append(components, m.GetName())
return strings.Join(components, ".")
}
// GoType returns a go type name for the message type.
// It prefixes the type name with the package alias if
// its belonging package is not "currentPackage".
func (m *Message) GoType(currentPackage string) string {
var components []string
components = append(components, m.Outers...)
components = append(components, m.GetName())
name := strings.Join(components, "_")
if m.File.GoPkg.Path == currentPackage {
return name
}
pkg := m.File.GoPkg.Name
if alias := m.File.GoPkg.Alias; alias != "" {
pkg = alias
}
return fmt.Sprintf("%s.%s", pkg, name)
}
// Enum describes a protocol buffer enum types
type Enum struct {
// File is the file where the enum is defined
File *File
// Outers is a list of outer messages if this enum is a nested type.
Outers []string
*descriptor.EnumDescriptorProto
Index int
}
// FQEN returns a fully qualified enum name of this enum.
func (e *Enum) FQEN() string {
components := []string{""}
if e.File.Package != nil {
components = append(components, e.File.GetPackage())
}
components = append(components, e.Outers...)
components = append(components, e.GetName())
return strings.Join(components, ".")
}
// Service wraps descriptor.ServiceDescriptorProto for richer features.
type Service struct {
// File is the file where this service is defined.
File *File
*descriptor.ServiceDescriptorProto
// Methods is the list of methods defined in this service.
Methods []*Method
}
// Method wraps descriptor.MethodDescriptorProto for richer features.
type Method struct {
// Service is the service which this method belongs to.
Service *Service
*descriptor.MethodDescriptorProto
// RequestType is the message type of requests to this method.
RequestType *Message
// ResponseType is the message type of responses from this method.
ResponseType *Message
Bindings []*Binding
}
// Binding describes how an HTTP endpoint is bound to a gRPC method.
type Binding struct {
// Method is the method which the endpoint is bound to.
Method *Method
// Index is a zero-origin index of the binding in the target method
Index int
// PathTmpl is path template where this method is mapped to.
PathTmpl httprule.Template
// HTTPMethod is the HTTP method which this method is mapped to.
HTTPMethod string
// PathParams is the list of parameters provided in HTTP request paths.
PathParams []Parameter
// Body describes parameters provided in HTTP request body.
Body *Body
}
// ExplicitParams returns a list of explicitly bound parameters of "b",
// i.e. a union of field path for body and field paths for path parameters.
func (b *Binding) ExplicitParams() []string {
var result []string
if b.Body != nil {
result = append(result, b.Body.FieldPath.String())
}
for _, p := range b.PathParams {
result = append(result, p.FieldPath.String())
}
return result
}
// Field wraps descriptor.FieldDescriptorProto for richer features.
type Field struct {
// Message is the message type which this field belongs to.
Message *Message
// FieldMessage is the message type of the field.
FieldMessage *Message
*descriptor.FieldDescriptorProto
}
// Parameter is a parameter provided in http requests
type Parameter struct {
// FieldPath is a path to a proto field which this parameter is mapped to.
FieldPath
// Target is the proto field which this parameter is mapped to.
Target *Field
// Method is the method which this parameter is used for.
Method *Method
}
// ConvertFuncExpr returns a go expression of a converter function.
// The converter function converts a string into a value for the parameter.
func (p Parameter) ConvertFuncExpr() (string, error) {
tbl := proto3ConvertFuncs
if p.Target.Message.File.proto2() {
tbl = proto2ConvertFuncs
}
typ := p.Target.GetType()
conv, ok := tbl[typ]
if !ok {
return "", fmt.Errorf("unsupported field type %s of parameter %s in %s.%s", typ, p.FieldPath, p.Method.Service.GetName(), p.Method.GetName())
}
return conv, nil
}
// Body describes a http requtest body to be sent to the method.
type Body struct {
// FieldPath is a path to a proto field which the request body is mapped to.
// The request body is mapped to the request type itself if FieldPath is empty.
FieldPath FieldPath
}
// RHS returns a right-hand-side expression in go to be used to initialize method request object.
// It starts with "msgExpr", which is the go expression of the method request object.
func (b Body) RHS(msgExpr string) string {
return b.FieldPath.RHS(msgExpr)
}
// FieldPath is a path to a field from a request message.
type FieldPath []FieldPathComponent
// String returns a string representation of the field path.
func (p FieldPath) String() string {
var components []string
for _, c := range p {
components = append(components, c.Name)
}
return strings.Join(components, ".")
}
// IsNestedProto3 indicates whether the FieldPath is a nested Proto3 path.
func (p FieldPath) IsNestedProto3() bool {
if len(p) > 1 && !p[0].Target.Message.File.proto2() {
return true
}
return false
}
// RHS is a right-hand-side expression in go to be used to assign a value to the target field.
// It starts with "msgExpr", which is the go expression of the method request object.
func (p FieldPath) RHS(msgExpr string) string {
l := len(p)
if l == 0 {
return msgExpr
}
components := []string{msgExpr}
for i, c := range p {
if i == l-1 {
components = append(components, c.RHS())
continue
}
components = append(components, c.LHS())
}
return strings.Join(components, ".")
}
// FieldPathComponent is a path component in FieldPath
type FieldPathComponent struct {
// Name is a name of the proto field which this component corresponds to.
// TODO(yugui) is this necessary?
Name string
// Target is the proto field which this component corresponds to.
Target *Field
}
// RHS returns a right-hand-side expression in go for this field.
func (c FieldPathComponent) RHS() string {
return gogen.CamelCase(c.Name)
}
// LHS returns a left-hand-side expression in go for this field.
func (c FieldPathComponent) LHS() string {
if c.Target.Message.File.proto2() {
return fmt.Sprintf("Get%s()", gogen.CamelCase(c.Name))
}
return gogen.CamelCase(c.Name)
}
var (
proto3ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{
descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64",
descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32",
descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64",
descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64",
descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32",
descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64",
descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32",
descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.Bool",
descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.String",
// FieldDescriptorProto_TYPE_GROUP
// FieldDescriptorProto_TYPE_MESSAGE
// FieldDescriptorProto_TYPE_BYTES
// TODO(yugui) Handle bytes
descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32",
// FieldDescriptorProto_TYPE_ENUM
// TODO(yugui) Handle Enum
descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32",
descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64",
descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32",
descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64",
}
proto2ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{
descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64P",
descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32P",
descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64P",
descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64P",
descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32P",
descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64P",
descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32P",
descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolP",
descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringP",
// FieldDescriptorProto_TYPE_GROUP
// FieldDescriptorProto_TYPE_MESSAGE
// FieldDescriptorProto_TYPE_BYTES
// TODO(yugui) Handle bytes
descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32P",
// FieldDescriptorProto_TYPE_ENUM
// TODO(yugui) Handle Enum
descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32P",
descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64P",
descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32P",
descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64P",
}
)

View File

@ -0,0 +1,13 @@
// Package generator provides an abstract interface to code generators.
package generator
import (
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
)
// Generator is an abstraction of code generators.
type Generator interface {
// Generate generates output files from input .proto files.
Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error)
}

View File

@ -0,0 +1,2 @@
// Package gengateway provides a code generator for grpc gateway files.
package gengateway

View File

@ -0,0 +1,112 @@
package gengateway
import (
"errors"
"fmt"
"go/format"
"path"
"path/filepath"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator"
options "google.golang.org/genproto/googleapis/api/annotations"
)
var (
errNoTargetService = errors.New("no target service defined in the file")
)
type generator struct {
reg *descriptor.Registry
baseImports []descriptor.GoPackage
useRequestContext bool
}
// New returns a new generator which generates grpc gateway files.
func New(reg *descriptor.Registry, useRequestContext bool) gen.Generator {
var imports []descriptor.GoPackage
for _, pkgpath := range []string{
"io",
"net/http",
"github.com/grpc-ecosystem/grpc-gateway/runtime",
"github.com/grpc-ecosystem/grpc-gateway/utilities",
"github.com/golang/protobuf/proto",
"golang.org/x/net/context",
"google.golang.org/grpc",
"google.golang.org/grpc/codes",
"google.golang.org/grpc/grpclog",
"google.golang.org/grpc/status",
} {
pkg := descriptor.GoPackage{
Path: pkgpath,
Name: path.Base(pkgpath),
}
if err := reg.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil {
for i := 0; ; i++ {
alias := fmt.Sprintf("%s_%d", pkg.Name, i)
if err := reg.ReserveGoPackageAlias(alias, pkg.Path); err != nil {
continue
}
pkg.Alias = alias
break
}
}
imports = append(imports, pkg)
}
return &generator{reg: reg, baseImports: imports, useRequestContext: useRequestContext}
}
func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) {
var files []*plugin.CodeGeneratorResponse_File
for _, file := range targets {
glog.V(1).Infof("Processing %s", file.GetName())
code, err := g.generate(file)
if err == errNoTargetService {
glog.V(1).Infof("%s: %v", file.GetName(), err)
continue
}
if err != nil {
return nil, err
}
formatted, err := format.Source([]byte(code))
if err != nil {
glog.Errorf("%v: %s", err, code)
return nil, err
}
name := file.GetName()
ext := filepath.Ext(name)
base := strings.TrimSuffix(name, ext)
output := fmt.Sprintf("%s.pb.gw.go", base)
files = append(files, &plugin.CodeGeneratorResponse_File{
Name: proto.String(output),
Content: proto.String(string(formatted)),
})
glog.V(1).Infof("Will emit %s", output)
}
return files, nil
}
func (g *generator) generate(file *descriptor.File) (string, error) {
pkgSeen := make(map[string]bool)
var imports []descriptor.GoPackage
for _, pkg := range g.baseImports {
pkgSeen[pkg.Path] = true
imports = append(imports, pkg)
}
for _, svc := range file.Services {
for _, m := range svc.Methods {
pkg := m.RequestType.File.GoPkg
if m.Options == nil || !proto.HasExtension(m.Options, options.E_Http) ||
pkg == file.GoPkg || pkgSeen[pkg.Path] {
continue
}
pkgSeen[pkg.Path] = true
imports = append(imports, pkg)
}
}
return applyTemplate(param{File: file, Imports: imports, UseRequestContext: g.useRequestContext})
}

View File

@ -0,0 +1,399 @@
package gengateway
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
)
type param struct {
*descriptor.File
Imports []descriptor.GoPackage
UseRequestContext bool
}
type binding struct {
*descriptor.Binding
}
// HasQueryParam determines if the binding needs parameters in query string.
//
// It sometimes returns true even though actually the binding does not need.
// But it is not serious because it just results in a small amount of extra codes generated.
func (b binding) HasQueryParam() bool {
if b.Body != nil && len(b.Body.FieldPath) == 0 {
return false
}
fields := make(map[string]bool)
for _, f := range b.Method.RequestType.Fields {
fields[f.GetName()] = true
}
if b.Body != nil {
delete(fields, b.Body.FieldPath.String())
}
for _, p := range b.PathParams {
delete(fields, p.FieldPath.String())
}
return len(fields) > 0
}
func (b binding) QueryParamFilter() queryParamFilter {
var seqs [][]string
if b.Body != nil {
seqs = append(seqs, strings.Split(b.Body.FieldPath.String(), "."))
}
for _, p := range b.PathParams {
seqs = append(seqs, strings.Split(p.FieldPath.String(), "."))
}
return queryParamFilter{utilities.NewDoubleArray(seqs)}
}
// queryParamFilter is a wrapper of utilities.DoubleArray which provides String() to output DoubleArray.Encoding in a stable and predictable format.
type queryParamFilter struct {
*utilities.DoubleArray
}
func (f queryParamFilter) String() string {
encodings := make([]string, len(f.Encoding))
for str, enc := range f.Encoding {
encodings[enc] = fmt.Sprintf("%q: %d", str, enc)
}
e := strings.Join(encodings, ", ")
return fmt.Sprintf("&utilities.DoubleArray{Encoding: map[string]int{%s}, Base: %#v, Check: %#v}", e, f.Base, f.Check)
}
type trailerParams struct {
Services []*descriptor.Service
UseRequestContext bool
}
func applyTemplate(p param) (string, error) {
w := bytes.NewBuffer(nil)
if err := headerTemplate.Execute(w, p); err != nil {
return "", err
}
var targetServices []*descriptor.Service
for _, svc := range p.Services {
var methodWithBindingsSeen bool
for _, meth := range svc.Methods {
glog.V(2).Infof("Processing %s.%s", svc.GetName(), meth.GetName())
methName := strings.Title(*meth.Name)
meth.Name = &methName
for _, b := range meth.Bindings {
methodWithBindingsSeen = true
if err := handlerTemplate.Execute(w, binding{Binding: b}); err != nil {
return "", err
}
}
}
if methodWithBindingsSeen {
targetServices = append(targetServices, svc)
}
}
if len(targetServices) == 0 {
return "", errNoTargetService
}
tp := trailerParams{
Services: targetServices,
UseRequestContext: p.UseRequestContext,
}
if err := trailerTemplate.Execute(w, tp); err != nil {
return "", err
}
return w.String(), nil
}
var (
headerTemplate = template.Must(template.New("header").Parse(`
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: {{.GetName}}
/*
Package {{.GoPkg.Name}} is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package {{.GoPkg.Name}}
import (
{{range $i := .Imports}}{{if $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}}
{{range $i := .Imports}}{{if not $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}}
)
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
`))
handlerTemplate = template.Must(template.New("handler").Parse(`
{{if and .Method.GetClientStreaming .Method.GetServerStreaming}}
{{template "bidi-streaming-request-func" .}}
{{else if .Method.GetClientStreaming}}
{{template "client-streaming-request-func" .}}
{{else}}
{{template "client-rpc-request-func" .}}
{{end}}
`))
_ = template.Must(handlerTemplate.New("request-func-signature").Parse(strings.Replace(`
{{if .Method.GetServerStreaming}}
func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) ({{.Method.Service.GetName}}_{{.Method.GetName}}Client, runtime.ServerMetadata, error)
{{else}}
func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error)
{{end}}`, "\n", "", -1)))
_ = template.Must(handlerTemplate.New("client-streaming-request-func").Parse(`
{{template "request-func-signature" .}} {
var metadata runtime.ServerMetadata
stream, err := client.{{.Method.GetName}}(ctx)
if err != nil {
grpclog.Printf("Failed to start streaming: %v", err)
return nil, metadata, err
}
dec := marshaler.NewDecoder(req.Body)
for {
var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}}
err = dec.Decode(&protoReq)
if err == io.EOF {
break
}
if err != nil {
grpclog.Printf("Failed to decode request: %v", err)
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err = stream.Send(&protoReq); err != nil {
grpclog.Printf("Failed to send request: %v", err)
return nil, metadata, err
}
}
if err := stream.CloseSend(); err != nil {
grpclog.Printf("Failed to terminate client stream: %v", err)
return nil, metadata, err
}
header, err := stream.Header()
if err != nil {
grpclog.Printf("Failed to get header from client: %v", err)
return nil, metadata, err
}
metadata.HeaderMD = header
{{if .Method.GetServerStreaming}}
return stream, metadata, nil
{{else}}
msg, err := stream.CloseAndRecv()
metadata.TrailerMD = stream.Trailer()
return msg, metadata, err
{{end}}
}
`))
_ = template.Must(handlerTemplate.New("client-rpc-request-func").Parse(`
{{if .HasQueryParam}}
var (
filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}} = {{.QueryParamFilter}}
)
{{end}}
{{template "request-func-signature" .}} {
var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}}
var metadata runtime.ServerMetadata
{{if .Body}}
if err := marshaler.NewDecoder(req.Body).Decode(&{{.Body.RHS "protoReq"}}); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
{{end}}
{{if .PathParams}}
var (
val string
ok bool
err error
_ = err
)
{{range $param := .PathParams}}
val, ok = pathParams[{{$param | printf "%q"}}]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", {{$param | printf "%q"}})
}
{{if $param.IsNestedProto3 }}
err = runtime.PopulateFieldFromPath(&protoReq, {{$param | printf "%q"}}, val)
{{else}}
{{$param.RHS "protoReq"}}, err = {{$param.ConvertFuncExpr}}(val)
{{end}}
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", {{$param | printf "%q"}}, err)
}
{{end}}
{{end}}
{{if .HasQueryParam}}
if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
{{end}}
{{if .Method.GetServerStreaming}}
stream, err := client.{{.Method.GetName}}(ctx, &protoReq)
if err != nil {
return nil, metadata, err
}
header, err := stream.Header()
if err != nil {
return nil, metadata, err
}
metadata.HeaderMD = header
return stream, metadata, nil
{{else}}
msg, err := client.{{.Method.GetName}}(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
{{end}}
}`))
_ = template.Must(handlerTemplate.New("bidi-streaming-request-func").Parse(`
{{template "request-func-signature" .}} {
var metadata runtime.ServerMetadata
stream, err := client.{{.Method.GetName}}(ctx)
if err != nil {
grpclog.Printf("Failed to start streaming: %v", err)
return nil, metadata, err
}
dec := marshaler.NewDecoder(req.Body)
handleSend := func() error {
var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}}
err = dec.Decode(&protoReq)
if err == io.EOF {
return err
}
if err != nil {
grpclog.Printf("Failed to decode request: %v", err)
return err
}
if err = stream.Send(&protoReq); err != nil {
grpclog.Printf("Failed to send request: %v", err)
return err
}
return nil
}
if err := handleSend(); err != nil {
if cerr := stream.CloseSend(); cerr != nil {
grpclog.Printf("Failed to terminate client stream: %v", cerr)
}
if err == io.EOF {
return stream, metadata, nil
}
return nil, metadata, err
}
go func() {
for {
if err := handleSend(); err != nil {
break
}
}
if err := stream.CloseSend(); err != nil {
grpclog.Printf("Failed to terminate client stream: %v", err)
}
}()
header, err := stream.Header()
if err != nil {
grpclog.Printf("Failed to get header from client: %v", err)
return nil, metadata, err
}
metadata.HeaderMD = header
return stream, metadata, nil
}
`))
trailerTemplate = template.Must(template.New("trailer").Parse(`
{{$UseRequestContext := .UseRequestContext}}
{{range $svc := .Services}}
// Register{{$svc.GetName}}HandlerFromEndpoint is same as Register{{$svc.GetName}}Handler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func Register{{$svc.GetName}}HandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return Register{{$svc.GetName}}Handler(ctx, mux, conn)
}
// Register{{$svc.GetName}}Handler registers the http handlers for service {{$svc.GetName}} to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func Register{{$svc.GetName}}Handler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
client := New{{$svc.GetName}}Client(conn)
{{range $m := $svc.Methods}}
{{range $b := $m.Bindings}}
mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
{{- if $UseRequestContext }}
ctx, cancel := context.WithCancel(req.Context())
{{- else -}}
ctx, cancel := context.WithCancel(ctx)
{{- end }}
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
{{if $m.GetServerStreaming}}
forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
{{else}}
forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
{{end}}
})
{{end}}
{{end}}
return nil
}
var (
{{range $m := $svc.Methods}}
{{range $b := $m.Bindings}}
pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = runtime.MustPattern(runtime.NewPattern({{$b.PathTmpl.Version}}, {{$b.PathTmpl.OpCodes | printf "%#v"}}, {{$b.PathTmpl.Pool | printf "%#v"}}, {{$b.PathTmpl.Verb | printf "%q"}}))
{{end}}
{{end}}
)
var (
{{range $m := $svc.Methods}}
{{range $b := $m.Bindings}}
forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = {{if $m.GetServerStreaming}}runtime.ForwardResponseStream{{else}}runtime.ForwardResponseMessage{{end}}
{{end}}
{{end}}
)
{{end}}`))
)

View File

@ -0,0 +1,117 @@
package httprule
import (
"github.com/grpc-ecosystem/grpc-gateway/utilities"
)
const (
opcodeVersion = 1
)
// Template is a compiled representation of path templates.
type Template struct {
// Version is the version number of the format.
Version int
// OpCodes is a sequence of operations.
OpCodes []int
// Pool is a constant pool
Pool []string
// Verb is a VERB part in the template.
Verb string
// Fields is a list of field paths bound in this template.
Fields []string
// Original template (example: /v1/a_bit_of_everything)
Template string
}
// Compiler compiles utilities representation of path templates into marshallable operations.
// They can be unmarshalled by runtime.NewPattern.
type Compiler interface {
Compile() Template
}
type op struct {
// code is the opcode of the operation
code utilities.OpCode
// str is a string operand of the code.
// num is ignored if str is not empty.
str string
// num is a numeric operand of the code.
num int
}
func (w wildcard) compile() []op {
return []op{
{code: utilities.OpPush},
}
}
func (w deepWildcard) compile() []op {
return []op{
{code: utilities.OpPushM},
}
}
func (l literal) compile() []op {
return []op{
{
code: utilities.OpLitPush,
str: string(l),
},
}
}
func (v variable) compile() []op {
var ops []op
for _, s := range v.segments {
ops = append(ops, s.compile()...)
}
ops = append(ops, op{
code: utilities.OpConcatN,
num: len(v.segments),
}, op{
code: utilities.OpCapture,
str: v.path,
})
return ops
}
func (t template) Compile() Template {
var rawOps []op
for _, s := range t.segments {
rawOps = append(rawOps, s.compile()...)
}
var (
ops []int
pool []string
fields []string
)
consts := make(map[string]int)
for _, op := range rawOps {
ops = append(ops, int(op.code))
if op.str == "" {
ops = append(ops, op.num)
} else {
if _, ok := consts[op.str]; !ok {
consts[op.str] = len(pool)
pool = append(pool, op.str)
}
ops = append(ops, consts[op.str])
}
if op.code == utilities.OpCapture {
fields = append(fields, op.str)
}
}
return Template{
Version: opcodeVersion,
OpCodes: ops,
Pool: pool,
Verb: t.verb,
Fields: fields,
Template: t.template,
}
}

View File

@ -0,0 +1,351 @@
package httprule
import (
"fmt"
"strings"
"github.com/golang/glog"
)
// InvalidTemplateError indicates that the path template is not valid.
type InvalidTemplateError struct {
tmpl string
msg string
}
func (e InvalidTemplateError) Error() string {
return fmt.Sprintf("%s: %s", e.msg, e.tmpl)
}
// Parse parses the string representation of path template
func Parse(tmpl string) (Compiler, error) {
if !strings.HasPrefix(tmpl, "/") {
return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"}
}
tokens, verb := tokenize(tmpl[1:])
p := parser{tokens: tokens}
segs, err := p.topLevelSegments()
if err != nil {
return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()}
}
return template{
segments: segs,
verb: verb,
template: tmpl,
}, nil
}
func tokenize(path string) (tokens []string, verb string) {
if path == "" {
return []string{eof}, ""
}
const (
init = iota
field
nested
)
var (
st = init
)
for path != "" {
var idx int
switch st {
case init:
idx = strings.IndexAny(path, "/{")
case field:
idx = strings.IndexAny(path, ".=}")
case nested:
idx = strings.IndexAny(path, "/}")
}
if idx < 0 {
tokens = append(tokens, path)
break
}
switch r := path[idx]; r {
case '/', '.':
case '{':
st = field
case '=':
st = nested
case '}':
st = init
}
if idx == 0 {
tokens = append(tokens, path[idx:idx+1])
} else {
tokens = append(tokens, path[:idx], path[idx:idx+1])
}
path = path[idx+1:]
}
l := len(tokens)
t := tokens[l-1]
if idx := strings.LastIndex(t, ":"); idx == 0 {
tokens, verb = tokens[:l-1], t[1:]
} else if idx > 0 {
tokens[l-1], verb = t[:idx], t[idx+1:]
}
tokens = append(tokens, eof)
return tokens, verb
}
// parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto.
type parser struct {
tokens []string
accepted []string
}
// topLevelSegments is the target of this parser.
func (p *parser) topLevelSegments() ([]segment, error) {
glog.V(1).Infof("Parsing %q", p.tokens)
segs, err := p.segments()
if err != nil {
return nil, err
}
glog.V(2).Infof("accept segments: %q; %q", p.accepted, p.tokens)
if _, err := p.accept(typeEOF); err != nil {
return nil, fmt.Errorf("unexpected token %q after segments %q", p.tokens[0], strings.Join(p.accepted, ""))
}
glog.V(2).Infof("accept eof: %q; %q", p.accepted, p.tokens)
return segs, nil
}
func (p *parser) segments() ([]segment, error) {
s, err := p.segment()
if err != nil {
return nil, err
}
glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens)
segs := []segment{s}
for {
if _, err := p.accept("/"); err != nil {
return segs, nil
}
s, err := p.segment()
if err != nil {
return segs, err
}
segs = append(segs, s)
glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens)
}
}
func (p *parser) segment() (segment, error) {
if _, err := p.accept("*"); err == nil {
return wildcard{}, nil
}
if _, err := p.accept("**"); err == nil {
return deepWildcard{}, nil
}
if l, err := p.literal(); err == nil {
return l, nil
}
v, err := p.variable()
if err != nil {
return nil, fmt.Errorf("segment neither wildcards, literal or variable: %v", err)
}
return v, err
}
func (p *parser) literal() (segment, error) {
lit, err := p.accept(typeLiteral)
if err != nil {
return nil, err
}
return literal(lit), nil
}
func (p *parser) variable() (segment, error) {
if _, err := p.accept("{"); err != nil {
return nil, err
}
path, err := p.fieldPath()
if err != nil {
return nil, err
}
var segs []segment
if _, err := p.accept("="); err == nil {
segs, err = p.segments()
if err != nil {
return nil, fmt.Errorf("invalid segment in variable %q: %v", path, err)
}
} else {
segs = []segment{wildcard{}}
}
if _, err := p.accept("}"); err != nil {
return nil, fmt.Errorf("unterminated variable segment: %s", path)
}
return variable{
path: path,
segments: segs,
}, nil
}
func (p *parser) fieldPath() (string, error) {
c, err := p.accept(typeIdent)
if err != nil {
return "", err
}
components := []string{c}
for {
if _, err = p.accept("."); err != nil {
return strings.Join(components, "."), nil
}
c, err := p.accept(typeIdent)
if err != nil {
return "", fmt.Errorf("invalid field path component: %v", err)
}
components = append(components, c)
}
}
// A termType is a type of terminal symbols.
type termType string
// These constants define some of valid values of termType.
// They improve readability of parse functions.
//
// You can also use "/", "*", "**", "." or "=" as valid values.
const (
typeIdent = termType("ident")
typeLiteral = termType("literal")
typeEOF = termType("$")
)
const (
// eof is the terminal symbol which always appears at the end of token sequence.
eof = "\u0000"
)
// accept tries to accept a token in "p".
// This function consumes a token and returns it if it matches to the specified "term".
// If it doesn't match, the function does not consume any tokens and return an error.
func (p *parser) accept(term termType) (string, error) {
t := p.tokens[0]
switch term {
case "/", "*", "**", ".", "=", "{", "}":
if t != string(term) {
return "", fmt.Errorf("expected %q but got %q", term, t)
}
case typeEOF:
if t != eof {
return "", fmt.Errorf("expected EOF but got %q", t)
}
case typeIdent:
if err := expectIdent(t); err != nil {
return "", err
}
case typeLiteral:
if err := expectPChars(t); err != nil {
return "", err
}
default:
return "", fmt.Errorf("unknown termType %q", term)
}
p.tokens = p.tokens[1:]
p.accepted = append(p.accepted, t)
return t, nil
}
// expectPChars determines if "t" consists of only pchars defined in RFC3986.
//
// https://www.ietf.org/rfc/rfc3986.txt, P.49
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
// pct-encoded = "%" HEXDIG HEXDIG
func expectPChars(t string) error {
const (
init = iota
pct1
pct2
)
st := init
for _, r := range t {
if st != init {
if !isHexDigit(r) {
return fmt.Errorf("invalid hexdigit: %c(%U)", r, r)
}
switch st {
case pct1:
st = pct2
case pct2:
st = init
}
continue
}
// unreserved
switch {
case 'A' <= r && r <= 'Z':
continue
case 'a' <= r && r <= 'z':
continue
case '0' <= r && r <= '9':
continue
}
switch r {
case '-', '.', '_', '~':
// unreserved
case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=':
// sub-delims
case ':', '@':
// rest of pchar
case '%':
// pct-encoded
st = pct1
default:
return fmt.Errorf("invalid character in path segment: %q(%U)", r, r)
}
}
if st != init {
return fmt.Errorf("invalid percent-encoding in %q", t)
}
return nil
}
// expectIdent determines if "ident" is a valid identifier in .proto schema ([[:alpha:]_][[:alphanum:]_]*).
func expectIdent(ident string) error {
if ident == "" {
return fmt.Errorf("empty identifier")
}
for pos, r := range ident {
switch {
case '0' <= r && r <= '9':
if pos == 0 {
return fmt.Errorf("identifier starting with digit: %s", ident)
}
continue
case 'A' <= r && r <= 'Z':
continue
case 'a' <= r && r <= 'z':
continue
case r == '_':
continue
default:
return fmt.Errorf("invalid character %q(%U) in identifier: %s", r, r, ident)
}
}
return nil
}
func isHexDigit(r rune) bool {
switch {
case '0' <= r && r <= '9':
return true
case 'A' <= r && r <= 'F':
return true
case 'a' <= r && r <= 'f':
return true
}
return false
}

View File

@ -0,0 +1,60 @@
package httprule
import (
"fmt"
"strings"
)
type template struct {
segments []segment
verb string
template string
}
type segment interface {
fmt.Stringer
compile() (ops []op)
}
type wildcard struct{}
type deepWildcard struct{}
type literal string
type variable struct {
path string
segments []segment
}
func (wildcard) String() string {
return "*"
}
func (deepWildcard) String() string {
return "**"
}
func (l literal) String() string {
return string(l)
}
func (v variable) String() string {
var segs []string
for _, s := range v.segments {
segs = append(segs, s.String())
}
return fmt.Sprintf("{%s=%s}", v.path, strings.Join(segs, "/"))
}
func (t template) String() string {
var segs []string
for _, s := range t.segments {
segs = append(segs, s.String())
}
str := strings.Join(segs, "/")
if t.verb != "" {
str = fmt.Sprintf("%s:%s", str, t.verb)
}
return "/" + str
}

View File

@ -0,0 +1,121 @@
// Command protoc-gen-grpc-gateway is a plugin for Google protocol buffer
// compiler to generate a reverse-proxy, which converts incoming RESTful
// HTTP/1 requests gRPC invocation.
// You rarely need to run this program directly. Instead, put this program
// into your $PATH with a name "protoc-gen-grpc-gateway" and run
// protoc --grpc-gateway_out=output_directory path/to/input.proto
//
// See README.md for more details.
package main
import (
"flag"
"io"
"io/ioutil"
"os"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway"
)
var (
importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files")
useRequestContext = flag.Bool("request_context", false, "determine whether to use http.Request's context or not")
allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body")
)
func parseReq(r io.Reader) (*plugin.CodeGeneratorRequest, error) {
glog.V(1).Info("Parsing code generator request")
input, err := ioutil.ReadAll(r)
if err != nil {
glog.Errorf("Failed to read code generator request: %v", err)
return nil, err
}
req := new(plugin.CodeGeneratorRequest)
if err = proto.Unmarshal(input, req); err != nil {
glog.Errorf("Failed to unmarshal code generator request: %v", err)
return nil, err
}
glog.V(1).Info("Parsed code generator request")
return req, nil
}
func main() {
flag.Parse()
defer glog.Flush()
reg := descriptor.NewRegistry()
glog.V(1).Info("Processing code generator request")
req, err := parseReq(os.Stdin)
if err != nil {
glog.Fatal(err)
}
if req.Parameter != nil {
for _, p := range strings.Split(req.GetParameter(), ",") {
spec := strings.SplitN(p, "=", 2)
if len(spec) == 1 {
if err := flag.CommandLine.Set(spec[0], ""); err != nil {
glog.Fatalf("Cannot set flag %s", p)
}
continue
}
name, value := spec[0], spec[1]
if strings.HasPrefix(name, "M") {
reg.AddPkgMap(name[1:], value)
continue
}
if err := flag.CommandLine.Set(name, value); err != nil {
glog.Fatalf("Cannot set flag %s", p)
}
}
}
g := gengateway.New(reg, *useRequestContext)
reg.SetPrefix(*importPrefix)
reg.SetAllowDeleteBody(*allowDeleteBody)
if err := reg.Load(req); err != nil {
emitError(err)
return
}
var targets []*descriptor.File
for _, target := range req.FileToGenerate {
f, err := reg.LookupFile(target)
if err != nil {
glog.Fatal(err)
}
targets = append(targets, f)
}
out, err := g.Generate(targets)
glog.V(1).Info("Processed code generator request")
if err != nil {
emitError(err)
return
}
emitFiles(out)
}
func emitFiles(out []*plugin.CodeGeneratorResponse_File) {
emitResp(&plugin.CodeGeneratorResponse{File: out})
}
func emitError(err error) {
emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())})
}
func emitResp(resp *plugin.CodeGeneratorResponse) {
buf, err := proto.Marshal(resp)
if err != nil {
glog.Fatal(err)
}
if _, err := os.Stdout.Write(buf); err != nil {
glog.Fatal(err)
}
}

View File

@ -0,0 +1,2 @@
// Package genswagger provides a code generator for swagger.
package genswagger

View File

@ -0,0 +1,58 @@
package genswagger
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator"
)
var (
errNoTargetService = errors.New("no target service defined in the file")
)
type generator struct {
reg *descriptor.Registry
}
// New returns a new generator which generates grpc gateway files.
func New(reg *descriptor.Registry) gen.Generator {
return &generator{reg: reg}
}
func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) {
var files []*plugin.CodeGeneratorResponse_File
for _, file := range targets {
glog.V(1).Infof("Processing %s", file.GetName())
code, err := applyTemplate(param{File: file, reg: g.reg})
if err == errNoTargetService {
glog.V(1).Infof("%s: %v", file.GetName(), err)
continue
}
if err != nil {
return nil, err
}
var formatted bytes.Buffer
json.Indent(&formatted, []byte(code), "", " ")
name := file.GetName()
ext := filepath.Ext(name)
base := strings.TrimSuffix(name, ext)
output := fmt.Sprintf("%s.swagger.json", base)
files = append(files, &plugin.CodeGeneratorResponse_File{
Name: proto.String(output),
Content: proto.String(formatted.String()),
})
glog.V(1).Infof("Will emit %s", output)
}
return files, nil
}

View File

@ -0,0 +1,860 @@
package genswagger
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
)
func listEnumNames(enum *descriptor.Enum) (names []string) {
for _, value := range enum.GetValue() {
names = append(names, value.GetName())
}
return names
}
func getEnumDefault(enum *descriptor.Enum) string {
for _, value := range enum.GetValue() {
if value.GetNumber() == 0 {
return value.GetName()
}
}
return ""
}
// messageToQueryParameters converts a message to a list of swagger query parameters.
func messageToQueryParameters(message *descriptor.Message, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) {
for _, field := range message.Fields {
p, err := queryParams(message, field, "", reg, pathParams)
if err != nil {
return nil, err
}
params = append(params, p...)
}
return params, nil
}
// queryParams converts a field to a list of swagger query parameters recuresively.
func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) {
// make sure the parameter is not already listed as a path parameter
for _, pathParam := range pathParams {
if pathParam.Target == field {
return nil, nil
}
}
schema := schemaOfField(field, reg)
fieldType := field.GetTypeName()
if message.File != nil {
comments := fieldProtoComments(reg, message, field)
if err := updateSwaggerDataFromComments(&schema, comments); err != nil {
return nil, err
}
}
isEnum := field.GetType() == pbdescriptor.FieldDescriptorProto_TYPE_ENUM
items := schema.Items
if schema.Type != "" || isEnum {
if schema.Type == "object" {
return nil, nil // TODO: currently, mapping object in query parameter is not supported
}
if items != nil && (items.Type == "" || items.Type == "object") && !isEnum {
return nil, nil // TODO: currently, mapping object in query parameter is not supported
}
desc := schema.Description
if schema.Title != "" { // merge title because title of parameter object will be ignored
desc = strings.TrimSpace(schema.Title + ". " + schema.Description)
}
param := swaggerParameterObject{
Name: prefix + field.GetName(),
Description: desc,
In: "query",
Type: schema.Type,
Items: schema.Items,
Format: schema.Format,
}
if isEnum {
enum, err := reg.LookupEnum("", fieldType)
if err != nil {
return nil, fmt.Errorf("unknown enum type %s", fieldType)
}
if items != nil { // array
param.Items = &swaggerItemsObject{
Type: "string",
Enum: listEnumNames(enum),
}
} else {
param.Type = "string"
param.Enum = listEnumNames(enum)
param.Default = getEnumDefault(enum)
}
valueComments := enumValueProtoComments(reg, enum)
if valueComments != "" {
param.Description = strings.TrimLeft(param.Description+"\n\n "+valueComments, "\n")
}
}
return []swaggerParameterObject{param}, nil
}
// nested type, recurse
msg, err := reg.LookupMsg("", fieldType)
if err != nil {
return nil, fmt.Errorf("unknown message type %s", fieldType)
}
for _, nestedField := range msg.Fields {
p, err := queryParams(msg, nestedField, prefix+field.GetName()+".", reg, pathParams)
if err != nil {
return nil, err
}
params = append(params, p...)
}
return params, nil
}
// findServicesMessagesAndEnumerations discovers all messages and enums defined in the RPC methods of the service.
func findServicesMessagesAndEnumerations(s []*descriptor.Service, reg *descriptor.Registry, m messageMap, e enumMap, refs refMap) {
for _, svc := range s {
for _, meth := range svc.Methods {
// Request may be fully included in query
if _, ok := refs[fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg))]; ok {
m[fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)] = meth.RequestType
findNestedMessagesAndEnumerations(meth.RequestType, reg, m, e)
}
m[fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)] = meth.ResponseType
findNestedMessagesAndEnumerations(meth.ResponseType, reg, m, e)
}
}
}
// findNestedMessagesAndEnumerations those can be generated by the services.
func findNestedMessagesAndEnumerations(message *descriptor.Message, reg *descriptor.Registry, m messageMap, e enumMap) {
// Iterate over all the fields that
for _, t := range message.Fields {
fieldType := t.GetTypeName()
// If the type is an empty string then it is a proto primitive
if fieldType != "" {
if _, ok := m[fieldType]; !ok {
msg, err := reg.LookupMsg("", fieldType)
if err != nil {
enum, err := reg.LookupEnum("", fieldType)
if err != nil {
panic(err)
}
e[fieldType] = enum
continue
}
m[fieldType] = msg
findNestedMessagesAndEnumerations(msg, reg, m, e)
}
}
}
}
func renderMessagesAsDefinition(messages messageMap, d swaggerDefinitionsObject, reg *descriptor.Registry) {
for name, msg := range messages {
switch name {
case ".google.protobuf.Timestamp":
continue
}
if opt := msg.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
continue
}
schema := swaggerSchemaObject{
schemaCore: schemaCore{
Type: "object",
},
}
msgComments := protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index))
if err := updateSwaggerDataFromComments(&schema, msgComments); err != nil {
panic(err)
}
for _, f := range msg.Fields {
fieldValue := schemaOfField(f, reg)
comments := fieldProtoComments(reg, msg, f)
if err := updateSwaggerDataFromComments(&fieldValue, comments); err != nil {
panic(err)
}
schema.Properties = append(schema.Properties, keyVal{f.GetName(), fieldValue})
}
d[fullyQualifiedNameToSwaggerName(msg.FQMN(), reg)] = schema
}
}
// schemaOfField returns a swagger Schema Object for a protobuf field.
func schemaOfField(f *descriptor.Field, reg *descriptor.Registry) swaggerSchemaObject {
const (
singular = 0
array = 1
object = 2
)
var (
core schemaCore
aggregate int
)
fd := f.FieldDescriptorProto
if m, err := reg.LookupMsg("", f.GetTypeName()); err == nil {
if opt := m.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
fd = m.GetField()[1]
aggregate = object
}
}
if fd.GetLabel() == pbdescriptor.FieldDescriptorProto_LABEL_REPEATED {
aggregate = array
}
switch ft := fd.GetType(); ft {
case pbdescriptor.FieldDescriptorProto_TYPE_ENUM, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE, pbdescriptor.FieldDescriptorProto_TYPE_GROUP:
if fd.GetTypeName() == ".google.protobuf.Timestamp" && pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE == ft {
core = schemaCore{
Type: "string",
Format: "date-time",
}
} else {
core = schemaCore{
Ref: "#/definitions/" + fullyQualifiedNameToSwaggerName(fd.GetTypeName(), reg),
}
}
default:
ftype, format, ok := primitiveSchema(ft)
if ok {
core = schemaCore{Type: ftype, Format: format}
} else {
core = schemaCore{Type: ft.String(), Format: "UNKNOWN"}
}
}
switch aggregate {
case array:
return swaggerSchemaObject{
schemaCore: schemaCore{
Type: "array",
Items: (*swaggerItemsObject)(&core),
},
}
case object:
return swaggerSchemaObject{
schemaCore: schemaCore{
Type: "object",
},
AdditionalProperties: &swaggerSchemaObject{schemaCore: core},
}
default:
return swaggerSchemaObject{schemaCore: core}
}
}
// primitiveSchema returns a pair of "Type" and "Format" in JSON Schema for
// the given primitive field type.
// The last return parameter is true iff the field type is actually primitive.
func primitiveSchema(t pbdescriptor.FieldDescriptorProto_Type) (ftype, format string, ok bool) {
switch t {
case pbdescriptor.FieldDescriptorProto_TYPE_DOUBLE:
return "number", "double", true
case pbdescriptor.FieldDescriptorProto_TYPE_FLOAT:
return "number", "float", true
case pbdescriptor.FieldDescriptorProto_TYPE_INT64:
return "string", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_UINT64:
// 64bit integer types are marshaled as string in the default JSONPb marshaler.
// TODO(yugui) Add an option to declare 64bit integers as int64.
//
// NOTE: uint64 is not a predefined format of integer type in Swagger spec.
// So we cannot expect that uint64 is commonly supported by swagger processor.
return "string", "uint64", true
case pbdescriptor.FieldDescriptorProto_TYPE_INT32:
return "integer", "int32", true
case pbdescriptor.FieldDescriptorProto_TYPE_FIXED64:
// Ditto.
return "string", "uint64", true
case pbdescriptor.FieldDescriptorProto_TYPE_FIXED32:
// Ditto.
return "integer", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_BOOL:
return "boolean", "boolean", true
case pbdescriptor.FieldDescriptorProto_TYPE_STRING:
// NOTE: in swagger specifition, format should be empty on string type
return "string", "", true
case pbdescriptor.FieldDescriptorProto_TYPE_BYTES:
return "string", "byte", true
case pbdescriptor.FieldDescriptorProto_TYPE_UINT32:
// Ditto.
return "integer", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED32:
return "integer", "int32", true
case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED64:
return "string", "int64", true
case pbdescriptor.FieldDescriptorProto_TYPE_SINT32:
return "integer", "int32", true
case pbdescriptor.FieldDescriptorProto_TYPE_SINT64:
return "string", "int64", true
default:
return "", "", false
}
}
// renderEnumerationsAsDefinition inserts enums into the definitions object.
func renderEnumerationsAsDefinition(enums enumMap, d swaggerDefinitionsObject, reg *descriptor.Registry) {
for _, enum := range enums {
enumComments := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index))
// it may be necessary to sort the result of the GetValue function.
enumNames := listEnumNames(enum)
defaultValue := getEnumDefault(enum)
valueComments := enumValueProtoComments(reg, enum)
if valueComments != "" {
enumComments = strings.TrimLeft(enumComments+"\n\n "+valueComments, "\n")
}
enumSchemaObject := swaggerSchemaObject{
schemaCore: schemaCore{
Type: "string",
Enum: enumNames,
Default: defaultValue,
},
}
if err := updateSwaggerDataFromComments(&enumSchemaObject, enumComments); err != nil {
panic(err)
}
d[fullyQualifiedNameToSwaggerName(enum.FQEN(), reg)] = enumSchemaObject
}
}
// Take in a FQMN or FQEN and return a swagger safe version of the FQMN
func fullyQualifiedNameToSwaggerName(fqn string, reg *descriptor.Registry) string {
registriesSeenMutex.Lock()
defer registriesSeenMutex.Unlock()
if mapping, present := registriesSeen[reg]; present {
return mapping[fqn]
}
mapping := resolveFullyQualifiedNameToSwaggerNames(append(reg.GetAllFQMNs(), reg.GetAllFQENs()...))
registriesSeen[reg] = mapping
return mapping[fqn]
}
// registriesSeen is used to memoise calls to resolveFullyQualifiedNameToSwaggerNames so
// we don't repeat it unnecessarily, since it can take some time.
var registriesSeen = map[*descriptor.Registry]map[string]string{}
var registriesSeenMutex sync.Mutex
// Take the names of every proto and "uniq-ify" them. The idea is to produce a
// set of names that meet a couple of conditions. They must be stable, they
// must be unique, and they must be shorter than the FQN.
//
// This likely could be made better. This will always generate the same names
// but may not always produce optimal names. This is a reasonably close
// approximation of what they should look like in most cases.
func resolveFullyQualifiedNameToSwaggerNames(messages []string) map[string]string {
packagesByDepth := make(map[int][][]string)
uniqueNames := make(map[string]string)
hierarchy := func(pkg string) []string {
return strings.Split(pkg, ".")
}
for _, p := range messages {
h := hierarchy(p)
for depth := range h {
if _, ok := packagesByDepth[depth]; !ok {
packagesByDepth[depth] = make([][]string, 0)
}
packagesByDepth[depth] = append(packagesByDepth[depth], h[len(h)-depth:])
}
}
count := func(list [][]string, item []string) int {
i := 0
for _, element := range list {
if reflect.DeepEqual(element, item) {
i++
}
}
return i
}
for _, p := range messages {
h := hierarchy(p)
for depth := 0; depth < len(h); depth++ {
if count(packagesByDepth[depth], h[len(h)-depth:]) == 1 {
uniqueNames[p] = strings.Join(h[len(h)-depth-1:], "")
break
}
if depth == len(h)-1 {
uniqueNames[p] = strings.Join(h, "")
}
}
}
return uniqueNames
}
// Swagger expects paths of the form /path/{string_value} but grpc-gateway paths are expected to be of the form /path/{string_value=strprefix/*}. This should reformat it correctly.
func templateToSwaggerPath(path string) string {
// It seems like the right thing to do here is to just use
// strings.Split(path, "/") but that breaks badly when you hit a url like
// /{my_field=prefix/*}/ and end up with 2 sections representing my_field.
// Instead do the right thing and write a small pushdown (counter) automata
// for it.
var parts []string
depth := 0
buffer := ""
for _, char := range path {
switch char {
case '{':
// Push on the stack
depth++
buffer += string(char)
break
case '}':
if depth == 0 {
panic("Encountered } without matching { before it.")
}
// Pop from the stack
depth--
buffer += "}"
case '/':
if depth == 0 {
parts = append(parts, buffer)
buffer = ""
// Since the stack was empty when we hit the '/' we are done with this
// section.
continue
}
default:
buffer += string(char)
break
}
}
// Now append the last element to parts
parts = append(parts, buffer)
// Parts is now an array of segments of the path. Interestingly, since the
// syntax for this subsection CAN be handled by a regexp since it has no
// memory.
re := regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}")
for index, part := range parts {
parts[index] = re.ReplaceAllString(part, "{$1}")
}
return strings.Join(parts, "/")
}
func renderServices(services []*descriptor.Service, paths swaggerPathsObject, reg *descriptor.Registry, refs refMap) error {
// Correctness of svcIdx and methIdx depends on 'services' containing the services in the same order as the 'file.Service' array.
for svcIdx, svc := range services {
for methIdx, meth := range svc.Methods {
for _, b := range meth.Bindings {
// Iterate over all the swagger parameters
parameters := swaggerParametersObject{}
for _, parameter := range b.PathParams {
var paramType, paramFormat string
switch pt := parameter.Target.GetType(); pt {
case pbdescriptor.FieldDescriptorProto_TYPE_GROUP, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE:
return fmt.Errorf("only primitive types are allowed in path parameters")
case pbdescriptor.FieldDescriptorProto_TYPE_ENUM:
paramType = fullyQualifiedNameToSwaggerName(parameter.Target.GetTypeName(), reg)
paramFormat = ""
default:
var ok bool
paramType, paramFormat, ok = primitiveSchema(pt)
if !ok {
return fmt.Errorf("unknown field type %v", pt)
}
}
parameters = append(parameters, swaggerParameterObject{
Name: parameter.String(),
In: "path",
Required: true,
// Parameters in gRPC-Gateway can only be strings?
Type: paramType,
Format: paramFormat,
})
}
// Now check if there is a body parameter
if b.Body != nil {
var schema swaggerSchemaObject
if len(b.Body.FieldPath) == 0 {
schema = swaggerSchemaObject{
schemaCore: schemaCore{
Ref: fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)),
},
}
} else {
lastField := b.Body.FieldPath[len(b.Body.FieldPath)-1]
schema = schemaOfField(lastField.Target, reg)
}
desc := ""
if meth.GetClientStreaming() {
desc = "(streaming inputs)"
}
parameters = append(parameters, swaggerParameterObject{
Name: "body",
Description: desc,
In: "body",
Required: true,
Schema: &schema,
})
} else if b.HTTPMethod == "GET" {
// add the parameters to the query string
queryParams, err := messageToQueryParameters(meth.RequestType, reg, b.PathParams)
if err != nil {
return err
}
parameters = append(parameters, queryParams...)
}
pathItemObject, ok := paths[templateToSwaggerPath(b.PathTmpl.Template)]
if !ok {
pathItemObject = swaggerPathItemObject{}
}
methProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method")
desc := ""
if meth.GetServerStreaming() {
desc += "(streaming responses)"
}
operationObject := &swaggerOperationObject{
Tags: []string{svc.GetName()},
OperationID: fmt.Sprintf("%s", meth.GetName()),
Parameters: parameters,
Responses: swaggerResponsesObject{
"200": swaggerResponseObject{
Description: desc,
Schema: swaggerSchemaObject{
schemaCore: schemaCore{
Ref: fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)),
},
},
},
},
}
// Fill reference map with referenced request messages
for _, param := range operationObject.Parameters {
if param.Schema != nil && param.Schema.Ref != "" {
refs[param.Schema.Ref] = struct{}{}
}
}
methComments := protoComments(reg, svc.File, nil, "Service", int32(svcIdx), methProtoPath, int32(methIdx))
if err := updateSwaggerDataFromComments(operationObject, methComments); err != nil {
panic(err)
}
switch b.HTTPMethod {
case "DELETE":
pathItemObject.Delete = operationObject
break
case "GET":
pathItemObject.Get = operationObject
break
case "POST":
pathItemObject.Post = operationObject
break
case "PUT":
pathItemObject.Put = operationObject
break
case "PATCH":
pathItemObject.Patch = operationObject
break
}
paths[templateToSwaggerPath(b.PathTmpl.Template)] = pathItemObject
}
}
}
// Success! return nil on the error object
return nil
}
// This function is called with a param which contains the entire definition of a method.
func applyTemplate(p param) (string, error) {
// Create the basic template object. This is the object that everything is
// defined off of.
s := swaggerObject{
// Swagger 2.0 is the version of this document
Swagger: "2.0",
Schemes: []string{"http", "https"},
Consumes: []string{"application/json"},
Produces: []string{"application/json"},
Paths: make(swaggerPathsObject),
Definitions: make(swaggerDefinitionsObject),
Info: swaggerInfoObject{
Title: *p.File.Name,
Version: "version not set",
},
}
// Loops through all the services and their exposed GET/POST/PUT/DELETE definitions
// and create entries for all of them.
refs := refMap{}
if err := renderServices(p.Services, s.Paths, p.reg, refs); err != nil {
panic(err)
}
// Find all the service's messages and enumerations that are defined (recursively) and then
// write their request and response types out as definition objects.
m := messageMap{}
e := enumMap{}
findServicesMessagesAndEnumerations(p.Services, p.reg, m, e, refs)
renderMessagesAsDefinition(m, s.Definitions, p.reg)
renderEnumerationsAsDefinition(e, s.Definitions, p.reg)
// File itself might have some comments and metadata.
packageProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package")
packageComments := protoComments(p.reg, p.File, nil, "Package", packageProtoPath)
if err := updateSwaggerDataFromComments(&s, packageComments); err != nil {
panic(err)
}
// We now have rendered the entire swagger object. Write the bytes out to a
// string so it can be written to disk.
var w bytes.Buffer
enc := json.NewEncoder(&w)
enc.Encode(&s)
return w.String(), nil
}
// updateSwaggerDataFromComments updates a Swagger object based on a comment
// from the proto file.
//
// First paragraph of a comment is used for summary. Remaining paragraphs of a
// comment are used for description. If 'Summary' field is not present on the
// passed swaggerObject, the summary and description are joined by \n\n.
//
// If there is a field named 'Info', its 'Summary' and 'Description' fields
// will be updated instead.
//
// If there is no 'Summary', the same behavior will be attempted on 'Title',
// but only if the last character is not a period.
func updateSwaggerDataFromComments(swaggerObject interface{}, comment string) error {
if len(comment) == 0 {
return nil
}
// Figure out what to apply changes to.
swaggerObjectValue := reflect.ValueOf(swaggerObject)
infoObjectValue := swaggerObjectValue.Elem().FieldByName("Info")
if !infoObjectValue.CanSet() {
// No such field? Apply summary and description directly to
// passed object.
infoObjectValue = swaggerObjectValue.Elem()
}
// Figure out which properties to update.
summaryValue := infoObjectValue.FieldByName("Summary")
descriptionValue := infoObjectValue.FieldByName("Description")
usingTitle := false
if !summaryValue.CanSet() {
summaryValue = infoObjectValue.FieldByName("Title")
usingTitle = true
}
// If there is a summary (or summary-equivalent), use the first
// paragraph as summary, and the rest as description.
if summaryValue.CanSet() {
paragraphs := strings.Split(comment, "\n\n")
summary := strings.TrimSpace(paragraphs[0])
description := strings.TrimSpace(strings.Join(paragraphs[1:], "\n\n"))
if !usingTitle || summary == "" || summary[len(summary)-1] != '.' {
if len(summary) > 0 {
summaryValue.Set(reflect.ValueOf(summary))
}
if len(description) > 0 {
if !descriptionValue.CanSet() {
return fmt.Errorf("Encountered object type with a summary, but no description")
}
descriptionValue.Set(reflect.ValueOf(description))
}
return nil
}
}
// There was no summary field on the swaggerObject. Try to apply the
// whole comment into description.
if descriptionValue.CanSet() {
descriptionValue.Set(reflect.ValueOf(comment))
return nil
}
return fmt.Errorf("no description nor summary property")
}
func fieldProtoComments(reg *descriptor.Registry, msg *descriptor.Message, field *descriptor.Field) string {
protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "Field")
for i, f := range msg.Fields {
if f == field {
return protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index), protoPath, int32(i))
}
}
return ""
}
func enumValueProtoComments(reg *descriptor.Registry, enum *descriptor.Enum) string {
protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.EnumDescriptorProto)(nil)), "Value")
var comments []string
for idx, value := range enum.GetValue() {
name := value.GetName()
str := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index), protoPath, int32(idx))
if str != "" {
comments = append(comments, name+": "+str)
}
}
if len(comments) > 0 {
return "- " + strings.Join(comments, "\n - ")
}
return ""
}
func protoComments(reg *descriptor.Registry, file *descriptor.File, outers []string, typeName string, typeIndex int32, fieldPaths ...int32) string {
if file.SourceCodeInfo == nil {
// Curious! A file without any source code info.
// This could be a test that's providing incomplete
// descriptor.File information.
//
// We could simply return no comments, but panic
// could make debugging easier.
panic("descriptor.File should not contain nil SourceCodeInfo")
}
outerPaths := make([]int32, len(outers))
for i := range outers {
location := ""
if file.Package != nil {
location = file.GetPackage()
}
msg, err := reg.LookupMsg(location, strings.Join(outers[:i+1], "."))
if err != nil {
panic(err)
}
outerPaths[i] = int32(msg.Index)
}
for _, loc := range file.SourceCodeInfo.Location {
if !isProtoPathMatches(loc.Path, outerPaths, typeName, typeIndex, fieldPaths) {
continue
}
comments := ""
if loc.LeadingComments != nil {
comments = strings.TrimRight(*loc.LeadingComments, "\n")
comments = strings.TrimSpace(comments)
// TODO(ivucica): this is a hack to fix "// " being interpreted as "//".
// perhaps we should:
// - split by \n
// - determine if every (but first and last) line begins with " "
// - trim every line only if that is the case
// - join by \n
comments = strings.Replace(comments, "\n ", "\n", -1)
}
return comments
}
return ""
}
var messageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "MessageType")
var nestedProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "NestedType")
var packageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package")
func isProtoPathMatches(paths []int32, outerPaths []int32, typeName string, typeIndex int32, fieldPaths []int32) bool {
if typeName == "Package" && typeIndex == packageProtoPath {
// path for package comments is just [2], and all the other processing
// is too complex for it.
if len(paths) == 0 || typeIndex != paths[0] {
return false
}
return true
}
if len(paths) != len(outerPaths)*2+2+len(fieldPaths) {
return false
}
typeNameDescriptor := reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil))
if len(outerPaths) > 0 {
if paths[0] != messageProtoPath || paths[1] != outerPaths[0] {
return false
}
paths = paths[2:]
outerPaths = outerPaths[1:]
for i, v := range outerPaths {
if paths[i*2] != nestedProtoPath || paths[i*2+1] != v {
return false
}
}
paths = paths[len(outerPaths)*2:]
if typeName == "MessageType" {
typeName = "NestedType"
}
typeNameDescriptor = reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil))
}
if paths[0] != protoPathIndex(typeNameDescriptor, typeName) || paths[1] != typeIndex {
return false
}
paths = paths[2:]
for i, v := range fieldPaths {
if paths[i] != v {
return false
}
}
return true
}
// protoPathIndex returns a path component for google.protobuf.descriptor.SourceCode_Location.
//
// Specifically, it returns an id as generated from descriptor proto which
// can be used to determine what type the id following it in the path is.
// For example, if we are trying to locate comments related to a field named
// `Address` in a message named `Person`, the path will be:
//
// [4, a, 2, b]
//
// While `a` gets determined by the order in which the messages appear in
// the proto file, and `b` is the field index specified in the proto
// file itself, the path actually needs to specify that `a` refers to a
// message and not, say, a service; and that `b` refers to a field and not
// an option.
//
// protoPathIndex figures out the values 4 and 2 in the above example. Because
// messages are top level objects, the value of 4 comes from field id for
// `MessageType` inside `google.protobuf.descriptor.FileDescriptor` message.
// This field has a message type `google.protobuf.descriptor.DescriptorProto`.
// And inside message `DescriptorProto`, there is a field named `Field` with id
// 2.
//
// Some code generators seem to be hardcoding these values; this method instead
// interprets them from `descriptor.proto`-derived Go source as necessary.
func protoPathIndex(descriptorType reflect.Type, what string) int32 {
field, ok := descriptorType.Elem().FieldByName(what)
if !ok {
panic(fmt.Errorf("could not find protobuf descriptor type id for %s", what))
}
pbtag := field.Tag.Get("protobuf")
if pbtag == "" {
panic(fmt.Errorf("no Go tag 'protobuf' on protobuf descriptor for %s", what))
}
path, err := strconv.Atoi(strings.Split(pbtag, ",")[1])
if err != nil {
panic(fmt.Errorf("protobuf descriptor id for %s cannot be converted to a number: %s", what, err.Error()))
}
return int32(path)
}

View File

@ -0,0 +1,192 @@
package genswagger
import (
"bytes"
"encoding/json"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
)
type param struct {
*descriptor.File
reg *descriptor.Registry
}
type binding struct {
*descriptor.Binding
}
// http://swagger.io/specification/#infoObject
type swaggerInfoObject struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
TermsOfService string `json:"termsOfService,omitempty"`
Version string `json:"version"`
Contact *swaggerContactObject `json:"contact,omitempty"`
License *swaggerLicenseObject `json:"license,omitempty"`
ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"`
}
// http://swagger.io/specification/#contactObject
type swaggerContactObject struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}
// http://swagger.io/specification/#licenseObject
type swaggerLicenseObject struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
}
// http://swagger.io/specification/#externalDocumentationObject
type swaggerExternalDocumentationObject struct {
Description string `json:"description,omitempty"`
URL string `json:"url,omitempty"`
}
// http://swagger.io/specification/#swaggerObject
type swaggerObject struct {
Swagger string `json:"swagger"`
Info swaggerInfoObject `json:"info"`
Host string `json:"host,omitempty"`
BasePath string `json:"basePath,omitempty"`
Schemes []string `json:"schemes"`
Consumes []string `json:"consumes"`
Produces []string `json:"produces"`
Paths swaggerPathsObject `json:"paths"`
Definitions swaggerDefinitionsObject `json:"definitions"`
}
// http://swagger.io/specification/#pathsObject
type swaggerPathsObject map[string]swaggerPathItemObject
// http://swagger.io/specification/#pathItemObject
type swaggerPathItemObject struct {
Get *swaggerOperationObject `json:"get,omitempty"`
Delete *swaggerOperationObject `json:"delete,omitempty"`
Post *swaggerOperationObject `json:"post,omitempty"`
Put *swaggerOperationObject `json:"put,omitempty"`
Patch *swaggerOperationObject `json:"patch,omitempty"`
}
// http://swagger.io/specification/#operationObject
type swaggerOperationObject struct {
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
OperationID string `json:"operationId"`
Responses swaggerResponsesObject `json:"responses"`
Parameters swaggerParametersObject `json:"parameters,omitempty"`
Tags []string `json:"tags,omitempty"`
ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"`
}
type swaggerParametersObject []swaggerParameterObject
// http://swagger.io/specification/#parameterObject
type swaggerParameterObject struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
In string `json:"in,omitempty"`
Required bool `json:"required"`
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Items *swaggerItemsObject `json:"items,omitempty"`
Enum []string `json:"enum,omitempty"`
Default string `json:"default,omitempty"`
// Or you can explicitly refer to another type. If this is defined all
// other fields should be empty
Schema *swaggerSchemaObject `json:"schema,omitempty"`
}
// core part of schema, which is common to itemsObject and schemaObject.
// http://swagger.io/specification/#itemsObject
type schemaCore struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Ref string `json:"$ref,omitempty"`
Items *swaggerItemsObject `json:"items,omitempty"`
// If the item is an enumeration include a list of all the *NAMES* of the
// enum values. I'm not sure how well this will work but assuming all enums
// start from 0 index it will be great. I don't think that is a good assumption.
Enum []string `json:"enum,omitempty"`
Default string `json:"default,omitempty"`
}
type swaggerItemsObject schemaCore
// http://swagger.io/specification/#responsesObject
type swaggerResponsesObject map[string]swaggerResponseObject
// http://swagger.io/specification/#responseObject
type swaggerResponseObject struct {
Description string `json:"description"`
Schema swaggerSchemaObject `json:"schema"`
}
type keyVal struct {
Key string
Value interface{}
}
type swaggerSchemaObjectProperties []keyVal
func (op swaggerSchemaObjectProperties) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
buf.WriteString("{")
for i, kv := range op {
if i != 0 {
buf.WriteString(",")
}
key, err := json.Marshal(kv.Key)
if err != nil {
return nil, err
}
buf.Write(key)
buf.WriteString(":")
val, err := json.Marshal(kv.Value)
if err != nil {
return nil, err
}
buf.Write(val)
}
buf.WriteString("}")
return buf.Bytes(), nil
}
// http://swagger.io/specification/#schemaObject
type swaggerSchemaObject struct {
schemaCore
// Properties can be recursively defined
Properties swaggerSchemaObjectProperties `json:"properties,omitempty"`
AdditionalProperties *swaggerSchemaObject `json:"additionalProperties,omitempty"`
Description string `json:"description,omitempty"`
Title string `json:"title,omitempty"`
}
// http://swagger.io/specification/#referenceObject
type swaggerReferenceObject struct {
Ref string `json:"$ref"`
}
// http://swagger.io/specification/#definitionsObject
type swaggerDefinitionsObject map[string]swaggerSchemaObject
// Internal type mapping from FQMN to descriptor.Message. Used as a set by the
// findServiceMessages function.
type messageMap map[string]*descriptor.Message
// Internal type mapping from FQEN to descriptor.Enum. Used as a set by the
// findServiceMessages function.
type enumMap map[string]*descriptor.Enum
// Internal type to store used references.
type refMap map[string]struct{}

View File

@ -0,0 +1,144 @@
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
"github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger"
)
var (
importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files")
file = flag.String("file", "stdin", "where to load data from")
allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body")
)
func parseReq(r io.Reader) (*plugin.CodeGeneratorRequest, error) {
glog.V(1).Info("Parsing code generator request")
input, err := ioutil.ReadAll(r)
if err != nil {
glog.Errorf("Failed to read code generator request: %v", err)
return nil, err
}
req := new(plugin.CodeGeneratorRequest)
if err = proto.Unmarshal(input, req); err != nil {
glog.Errorf("Failed to unmarshal code generator request: %v", err)
return nil, err
}
glog.V(1).Info("Parsed code generator request")
return req, nil
}
func main() {
flag.Parse()
defer glog.Flush()
reg := descriptor.NewRegistry()
glog.V(1).Info("Processing code generator request")
f := os.Stdin
if *file != "stdin" {
f, _ = os.Open("input.txt")
}
req, err := parseReq(f)
if err != nil {
glog.Fatal(err)
}
pkgMap := make(map[string]string)
if req.Parameter != nil {
err := parseReqParam(req.GetParameter(), flag.CommandLine, pkgMap)
if err != nil {
glog.Fatalf("Error parsing flags: %v", err)
}
}
reg.SetPrefix(*importPrefix)
reg.SetAllowDeleteBody(*allowDeleteBody)
for k, v := range pkgMap {
reg.AddPkgMap(k, v)
}
g := genswagger.New(reg)
if err := reg.Load(req); err != nil {
emitError(err)
return
}
var targets []*descriptor.File
for _, target := range req.FileToGenerate {
f, err := reg.LookupFile(target)
if err != nil {
glog.Fatal(err)
}
targets = append(targets, f)
}
out, err := g.Generate(targets)
glog.V(1).Info("Processed code generator request")
if err != nil {
emitError(err)
return
}
emitFiles(out)
}
func emitFiles(out []*plugin.CodeGeneratorResponse_File) {
emitResp(&plugin.CodeGeneratorResponse{File: out})
}
func emitError(err error) {
emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())})
}
func emitResp(resp *plugin.CodeGeneratorResponse) {
buf, err := proto.Marshal(resp)
if err != nil {
glog.Fatal(err)
}
if _, err := os.Stdout.Write(buf); err != nil {
glog.Fatal(err)
}
}
// parseReqParam parses a CodeGeneratorRequest parameter and adds the
// extracted values to the given FlagSet and pkgMap. Returns a non-nil
// error if setting a flag failed.
func parseReqParam(param string, f *flag.FlagSet, pkgMap map[string]string) error {
if param == "" {
return nil
}
for _, p := range strings.Split(param, ",") {
spec := strings.SplitN(p, "=", 2)
if len(spec) == 1 {
if spec[0] == "allow_delete_body" {
err := f.Set(spec[0], "true")
if err != nil {
return fmt.Errorf("Cannot set flag %s: %v", p, err)
}
continue
}
err := f.Set(spec[0], "")
if err != nil {
return fmt.Errorf("Cannot set flag %s: %v", p, err)
}
continue
}
name, value := spec[0], spec[1]
if strings.HasPrefix(name, "M") {
pkgMap[name[1:]] = value
continue
}
if err := f.Set(name, value); err != nil {
return fmt.Errorf("Cannot set flag %s: %v", p, err)
}
}
return nil
}

View File

@ -0,0 +1,61 @@
package runtime
import (
"io"
"net/http"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
// ProtoErrorHandlerFunc handles the error as a gRPC error generated via status package and replies to the request.
type ProtoErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, error)
var _ ProtoErrorHandlerFunc = DefaultHTTPProtoErrorHandler
// DefaultHTTPProtoErrorHandler is an implementation of HTTPError.
// If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode.
// If otherwise, it replies with http.StatusInternalServerError.
//
// The response body returned by this function is a Status message marshaled by a Marshaler.
//
// Do not set this function to HTTPError variable directly, use WithProtoErrorHandler option instead.
func DefaultHTTPProtoErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error) {
// return Internal when Marshal failed
const fallback = `{"code": 13, "message": "failed to marshal error message"}`
w.Header().Del("Trailer")
w.Header().Set("Content-Type", marshaler.ContentType())
s, ok := status.FromError(err)
if !ok {
s = status.New(codes.Unknown, err.Error())
}
buf, merr := marshaler.Marshal(s.Proto())
if merr != nil {
grpclog.Printf("Failed to marshal error message %q: %v", s.Proto(), merr)
w.WriteHeader(http.StatusInternalServerError)
if _, err := io.WriteString(w, fallback); err != nil {
grpclog.Printf("Failed to write response: %v", err)
}
return
}
md, ok := ServerMetadataFromContext(ctx)
if !ok {
grpclog.Printf("Failed to extract ServerMetadata from context")
}
handleForwardResponseServerMetadata(w, mux, md)
handleForwardResponseTrailerHeader(w, md)
st := HTTPStatusFromCode(s.Code())
w.WriteHeader(st)
if _, err := w.Write(buf); err != nil {
grpclog.Printf("Failed to write response: %v", err)
}
handleForwardResponseTrailer(w, md)
}

66
vendor/github.com/rogpeppe/fastuuid/uuid.go generated vendored Normal file
View File

@ -0,0 +1,66 @@
// Package fastuuid provides fast UUID generation of 192 bit
// universally unique identifiers. It does not provide
// formatting or parsing of the identifiers (it is assumed
// that a simple hexadecimal or base64 representation
// is sufficient, for which adequate functionality exists elsewhere).
//
// Note that the generated UUIDs are not unguessable - each
// UUID generated from a Generator is adjacent to the
// previously generated UUID.
//
// It ignores RFC 4122.
package fastuuid
import (
"crypto/rand"
"encoding/binary"
"errors"
"sync/atomic"
)
// Generator represents a UUID generator that
// generates UUIDs in sequence from a random starting
// point.
type Generator struct {
seed [24]byte
counter uint64
}
// NewGenerator returns a new Generator.
// It can fail if the crypto/rand read fails.
func NewGenerator() (*Generator, error) {
var g Generator
_, err := rand.Read(g.seed[:])
if err != nil {
return nil, errors.New("cannot generate random seed: " + err.Error())
}
return &g, nil
}
// MustNewGenerator is like NewGenerator
// but panics on failure.
func MustNewGenerator() *Generator {
g, err := NewGenerator()
if err != nil {
panic(err)
}
return g
}
// Next returns the next UUID from the generator.
// Only the first 8 bytes can differ from the previous
// UUID, so taking a slice of the first 16 bytes
// is sufficient to provide a somewhat less secure 128 bit UUID.
//
// It is OK to call this method concurrently.
func (g *Generator) Next() [24]byte {
x := atomic.AddUint64(&g.counter, 1)
var counterBytes [8]byte
binary.LittleEndian.PutUint64(counterBytes[:], x)
uuid := g.seed
for i, b := range counterBytes {
uuid[i] ^= b
}
return uuid
}

951
vendor/golang.org/x/crypto/ssh/terminal/terminal.go generated vendored Normal file
View File

@ -0,0 +1,951 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import (
"bytes"
"io"
"sync"
"unicode/utf8"
)
// EscapeCodes contains escape sequences that can be written to the terminal in
// order to achieve different styles of text.
type EscapeCodes struct {
// Foreground colors
Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte
// Reset all attributes
Reset []byte
}
var vt100EscapeCodes = EscapeCodes{
Black: []byte{keyEscape, '[', '3', '0', 'm'},
Red: []byte{keyEscape, '[', '3', '1', 'm'},
Green: []byte{keyEscape, '[', '3', '2', 'm'},
Yellow: []byte{keyEscape, '[', '3', '3', 'm'},
Blue: []byte{keyEscape, '[', '3', '4', 'm'},
Magenta: []byte{keyEscape, '[', '3', '5', 'm'},
Cyan: []byte{keyEscape, '[', '3', '6', 'm'},
White: []byte{keyEscape, '[', '3', '7', 'm'},
Reset: []byte{keyEscape, '[', '0', 'm'},
}
// Terminal contains the state for running a VT100 terminal that is capable of
// reading lines of input.
type Terminal struct {
// AutoCompleteCallback, if non-null, is called for each keypress with
// the full input line and the current position of the cursor (in
// bytes, as an index into |line|). If it returns ok=false, the key
// press is processed normally. Otherwise it returns a replacement line
// and the new cursor position.
AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool)
// Escape contains a pointer to the escape codes for this terminal.
// It's always a valid pointer, although the escape codes themselves
// may be empty if the terminal doesn't support them.
Escape *EscapeCodes
// lock protects the terminal and the state in this object from
// concurrent processing of a key press and a Write() call.
lock sync.Mutex
c io.ReadWriter
prompt []rune
// line is the current line being entered.
line []rune
// pos is the logical position of the cursor in line
pos int
// echo is true if local echo is enabled
echo bool
// pasteActive is true iff there is a bracketed paste operation in
// progress.
pasteActive bool
// cursorX contains the current X value of the cursor where the left
// edge is 0. cursorY contains the row number where the first row of
// the current line is 0.
cursorX, cursorY int
// maxLine is the greatest value of cursorY so far.
maxLine int
termWidth, termHeight int
// outBuf contains the terminal data to be sent.
outBuf []byte
// remainder contains the remainder of any partial key sequences after
// a read. It aliases into inBuf.
remainder []byte
inBuf [256]byte
// history contains previously entered commands so that they can be
// accessed with the up and down keys.
history stRingBuffer
// historyIndex stores the currently accessed history entry, where zero
// means the immediately previous entry.
historyIndex int
// When navigating up and down the history it's possible to return to
// the incomplete, initial line. That value is stored in
// historyPending.
historyPending string
}
// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
// a local terminal, that terminal must first have been put into raw mode.
// prompt is a string that is written at the start of each input line (i.e.
// "> ").
func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
return &Terminal{
Escape: &vt100EscapeCodes,
c: c,
prompt: []rune(prompt),
termWidth: 80,
termHeight: 24,
echo: true,
historyIndex: -1,
}
}
const (
keyCtrlD = 4
keyCtrlU = 21
keyEnter = '\r'
keyEscape = 27
keyBackspace = 127
keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota
keyUp
keyDown
keyLeft
keyRight
keyAltLeft
keyAltRight
keyHome
keyEnd
keyDeleteWord
keyDeleteLine
keyClearScreen
keyPasteStart
keyPasteEnd
)
var (
crlf = []byte{'\r', '\n'}
pasteStart = []byte{keyEscape, '[', '2', '0', '0', '~'}
pasteEnd = []byte{keyEscape, '[', '2', '0', '1', '~'}
)
// bytesToKey tries to parse a key sequence from b. If successful, it returns
// the key and the remainder of the input. Otherwise it returns utf8.RuneError.
func bytesToKey(b []byte, pasteActive bool) (rune, []byte) {
if len(b) == 0 {
return utf8.RuneError, nil
}
if !pasteActive {
switch b[0] {
case 1: // ^A
return keyHome, b[1:]
case 5: // ^E
return keyEnd, b[1:]
case 8: // ^H
return keyBackspace, b[1:]
case 11: // ^K
return keyDeleteLine, b[1:]
case 12: // ^L
return keyClearScreen, b[1:]
case 23: // ^W
return keyDeleteWord, b[1:]
}
}
if b[0] != keyEscape {
if !utf8.FullRune(b) {
return utf8.RuneError, b
}
r, l := utf8.DecodeRune(b)
return r, b[l:]
}
if !pasteActive && len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
switch b[2] {
case 'A':
return keyUp, b[3:]
case 'B':
return keyDown, b[3:]
case 'C':
return keyRight, b[3:]
case 'D':
return keyLeft, b[3:]
case 'H':
return keyHome, b[3:]
case 'F':
return keyEnd, b[3:]
}
}
if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
switch b[5] {
case 'C':
return keyAltRight, b[6:]
case 'D':
return keyAltLeft, b[6:]
}
}
if !pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteStart) {
return keyPasteStart, b[6:]
}
if pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteEnd) {
return keyPasteEnd, b[6:]
}
// If we get here then we have a key that we don't recognise, or a
// partial sequence. It's not clear how one should find the end of a
// sequence without knowing them all, but it seems that [a-zA-Z~] only
// appears at the end of a sequence.
for i, c := range b[0:] {
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '~' {
return keyUnknown, b[i+1:]
}
}
return utf8.RuneError, b
}
// queue appends data to the end of t.outBuf
func (t *Terminal) queue(data []rune) {
t.outBuf = append(t.outBuf, []byte(string(data))...)
}
var eraseUnderCursor = []rune{' ', keyEscape, '[', 'D'}
var space = []rune{' '}
func isPrintable(key rune) bool {
isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
return key >= 32 && !isInSurrogateArea
}
// moveCursorToPos appends data to t.outBuf which will move the cursor to the
// given, logical position in the text.
func (t *Terminal) moveCursorToPos(pos int) {
if !t.echo {
return
}
x := visualLength(t.prompt) + pos
y := x / t.termWidth
x = x % t.termWidth
up := 0
if y < t.cursorY {
up = t.cursorY - y
}
down := 0
if y > t.cursorY {
down = y - t.cursorY
}
left := 0
if x < t.cursorX {
left = t.cursorX - x
}
right := 0
if x > t.cursorX {
right = x - t.cursorX
}
t.cursorX = x
t.cursorY = y
t.move(up, down, left, right)
}
func (t *Terminal) move(up, down, left, right int) {
movement := make([]rune, 3*(up+down+left+right))
m := movement
for i := 0; i < up; i++ {
m[0] = keyEscape
m[1] = '['
m[2] = 'A'
m = m[3:]
}
for i := 0; i < down; i++ {
m[0] = keyEscape
m[1] = '['
m[2] = 'B'
m = m[3:]
}
for i := 0; i < left; i++ {
m[0] = keyEscape
m[1] = '['
m[2] = 'D'
m = m[3:]
}
for i := 0; i < right; i++ {
m[0] = keyEscape
m[1] = '['
m[2] = 'C'
m = m[3:]
}
t.queue(movement)
}
func (t *Terminal) clearLineToRight() {
op := []rune{keyEscape, '[', 'K'}
t.queue(op)
}
const maxLineLength = 4096
func (t *Terminal) setLine(newLine []rune, newPos int) {
if t.echo {
t.moveCursorToPos(0)
t.writeLine(newLine)
for i := len(newLine); i < len(t.line); i++ {
t.writeLine(space)
}
t.moveCursorToPos(newPos)
}
t.line = newLine
t.pos = newPos
}
func (t *Terminal) advanceCursor(places int) {
t.cursorX += places
t.cursorY += t.cursorX / t.termWidth
if t.cursorY > t.maxLine {
t.maxLine = t.cursorY
}
t.cursorX = t.cursorX % t.termWidth
if places > 0 && t.cursorX == 0 {
// Normally terminals will advance the current position
// when writing a character. But that doesn't happen
// for the last character in a line. However, when
// writing a character (except a new line) that causes
// a line wrap, the position will be advanced two
// places.
//
// So, if we are stopping at the end of a line, we
// need to write a newline so that our cursor can be
// advanced to the next line.
t.outBuf = append(t.outBuf, '\r', '\n')
}
}
func (t *Terminal) eraseNPreviousChars(n int) {
if n == 0 {
return
}
if t.pos < n {
n = t.pos
}
t.pos -= n
t.moveCursorToPos(t.pos)
copy(t.line[t.pos:], t.line[n+t.pos:])
t.line = t.line[:len(t.line)-n]
if t.echo {
t.writeLine(t.line[t.pos:])
for i := 0; i < n; i++ {
t.queue(space)
}
t.advanceCursor(n)
t.moveCursorToPos(t.pos)
}
}
// countToLeftWord returns then number of characters from the cursor to the
// start of the previous word.
func (t *Terminal) countToLeftWord() int {
if t.pos == 0 {
return 0
}
pos := t.pos - 1
for pos > 0 {
if t.line[pos] != ' ' {
break
}
pos--
}
for pos > 0 {
if t.line[pos] == ' ' {
pos++
break
}
pos--
}
return t.pos - pos
}
// countToRightWord returns then number of characters from the cursor to the
// start of the next word.
func (t *Terminal) countToRightWord() int {
pos := t.pos
for pos < len(t.line) {
if t.line[pos] == ' ' {
break
}
pos++
}
for pos < len(t.line) {
if t.line[pos] != ' ' {
break
}
pos++
}
return pos - t.pos
}
// visualLength returns the number of visible glyphs in s.
func visualLength(runes []rune) int {
inEscapeSeq := false
length := 0
for _, r := range runes {
switch {
case inEscapeSeq:
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
inEscapeSeq = false
}
case r == '\x1b':
inEscapeSeq = true
default:
length++
}
}
return length
}
// handleKey processes the given key and, optionally, returns a line of text
// that the user has entered.
func (t *Terminal) handleKey(key rune) (line string, ok bool) {
if t.pasteActive && key != keyEnter {
t.addKeyToLine(key)
return
}
switch key {
case keyBackspace:
if t.pos == 0 {
return
}
t.eraseNPreviousChars(1)
case keyAltLeft:
// move left by a word.
t.pos -= t.countToLeftWord()
t.moveCursorToPos(t.pos)
case keyAltRight:
// move right by a word.
t.pos += t.countToRightWord()
t.moveCursorToPos(t.pos)
case keyLeft:
if t.pos == 0 {
return
}
t.pos--
t.moveCursorToPos(t.pos)
case keyRight:
if t.pos == len(t.line) {
return
}
t.pos++
t.moveCursorToPos(t.pos)
case keyHome:
if t.pos == 0 {
return
}
t.pos = 0
t.moveCursorToPos(t.pos)
case keyEnd:
if t.pos == len(t.line) {
return
}
t.pos = len(t.line)
t.moveCursorToPos(t.pos)
case keyUp:
entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
if !ok {
return "", false
}
if t.historyIndex == -1 {
t.historyPending = string(t.line)
}
t.historyIndex++
runes := []rune(entry)
t.setLine(runes, len(runes))
case keyDown:
switch t.historyIndex {
case -1:
return
case 0:
runes := []rune(t.historyPending)
t.setLine(runes, len(runes))
t.historyIndex--
default:
entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
if ok {
t.historyIndex--
runes := []rune(entry)
t.setLine(runes, len(runes))
}
}
case keyEnter:
t.moveCursorToPos(len(t.line))
t.queue([]rune("\r\n"))
line = string(t.line)
ok = true
t.line = t.line[:0]
t.pos = 0
t.cursorX = 0
t.cursorY = 0
t.maxLine = 0
case keyDeleteWord:
// Delete zero or more spaces and then one or more characters.
t.eraseNPreviousChars(t.countToLeftWord())
case keyDeleteLine:
// Delete everything from the current cursor position to the
// end of line.
for i := t.pos; i < len(t.line); i++ {
t.queue(space)
t.advanceCursor(1)
}
t.line = t.line[:t.pos]
t.moveCursorToPos(t.pos)
case keyCtrlD:
// Erase the character under the current position.
// The EOF case when the line is empty is handled in
// readLine().
if t.pos < len(t.line) {
t.pos++
t.eraseNPreviousChars(1)
}
case keyCtrlU:
t.eraseNPreviousChars(t.pos)
case keyClearScreen:
// Erases the screen and moves the cursor to the home position.
t.queue([]rune("\x1b[2J\x1b[H"))
t.queue(t.prompt)
t.cursorX, t.cursorY = 0, 0
t.advanceCursor(visualLength(t.prompt))
t.setLine(t.line, t.pos)
default:
if t.AutoCompleteCallback != nil {
prefix := string(t.line[:t.pos])
suffix := string(t.line[t.pos:])
t.lock.Unlock()
newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
t.lock.Lock()
if completeOk {
t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
return
}
}
if !isPrintable(key) {
return
}
if len(t.line) == maxLineLength {
return
}
t.addKeyToLine(key)
}
return
}
// addKeyToLine inserts the given key at the current position in the current
// line.
func (t *Terminal) addKeyToLine(key rune) {
if len(t.line) == cap(t.line) {
newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
copy(newLine, t.line)
t.line = newLine
}
t.line = t.line[:len(t.line)+1]
copy(t.line[t.pos+1:], t.line[t.pos:])
t.line[t.pos] = key
if t.echo {
t.writeLine(t.line[t.pos:])
}
t.pos++
t.moveCursorToPos(t.pos)
}
func (t *Terminal) writeLine(line []rune) {
for len(line) != 0 {
remainingOnLine := t.termWidth - t.cursorX
todo := len(line)
if todo > remainingOnLine {
todo = remainingOnLine
}
t.queue(line[:todo])
t.advanceCursor(visualLength(line[:todo]))
line = line[todo:]
}
}
// writeWithCRLF writes buf to w but replaces all occurrences of \n with \r\n.
func writeWithCRLF(w io.Writer, buf []byte) (n int, err error) {
for len(buf) > 0 {
i := bytes.IndexByte(buf, '\n')
todo := len(buf)
if i >= 0 {
todo = i
}
var nn int
nn, err = w.Write(buf[:todo])
n += nn
if err != nil {
return n, err
}
buf = buf[todo:]
if i >= 0 {
if _, err = w.Write(crlf); err != nil {
return n, err
}
n += 1
buf = buf[1:]
}
}
return n, nil
}
func (t *Terminal) Write(buf []byte) (n int, err error) {
t.lock.Lock()
defer t.lock.Unlock()
if t.cursorX == 0 && t.cursorY == 0 {
// This is the easy case: there's nothing on the screen that we
// have to move out of the way.
return writeWithCRLF(t.c, buf)
}
// We have a prompt and possibly user input on the screen. We
// have to clear it first.
t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
t.cursorX = 0
t.clearLineToRight()
for t.cursorY > 0 {
t.move(1 /* up */, 0, 0, 0)
t.cursorY--
t.clearLineToRight()
}
if _, err = t.c.Write(t.outBuf); err != nil {
return
}
t.outBuf = t.outBuf[:0]
if n, err = writeWithCRLF(t.c, buf); err != nil {
return
}
t.writeLine(t.prompt)
if t.echo {
t.writeLine(t.line)
}
t.moveCursorToPos(t.pos)
if _, err = t.c.Write(t.outBuf); err != nil {
return
}
t.outBuf = t.outBuf[:0]
return
}
// ReadPassword temporarily changes the prompt and reads a password, without
// echo, from the terminal.
func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
t.lock.Lock()
defer t.lock.Unlock()
oldPrompt := t.prompt
t.prompt = []rune(prompt)
t.echo = false
line, err = t.readLine()
t.prompt = oldPrompt
t.echo = true
return
}
// ReadLine returns a line of input from the terminal.
func (t *Terminal) ReadLine() (line string, err error) {
t.lock.Lock()
defer t.lock.Unlock()
return t.readLine()
}
func (t *Terminal) readLine() (line string, err error) {
// t.lock must be held at this point
if t.cursorX == 0 && t.cursorY == 0 {
t.writeLine(t.prompt)
t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
}
lineIsPasted := t.pasteActive
for {
rest := t.remainder
lineOk := false
for !lineOk {
var key rune
key, rest = bytesToKey(rest, t.pasteActive)
if key == utf8.RuneError {
break
}
if !t.pasteActive {
if key == keyCtrlD {
if len(t.line) == 0 {
return "", io.EOF
}
}
if key == keyPasteStart {
t.pasteActive = true
if len(t.line) == 0 {
lineIsPasted = true
}
continue
}
} else if key == keyPasteEnd {
t.pasteActive = false
continue
}
if !t.pasteActive {
lineIsPasted = false
}
line, lineOk = t.handleKey(key)
}
if len(rest) > 0 {
n := copy(t.inBuf[:], rest)
t.remainder = t.inBuf[:n]
} else {
t.remainder = nil
}
t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
if lineOk {
if t.echo {
t.historyIndex = -1
t.history.Add(line)
}
if lineIsPasted {
err = ErrPasteIndicator
}
return
}
// t.remainder is a slice at the beginning of t.inBuf
// containing a partial key sequence
readBuf := t.inBuf[len(t.remainder):]
var n int
t.lock.Unlock()
n, err = t.c.Read(readBuf)
t.lock.Lock()
if err != nil {
return
}
t.remainder = t.inBuf[:n+len(t.remainder)]
}
}
// SetPrompt sets the prompt to be used when reading subsequent lines.
func (t *Terminal) SetPrompt(prompt string) {
t.lock.Lock()
defer t.lock.Unlock()
t.prompt = []rune(prompt)
}
func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) {
// Move cursor to column zero at the start of the line.
t.move(t.cursorY, 0, t.cursorX, 0)
t.cursorX, t.cursorY = 0, 0
t.clearLineToRight()
for t.cursorY < numPrevLines {
// Move down a line
t.move(0, 1, 0, 0)
t.cursorY++
t.clearLineToRight()
}
// Move back to beginning.
t.move(t.cursorY, 0, 0, 0)
t.cursorX, t.cursorY = 0, 0
t.queue(t.prompt)
t.advanceCursor(visualLength(t.prompt))
t.writeLine(t.line)
t.moveCursorToPos(t.pos)
}
func (t *Terminal) SetSize(width, height int) error {
t.lock.Lock()
defer t.lock.Unlock()
if width == 0 {
width = 1
}
oldWidth := t.termWidth
t.termWidth, t.termHeight = width, height
switch {
case width == oldWidth:
// If the width didn't change then nothing else needs to be
// done.
return nil
case len(t.line) == 0 && t.cursorX == 0 && t.cursorY == 0:
// If there is nothing on current line and no prompt printed,
// just do nothing
return nil
case width < oldWidth:
// Some terminals (e.g. xterm) will truncate lines that were
// too long when shinking. Others, (e.g. gnome-terminal) will
// attempt to wrap them. For the former, repainting t.maxLine
// works great, but that behaviour goes badly wrong in the case
// of the latter because they have doubled every full line.
// We assume that we are working on a terminal that wraps lines
// and adjust the cursor position based on every previous line
// wrapping and turning into two. This causes the prompt on
// xterms to move upwards, which isn't great, but it avoids a
// huge mess with gnome-terminal.
if t.cursorX >= t.termWidth {
t.cursorX = t.termWidth - 1
}
t.cursorY *= 2
t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2)
case width > oldWidth:
// If the terminal expands then our position calculations will
// be wrong in the future because we think the cursor is
// |t.pos| chars into the string, but there will be a gap at
// the end of any wrapped line.
//
// But the position will actually be correct until we move, so
// we can move back to the beginning and repaint everything.
t.clearAndRepaintLinePlusNPrevious(t.maxLine)
}
_, err := t.c.Write(t.outBuf)
t.outBuf = t.outBuf[:0]
return err
}
type pasteIndicatorError struct{}
func (pasteIndicatorError) Error() string {
return "terminal: ErrPasteIndicator not correctly handled"
}
// ErrPasteIndicator may be returned from ReadLine as the error, in addition
// to valid line data. It indicates that bracketed paste mode is enabled and
// that the returned line consists only of pasted data. Programs may wish to
// interpret pasted data more literally than typed data.
var ErrPasteIndicator = pasteIndicatorError{}
// SetBracketedPasteMode requests that the terminal bracket paste operations
// with markers. Not all terminals support this but, if it is supported, then
// enabling this mode will stop any autocomplete callback from running due to
// pastes. Additionally, any lines that are completely pasted will be returned
// from ReadLine with the error set to ErrPasteIndicator.
func (t *Terminal) SetBracketedPasteMode(on bool) {
if on {
io.WriteString(t.c, "\x1b[?2004h")
} else {
io.WriteString(t.c, "\x1b[?2004l")
}
}
// stRingBuffer is a ring buffer of strings.
type stRingBuffer struct {
// entries contains max elements.
entries []string
max int
// head contains the index of the element most recently added to the ring.
head int
// size contains the number of elements in the ring.
size int
}
func (s *stRingBuffer) Add(a string) {
if s.entries == nil {
const defaultNumEntries = 100
s.entries = make([]string, defaultNumEntries)
s.max = defaultNumEntries
}
s.head = (s.head + 1) % s.max
s.entries[s.head] = a
if s.size < s.max {
s.size++
}
}
// NthPreviousEntry returns the value passed to the nth previous call to Add.
// If n is zero then the immediately prior value is returned, if one, then the
// next most recent, and so on. If such an element doesn't exist then ok is
// false.
func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
if n >= s.size {
return "", false
}
index := s.head - n
if index < 0 {
index += s.max
}
return s.entries[index], true
}
// readPasswordLine reads from reader until it finds \n or io.EOF.
// The slice returned does not include the \n.
// readPasswordLine also ignores any \r it finds.
func readPasswordLine(reader io.Reader) ([]byte, error) {
var buf [1]byte
var ret []byte
for {
n, err := reader.Read(buf[:])
if n > 0 {
switch buf[0] {
case '\n':
return ret, nil
case '\r':
// remove \r from passwords on Windows
default:
ret = append(ret, buf[0])
}
continue
}
if err != nil {
if err == io.EOF && len(ret) > 0 {
return ret, nil
}
return ret, err
}
}
}

123
vendor/golang.org/x/crypto/ssh/terminal/util.go generated vendored Normal file
View File

@ -0,0 +1,123 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux,!appengine netbsd openbsd
// Package terminal provides support functions for dealing with terminals, as
// commonly found on UNIX systems.
//
// Putting a terminal into raw mode is the most common requirement:
//
// oldState, err := terminal.MakeRaw(0)
// if err != nil {
// panic(err)
// }
// defer terminal.Restore(0, oldState)
package terminal // import "golang.org/x/crypto/ssh/terminal"
import (
"syscall"
"unsafe"
"golang.org/x/sys/unix"
)
// State contains the state of a terminal.
type State struct {
termios syscall.Termios
}
// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
var termios syscall.Termios
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
return err == 0
}
// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd int) (*State, error) {
var oldState State
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 {
return nil, err
}
newState := oldState.termios
// This attempts to replicate the behaviour documented for cfmakeraw in
// the termios(3) manpage.
newState.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON
newState.Oflag &^= syscall.OPOST
newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN
newState.Cflag &^= syscall.CSIZE | syscall.PARENB
newState.Cflag |= syscall.CS8
newState.Cc[unix.VMIN] = 1
newState.Cc[unix.VTIME] = 0
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
return nil, err
}
return &oldState, nil
}
// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
func GetState(fd int) (*State, error) {
var oldState State
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 {
return nil, err
}
return &oldState, nil
}
// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, state *State) error {
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&state.termios)), 0, 0, 0); err != 0 {
return err
}
return nil
}
// GetSize returns the dimensions of the given terminal.
func GetSize(fd int) (width, height int, err error) {
var dimensions [4]uint16
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0); err != 0 {
return -1, -1, err
}
return int(dimensions[1]), int(dimensions[0]), nil
}
// passwordReader is an io.Reader that reads from a specific file descriptor.
type passwordReader int
func (r passwordReader) Read(buf []byte) (int, error) {
return syscall.Read(int(r), buf)
}
// ReadPassword reads a line of input from a terminal without local echo. This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(fd int) ([]byte, error) {
var oldState syscall.Termios
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 {
return nil, err
}
newState := oldState
newState.Lflag &^= syscall.ECHO
newState.Lflag |= syscall.ICANON | syscall.ISIG
newState.Iflag |= syscall.ICRNL
if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
return nil, err
}
defer func() {
syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0)
}()
return readPasswordLine(passwordReader(fd))
}

12
vendor/golang.org/x/crypto/ssh/terminal/util_bsd.go generated vendored Normal file
View File

@ -0,0 +1,12 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd netbsd openbsd
package terminal
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TIOCGETA
const ioctlWriteTermios = unix.TIOCSETA

10
vendor/golang.org/x/crypto/ssh/terminal/util_linux.go generated vendored Normal file
View File

@ -0,0 +1,10 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package terminal
import "golang.org/x/sys/unix"
const ioctlReadTermios = unix.TCGETS
const ioctlWriteTermios = unix.TCSETS

58
vendor/golang.org/x/crypto/ssh/terminal/util_plan9.go generated vendored Normal file
View File

@ -0,0 +1,58 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package terminal provides support functions for dealing with terminals, as
// commonly found on UNIX systems.
//
// Putting a terminal into raw mode is the most common requirement:
//
// oldState, err := terminal.MakeRaw(0)
// if err != nil {
// panic(err)
// }
// defer terminal.Restore(0, oldState)
package terminal
import (
"fmt"
"runtime"
)
type State struct{}
// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
return false
}
// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd int) (*State, error) {
return nil, fmt.Errorf("terminal: MakeRaw not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
func GetState(fd int) (*State, error) {
return nil, fmt.Errorf("terminal: GetState not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, state *State) error {
return fmt.Errorf("terminal: Restore not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
// GetSize returns the dimensions of the given terminal.
func GetSize(fd int) (width, height int, err error) {
return 0, 0, fmt.Errorf("terminal: GetSize not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
// ReadPassword reads a line of input from a terminal without local echo. This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(fd int) ([]byte, error) {
return nil, fmt.Errorf("terminal: ReadPassword not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}

128
vendor/golang.org/x/crypto/ssh/terminal/util_solaris.go generated vendored Normal file
View File

@ -0,0 +1,128 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build solaris
package terminal // import "golang.org/x/crypto/ssh/terminal"
import (
"golang.org/x/sys/unix"
"io"
"syscall"
)
// State contains the state of a terminal.
type State struct {
state *unix.Termios
}
// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
_, err := unix.IoctlGetTermio(fd, unix.TCGETA)
return err == nil
}
// ReadPassword reads a line of input from a terminal without local echo. This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(fd int) ([]byte, error) {
// see also: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libast/common/uwin/getpass.c
val, err := unix.IoctlGetTermios(fd, unix.TCGETS)
if err != nil {
return nil, err
}
oldState := *val
newState := oldState
newState.Lflag &^= syscall.ECHO
newState.Lflag |= syscall.ICANON | syscall.ISIG
newState.Iflag |= syscall.ICRNL
err = unix.IoctlSetTermios(fd, unix.TCSETS, &newState)
if err != nil {
return nil, err
}
defer unix.IoctlSetTermios(fd, unix.TCSETS, &oldState)
var buf [16]byte
var ret []byte
for {
n, err := syscall.Read(fd, buf[:])
if err != nil {
return nil, err
}
if n == 0 {
if len(ret) == 0 {
return nil, io.EOF
}
break
}
if buf[n-1] == '\n' {
n--
}
ret = append(ret, buf[:n]...)
if n < len(buf) {
break
}
}
return ret, nil
}
// MakeRaw puts the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
// see http://cr.illumos.org/~webrev/andy_js/1060/
func MakeRaw(fd int) (*State, error) {
oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS)
if err != nil {
return nil, err
}
oldTermios := *oldTermiosPtr
newTermios := oldTermios
newTermios.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON
newTermios.Oflag &^= syscall.OPOST
newTermios.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN
newTermios.Cflag &^= syscall.CSIZE | syscall.PARENB
newTermios.Cflag |= syscall.CS8
newTermios.Cc[unix.VMIN] = 1
newTermios.Cc[unix.VTIME] = 0
if err := unix.IoctlSetTermios(fd, unix.TCSETS, &newTermios); err != nil {
return nil, err
}
return &State{
state: oldTermiosPtr,
}, nil
}
// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, oldState *State) error {
return unix.IoctlSetTermios(fd, unix.TCSETS, oldState.state)
}
// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
func GetState(fd int) (*State, error) {
oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS)
if err != nil {
return nil, err
}
return &State{
state: oldTermiosPtr,
}, nil
}
// GetSize returns the dimensions of the given terminal.
func GetSize(fd int) (width, height int, err error) {
ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
if err != nil {
return 0, 0, err
}
return int(ws.Col), int(ws.Row), nil
}

102
vendor/golang.org/x/crypto/ssh/terminal/util_windows.go generated vendored Normal file
View File

@ -0,0 +1,102 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
// Package terminal provides support functions for dealing with terminals, as
// commonly found on UNIX systems.
//
// Putting a terminal into raw mode is the most common requirement:
//
// oldState, err := terminal.MakeRaw(0)
// if err != nil {
// panic(err)
// }
// defer terminal.Restore(0, oldState)
package terminal
import (
"golang.org/x/sys/windows"
)
type State struct {
mode uint32
}
// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
var st uint32
err := windows.GetConsoleMode(windows.Handle(fd), &st)
return err == nil
}
// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd int) (*State, error) {
var st uint32
if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
return nil, err
}
raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil {
return nil, err
}
return &State{st}, nil
}
// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
func GetState(fd int) (*State, error) {
var st uint32
if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
return nil, err
}
return &State{st}, nil
}
// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, state *State) error {
return windows.SetConsoleMode(windows.Handle(fd), state.mode)
}
// GetSize returns the dimensions of the given terminal.
func GetSize(fd int) (width, height int, err error) {
var info windows.ConsoleScreenBufferInfo
if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil {
return 0, 0, err
}
return int(info.Size.X), int(info.Size.Y), nil
}
// passwordReader is an io.Reader that reads from a specific Windows HANDLE.
type passwordReader int
func (r passwordReader) Read(buf []byte) (int, error) {
return windows.Read(windows.Handle(r), buf)
}
// ReadPassword reads a line of input from a terminal without local echo. This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(fd int) ([]byte, error) {
var st uint32
if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
return nil, err
}
old := st
st &^= (windows.ENABLE_ECHO_INPUT)
st |= (windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
if err := windows.SetConsoleMode(windows.Handle(fd), st); err != nil {
return nil, err
}
defer func() {
windows.SetConsoleMode(windows.Handle(fd), old)
}()
return readPasswordLine(passwordReader(fd))
}

View File

@ -76,54 +76,54 @@ const (
// ExtLen returns the length of the packet.
ExtLen Extension = 1
// ExtProto returns the packet's L3 protocol type.
ExtProto = 0
ExtProto Extension = 0
// ExtType returns the packet's type (skb->pkt_type in the kernel)
//
// TODO: better documentation. How nice an API do we want to
// provide for these esoteric extensions?
ExtType = 4
ExtType Extension = 4
// ExtPayloadOffset returns the offset of the packet payload, or
// the first protocol header that the kernel does not know how to
// parse.
ExtPayloadOffset = 52
ExtPayloadOffset Extension = 52
// ExtInterfaceIndex returns the index of the interface on which
// the packet was received.
ExtInterfaceIndex = 8
ExtInterfaceIndex Extension = 8
// ExtNetlinkAttr returns the netlink attribute of type X at
// offset A.
ExtNetlinkAttr = 12
ExtNetlinkAttr Extension = 12
// ExtNetlinkAttrNested returns the nested netlink attribute of
// type X at offset A.
ExtNetlinkAttrNested = 16
ExtNetlinkAttrNested Extension = 16
// ExtMark returns the packet's mark value.
ExtMark = 20
ExtMark Extension = 20
// ExtQueue returns the packet's assigned hardware queue.
ExtQueue = 24
ExtQueue Extension = 24
// ExtLinkLayerType returns the packet's hardware address type
// (e.g. Ethernet, Infiniband).
ExtLinkLayerType = 28
ExtLinkLayerType Extension = 28
// ExtRXHash returns the packets receive hash.
//
// TODO: figure out what this rxhash actually is.
ExtRXHash = 32
ExtRXHash Extension = 32
// ExtCPUID returns the ID of the CPU processing the current
// packet.
ExtCPUID = 36
ExtCPUID Extension = 36
// ExtVLANTag returns the packet's VLAN tag.
ExtVLANTag = 44
ExtVLANTag Extension = 44
// ExtVLANTagPresent returns non-zero if the packet has a VLAN
// tag.
//
// TODO: I think this might be a lie: it reads bit 0x1000 of the
// VLAN header, which changed meaning in recent revisions of the
// spec - this extension may now return meaningless information.
ExtVLANTagPresent = 48
ExtVLANTagPresent Extension = 48
// ExtVLANProto returns 0x8100 if the frame has a VLAN header,
// 0x88a8 if the frame has a "Q-in-Q" double VLAN header, or some
// other value if no VLAN information is present.
ExtVLANProto = 60
ExtVLANProto Extension = 60
// ExtRand returns a uniformly random uint32.
ExtRand = 56
ExtRand Extension = 56
)
// The following gives names to various bit patterns used in opcode construction.

10
vendor/golang.org/x/net/bpf/setter.go generated vendored Normal file
View File

@ -0,0 +1,10 @@
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bpf
// A Setter is a type which can attach a compiled BPF filter to itself.
type Setter interface {
SetBPF(filter []RawInstruction) error
}

54
vendor/golang.org/x/net/context/context.go generated vendored Normal file
View File

@ -0,0 +1,54 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package context defines the Context type, which carries deadlines,
// cancelation signals, and other request-scoped values across API boundaries
// and between processes.
//
// Incoming requests to a server should create a Context, and outgoing calls to
// servers should accept a Context. The chain of function calls between must
// propagate the Context, optionally replacing it with a modified copy created
// using WithDeadline, WithTimeout, WithCancel, or WithValue.
//
// Programs that use Contexts should follow these rules to keep interfaces
// consistent across packages and enable static analysis tools to check context
// propagation:
//
// Do not store Contexts inside a struct type; instead, pass a Context
// explicitly to each function that needs it. The Context should be the first
// parameter, typically named ctx:
//
// func DoSomething(ctx context.Context, arg Arg) error {
// // ... use ctx ...
// }
//
// Do not pass a nil Context, even if a function permits it. Pass context.TODO
// if you are unsure about which Context to use.
//
// Use context Values only for request-scoped data that transits processes and
// APIs, not for passing optional parameters to functions.
//
// The same Context may be passed to functions running in different goroutines;
// Contexts are safe for simultaneous use by multiple goroutines.
//
// See http://blog.golang.org/context for example code for a server that uses
// Contexts.
package context // import "golang.org/x/net/context"
// Background returns a non-nil, empty Context. It is never canceled, has no
// values, and has no deadline. It is typically used by the main function,
// initialization, and tests, and as the top-level Context for incoming
// requests.
func Background() Context {
return background
}
// TODO returns a non-nil, empty Context. Code should use context.TODO when
// it's unclear which Context to use or it is not yet available (because the
// surrounding function has not yet been extended to accept a Context
// parameter). TODO is recognized by static analysis tools that determine
// whether Contexts are propagated correctly in a program.
func TODO() Context {
return todo
}

583
vendor/golang.org/x/net/context/context_test.go generated vendored Normal file
View File

@ -0,0 +1,583 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !go1.7
package context
import (
"fmt"
"math/rand"
"runtime"
"strings"
"sync"
"testing"
"time"
)
// otherContext is a Context that's not one of the types defined in context.go.
// This lets us test code paths that differ based on the underlying type of the
// Context.
type otherContext struct {
Context
}
func TestBackground(t *testing.T) {
c := Background()
if c == nil {
t.Fatalf("Background returned nil")
}
select {
case x := <-c.Done():
t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
default:
}
if got, want := fmt.Sprint(c), "context.Background"; got != want {
t.Errorf("Background().String() = %q want %q", got, want)
}
}
func TestTODO(t *testing.T) {
c := TODO()
if c == nil {
t.Fatalf("TODO returned nil")
}
select {
case x := <-c.Done():
t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
default:
}
if got, want := fmt.Sprint(c), "context.TODO"; got != want {
t.Errorf("TODO().String() = %q want %q", got, want)
}
}
func TestWithCancel(t *testing.T) {
c1, cancel := WithCancel(Background())
if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want {
t.Errorf("c1.String() = %q want %q", got, want)
}
o := otherContext{c1}
c2, _ := WithCancel(o)
contexts := []Context{c1, o, c2}
for i, c := range contexts {
if d := c.Done(); d == nil {
t.Errorf("c[%d].Done() == %v want non-nil", i, d)
}
if e := c.Err(); e != nil {
t.Errorf("c[%d].Err() == %v want nil", i, e)
}
select {
case x := <-c.Done():
t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
default:
}
}
cancel()
time.Sleep(100 * time.Millisecond) // let cancelation propagate
for i, c := range contexts {
select {
case <-c.Done():
default:
t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i)
}
if e := c.Err(); e != Canceled {
t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled)
}
}
}
func TestParentFinishesChild(t *testing.T) {
// Context tree:
// parent -> cancelChild
// parent -> valueChild -> timerChild
parent, cancel := WithCancel(Background())
cancelChild, stop := WithCancel(parent)
defer stop()
valueChild := WithValue(parent, "key", "value")
timerChild, stop := WithTimeout(valueChild, 10000*time.Hour)
defer stop()
select {
case x := <-parent.Done():
t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
case x := <-cancelChild.Done():
t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x)
case x := <-timerChild.Done():
t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x)
case x := <-valueChild.Done():
t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x)
default:
}
// The parent's children should contain the two cancelable children.
pc := parent.(*cancelCtx)
cc := cancelChild.(*cancelCtx)
tc := timerChild.(*timerCtx)
pc.mu.Lock()
if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] {
t.Errorf("bad linkage: pc.children = %v, want %v and %v",
pc.children, cc, tc)
}
pc.mu.Unlock()
if p, ok := parentCancelCtx(cc.Context); !ok || p != pc {
t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc)
}
if p, ok := parentCancelCtx(tc.Context); !ok || p != pc {
t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc)
}
cancel()
pc.mu.Lock()
if len(pc.children) != 0 {
t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children)
}
pc.mu.Unlock()
// parent and children should all be finished.
check := func(ctx Context, name string) {
select {
case <-ctx.Done():
default:
t.Errorf("<-%s.Done() blocked, but shouldn't have", name)
}
if e := ctx.Err(); e != Canceled {
t.Errorf("%s.Err() == %v want %v", name, e, Canceled)
}
}
check(parent, "parent")
check(cancelChild, "cancelChild")
check(valueChild, "valueChild")
check(timerChild, "timerChild")
// WithCancel should return a canceled context on a canceled parent.
precanceledChild := WithValue(parent, "key", "value")
select {
case <-precanceledChild.Done():
default:
t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have")
}
if e := precanceledChild.Err(); e != Canceled {
t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled)
}
}
func TestChildFinishesFirst(t *testing.T) {
cancelable, stop := WithCancel(Background())
defer stop()
for _, parent := range []Context{Background(), cancelable} {
child, cancel := WithCancel(parent)
select {
case x := <-parent.Done():
t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
case x := <-child.Done():
t.Errorf("<-child.Done() == %v want nothing (it should block)", x)
default:
}
cc := child.(*cancelCtx)
pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background()
if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) {
t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok)
}
if pcok {
pc.mu.Lock()
if len(pc.children) != 1 || !pc.children[cc] {
t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc)
}
pc.mu.Unlock()
}
cancel()
if pcok {
pc.mu.Lock()
if len(pc.children) != 0 {
t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children)
}
pc.mu.Unlock()
}
// child should be finished.
select {
case <-child.Done():
default:
t.Errorf("<-child.Done() blocked, but shouldn't have")
}
if e := child.Err(); e != Canceled {
t.Errorf("child.Err() == %v want %v", e, Canceled)
}
// parent should not be finished.
select {
case x := <-parent.Done():
t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
default:
}
if e := parent.Err(); e != nil {
t.Errorf("parent.Err() == %v want nil", e)
}
}
}
func testDeadline(c Context, wait time.Duration, t *testing.T) {
select {
case <-time.After(wait):
t.Fatalf("context should have timed out")
case <-c.Done():
}
if e := c.Err(); e != DeadlineExceeded {
t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded)
}
}
func TestDeadline(t *testing.T) {
t.Parallel()
const timeUnit = 500 * time.Millisecond
c, _ := WithDeadline(Background(), time.Now().Add(1*timeUnit))
if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
t.Errorf("c.String() = %q want prefix %q", got, prefix)
}
testDeadline(c, 2*timeUnit, t)
c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit))
o := otherContext{c}
testDeadline(o, 2*timeUnit, t)
c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit))
o = otherContext{c}
c, _ = WithDeadline(o, time.Now().Add(3*timeUnit))
testDeadline(c, 2*timeUnit, t)
}
func TestTimeout(t *testing.T) {
t.Parallel()
const timeUnit = 500 * time.Millisecond
c, _ := WithTimeout(Background(), 1*timeUnit)
if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
t.Errorf("c.String() = %q want prefix %q", got, prefix)
}
testDeadline(c, 2*timeUnit, t)
c, _ = WithTimeout(Background(), 1*timeUnit)
o := otherContext{c}
testDeadline(o, 2*timeUnit, t)
c, _ = WithTimeout(Background(), 1*timeUnit)
o = otherContext{c}
c, _ = WithTimeout(o, 3*timeUnit)
testDeadline(c, 2*timeUnit, t)
}
func TestCanceledTimeout(t *testing.T) {
t.Parallel()
const timeUnit = 500 * time.Millisecond
c, _ := WithTimeout(Background(), 2*timeUnit)
o := otherContext{c}
c, cancel := WithTimeout(o, 4*timeUnit)
cancel()
time.Sleep(1 * timeUnit) // let cancelation propagate
select {
case <-c.Done():
default:
t.Errorf("<-c.Done() blocked, but shouldn't have")
}
if e := c.Err(); e != Canceled {
t.Errorf("c.Err() == %v want %v", e, Canceled)
}
}
type key1 int
type key2 int
var k1 = key1(1)
var k2 = key2(1) // same int as k1, different type
var k3 = key2(3) // same type as k2, different int
func TestValues(t *testing.T) {
check := func(c Context, nm, v1, v2, v3 string) {
if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 {
t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0)
}
if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 {
t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0)
}
if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 {
t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0)
}
}
c0 := Background()
check(c0, "c0", "", "", "")
c1 := WithValue(Background(), k1, "c1k1")
check(c1, "c1", "c1k1", "", "")
if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want {
t.Errorf("c.String() = %q want %q", got, want)
}
c2 := WithValue(c1, k2, "c2k2")
check(c2, "c2", "c1k1", "c2k2", "")
c3 := WithValue(c2, k3, "c3k3")
check(c3, "c2", "c1k1", "c2k2", "c3k3")
c4 := WithValue(c3, k1, nil)
check(c4, "c4", "", "c2k2", "c3k3")
o0 := otherContext{Background()}
check(o0, "o0", "", "", "")
o1 := otherContext{WithValue(Background(), k1, "c1k1")}
check(o1, "o1", "c1k1", "", "")
o2 := WithValue(o1, k2, "o2k2")
check(o2, "o2", "c1k1", "o2k2", "")
o3 := otherContext{c4}
check(o3, "o3", "", "c2k2", "c3k3")
o4 := WithValue(o3, k3, nil)
check(o4, "o4", "", "c2k2", "")
}
func TestAllocs(t *testing.T) {
bg := Background()
for _, test := range []struct {
desc string
f func()
limit float64
gccgoLimit float64
}{
{
desc: "Background()",
f: func() { Background() },
limit: 0,
gccgoLimit: 0,
},
{
desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1),
f: func() {
c := WithValue(bg, k1, nil)
c.Value(k1)
},
limit: 3,
gccgoLimit: 3,
},
{
desc: "WithTimeout(bg, 15*time.Millisecond)",
f: func() {
c, _ := WithTimeout(bg, 15*time.Millisecond)
<-c.Done()
},
limit: 8,
gccgoLimit: 16,
},
{
desc: "WithCancel(bg)",
f: func() {
c, cancel := WithCancel(bg)
cancel()
<-c.Done()
},
limit: 5,
gccgoLimit: 8,
},
{
desc: "WithTimeout(bg, 100*time.Millisecond)",
f: func() {
c, cancel := WithTimeout(bg, 100*time.Millisecond)
cancel()
<-c.Done()
},
limit: 8,
gccgoLimit: 25,
},
} {
limit := test.limit
if runtime.Compiler == "gccgo" {
// gccgo does not yet do escape analysis.
// TODO(iant): Remove this when gccgo does do escape analysis.
limit = test.gccgoLimit
}
if n := testing.AllocsPerRun(100, test.f); n > limit {
t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit))
}
}
}
func TestSimultaneousCancels(t *testing.T) {
root, cancel := WithCancel(Background())
m := map[Context]CancelFunc{root: cancel}
q := []Context{root}
// Create a tree of contexts.
for len(q) != 0 && len(m) < 100 {
parent := q[0]
q = q[1:]
for i := 0; i < 4; i++ {
ctx, cancel := WithCancel(parent)
m[ctx] = cancel
q = append(q, ctx)
}
}
// Start all the cancels in a random order.
var wg sync.WaitGroup
wg.Add(len(m))
for _, cancel := range m {
go func(cancel CancelFunc) {
cancel()
wg.Done()
}(cancel)
}
// Wait on all the contexts in a random order.
for ctx := range m {
select {
case <-ctx.Done():
case <-time.After(1 * time.Second):
buf := make([]byte, 10<<10)
n := runtime.Stack(buf, true)
t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n])
}
}
// Wait for all the cancel functions to return.
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(1 * time.Second):
buf := make([]byte, 10<<10)
n := runtime.Stack(buf, true)
t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n])
}
}
func TestInterlockedCancels(t *testing.T) {
parent, cancelParent := WithCancel(Background())
child, cancelChild := WithCancel(parent)
go func() {
parent.Done()
cancelChild()
}()
cancelParent()
select {
case <-child.Done():
case <-time.After(1 * time.Second):
buf := make([]byte, 10<<10)
n := runtime.Stack(buf, true)
t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n])
}
}
func TestLayersCancel(t *testing.T) {
testLayers(t, time.Now().UnixNano(), false)
}
func TestLayersTimeout(t *testing.T) {
testLayers(t, time.Now().UnixNano(), true)
}
func testLayers(t *testing.T, seed int64, testTimeout bool) {
rand.Seed(seed)
errorf := func(format string, a ...interface{}) {
t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...)
}
const (
timeout = 200 * time.Millisecond
minLayers = 30
)
type value int
var (
vals []*value
cancels []CancelFunc
numTimers int
ctx = Background()
)
for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ {
switch rand.Intn(3) {
case 0:
v := new(value)
ctx = WithValue(ctx, v, v)
vals = append(vals, v)
case 1:
var cancel CancelFunc
ctx, cancel = WithCancel(ctx)
cancels = append(cancels, cancel)
case 2:
var cancel CancelFunc
ctx, cancel = WithTimeout(ctx, timeout)
cancels = append(cancels, cancel)
numTimers++
}
}
checkValues := func(when string) {
for _, key := range vals {
if val := ctx.Value(key).(*value); key != val {
errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key)
}
}
}
select {
case <-ctx.Done():
errorf("ctx should not be canceled yet")
default:
}
if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) {
t.Errorf("ctx.String() = %q want prefix %q", s, prefix)
}
t.Log(ctx)
checkValues("before cancel")
if testTimeout {
select {
case <-ctx.Done():
case <-time.After(timeout + 100*time.Millisecond):
errorf("ctx should have timed out")
}
checkValues("after timeout")
} else {
cancel := cancels[rand.Intn(len(cancels))]
cancel()
select {
case <-ctx.Done():
default:
errorf("ctx should be canceled")
}
checkValues("after cancel")
}
}
func TestCancelRemoves(t *testing.T) {
checkChildren := func(when string, ctx Context, want int) {
if got := len(ctx.(*cancelCtx).children); got != want {
t.Errorf("%s: context has %d children, want %d", when, got, want)
}
}
ctx, _ := WithCancel(Background())
checkChildren("after creation", ctx, 0)
_, cancel := WithCancel(ctx)
checkChildren("with WithCancel child ", ctx, 1)
cancel()
checkChildren("after cancelling WithCancel child", ctx, 0)
ctx, _ = WithCancel(Background())
checkChildren("after creation", ctx, 0)
_, cancel = WithTimeout(ctx, 60*time.Minute)
checkChildren("with WithTimeout child ", ctx, 1)
cancel()
checkChildren("after cancelling WithTimeout child", ctx, 0)
}

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