repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
micro/go-plugins
client/grpc/grpc.go
secure
func (g *grpcClient) secure() grpc.DialOption { if g.opts.Context != nil { if v := g.opts.Context.Value(tlsAuth{}); v != nil { tls := v.(*tls.Config) creds := credentials.NewTLS(tls) return grpc.WithTransportCredentials(creds) } } return grpc.WithInsecure() }
go
func (g *grpcClient) secure() grpc.DialOption { if g.opts.Context != nil { if v := g.opts.Context.Value(tlsAuth{}); v != nil { tls := v.(*tls.Config) creds := credentials.NewTLS(tls) return grpc.WithTransportCredentials(creds) } } return grpc.WithInsecure() }
[ "func", "(", "g", "*", "grpcClient", ")", "secure", "(", ")", "grpc", ".", "DialOption", "{", "if", "g", ".", "opts", ".", "Context", "!=", "nil", "{", "if", "v", ":=", "g", ".", "opts", ".", "Context", ".", "Value", "(", "tlsAuth", "{", "}", ")", ";", "v", "!=", "nil", "{", "tls", ":=", "v", ".", "(", "*", "tls", ".", "Config", ")", "\n", "creds", ":=", "credentials", ".", "NewTLS", "(", "tls", ")", "\n", "return", "grpc", ".", "WithTransportCredentials", "(", "creds", ")", "\n", "}", "\n", "}", "\n", "return", "grpc", ".", "WithInsecure", "(", ")", "\n", "}" ]
// secure returns the dial option for whether its a secure or insecure connection
[ "secure", "returns", "the", "dial", "option", "for", "whether", "its", "a", "secure", "or", "insecure", "connection" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/client/grpc/grpc.go#L42-L51
train
micro/go-plugins
wrapper/trace/awsxray/awsxray.go
NewCallWrapper
func NewCallWrapper(opts ...Option) client.CallWrapper { options := Options{ Name: "go.micro.client.CallFunc", Daemon: "localhost:2000", } for _, o := range opts { o(&options) } x := newXRay(options) return func(cf client.CallFunc) client.CallFunc { return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { var err error s := getSegment(options.Name, ctx) defer func() { setCallStatus(s, node.Address, req.Endpoint(), err) go record(x, s) }() ctx = newContext(ctx, s) err = cf(ctx, node, req, rsp, opts) return err } } }
go
func NewCallWrapper(opts ...Option) client.CallWrapper { options := Options{ Name: "go.micro.client.CallFunc", Daemon: "localhost:2000", } for _, o := range opts { o(&options) } x := newXRay(options) return func(cf client.CallFunc) client.CallFunc { return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { var err error s := getSegment(options.Name, ctx) defer func() { setCallStatus(s, node.Address, req.Endpoint(), err) go record(x, s) }() ctx = newContext(ctx, s) err = cf(ctx, node, req, rsp, opts) return err } } }
[ "func", "NewCallWrapper", "(", "opts", "...", "Option", ")", "client", ".", "CallWrapper", "{", "options", ":=", "Options", "{", "Name", ":", "\"", "\"", ",", "Daemon", ":", "\"", "\"", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "x", ":=", "newXRay", "(", "options", ")", "\n\n", "return", "func", "(", "cf", "client", ".", "CallFunc", ")", "client", ".", "CallFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "node", "*", "registry", ".", "Node", ",", "req", "client", ".", "Request", ",", "rsp", "interface", "{", "}", ",", "opts", "client", ".", "CallOptions", ")", "error", "{", "var", "err", "error", "\n", "s", ":=", "getSegment", "(", "options", ".", "Name", ",", "ctx", ")", "\n\n", "defer", "func", "(", ")", "{", "setCallStatus", "(", "s", ",", "node", ".", "Address", ",", "req", ".", "Endpoint", "(", ")", ",", "err", ")", "\n", "go", "record", "(", "x", ",", "s", ")", "\n", "}", "(", ")", "\n\n", "ctx", "=", "newContext", "(", "ctx", ",", "s", ")", "\n", "err", "=", "cf", "(", "ctx", ",", "node", ",", "req", ",", "rsp", ",", "opts", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// NewCallWrapper accepts Options and returns a Trace Call Wrapper for individual node calls made by the client
[ "NewCallWrapper", "accepts", "Options", "and", "returns", "a", "Trace", "Call", "Wrapper", "for", "individual", "node", "calls", "made", "by", "the", "client" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/awsxray/awsxray.go#L33-L60
train
micro/go-plugins
wrapper/trace/awsxray/awsxray.go
NewClientWrapper
func NewClientWrapper(opts ...Option) client.Wrapper { options := Options{ Name: "go.micro.client.Call", Daemon: "localhost:2000", } for _, o := range opts { o(&options) } return func(c client.Client) client.Client { return &xrayWrapper{options, newXRay(options), c} } }
go
func NewClientWrapper(opts ...Option) client.Wrapper { options := Options{ Name: "go.micro.client.Call", Daemon: "localhost:2000", } for _, o := range opts { o(&options) } return func(c client.Client) client.Client { return &xrayWrapper{options, newXRay(options), c} } }
[ "func", "NewClientWrapper", "(", "opts", "...", "Option", ")", "client", ".", "Wrapper", "{", "options", ":=", "Options", "{", "Name", ":", "\"", "\"", ",", "Daemon", ":", "\"", "\"", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "xrayWrapper", "{", "options", ",", "newXRay", "(", "options", ")", ",", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper accepts Options and returns a Trace Client Wrapper which tracks high level service calls
[ "NewClientWrapper", "accepts", "Options", "and", "returns", "a", "Trace", "Client", "Wrapper", "which", "tracks", "high", "level", "service", "calls" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/awsxray/awsxray.go#L63-L76
train
micro/go-plugins
wrapper/trace/awsxray/awsxray.go
NewHandlerWrapper
func NewHandlerWrapper(opts ...Option) server.HandlerWrapper { options := Options{ Daemon: "localhost:2000", } for _, o := range opts { o(&options) } x := newXRay(options) return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { name := options.Name if len(name) == 0 { // default name name = req.Service() + "." + req.Endpoint() } var err error s := getSegment(name, ctx) defer func() { setCallStatus(s, req.Service(), req.Endpoint(), err) go record(x, s) }() ctx = newContext(ctx, s) err = h(ctx, req, rsp) return err } } }
go
func NewHandlerWrapper(opts ...Option) server.HandlerWrapper { options := Options{ Daemon: "localhost:2000", } for _, o := range opts { o(&options) } x := newXRay(options) return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { name := options.Name if len(name) == 0 { // default name name = req.Service() + "." + req.Endpoint() } var err error s := getSegment(name, ctx) defer func() { setCallStatus(s, req.Service(), req.Endpoint(), err) go record(x, s) }() ctx = newContext(ctx, s) err = h(ctx, req, rsp) return err } } }
[ "func", "NewHandlerWrapper", "(", "opts", "...", "Option", ")", "server", ".", "HandlerWrapper", "{", "options", ":=", "Options", "{", "Daemon", ":", "\"", "\"", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "x", ":=", "newXRay", "(", "options", ")", "\n\n", "return", "func", "(", "h", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "error", "{", "name", ":=", "options", ".", "Name", "\n", "if", "len", "(", "name", ")", "==", "0", "{", "// default name", "name", "=", "req", ".", "Service", "(", ")", "+", "\"", "\"", "+", "req", ".", "Endpoint", "(", ")", "\n", "}", "\n\n", "var", "err", "error", "\n", "s", ":=", "getSegment", "(", "name", ",", "ctx", ")", "\n\n", "defer", "func", "(", ")", "{", "setCallStatus", "(", "s", ",", "req", ".", "Service", "(", ")", ",", "req", ".", "Endpoint", "(", ")", ",", "err", ")", "\n", "go", "record", "(", "x", ",", "s", ")", "\n", "}", "(", ")", "\n\n", "ctx", "=", "newContext", "(", "ctx", ",", "s", ")", "\n", "err", "=", "h", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper accepts Options and returns a Trace Handler Wrapper
[ "NewHandlerWrapper", "accepts", "Options", "and", "returns", "a", "Trace", "Handler", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/awsxray/awsxray.go#L79-L111
train
micro/go-plugins
selector/label/options.go
Label
func Label(k, v string) selector.Option { return func(o *selector.Options) { l, ok := o.Context.Value(labelKey{}).([]label) if !ok { l = []label{} } l = append(l, label{k, v}) o.Context = context.WithValue(o.Context, labelKey{}, l) } }
go
func Label(k, v string) selector.Option { return func(o *selector.Options) { l, ok := o.Context.Value(labelKey{}).([]label) if !ok { l = []label{} } l = append(l, label{k, v}) o.Context = context.WithValue(o.Context, labelKey{}, l) } }
[ "func", "Label", "(", "k", ",", "v", "string", ")", "selector", ".", "Option", "{", "return", "func", "(", "o", "*", "selector", ".", "Options", ")", "{", "l", ",", "ok", ":=", "o", ".", "Context", ".", "Value", "(", "labelKey", "{", "}", ")", ".", "(", "[", "]", "label", ")", "\n", "if", "!", "ok", "{", "l", "=", "[", "]", "label", "{", "}", "\n", "}", "\n", "l", "=", "append", "(", "l", ",", "label", "{", "k", ",", "v", "}", ")", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "labelKey", "{", "}", ",", "l", ")", "\n", "}", "\n", "}" ]
// Label used in the priority label list
[ "Label", "used", "in", "the", "priority", "label", "list" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/selector/label/options.go#L17-L26
train
micro/go-plugins
broker/stomp/options.go
Auth
func Auth(username string, password string) broker.Option { return setBrokerOption(authKey{}, &authRecord{ username: username, password: password, }) }
go
func Auth(username string, password string) broker.Option { return setBrokerOption(authKey{}, &authRecord{ username: username, password: password, }) }
[ "func", "Auth", "(", "username", "string", ",", "password", "string", ")", "broker", ".", "Option", "{", "return", "setBrokerOption", "(", "authKey", "{", "}", ",", "&", "authRecord", "{", "username", ":", "username", ",", "password", ":", "password", ",", "}", ")", "\n", "}" ]
// Auth sets the authentication information
[ "Auth", "sets", "the", "authentication", "information" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/stomp/options.go#L50-L55
train
micro/go-plugins
micro/index/index.go
WithResponse
func WithResponse(status int, header http.Header, body []byte) plugin.Plugin { return &index{ r: &response{ status: status, header: header, body: body, }, } }
go
func WithResponse(status int, header http.Header, body []byte) plugin.Plugin { return &index{ r: &response{ status: status, header: header, body: body, }, } }
[ "func", "WithResponse", "(", "status", "int", ",", "header", "http", ".", "Header", ",", "body", "[", "]", "byte", ")", "plugin", ".", "Plugin", "{", "return", "&", "index", "{", "r", ":", "&", "response", "{", "status", ":", "status", ",", "header", ":", "header", ",", "body", ":", "body", ",", "}", ",", "}", "\n", "}" ]
// WithContent will write the given status, header and body
[ "WithContent", "will", "write", "the", "given", "status", "header", "and", "body" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/index/index.go#L139-L147
train
micro/go-plugins
broker/sqs/sqs.go
run
func (s *subscriber) run(hdlr broker.Handler) { log.Log(fmt.Sprintf("SQS subscription started. Queue:%s, URL: %s", s.queueName, s.URL)) for { select { case <-s.exit: return default: result, err := s.svc.ReceiveMessage(&sqs.ReceiveMessageInput{ QueueUrl: &s.URL, MaxNumberOfMessages: s.getMaxMessages(), VisibilityTimeout: s.getVisibilityTimeout(), WaitTimeSeconds: s.getWaitSeconds(), AttributeNames: aws.StringSlice([]string{ "SentTimestamp", // TODO: not currently exposing this to plugin users }), MessageAttributeNames: aws.StringSlice([]string{ "All", }), }) if err != nil { time.Sleep(time.Second) log.Log(fmt.Sprintf("Error receiving SQS message: %s", err.Error())) continue } if len(result.Messages) == 0 { time.Sleep(time.Second) continue } for _, sm := range result.Messages { s.handleMessage(sm, hdlr) } } } }
go
func (s *subscriber) run(hdlr broker.Handler) { log.Log(fmt.Sprintf("SQS subscription started. Queue:%s, URL: %s", s.queueName, s.URL)) for { select { case <-s.exit: return default: result, err := s.svc.ReceiveMessage(&sqs.ReceiveMessageInput{ QueueUrl: &s.URL, MaxNumberOfMessages: s.getMaxMessages(), VisibilityTimeout: s.getVisibilityTimeout(), WaitTimeSeconds: s.getWaitSeconds(), AttributeNames: aws.StringSlice([]string{ "SentTimestamp", // TODO: not currently exposing this to plugin users }), MessageAttributeNames: aws.StringSlice([]string{ "All", }), }) if err != nil { time.Sleep(time.Second) log.Log(fmt.Sprintf("Error receiving SQS message: %s", err.Error())) continue } if len(result.Messages) == 0 { time.Sleep(time.Second) continue } for _, sm := range result.Messages { s.handleMessage(sm, hdlr) } } } }
[ "func", "(", "s", "*", "subscriber", ")", "run", "(", "hdlr", "broker", ".", "Handler", ")", "{", "log", ".", "Log", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "queueName", ",", "s", ".", "URL", ")", ")", "\n", "for", "{", "select", "{", "case", "<-", "s", ".", "exit", ":", "return", "\n", "default", ":", "result", ",", "err", ":=", "s", ".", "svc", ".", "ReceiveMessage", "(", "&", "sqs", ".", "ReceiveMessageInput", "{", "QueueUrl", ":", "&", "s", ".", "URL", ",", "MaxNumberOfMessages", ":", "s", ".", "getMaxMessages", "(", ")", ",", "VisibilityTimeout", ":", "s", ".", "getVisibilityTimeout", "(", ")", ",", "WaitTimeSeconds", ":", "s", ".", "getWaitSeconds", "(", ")", ",", "AttributeNames", ":", "aws", ".", "StringSlice", "(", "[", "]", "string", "{", "\"", "\"", ",", "// TODO: not currently exposing this to plugin users", "}", ")", ",", "MessageAttributeNames", ":", "aws", ".", "StringSlice", "(", "[", "]", "string", "{", "\"", "\"", ",", "}", ")", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "log", ".", "Log", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "continue", "\n", "}", "\n\n", "if", "len", "(", "result", ".", "Messages", ")", "==", "0", "{", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "continue", "\n", "}", "\n\n", "for", "_", ",", "sm", ":=", "range", "result", ".", "Messages", "{", "s", ".", "handleMessage", "(", "sm", ",", "hdlr", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// run is designed to run as a goroutine and poll SQS for new messages. Note that it's possible to receive // more than one message from a single poll depending on the options configured for the plugin
[ "run", "is", "designed", "to", "run", "as", "a", "goroutine", "and", "poll", "SQS", "for", "new", "messages", ".", "Note", "that", "it", "s", "possible", "to", "receive", "more", "than", "one", "message", "from", "a", "single", "poll", "depending", "on", "the", "options", "configured", "for", "the", "plugin" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/sqs.go#L54-L90
train
micro/go-plugins
broker/sqs/sqs.go
Init
func (b *sqsBroker) Init(opts ...broker.Option) error { for _, o := range opts { o(&b.options) } return nil }
go
func (b *sqsBroker) Init(opts ...broker.Option) error { for _, o := range opts { o(&b.options) } return nil }
[ "func", "(", "b", "*", "sqsBroker", ")", "Init", "(", "opts", "...", "broker", ".", "Option", ")", "error", "{", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "b", ".", "options", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Init initializes a broker and configures an AWS session and SQS struct
[ "Init", "initializes", "a", "broker", "and", "configures", "an", "AWS", "session", "and", "SQS", "struct" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/sqs.go#L206-L212
train
micro/go-plugins
broker/sqs/sqs.go
Publish
func (b *sqsBroker) Publish(queueName string, msg *broker.Message, opts ...broker.PublishOption) error { queueURL, err := b.urlFromQueueName(queueName) if err != nil { return err } input := &sqs.SendMessageInput{ MessageBody: aws.String(string(msg.Body[:])), QueueUrl: &queueURL, } input.MessageAttributes = copyMessageHeader(msg) input.MessageDeduplicationId = b.generateDedupID(msg) input.MessageGroupId = b.generateGroupID(msg) log.Log(fmt.Sprintf("Publishing SQS message, %d bytes", len(msg.Body))) _, err = b.svc.SendMessage(input) if err != nil { return err } // Broker interfaces don't let us do anything with message ID or sequence number return nil }
go
func (b *sqsBroker) Publish(queueName string, msg *broker.Message, opts ...broker.PublishOption) error { queueURL, err := b.urlFromQueueName(queueName) if err != nil { return err } input := &sqs.SendMessageInput{ MessageBody: aws.String(string(msg.Body[:])), QueueUrl: &queueURL, } input.MessageAttributes = copyMessageHeader(msg) input.MessageDeduplicationId = b.generateDedupID(msg) input.MessageGroupId = b.generateGroupID(msg) log.Log(fmt.Sprintf("Publishing SQS message, %d bytes", len(msg.Body))) _, err = b.svc.SendMessage(input) if err != nil { return err } // Broker interfaces don't let us do anything with message ID or sequence number return nil }
[ "func", "(", "b", "*", "sqsBroker", ")", "Publish", "(", "queueName", "string", ",", "msg", "*", "broker", ".", "Message", ",", "opts", "...", "broker", ".", "PublishOption", ")", "error", "{", "queueURL", ",", "err", ":=", "b", ".", "urlFromQueueName", "(", "queueName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "input", ":=", "&", "sqs", ".", "SendMessageInput", "{", "MessageBody", ":", "aws", ".", "String", "(", "string", "(", "msg", ".", "Body", "[", ":", "]", ")", ")", ",", "QueueUrl", ":", "&", "queueURL", ",", "}", "\n", "input", ".", "MessageAttributes", "=", "copyMessageHeader", "(", "msg", ")", "\n", "input", ".", "MessageDeduplicationId", "=", "b", ".", "generateDedupID", "(", "msg", ")", "\n", "input", ".", "MessageGroupId", "=", "b", ".", "generateGroupID", "(", "msg", ")", "\n\n", "log", ".", "Log", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "msg", ".", "Body", ")", ")", ")", "\n", "_", ",", "err", "=", "b", ".", "svc", ".", "SendMessage", "(", "input", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Broker interfaces don't let us do anything with message ID or sequence number", "return", "nil", "\n", "}" ]
// Publish publishes a message via SQS
[ "Publish", "publishes", "a", "message", "via", "SQS" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/sqs.go#L215-L238
train
micro/go-plugins
broker/sqs/sqs.go
Subscribe
func (b *sqsBroker) Subscribe(queueName string, h broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { queueURL, err := b.urlFromQueueName(queueName) if err != nil { return nil, err } options := broker.SubscribeOptions{ AutoAck: true, Queue: queueName, Context: context.Background(), } for _, o := range opts { o(&options) } subscriber := &subscriber{ options: options, URL: queueURL, queueName: queueName, svc: b.svc, exit: make(chan bool), } go subscriber.run(h) return subscriber, nil }
go
func (b *sqsBroker) Subscribe(queueName string, h broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { queueURL, err := b.urlFromQueueName(queueName) if err != nil { return nil, err } options := broker.SubscribeOptions{ AutoAck: true, Queue: queueName, Context: context.Background(), } for _, o := range opts { o(&options) } subscriber := &subscriber{ options: options, URL: queueURL, queueName: queueName, svc: b.svc, exit: make(chan bool), } go subscriber.run(h) return subscriber, nil }
[ "func", "(", "b", "*", "sqsBroker", ")", "Subscribe", "(", "queueName", "string", ",", "h", "broker", ".", "Handler", ",", "opts", "...", "broker", ".", "SubscribeOption", ")", "(", "broker", ".", "Subscriber", ",", "error", ")", "{", "queueURL", ",", "err", ":=", "b", ".", "urlFromQueueName", "(", "queueName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "options", ":=", "broker", ".", "SubscribeOptions", "{", "AutoAck", ":", "true", ",", "Queue", ":", "queueName", ",", "Context", ":", "context", ".", "Background", "(", ")", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "subscriber", ":=", "&", "subscriber", "{", "options", ":", "options", ",", "URL", ":", "queueURL", ",", "queueName", ":", "queueName", ",", "svc", ":", "b", ".", "svc", ",", "exit", ":", "make", "(", "chan", "bool", ")", ",", "}", "\n", "go", "subscriber", ".", "run", "(", "h", ")", "\n\n", "return", "subscriber", ",", "nil", "\n", "}" ]
// Subscribe subscribes to an SQS queue, starting a goroutine to poll for messages
[ "Subscribe", "subscribes", "to", "an", "SQS", "queue", "starting", "a", "goroutine", "to", "poll", "for", "messages" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/sqs.go#L241-L267
train
micro/go-plugins
broker/sqs/sqs.go
NewBroker
func NewBroker(opts ...broker.Option) broker.Broker { options := broker.Options{ Context: context.Background(), } for _, o := range opts { o(&options) } return &sqsBroker{ options: options, } }
go
func NewBroker(opts ...broker.Option) broker.Broker { options := broker.Options{ Context: context.Background(), } for _, o := range opts { o(&options) } return &sqsBroker{ options: options, } }
[ "func", "NewBroker", "(", "opts", "...", "broker", ".", "Option", ")", "broker", ".", "Broker", "{", "options", ":=", "broker", ".", "Options", "{", "Context", ":", "context", ".", "Background", "(", ")", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "return", "&", "sqsBroker", "{", "options", ":", "options", ",", "}", "\n", "}" ]
// NewBroker creates a new broker with options
[ "NewBroker", "creates", "a", "new", "broker", "with", "options" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/sqs.go#L335-L347
train
micro/go-plugins
broker/grpc/grpc.go
Publish
func (h *grpcHandler) Publish(ctx context.Context, msg *proto.Message) (*proto.Empty, error) { if len(msg.Topic) == 0 { return nil, merr.InternalServerError("go.micro.broker", "Topic not found") } m := &broker.Message{ Header: msg.Header, Body: msg.Body, } p := &grpcPublication{m: m, t: msg.Topic} h.g.RLock() for _, subscriber := range h.g.subscribers[msg.Topic] { if msg.Id == subscriber.id { // sub is sync; crufty rate limiting // so we don't hose the cpu subscriber.fn(p) } } h.g.RUnlock() return new(proto.Empty), nil }
go
func (h *grpcHandler) Publish(ctx context.Context, msg *proto.Message) (*proto.Empty, error) { if len(msg.Topic) == 0 { return nil, merr.InternalServerError("go.micro.broker", "Topic not found") } m := &broker.Message{ Header: msg.Header, Body: msg.Body, } p := &grpcPublication{m: m, t: msg.Topic} h.g.RLock() for _, subscriber := range h.g.subscribers[msg.Topic] { if msg.Id == subscriber.id { // sub is sync; crufty rate limiting // so we don't hose the cpu subscriber.fn(p) } } h.g.RUnlock() return new(proto.Empty), nil }
[ "func", "(", "h", "*", "grpcHandler", ")", "Publish", "(", "ctx", "context", ".", "Context", ",", "msg", "*", "proto", ".", "Message", ")", "(", "*", "proto", ".", "Empty", ",", "error", ")", "{", "if", "len", "(", "msg", ".", "Topic", ")", "==", "0", "{", "return", "nil", ",", "merr", ".", "InternalServerError", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "m", ":=", "&", "broker", ".", "Message", "{", "Header", ":", "msg", ".", "Header", ",", "Body", ":", "msg", ".", "Body", ",", "}", "\n\n", "p", ":=", "&", "grpcPublication", "{", "m", ":", "m", ",", "t", ":", "msg", ".", "Topic", "}", "\n\n", "h", ".", "g", ".", "RLock", "(", ")", "\n", "for", "_", ",", "subscriber", ":=", "range", "h", ".", "g", ".", "subscribers", "[", "msg", ".", "Topic", "]", "{", "if", "msg", ".", "Id", "==", "subscriber", ".", "id", "{", "// sub is sync; crufty rate limiting", "// so we don't hose the cpu", "subscriber", ".", "fn", "(", "p", ")", "\n", "}", "\n", "}", "\n", "h", ".", "g", ".", "RUnlock", "(", ")", "\n", "return", "new", "(", "proto", ".", "Empty", ")", ",", "nil", "\n", "}" ]
// The grpc handler
[ "The", "grpc", "handler" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/grpc/grpc.go#L148-L170
train
micro/go-plugins
registry/kubernetes/client/api/request.go
verb
func (r *Request) verb(method string) *Request { r.method = method return r }
go
func (r *Request) verb(method string) *Request { r.method = method return r }
[ "func", "(", "r", "*", "Request", ")", "verb", "(", "method", "string", ")", "*", "Request", "{", "r", ".", "method", "=", "method", "\n", "return", "r", "\n", "}" ]
// verb sets method
[ "verb", "sets", "method" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L38-L41
train
micro/go-plugins
registry/kubernetes/client/api/request.go
Namespace
func (r *Request) Namespace(s string) *Request { r.namespace = s return r }
go
func (r *Request) Namespace(s string) *Request { r.namespace = s return r }
[ "func", "(", "r", "*", "Request", ")", "Namespace", "(", "s", "string", ")", "*", "Request", "{", "r", ".", "namespace", "=", "s", "\n", "return", "r", "\n", "}" ]
// Namespace is to set the namespace to operate on
[ "Namespace", "is", "to", "set", "the", "namespace", "to", "operate", "on" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L70-L73
train
micro/go-plugins
registry/kubernetes/client/api/request.go
Resource
func (r *Request) Resource(s string) *Request { r.resource = s return r }
go
func (r *Request) Resource(s string) *Request { r.resource = s return r }
[ "func", "(", "r", "*", "Request", ")", "Resource", "(", "s", "string", ")", "*", "Request", "{", "r", ".", "resource", "=", "s", "\n", "return", "r", "\n", "}" ]
// Resource is the type of resource the operation is // for, such as "services", "endpoints" or "pods"
[ "Resource", "is", "the", "type", "of", "resource", "the", "operation", "is", "for", "such", "as", "services", "endpoints", "or", "pods" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L77-L80
train
micro/go-plugins
registry/kubernetes/client/api/request.go
Name
func (r *Request) Name(s string) *Request { r.resourceName = &s return r }
go
func (r *Request) Name(s string) *Request { r.resourceName = &s return r }
[ "func", "(", "r", "*", "Request", ")", "Name", "(", "s", "string", ")", "*", "Request", "{", "r", ".", "resourceName", "=", "&", "s", "\n", "return", "r", "\n", "}" ]
// Name is for targeting a specific resource by id
[ "Name", "is", "for", "targeting", "a", "specific", "resource", "by", "id" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L83-L86
train
micro/go-plugins
registry/kubernetes/client/api/request.go
Body
func (r *Request) Body(in interface{}) *Request { b := new(bytes.Buffer) if err := json.NewEncoder(b).Encode(&in); err != nil { r.err = err return r } r.body = b return r }
go
func (r *Request) Body(in interface{}) *Request { b := new(bytes.Buffer) if err := json.NewEncoder(b).Encode(&in); err != nil { r.err = err return r } r.body = b return r }
[ "func", "(", "r", "*", "Request", ")", "Body", "(", "in", "interface", "{", "}", ")", "*", "Request", "{", "b", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "b", ")", ".", "Encode", "(", "&", "in", ")", ";", "err", "!=", "nil", "{", "r", ".", "err", "=", "err", "\n", "return", "r", "\n", "}", "\n", "r", ".", "body", "=", "b", "\n", "return", "r", "\n", "}" ]
// Body pass in a body to set, this is for POST, PUT // and PATCH requests
[ "Body", "pass", "in", "a", "body", "to", "set", "this", "is", "for", "POST", "PUT", "and", "PATCH", "requests" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L90-L98
train
micro/go-plugins
registry/kubernetes/client/api/request.go
Params
func (r *Request) Params(p *Params) *Request { for k, v := range p.LabelSelector { r.params.Add("labelSelectors", k+"="+v) } return r }
go
func (r *Request) Params(p *Params) *Request { for k, v := range p.LabelSelector { r.params.Add("labelSelectors", k+"="+v) } return r }
[ "func", "(", "r", "*", "Request", ")", "Params", "(", "p", "*", "Params", ")", "*", "Request", "{", "for", "k", ",", "v", ":=", "range", "p", ".", "LabelSelector", "{", "r", ".", "params", ".", "Add", "(", "\"", "\"", ",", "k", "+", "\"", "\"", "+", "v", ")", "\n", "}", "\n\n", "return", "r", "\n", "}" ]
// Params isused to set paramters on a request
[ "Params", "isused", "to", "set", "paramters", "on", "a", "request" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L101-L107
train
micro/go-plugins
registry/kubernetes/client/api/request.go
SetHeader
func (r *Request) SetHeader(key, value string) *Request { r.header.Add(key, value) return r }
go
func (r *Request) SetHeader(key, value string) *Request { r.header.Add(key, value) return r }
[ "func", "(", "r", "*", "Request", ")", "SetHeader", "(", "key", ",", "value", "string", ")", "*", "Request", "{", "r", ".", "header", ".", "Add", "(", "key", ",", "value", ")", "\n", "return", "r", "\n", "}" ]
// SetHeader sets a header on a request with // a `key` and `value`
[ "SetHeader", "sets", "a", "header", "on", "a", "request", "with", "a", "key", "and", "value" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L111-L114
train
micro/go-plugins
registry/kubernetes/client/api/request.go
request
func (r *Request) request() (*http.Request, error) { url := fmt.Sprintf("%s/api/v1/namespaces/%s/%s/", r.host, r.namespace, r.resource) // append resourceName if it is present if r.resourceName != nil { url += *r.resourceName } // append any query params if len(r.params) > 0 { url += "?" + r.params.Encode() } // build request req, err := http.NewRequest(r.method, url, r.body) if err != nil { return nil, err } // set headers on request req.Header = r.header return req, nil }
go
func (r *Request) request() (*http.Request, error) { url := fmt.Sprintf("%s/api/v1/namespaces/%s/%s/", r.host, r.namespace, r.resource) // append resourceName if it is present if r.resourceName != nil { url += *r.resourceName } // append any query params if len(r.params) > 0 { url += "?" + r.params.Encode() } // build request req, err := http.NewRequest(r.method, url, r.body) if err != nil { return nil, err } // set headers on request req.Header = r.header return req, nil }
[ "func", "(", "r", "*", "Request", ")", "request", "(", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "host", ",", "r", ".", "namespace", ",", "r", ".", "resource", ")", "\n\n", "// append resourceName if it is present", "if", "r", ".", "resourceName", "!=", "nil", "{", "url", "+=", "*", "r", ".", "resourceName", "\n", "}", "\n\n", "// append any query params", "if", "len", "(", "r", ".", "params", ")", ">", "0", "{", "url", "+=", "\"", "\"", "+", "r", ".", "params", ".", "Encode", "(", ")", "\n", "}", "\n\n", "// build request", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "r", ".", "method", ",", "url", ",", "r", ".", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// set headers on request", "req", ".", "Header", "=", "r", ".", "header", "\n", "return", "req", ",", "nil", "\n", "}" ]
// request builds the http.Request from the options
[ "request", "builds", "the", "http", ".", "Request", "from", "the", "options" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L117-L139
train
micro/go-plugins
registry/kubernetes/client/api/request.go
Do
func (r *Request) Do() *Response { if r.err != nil { return &Response{ err: r.err, } } req, err := r.request() if err != nil { return &Response{ err: err, } } res, err := r.client.Do(req) if err != nil { return &Response{ err: err, } } // return res, err return newResponse(res, err) }
go
func (r *Request) Do() *Response { if r.err != nil { return &Response{ err: r.err, } } req, err := r.request() if err != nil { return &Response{ err: err, } } res, err := r.client.Do(req) if err != nil { return &Response{ err: err, } } // return res, err return newResponse(res, err) }
[ "func", "(", "r", "*", "Request", ")", "Do", "(", ")", "*", "Response", "{", "if", "r", ".", "err", "!=", "nil", "{", "return", "&", "Response", "{", "err", ":", "r", ".", "err", ",", "}", "\n", "}", "\n\n", "req", ",", "err", ":=", "r", ".", "request", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "Response", "{", "err", ":", "err", ",", "}", "\n", "}", "\n\n", "res", ",", "err", ":=", "r", ".", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "Response", "{", "err", ":", "err", ",", "}", "\n", "}", "\n\n", "// return res, err", "return", "newResponse", "(", "res", ",", "err", ")", "\n", "}" ]
// Do builds and triggers the request
[ "Do", "builds", "and", "triggers", "the", "request" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L142-L165
train
micro/go-plugins
registry/kubernetes/client/api/request.go
Watch
func (r *Request) Watch() (watch.Watch, error) { if r.err != nil { return nil, r.err } r.params.Set("watch", "true") req, err := r.request() if err != nil { return nil, err } w, err := watch.NewBodyWatcher(req, r.client) return w, err }
go
func (r *Request) Watch() (watch.Watch, error) { if r.err != nil { return nil, r.err } r.params.Set("watch", "true") req, err := r.request() if err != nil { return nil, err } w, err := watch.NewBodyWatcher(req, r.client) return w, err }
[ "func", "(", "r", "*", "Request", ")", "Watch", "(", ")", "(", "watch", ".", "Watch", ",", "error", ")", "{", "if", "r", ".", "err", "!=", "nil", "{", "return", "nil", ",", "r", ".", "err", "\n", "}", "\n\n", "r", ".", "params", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "req", ",", "err", ":=", "r", ".", "request", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "w", ",", "err", ":=", "watch", ".", "NewBodyWatcher", "(", "req", ",", "r", ".", "client", ")", "\n", "return", "w", ",", "err", "\n", "}" ]
// Watch builds and triggers the request, but // will watch instead of return an object
[ "Watch", "builds", "and", "triggers", "the", "request", "but", "will", "watch", "instead", "of", "return", "an", "object" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L169-L183
train
micro/go-plugins
registry/kubernetes/client/api/request.go
NewRequest
func NewRequest(opts *Options) *Request { req := &Request{ header: make(http.Header), params: make(url.Values), client: opts.Client, namespace: opts.Namespace, host: opts.Host, } if opts.BearerToken != nil { req.SetHeader("Authorization", "Bearer "+*opts.BearerToken) } return req }
go
func NewRequest(opts *Options) *Request { req := &Request{ header: make(http.Header), params: make(url.Values), client: opts.Client, namespace: opts.Namespace, host: opts.Host, } if opts.BearerToken != nil { req.SetHeader("Authorization", "Bearer "+*opts.BearerToken) } return req }
[ "func", "NewRequest", "(", "opts", "*", "Options", ")", "*", "Request", "{", "req", ":=", "&", "Request", "{", "header", ":", "make", "(", "http", ".", "Header", ")", ",", "params", ":", "make", "(", "url", ".", "Values", ")", ",", "client", ":", "opts", ".", "Client", ",", "namespace", ":", "opts", ".", "Namespace", ",", "host", ":", "opts", ".", "Host", ",", "}", "\n\n", "if", "opts", ".", "BearerToken", "!=", "nil", "{", "req", ".", "SetHeader", "(", "\"", "\"", ",", "\"", "\"", "+", "*", "opts", ".", "BearerToken", ")", "\n", "}", "\n\n", "return", "req", "\n", "}" ]
// NewRequest creates a k8s api request
[ "NewRequest", "creates", "a", "k8s", "api", "request" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/request.go#L194-L208
train
micro/go-plugins
broker/stomp/stomp.go
stompHeaderToMap
func stompHeaderToMap(h *frame.Header) map[string]string { m := map[string]string{} for i := 0; i < h.Len(); i++ { k, v := h.GetAt(i) m[k] = v } return m }
go
func stompHeaderToMap(h *frame.Header) map[string]string { m := map[string]string{} for i := 0; i < h.Len(); i++ { k, v := h.GetAt(i) m[k] = v } return m }
[ "func", "stompHeaderToMap", "(", "h", "*", "frame", ".", "Header", ")", "map", "[", "string", "]", "string", "{", "m", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "h", ".", "Len", "(", ")", ";", "i", "++", "{", "k", ",", "v", ":=", "h", ".", "GetAt", "(", "i", ")", "\n", "m", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "m", "\n", "}" ]
// stompHeaderToMap converts STOMP header to broker friendly header
[ "stompHeaderToMap", "converts", "STOMP", "header", "to", "broker", "friendly", "header" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/stomp/stomp.go#L29-L36
train
micro/go-plugins
broker/stomp/stomp.go
defaults
func (r *rbroker) defaults() { ConnectTimeout(30 * time.Second)(&r.opts) VirtualHost("/")(&r.opts) }
go
func (r *rbroker) defaults() { ConnectTimeout(30 * time.Second)(&r.opts) VirtualHost("/")(&r.opts) }
[ "func", "(", "r", "*", "rbroker", ")", "defaults", "(", ")", "{", "ConnectTimeout", "(", "30", "*", "time", ".", "Second", ")", "(", "&", "r", ".", "opts", ")", "\n", "VirtualHost", "(", "\"", "\"", ")", "(", "&", "r", ".", "opts", ")", "\n", "}" ]
// defaults sets 'sane' STOMP default
[ "defaults", "sets", "sane", "STOMP", "default" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/stomp/stomp.go#L39-L42
train
micro/go-plugins
broker/stomp/stomp.go
NewBroker
func NewBroker(opts ...broker.Option) broker.Broker { r := &rbroker{ opts: broker.Options{ Context: context.Background(), }, } r.Init(opts...) return r }
go
func NewBroker(opts ...broker.Option) broker.Broker { r := &rbroker{ opts: broker.Options{ Context: context.Background(), }, } r.Init(opts...) return r }
[ "func", "NewBroker", "(", "opts", "...", "broker", ".", "Option", ")", "broker", ".", "Broker", "{", "r", ":=", "&", "rbroker", "{", "opts", ":", "broker", ".", "Options", "{", "Context", ":", "context", ".", "Background", "(", ")", ",", "}", ",", "}", "\n", "r", ".", "Init", "(", "opts", "...", ")", "\n", "return", "r", "\n", "}" ]
// NewBroker returns a STOMP broker
[ "NewBroker", "returns", "a", "STOMP", "broker" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/stomp/stomp.go#L236-L244
train
micro/go-plugins
wrapper/trace/datadog/tracker.go
finishWithError
func (t *tracker) finishWithError(err error, noDebugStack bool) { if t.span == nil { return } statusCode := codes.OK finishOptions := []tracer.FinishOption{ tracer.FinishTime(time.Now()), } microErr, ok := err.(*microerr.Error) if ok { finishOptions = append(finishOptions, tracer.WithError( fmt.Errorf("%s: %s", microErr.Id, microErr.Detail), )) c, ok := microCodeToStatusCode[microErr.Code] if ok { statusCode = c } else { statusCode = codes.Unknown } } t.span.SetTag(tagStatus, statusCode.String()) if noDebugStack { finishOptions = append(finishOptions, tracer.NoDebugStack()) } t.span.Finish(finishOptions...) t.span = nil }
go
func (t *tracker) finishWithError(err error, noDebugStack bool) { if t.span == nil { return } statusCode := codes.OK finishOptions := []tracer.FinishOption{ tracer.FinishTime(time.Now()), } microErr, ok := err.(*microerr.Error) if ok { finishOptions = append(finishOptions, tracer.WithError( fmt.Errorf("%s: %s", microErr.Id, microErr.Detail), )) c, ok := microCodeToStatusCode[microErr.Code] if ok { statusCode = c } else { statusCode = codes.Unknown } } t.span.SetTag(tagStatus, statusCode.String()) if noDebugStack { finishOptions = append(finishOptions, tracer.NoDebugStack()) } t.span.Finish(finishOptions...) t.span = nil }
[ "func", "(", "t", "*", "tracker", ")", "finishWithError", "(", "err", "error", ",", "noDebugStack", "bool", ")", "{", "if", "t", ".", "span", "==", "nil", "{", "return", "\n", "}", "\n\n", "statusCode", ":=", "codes", ".", "OK", "\n", "finishOptions", ":=", "[", "]", "tracer", ".", "FinishOption", "{", "tracer", ".", "FinishTime", "(", "time", ".", "Now", "(", ")", ")", ",", "}", "\n\n", "microErr", ",", "ok", ":=", "err", ".", "(", "*", "microerr", ".", "Error", ")", "\n\n", "if", "ok", "{", "finishOptions", "=", "append", "(", "finishOptions", ",", "tracer", ".", "WithError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "microErr", ".", "Id", ",", "microErr", ".", "Detail", ")", ",", ")", ")", "\n\n", "c", ",", "ok", ":=", "microCodeToStatusCode", "[", "microErr", ".", "Code", "]", "\n", "if", "ok", "{", "statusCode", "=", "c", "\n", "}", "else", "{", "statusCode", "=", "codes", ".", "Unknown", "\n", "}", "\n", "}", "\n\n", "t", ".", "span", ".", "SetTag", "(", "tagStatus", ",", "statusCode", ".", "String", "(", ")", ")", "\n\n", "if", "noDebugStack", "{", "finishOptions", "=", "append", "(", "finishOptions", ",", "tracer", ".", "NoDebugStack", "(", ")", ")", "\n", "}", "\n\n", "t", ".", "span", ".", "Finish", "(", "finishOptions", "...", ")", "\n", "t", ".", "span", "=", "nil", "\n", "}" ]
// finishWithError end a request's monitoring session. If there is a span ongoing, it will // be ended.
[ "finishWithError", "end", "a", "request", "s", "monitoring", "session", ".", "If", "there", "is", "a", "span", "ongoing", "it", "will", "be", "ended", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/datadog/tracker.go#L72-L105
train
micro/go-plugins
client/grpc/options.go
AuthTLS
func AuthTLS(t *tls.Config) client.Option { return func(o *client.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, tlsAuth{}, t) } }
go
func AuthTLS(t *tls.Config) client.Option { return func(o *client.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, tlsAuth{}, t) } }
[ "func", "AuthTLS", "(", "t", "*", "tls", ".", "Config", ")", "client", ".", "Option", "{", "return", "func", "(", "o", "*", "client", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "tlsAuth", "{", "}", ",", "t", ")", "\n", "}", "\n", "}" ]
// AuthTLS should be used to setup a secure authentication using TLS
[ "AuthTLS", "should", "be", "used", "to", "setup", "a", "secure", "authentication", "using", "TLS" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/client/grpc/options.go#L43-L50
train
micro/go-plugins
client/grpc/options.go
MaxRecvMsgSize
func MaxRecvMsgSize(s int) client.Option { return func(o *client.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxRecvMsgSizeKey{}, s) } }
go
func MaxRecvMsgSize(s int) client.Option { return func(o *client.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxRecvMsgSizeKey{}, s) } }
[ "func", "MaxRecvMsgSize", "(", "s", "int", ")", "client", ".", "Option", "{", "return", "func", "(", "o", "*", "client", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "maxRecvMsgSizeKey", "{", "}", ",", "s", ")", "\n", "}", "\n", "}" ]
// // MaxRecvMsgSize set the maximum size of message that client can receive. //
[ "MaxRecvMsgSize", "set", "the", "maximum", "size", "of", "message", "that", "client", "can", "receive", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/client/grpc/options.go#L55-L62
train
micro/go-plugins
client/grpc/options.go
MaxSendMsgSize
func MaxSendMsgSize(s int) client.Option { return func(o *client.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxSendMsgSizeKey{}, s) } }
go
func MaxSendMsgSize(s int) client.Option { return func(o *client.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxSendMsgSizeKey{}, s) } }
[ "func", "MaxSendMsgSize", "(", "s", "int", ")", "client", ".", "Option", "{", "return", "func", "(", "o", "*", "client", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "maxSendMsgSizeKey", "{", "}", ",", "s", ")", "\n", "}", "\n", "}" ]
// // MaxSendMsgSize set the maximum size of message that client can send. //
[ "MaxSendMsgSize", "set", "the", "maximum", "size", "of", "message", "that", "client", "can", "send", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/client/grpc/options.go#L67-L74
train
micro/go-plugins
broker/sqs/options.go
DeduplicationFunction
func DeduplicationFunction(dedup StringFromMessageFunc) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, dedupFunctionKey{}, dedup) } }
go
func DeduplicationFunction(dedup StringFromMessageFunc) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, dedupFunctionKey{}, dedup) } }
[ "func", "DeduplicationFunction", "(", "dedup", "StringFromMessageFunc", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "dedupFunctionKey", "{", "}", ",", "dedup", ")", "\n", "}", "\n", "}" ]
// DeduplicationFunction sets the function used to create the deduplication string // for a given message
[ "DeduplicationFunction", "sets", "the", "function", "used", "to", "create", "the", "deduplication", "string", "for", "a", "given", "message" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/options.go#L21-L28
train
micro/go-plugins
broker/sqs/options.go
GroupIDFunction
func GroupIDFunction(groupfunc StringFromMessageFunc) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, groupIdFunctionKey{}, groupfunc) } }
go
func GroupIDFunction(groupfunc StringFromMessageFunc) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, groupIdFunctionKey{}, groupfunc) } }
[ "func", "GroupIDFunction", "(", "groupfunc", "StringFromMessageFunc", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "groupIdFunctionKey", "{", "}", ",", "groupfunc", ")", "\n", "}", "\n", "}" ]
// GroupIDFunction sets the function used to create the group ID string for a // given message
[ "GroupIDFunction", "sets", "the", "function", "used", "to", "create", "the", "group", "ID", "string", "for", "a", "given", "message" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/options.go#L32-L39
train
micro/go-plugins
broker/sqs/options.go
MaxReceiveMessages
func MaxReceiveMessages(max int64) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxMessagesKey{}, max) } }
go
func MaxReceiveMessages(max int64) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxMessagesKey{}, max) } }
[ "func", "MaxReceiveMessages", "(", "max", "int64", ")", "broker", ".", "SubscribeOption", "{", "return", "func", "(", "o", "*", "broker", ".", "SubscribeOptions", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "maxMessagesKey", "{", "}", ",", "max", ")", "\n", "}", "\n", "}" ]
// MaxReceiveMessages indicates how many messages a receive operation should pull // during any single call
[ "MaxReceiveMessages", "indicates", "how", "many", "messages", "a", "receive", "operation", "should", "pull", "during", "any", "single", "call" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/options.go#L43-L50
train
micro/go-plugins
broker/sqs/options.go
VisibilityTimeout
func VisibilityTimeout(seconds int64) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, visiblityTimeoutKey{}, seconds) } }
go
func VisibilityTimeout(seconds int64) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, visiblityTimeoutKey{}, seconds) } }
[ "func", "VisibilityTimeout", "(", "seconds", "int64", ")", "broker", ".", "SubscribeOption", "{", "return", "func", "(", "o", "*", "broker", ".", "SubscribeOptions", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "visiblityTimeoutKey", "{", "}", ",", "seconds", ")", "\n", "}", "\n", "}" ]
// VisibilityTimeout controls how long a message is hidden from other queue consumers // before being put back. If a consumer does not delete the message, it will be put back // even if it was "processed"
[ "VisibilityTimeout", "controls", "how", "long", "a", "message", "is", "hidden", "from", "other", "queue", "consumers", "before", "being", "put", "back", ".", "If", "a", "consumer", "does", "not", "delete", "the", "message", "it", "will", "be", "put", "back", "even", "if", "it", "was", "processed" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/options.go#L55-L62
train
micro/go-plugins
broker/sqs/options.go
WaitTimeSeconds
func WaitTimeSeconds(seconds int64) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, waitTimeSecondsKey{}, seconds) } }
go
func WaitTimeSeconds(seconds int64) broker.SubscribeOption { return func(o *broker.SubscribeOptions) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, waitTimeSecondsKey{}, seconds) } }
[ "func", "WaitTimeSeconds", "(", "seconds", "int64", ")", "broker", ".", "SubscribeOption", "{", "return", "func", "(", "o", "*", "broker", ".", "SubscribeOptions", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "waitTimeSecondsKey", "{", "}", ",", "seconds", ")", "\n", "}", "\n", "}" ]
// WaitTimeSeconds controls the length of long polling for available messages
[ "WaitTimeSeconds", "controls", "the", "length", "of", "long", "polling", "for", "available", "messages" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/options.go#L65-L72
train
micro/go-plugins
broker/sqs/options.go
Client
func Client(c *sqs.SQS) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, sqsClientKey{}, c) } }
go
func Client(c *sqs.SQS) broker.Option { return func(o *broker.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, sqsClientKey{}, c) } }
[ "func", "Client", "(", "c", "*", "sqs", ".", "SQS", ")", "broker", ".", "Option", "{", "return", "func", "(", "o", "*", "broker", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "sqsClientKey", "{", "}", ",", "c", ")", "\n", "}", "\n", "}" ]
// Client receives an instantiated instance of an SQS client which is used instead of initialising a new client
[ "Client", "receives", "an", "instantiated", "instance", "of", "an", "SQS", "client", "which", "is", "used", "instead", "of", "initialising", "a", "new", "client" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/sqs/options.go#L75-L82
train
micro/go-plugins
wrapper/ratelimiter/uber/uber.go
NewClientWrapper
func NewClientWrapper(rate int, opts ...ratelimit.Option) client.Wrapper { r := ratelimit.New(rate, opts...) return func(c client.Client) client.Client { return &clientWrapper{r, c} } }
go
func NewClientWrapper(rate int, opts ...ratelimit.Option) client.Wrapper { r := ratelimit.New(rate, opts...) return func(c client.Client) client.Client { return &clientWrapper{r, c} } }
[ "func", "NewClientWrapper", "(", "rate", "int", ",", "opts", "...", "ratelimit", ".", "Option", ")", "client", ".", "Wrapper", "{", "r", ":=", "ratelimit", ".", "New", "(", "rate", ",", "opts", "...", ")", "\n\n", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "clientWrapper", "{", "r", ",", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper creates a blocking side rate limiter
[ "NewClientWrapper", "creates", "a", "blocking", "side", "rate", "limiter" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/ratelimiter/uber/uber.go#L22-L28
train
micro/go-plugins
wrapper/ratelimiter/uber/uber.go
NewHandlerWrapper
func NewHandlerWrapper(rate int, opts ...ratelimit.Option) server.HandlerWrapper { r := ratelimit.New(rate, opts...) return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { r.Take() return h(ctx, req, rsp) } } }
go
func NewHandlerWrapper(rate int, opts ...ratelimit.Option) server.HandlerWrapper { r := ratelimit.New(rate, opts...) return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { r.Take() return h(ctx, req, rsp) } } }
[ "func", "NewHandlerWrapper", "(", "rate", "int", ",", "opts", "...", "ratelimit", ".", "Option", ")", "server", ".", "HandlerWrapper", "{", "r", ":=", "ratelimit", ".", "New", "(", "rate", ",", "opts", "...", ")", "\n\n", "return", "func", "(", "h", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "error", "{", "r", ".", "Take", "(", ")", "\n", "return", "h", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper creates a blocking server side rate limiter
[ "NewHandlerWrapper", "creates", "a", "blocking", "server", "side", "rate", "limiter" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/ratelimiter/uber/uber.go#L31-L40
train
micro/go-plugins
wrapper/select/roundrobin/roundrobin.go
NewClientWrapper
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { return &roundrobin{ rr: make(map[string]int), Client: c, } } }
go
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { return &roundrobin{ rr: make(map[string]int), Client: c, } } }
[ "func", "NewClientWrapper", "(", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "roundrobin", "{", "rr", ":", "make", "(", "map", "[", "string", "]", "int", ")", ",", "Client", ":", "c", ",", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper is a wrapper which roundrobins requests
[ "NewClientWrapper", "is", "a", "wrapper", "which", "roundrobins", "requests" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/select/roundrobin/roundrobin.go#L55-L62
train
micro/go-plugins
micro/trace/awsxray/util.go
complete
func complete(s *awsxray.Segment, status int) { switch { case status >= 500: s.Fault = true case status >= 400: s.Error = true } s.HTTP.Response.Status = status s.EndTime = float64(time.Now().Truncate(time.Millisecond).UnixNano()) / 1e9 }
go
func complete(s *awsxray.Segment, status int) { switch { case status >= 500: s.Fault = true case status >= 400: s.Error = true } s.HTTP.Response.Status = status s.EndTime = float64(time.Now().Truncate(time.Millisecond).UnixNano()) / 1e9 }
[ "func", "complete", "(", "s", "*", "awsxray", ".", "Segment", ",", "status", "int", ")", "{", "switch", "{", "case", "status", ">=", "500", ":", "s", ".", "Fault", "=", "true", "\n", "case", "status", ">=", "400", ":", "s", ".", "Error", "=", "true", "\n", "}", "\n", "s", ".", "HTTP", ".", "Response", ".", "Status", "=", "status", "\n", "s", ".", "EndTime", "=", "float64", "(", "time", ".", "Now", "(", ")", ".", "Truncate", "(", "time", ".", "Millisecond", ")", ".", "UnixNano", "(", ")", ")", "/", "1e9", "\n", "}" ]
// complete sets the response status and end time
[ "complete", "sets", "the", "response", "status", "and", "end", "time" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/trace/awsxray/util.go#L15-L24
train
micro/go-plugins
micro/trace/awsxray/util.go
getIp
func getIp(r *http.Request) string { for _, h := range []string{"X-Forwarded-For", "X-Real-Ip"} { for _, ip := range strings.Split(r.Header.Get(h), ",") { if len(ip) == 0 { continue } realIP := net.ParseIP(strings.Replace(ip, " ", "", -1)) return realIP.String() } } // not found in header host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { // just return remote addr return r.RemoteAddr } return host }
go
func getIp(r *http.Request) string { for _, h := range []string{"X-Forwarded-For", "X-Real-Ip"} { for _, ip := range strings.Split(r.Header.Get(h), ",") { if len(ip) == 0 { continue } realIP := net.ParseIP(strings.Replace(ip, " ", "", -1)) return realIP.String() } } // not found in header host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { // just return remote addr return r.RemoteAddr } return host }
[ "func", "getIp", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "for", "_", ",", "h", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "{", "for", "_", ",", "ip", ":=", "range", "strings", ".", "Split", "(", "r", ".", "Header", ".", "Get", "(", "h", ")", ",", "\"", "\"", ")", "{", "if", "len", "(", "ip", ")", "==", "0", "{", "continue", "\n", "}", "\n", "realIP", ":=", "net", ".", "ParseIP", "(", "strings", ".", "Replace", "(", "ip", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", ")", "\n", "return", "realIP", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n\n", "// not found in header", "host", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "r", ".", "RemoteAddr", ")", "\n", "if", "err", "!=", "nil", "{", "// just return remote addr", "return", "r", ".", "RemoteAddr", "\n", "}", "\n\n", "return", "host", "\n", "}" ]
// getIp naively returns an ip for the request
[ "getIp", "naively", "returns", "an", "ip", "for", "the", "request" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/trace/awsxray/util.go#L27-L46
train
micro/go-plugins
micro/trace/awsxray/util.go
newHTTP
func newHTTP(r *http.Request) *awsxray.HTTP { scheme := "http" host := r.Host if len(r.URL.Scheme) > 0 { scheme = r.URL.Scheme } if len(r.URL.Host) > 0 { host = r.URL.Host } return &awsxray.HTTP{ Request: &awsxray.Request{ Method: r.Method, URL: fmt.Sprintf("%s://%s%s", scheme, host, r.URL.Path), ClientIP: getIp(r), UserAgent: r.UserAgent(), }, Response: &awsxray.Response{ Status: 200, }, } }
go
func newHTTP(r *http.Request) *awsxray.HTTP { scheme := "http" host := r.Host if len(r.URL.Scheme) > 0 { scheme = r.URL.Scheme } if len(r.URL.Host) > 0 { host = r.URL.Host } return &awsxray.HTTP{ Request: &awsxray.Request{ Method: r.Method, URL: fmt.Sprintf("%s://%s%s", scheme, host, r.URL.Path), ClientIP: getIp(r), UserAgent: r.UserAgent(), }, Response: &awsxray.Response{ Status: 200, }, } }
[ "func", "newHTTP", "(", "r", "*", "http", ".", "Request", ")", "*", "awsxray", ".", "HTTP", "{", "scheme", ":=", "\"", "\"", "\n", "host", ":=", "r", ".", "Host", "\n\n", "if", "len", "(", "r", ".", "URL", ".", "Scheme", ")", ">", "0", "{", "scheme", "=", "r", ".", "URL", ".", "Scheme", "\n", "}", "\n\n", "if", "len", "(", "r", ".", "URL", ".", "Host", ")", ">", "0", "{", "host", "=", "r", ".", "URL", ".", "Host", "\n", "}", "\n\n", "return", "&", "awsxray", ".", "HTTP", "{", "Request", ":", "&", "awsxray", ".", "Request", "{", "Method", ":", "r", ".", "Method", ",", "URL", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scheme", ",", "host", ",", "r", ".", "URL", ".", "Path", ")", ",", "ClientIP", ":", "getIp", "(", "r", ")", ",", "UserAgent", ":", "r", ".", "UserAgent", "(", ")", ",", "}", ",", "Response", ":", "&", "awsxray", ".", "Response", "{", "Status", ":", "200", ",", "}", ",", "}", "\n", "}" ]
// newHTTP returns a http struct
[ "newHTTP", "returns", "a", "http", "struct" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/trace/awsxray/util.go#L81-L104
train
micro/go-plugins
micro/trace/awsxray/util.go
newSegment
func newSegment(name string, r *http.Request) *awsxray.Segment { // attempt to get IDs first parentId := getParentId(r.Header) traceId := getTraceId(r.Header) // now set the trace ID traceHdr := r.Header.Get(awsxray.TraceHeader) traceHdr = awsxray.SetTraceId(traceHdr, traceId) // create segment s := &awsxray.Segment{ Id: getRandom(8), HTTP: newHTTP(r), Name: name, TraceId: traceId, StartTime: float64(time.Now().Truncate(time.Millisecond).UnixNano()) / 1e9, } // if we have a parent then we are a subsegment if len(parentId) > 0 { s.ParentId = parentId s.Type = "subsegment" } else { // set a new parent Id traceHdr = awsxray.SetParentId(traceHdr, s.Id) } // now save the header for the future context r.Header.Set(awsxray.TraceHeader, traceHdr) return s }
go
func newSegment(name string, r *http.Request) *awsxray.Segment { // attempt to get IDs first parentId := getParentId(r.Header) traceId := getTraceId(r.Header) // now set the trace ID traceHdr := r.Header.Get(awsxray.TraceHeader) traceHdr = awsxray.SetTraceId(traceHdr, traceId) // create segment s := &awsxray.Segment{ Id: getRandom(8), HTTP: newHTTP(r), Name: name, TraceId: traceId, StartTime: float64(time.Now().Truncate(time.Millisecond).UnixNano()) / 1e9, } // if we have a parent then we are a subsegment if len(parentId) > 0 { s.ParentId = parentId s.Type = "subsegment" } else { // set a new parent Id traceHdr = awsxray.SetParentId(traceHdr, s.Id) } // now save the header for the future context r.Header.Set(awsxray.TraceHeader, traceHdr) return s }
[ "func", "newSegment", "(", "name", "string", ",", "r", "*", "http", ".", "Request", ")", "*", "awsxray", ".", "Segment", "{", "// attempt to get IDs first", "parentId", ":=", "getParentId", "(", "r", ".", "Header", ")", "\n", "traceId", ":=", "getTraceId", "(", "r", ".", "Header", ")", "\n\n", "// now set the trace ID", "traceHdr", ":=", "r", ".", "Header", ".", "Get", "(", "awsxray", ".", "TraceHeader", ")", "\n", "traceHdr", "=", "awsxray", ".", "SetTraceId", "(", "traceHdr", ",", "traceId", ")", "\n\n", "// create segment", "s", ":=", "&", "awsxray", ".", "Segment", "{", "Id", ":", "getRandom", "(", "8", ")", ",", "HTTP", ":", "newHTTP", "(", "r", ")", ",", "Name", ":", "name", ",", "TraceId", ":", "traceId", ",", "StartTime", ":", "float64", "(", "time", ".", "Now", "(", ")", ".", "Truncate", "(", "time", ".", "Millisecond", ")", ".", "UnixNano", "(", ")", ")", "/", "1e9", ",", "}", "\n\n", "// if we have a parent then we are a subsegment", "if", "len", "(", "parentId", ")", ">", "0", "{", "s", ".", "ParentId", "=", "parentId", "\n", "s", ".", "Type", "=", "\"", "\"", "\n", "}", "else", "{", "// set a new parent Id", "traceHdr", "=", "awsxray", ".", "SetParentId", "(", "traceHdr", ",", "s", ".", "Id", ")", "\n", "}", "\n\n", "// now save the header for the future context", "r", ".", "Header", ".", "Set", "(", "awsxray", ".", "TraceHeader", ",", "traceHdr", ")", "\n\n", "return", "s", "\n", "}" ]
// newSegment creates a new segment based on whether we're part of an existing flow
[ "newSegment", "creates", "a", "new", "segment", "based", "on", "whether", "we", "re", "part", "of", "an", "existing", "flow" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/trace/awsxray/util.go#L107-L138
train
micro/go-plugins
wrapper/breaker/gobreaker/gobreaker.go
NewClientWrapper
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { w := &clientWrapper{} w.bs = gobreaker.Settings{} w.cbs = make(map[string]*gobreaker.TwoStepCircuitBreaker) w.Client = c return w } }
go
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { w := &clientWrapper{} w.bs = gobreaker.Settings{} w.cbs = make(map[string]*gobreaker.TwoStepCircuitBreaker) w.Client = c return w } }
[ "func", "NewClientWrapper", "(", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "w", ":=", "&", "clientWrapper", "{", "}", "\n", "w", ".", "bs", "=", "gobreaker", ".", "Settings", "{", "}", "\n", "w", ".", "cbs", "=", "make", "(", "map", "[", "string", "]", "*", "gobreaker", ".", "TwoStepCircuitBreaker", ")", "\n", "w", ".", "Client", "=", "c", "\n", "return", "w", "\n", "}", "\n", "}" ]
// NewClientWrapper returns a client Wrapper.
[ "NewClientWrapper", "returns", "a", "client", "Wrapper", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/breaker/gobreaker/gobreaker.go#L73-L81
train
micro/go-plugins
wrapper/breaker/gobreaker/gobreaker.go
NewCustomClientWrapper
func NewCustomClientWrapper(bs gobreaker.Settings, bm BreakerMethod) client.Wrapper { return func(c client.Client) client.Client { w := &clientWrapper{} w.bm = bm w.bs = bs w.cbs = make(map[string]*gobreaker.TwoStepCircuitBreaker) w.Client = c return w } }
go
func NewCustomClientWrapper(bs gobreaker.Settings, bm BreakerMethod) client.Wrapper { return func(c client.Client) client.Client { w := &clientWrapper{} w.bm = bm w.bs = bs w.cbs = make(map[string]*gobreaker.TwoStepCircuitBreaker) w.Client = c return w } }
[ "func", "NewCustomClientWrapper", "(", "bs", "gobreaker", ".", "Settings", ",", "bm", "BreakerMethod", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "w", ":=", "&", "clientWrapper", "{", "}", "\n", "w", ".", "bm", "=", "bm", "\n", "w", ".", "bs", "=", "bs", "\n", "w", ".", "cbs", "=", "make", "(", "map", "[", "string", "]", "*", "gobreaker", ".", "TwoStepCircuitBreaker", ")", "\n", "w", ".", "Client", "=", "c", "\n", "return", "w", "\n", "}", "\n", "}" ]
// NewCustomClientWrapper takes a gobreaker.Settings and BreakerMethod. Returns a client Wrapper.
[ "NewCustomClientWrapper", "takes", "a", "gobreaker", ".", "Settings", "and", "BreakerMethod", ".", "Returns", "a", "client", "Wrapper", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/breaker/gobreaker/gobreaker.go#L84-L93
train
micro/go-plugins
wrapper/trace/opencensus/opencensus.go
Call
func (w *clientWrapper) Call( ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) (err error) { t := newRequestTracker(req, ClientProfile) ctx = t.start(ctx, true) defer func() { t.end(ctx, err) }() ctx = injectTraceIntoCtx(ctx, t.span) err = w.Client.Call(ctx, req, rsp, opts...) return }
go
func (w *clientWrapper) Call( ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) (err error) { t := newRequestTracker(req, ClientProfile) ctx = t.start(ctx, true) defer func() { t.end(ctx, err) }() ctx = injectTraceIntoCtx(ctx, t.span) err = w.Client.Call(ctx, req, rsp, opts...) return }
[ "func", "(", "w", "*", "clientWrapper", ")", "Call", "(", "ctx", "context", ".", "Context", ",", "req", "client", ".", "Request", ",", "rsp", "interface", "{", "}", ",", "opts", "...", "client", ".", "CallOption", ")", "(", "err", "error", ")", "{", "t", ":=", "newRequestTracker", "(", "req", ",", "ClientProfile", ")", "\n", "ctx", "=", "t", ".", "start", "(", "ctx", ",", "true", ")", "\n\n", "defer", "func", "(", ")", "{", "t", ".", "end", "(", "ctx", ",", "err", ")", "}", "(", ")", "\n\n", "ctx", "=", "injectTraceIntoCtx", "(", "ctx", ",", "t", ".", "span", ")", "\n\n", "err", "=", "w", ".", "Client", ".", "Call", "(", "ctx", ",", "req", ",", "rsp", ",", "opts", "...", ")", "\n", "return", "\n", "}" ]
// Call implements client.Client.Call.
[ "Call", "implements", "client", ".", "Client", ".", "Call", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opencensus/opencensus.go#L42-L56
train
micro/go-plugins
wrapper/trace/opencensus/opencensus.go
Publish
func (w *clientWrapper) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) (err error) { t := newPublicationTracker(p, ClientProfile) ctx = t.start(ctx, true) defer func() { t.end(ctx, err) }() ctx = injectTraceIntoCtx(ctx, t.span) err = w.Client.Publish(ctx, p, opts...) return }
go
func (w *clientWrapper) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) (err error) { t := newPublicationTracker(p, ClientProfile) ctx = t.start(ctx, true) defer func() { t.end(ctx, err) }() ctx = injectTraceIntoCtx(ctx, t.span) err = w.Client.Publish(ctx, p, opts...) return }
[ "func", "(", "w", "*", "clientWrapper", ")", "Publish", "(", "ctx", "context", ".", "Context", ",", "p", "client", ".", "Message", ",", "opts", "...", "client", ".", "PublishOption", ")", "(", "err", "error", ")", "{", "t", ":=", "newPublicationTracker", "(", "p", ",", "ClientProfile", ")", "\n", "ctx", "=", "t", ".", "start", "(", "ctx", ",", "true", ")", "\n\n", "defer", "func", "(", ")", "{", "t", ".", "end", "(", "ctx", ",", "err", ")", "}", "(", ")", "\n\n", "ctx", "=", "injectTraceIntoCtx", "(", "ctx", ",", "t", ".", "span", ")", "\n\n", "err", "=", "w", ".", "Client", ".", "Publish", "(", "ctx", ",", "p", ",", "opts", "...", ")", "\n", "return", "\n", "}" ]
// Publish implements client.Client.Publish.
[ "Publish", "implements", "client", ".", "Client", ".", "Publish", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opencensus/opencensus.go#L59-L69
train
micro/go-plugins
wrapper/trace/opencensus/opencensus.go
NewHandlerWrapper
func NewHandlerWrapper() server.HandlerWrapper { return func(fn server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) (err error) { t := newRequestTracker(req, ServerProfile) ctx = t.start(ctx, false) defer func() { t.end(ctx, err) }() spanCtx := getTraceFromCtx(ctx) if spanCtx != nil { ctx, t.span = trace.StartSpanWithRemoteParent( ctx, fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()), *spanCtx, ) } else { ctx, t.span = trace.StartSpan( ctx, fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()), ) } err = fn(ctx, req, rsp) return } } }
go
func NewHandlerWrapper() server.HandlerWrapper { return func(fn server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) (err error) { t := newRequestTracker(req, ServerProfile) ctx = t.start(ctx, false) defer func() { t.end(ctx, err) }() spanCtx := getTraceFromCtx(ctx) if spanCtx != nil { ctx, t.span = trace.StartSpanWithRemoteParent( ctx, fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()), *spanCtx, ) } else { ctx, t.span = trace.StartSpan( ctx, fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()), ) } err = fn(ctx, req, rsp) return } } }
[ "func", "NewHandlerWrapper", "(", ")", "server", ".", "HandlerWrapper", "{", "return", "func", "(", "fn", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "t", ":=", "newRequestTracker", "(", "req", ",", "ServerProfile", ")", "\n", "ctx", "=", "t", ".", "start", "(", "ctx", ",", "false", ")", "\n\n", "defer", "func", "(", ")", "{", "t", ".", "end", "(", "ctx", ",", "err", ")", "}", "(", ")", "\n\n", "spanCtx", ":=", "getTraceFromCtx", "(", "ctx", ")", "\n", "if", "spanCtx", "!=", "nil", "{", "ctx", ",", "t", ".", "span", "=", "trace", ".", "StartSpanWithRemoteParent", "(", "ctx", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ServerProfile", ".", "Role", ",", "req", ".", "Service", "(", ")", ",", "req", ".", "Endpoint", "(", ")", ")", ",", "*", "spanCtx", ",", ")", "\n", "}", "else", "{", "ctx", ",", "t", ".", "span", "=", "trace", ".", "StartSpan", "(", "ctx", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ServerProfile", ".", "Role", ",", "req", ".", "Service", "(", ")", ",", "req", ".", "Endpoint", "(", ")", ")", ",", ")", "\n", "}", "\n\n", "err", "=", "fn", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper returns a server.HandlerWrapper // that adds tracing to incoming requests.
[ "NewHandlerWrapper", "returns", "a", "server", ".", "HandlerWrapper", "that", "adds", "tracing", "to", "incoming", "requests", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opencensus/opencensus.go#L107-L133
train
micro/go-plugins
wrapper/trace/opencensus/opencensus.go
NewSubscriberWrapper
func NewSubscriberWrapper() server.SubscriberWrapper { return func(fn server.SubscriberFunc) server.SubscriberFunc { return func(ctx context.Context, p server.Message) (err error) { t := newPublicationTracker(p, ServerProfile) ctx = t.start(ctx, false) defer func() { t.end(ctx, err) }() spanCtx := getTraceFromCtx(ctx) if spanCtx != nil { ctx, t.span = trace.StartSpanWithRemoteParent( ctx, fmt.Sprintf("rpc/%s/pubsub/%s", ServerProfile.Role, p.Topic()), *spanCtx, ) } else { ctx, t.span = trace.StartSpan( ctx, fmt.Sprintf("rpc/%s/pubsub/%s", ServerProfile.Role, p.Topic()), ) } err = fn(ctx, p) return } } }
go
func NewSubscriberWrapper() server.SubscriberWrapper { return func(fn server.SubscriberFunc) server.SubscriberFunc { return func(ctx context.Context, p server.Message) (err error) { t := newPublicationTracker(p, ServerProfile) ctx = t.start(ctx, false) defer func() { t.end(ctx, err) }() spanCtx := getTraceFromCtx(ctx) if spanCtx != nil { ctx, t.span = trace.StartSpanWithRemoteParent( ctx, fmt.Sprintf("rpc/%s/pubsub/%s", ServerProfile.Role, p.Topic()), *spanCtx, ) } else { ctx, t.span = trace.StartSpan( ctx, fmt.Sprintf("rpc/%s/pubsub/%s", ServerProfile.Role, p.Topic()), ) } err = fn(ctx, p) return } } }
[ "func", "NewSubscriberWrapper", "(", ")", "server", ".", "SubscriberWrapper", "{", "return", "func", "(", "fn", "server", ".", "SubscriberFunc", ")", "server", ".", "SubscriberFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "p", "server", ".", "Message", ")", "(", "err", "error", ")", "{", "t", ":=", "newPublicationTracker", "(", "p", ",", "ServerProfile", ")", "\n", "ctx", "=", "t", ".", "start", "(", "ctx", ",", "false", ")", "\n\n", "defer", "func", "(", ")", "{", "t", ".", "end", "(", "ctx", ",", "err", ")", "}", "(", ")", "\n\n", "spanCtx", ":=", "getTraceFromCtx", "(", "ctx", ")", "\n", "if", "spanCtx", "!=", "nil", "{", "ctx", ",", "t", ".", "span", "=", "trace", ".", "StartSpanWithRemoteParent", "(", "ctx", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ServerProfile", ".", "Role", ",", "p", ".", "Topic", "(", ")", ")", ",", "*", "spanCtx", ",", ")", "\n", "}", "else", "{", "ctx", ",", "t", ".", "span", "=", "trace", ".", "StartSpan", "(", "ctx", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ServerProfile", ".", "Role", ",", "p", ".", "Topic", "(", ")", ")", ",", ")", "\n", "}", "\n\n", "err", "=", "fn", "(", "ctx", ",", "p", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// NewSubscriberWrapper returns a server.SubscriberWrapper // that adds tracing to subscription requests.
[ "NewSubscriberWrapper", "returns", "a", "server", ".", "SubscriberWrapper", "that", "adds", "tracing", "to", "subscription", "requests", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opencensus/opencensus.go#L137-L163
train
micro/go-plugins
broker/googlepubsub/googlepubsub.go
Publish
func (b *pubsubBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { t := b.client.Topic(topic) ctx := context.Background() exists, err := t.Exists(ctx) if err != nil { return err } if !exists { tt, err := b.client.CreateTopic(ctx, topic) if err != nil { return err } t = tt } m := &pubsub.Message{ ID: "m-" + uuid.New().String(), Data: msg.Body, Attributes: msg.Header, } pr := t.Publish(ctx, m) _, err = pr.Get(ctx) return err }
go
func (b *pubsubBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { t := b.client.Topic(topic) ctx := context.Background() exists, err := t.Exists(ctx) if err != nil { return err } if !exists { tt, err := b.client.CreateTopic(ctx, topic) if err != nil { return err } t = tt } m := &pubsub.Message{ ID: "m-" + uuid.New().String(), Data: msg.Body, Attributes: msg.Header, } pr := t.Publish(ctx, m) _, err = pr.Get(ctx) return err }
[ "func", "(", "b", "*", "pubsubBroker", ")", "Publish", "(", "topic", "string", ",", "msg", "*", "broker", ".", "Message", ",", "opts", "...", "broker", ".", "PublishOption", ")", "error", "{", "t", ":=", "b", ".", "client", ".", "Topic", "(", "topic", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n\n", "exists", ",", "err", ":=", "t", ".", "Exists", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "exists", "{", "tt", ",", "err", ":=", "b", ".", "client", ".", "CreateTopic", "(", "ctx", ",", "topic", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", "=", "tt", "\n", "}", "\n\n", "m", ":=", "&", "pubsub", ".", "Message", "{", "ID", ":", "\"", "\"", "+", "uuid", ".", "New", "(", ")", ".", "String", "(", ")", ",", "Data", ":", "msg", ".", "Body", ",", "Attributes", ":", "msg", ".", "Header", ",", "}", "\n\n", "pr", ":=", "t", ".", "Publish", "(", "ctx", ",", "m", ")", "\n", "_", ",", "err", "=", "pr", ".", "Get", "(", "ctx", ")", "\n", "return", "err", "\n", "}" ]
// Publish checks if the topic exists and then publishes via google pubsub
[ "Publish", "checks", "if", "the", "topic", "exists", "and", "then", "publishes", "via", "google", "pubsub" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/googlepubsub.go#L142-L168
train
micro/go-plugins
broker/googlepubsub/googlepubsub.go
Subscribe
func (b *pubsubBroker) Subscribe(topic string, h broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { options := broker.SubscribeOptions{ AutoAck: true, Queue: "q-" + uuid.New().String(), Context: b.options.Context, } for _, o := range opts { o(&options) } ctx := context.Background() sub := b.client.Subscription(options.Queue) if createSubscription, ok := b.options.Context.Value(createSubscription{}).(bool); !ok || createSubscription { exists, err := sub.Exists(ctx) if err != nil { return nil, err } if !exists { tt := b.client.Topic(topic) subb, err := b.client.CreateSubscription(ctx, options.Queue, pubsub.SubscriptionConfig{ Topic: tt, AckDeadline: time.Duration(0), }) if err != nil { return nil, err } sub = subb } } subscriber := &subscriber{ options: options, topic: topic, exit: make(chan bool), sub: sub, } go subscriber.run(h) return subscriber, nil }
go
func (b *pubsubBroker) Subscribe(topic string, h broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { options := broker.SubscribeOptions{ AutoAck: true, Queue: "q-" + uuid.New().String(), Context: b.options.Context, } for _, o := range opts { o(&options) } ctx := context.Background() sub := b.client.Subscription(options.Queue) if createSubscription, ok := b.options.Context.Value(createSubscription{}).(bool); !ok || createSubscription { exists, err := sub.Exists(ctx) if err != nil { return nil, err } if !exists { tt := b.client.Topic(topic) subb, err := b.client.CreateSubscription(ctx, options.Queue, pubsub.SubscriptionConfig{ Topic: tt, AckDeadline: time.Duration(0), }) if err != nil { return nil, err } sub = subb } } subscriber := &subscriber{ options: options, topic: topic, exit: make(chan bool), sub: sub, } go subscriber.run(h) return subscriber, nil }
[ "func", "(", "b", "*", "pubsubBroker", ")", "Subscribe", "(", "topic", "string", ",", "h", "broker", ".", "Handler", ",", "opts", "...", "broker", ".", "SubscribeOption", ")", "(", "broker", ".", "Subscriber", ",", "error", ")", "{", "options", ":=", "broker", ".", "SubscribeOptions", "{", "AutoAck", ":", "true", ",", "Queue", ":", "\"", "\"", "+", "uuid", ".", "New", "(", ")", ".", "String", "(", ")", ",", "Context", ":", "b", ".", "options", ".", "Context", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "sub", ":=", "b", ".", "client", ".", "Subscription", "(", "options", ".", "Queue", ")", "\n\n", "if", "createSubscription", ",", "ok", ":=", "b", ".", "options", ".", "Context", ".", "Value", "(", "createSubscription", "{", "}", ")", ".", "(", "bool", ")", ";", "!", "ok", "||", "createSubscription", "{", "exists", ",", "err", ":=", "sub", ".", "Exists", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "exists", "{", "tt", ":=", "b", ".", "client", ".", "Topic", "(", "topic", ")", "\n", "subb", ",", "err", ":=", "b", ".", "client", ".", "CreateSubscription", "(", "ctx", ",", "options", ".", "Queue", ",", "pubsub", ".", "SubscriptionConfig", "{", "Topic", ":", "tt", ",", "AckDeadline", ":", "time", ".", "Duration", "(", "0", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sub", "=", "subb", "\n", "}", "\n", "}", "\n\n", "subscriber", ":=", "&", "subscriber", "{", "options", ":", "options", ",", "topic", ":", "topic", ",", "exit", ":", "make", "(", "chan", "bool", ")", ",", "sub", ":", "sub", ",", "}", "\n\n", "go", "subscriber", ".", "run", "(", "h", ")", "\n\n", "return", "subscriber", ",", "nil", "\n", "}" ]
// Subscribe registers a subscription to the given topic against the google pubsub api
[ "Subscribe", "registers", "a", "subscription", "to", "the", "given", "topic", "against", "the", "google", "pubsub", "api" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/googlepubsub.go#L171-L214
train
micro/go-plugins
broker/googlepubsub/googlepubsub.go
NewBroker
func NewBroker(opts ...broker.Option) broker.Broker { options := broker.Options{ Context: context.Background(), } for _, o := range opts { o(&options) } // retrieve project id prjID, _ := options.Context.Value(projectIDKey{}).(string) // retrieve client opts cOpts, _ := options.Context.Value(clientOptionKey{}).([]option.ClientOption) // create pubsub client c, err := pubsub.NewClient(context.Background(), prjID, cOpts...) if err != nil { panic(err.Error()) } return &pubsubBroker{ client: c, options: options, } }
go
func NewBroker(opts ...broker.Option) broker.Broker { options := broker.Options{ Context: context.Background(), } for _, o := range opts { o(&options) } // retrieve project id prjID, _ := options.Context.Value(projectIDKey{}).(string) // retrieve client opts cOpts, _ := options.Context.Value(clientOptionKey{}).([]option.ClientOption) // create pubsub client c, err := pubsub.NewClient(context.Background(), prjID, cOpts...) if err != nil { panic(err.Error()) } return &pubsubBroker{ client: c, options: options, } }
[ "func", "NewBroker", "(", "opts", "...", "broker", ".", "Option", ")", "broker", ".", "Broker", "{", "options", ":=", "broker", ".", "Options", "{", "Context", ":", "context", ".", "Background", "(", ")", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n\n", "// retrieve project id", "prjID", ",", "_", ":=", "options", ".", "Context", ".", "Value", "(", "projectIDKey", "{", "}", ")", ".", "(", "string", ")", "\n", "// retrieve client opts", "cOpts", ",", "_", ":=", "options", ".", "Context", ".", "Value", "(", "clientOptionKey", "{", "}", ")", ".", "(", "[", "]", "option", ".", "ClientOption", ")", "\n\n", "// create pubsub client", "c", ",", "err", ":=", "pubsub", ".", "NewClient", "(", "context", ".", "Background", "(", ")", ",", "prjID", ",", "cOpts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "return", "&", "pubsubBroker", "{", "client", ":", "c", ",", "options", ":", "options", ",", "}", "\n", "}" ]
// NewBroker creates a new google pubsub broker
[ "NewBroker", "creates", "a", "new", "google", "pubsub", "broker" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/googlepubsub/googlepubsub.go#L221-L245
train
micro/go-plugins
server/grpc/options.go
Options
func Options(opts ...grpc.ServerOption) server.Option { return func(o *server.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, grpcOptions{}, opts) } }
go
func Options(opts ...grpc.ServerOption) server.Option { return func(o *server.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, grpcOptions{}, opts) } }
[ "func", "Options", "(", "opts", "...", "grpc", ".", "ServerOption", ")", "server", ".", "Option", "{", "return", "func", "(", "o", "*", "server", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "grpcOptions", "{", "}", ",", "opts", ")", "\n", "}", "\n", "}" ]
// Options to be used to configure gRPC options
[ "Options", "to", "be", "used", "to", "configure", "gRPC", "options" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/server/grpc/options.go#L48-L55
train
micro/go-plugins
server/grpc/options.go
MaxMsgSize
func MaxMsgSize(s int) server.Option { return func(o *server.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxMsgSizeKey{}, s) } }
go
func MaxMsgSize(s int) server.Option { return func(o *server.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, maxMsgSizeKey{}, s) } }
[ "func", "MaxMsgSize", "(", "s", "int", ")", "server", ".", "Option", "{", "return", "func", "(", "o", "*", "server", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "maxMsgSizeKey", "{", "}", ",", "s", ")", "\n", "}", "\n", "}" ]
// // MaxMsgSize set the maximum message in bytes the server can receive and // send. Default maximum message size is 4 MB. //
[ "MaxMsgSize", "set", "the", "maximum", "message", "in", "bytes", "the", "server", "can", "receive", "and", "send", ".", "Default", "maximum", "message", "size", "is", "4", "MB", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/server/grpc/options.go#L61-L68
train
micro/go-plugins
selector/shard/shard.go
NewSelector
func NewSelector(keys []string) selector.SelectOption { return selector.WithStrategy(func(services []*registry.Service) selector.Next { return Next(keys, services) }) }
go
func NewSelector(keys []string) selector.SelectOption { return selector.WithStrategy(func(services []*registry.Service) selector.Next { return Next(keys, services) }) }
[ "func", "NewSelector", "(", "keys", "[", "]", "string", ")", "selector", ".", "SelectOption", "{", "return", "selector", ".", "WithStrategy", "(", "func", "(", "services", "[", "]", "*", "registry", ".", "Service", ")", "selector", ".", "Next", "{", "return", "Next", "(", "keys", ",", "services", ")", "\n", "}", ")", "\n", "}" ]
// NewSelector returns a `SelectOption` that directs all request according to the given `keys`.
[ "NewSelector", "returns", "a", "SelectOption", "that", "directs", "all", "request", "according", "to", "the", "given", "keys", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/selector/shard/shard.go#L27-L31
train
micro/go-plugins
selector/shard/shard.go
Next
func Next(keys []string, services []*registry.Service) selector.Next { possibleNodes, scores := ScoreNodes(keys, services) return func() (*registry.Node, error) { var best uint64 pos := -1 // Find the best scoring node from those available. for i, score := range scores { if score >= best && possibleNodes[i] != nil { best = score pos = i } } if pos < 0 { // There was no node found. return nil, selector.ErrNoneAvailable } // Choose this node and set it's score to zero to stop it being selected again. node := possibleNodes[pos] possibleNodes[pos] = nil scores[pos] = 0 return node, nil } }
go
func Next(keys []string, services []*registry.Service) selector.Next { possibleNodes, scores := ScoreNodes(keys, services) return func() (*registry.Node, error) { var best uint64 pos := -1 // Find the best scoring node from those available. for i, score := range scores { if score >= best && possibleNodes[i] != nil { best = score pos = i } } if pos < 0 { // There was no node found. return nil, selector.ErrNoneAvailable } // Choose this node and set it's score to zero to stop it being selected again. node := possibleNodes[pos] possibleNodes[pos] = nil scores[pos] = 0 return node, nil } }
[ "func", "Next", "(", "keys", "[", "]", "string", ",", "services", "[", "]", "*", "registry", ".", "Service", ")", "selector", ".", "Next", "{", "possibleNodes", ",", "scores", ":=", "ScoreNodes", "(", "keys", ",", "services", ")", "\n\n", "return", "func", "(", ")", "(", "*", "registry", ".", "Node", ",", "error", ")", "{", "var", "best", "uint64", "\n", "pos", ":=", "-", "1", "\n\n", "// Find the best scoring node from those available.", "for", "i", ",", "score", ":=", "range", "scores", "{", "if", "score", ">=", "best", "&&", "possibleNodes", "[", "i", "]", "!=", "nil", "{", "best", "=", "score", "\n", "pos", "=", "i", "\n", "}", "\n", "}", "\n\n", "if", "pos", "<", "0", "{", "// There was no node found.", "return", "nil", ",", "selector", ".", "ErrNoneAvailable", "\n", "}", "\n\n", "// Choose this node and set it's score to zero to stop it being selected again.", "node", ":=", "possibleNodes", "[", "pos", "]", "\n", "possibleNodes", "[", "pos", "]", "=", "nil", "\n", "scores", "[", "pos", "]", "=", "0", "\n", "return", "node", ",", "nil", "\n", "}", "\n", "}" ]
// Next returns a `Next` function which returns the next highest scoring node.
[ "Next", "returns", "a", "Next", "function", "which", "returns", "the", "next", "highest", "scoring", "node", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/selector/shard/shard.go#L34-L60
train
micro/go-plugins
selector/shard/shard.go
ScoreNodes
func ScoreNodes(keys []string, services []*registry.Service) (possibleNodes []*registry.Node, scores []uint64) { // Generate a base hashing key based off the supplied keys values. key := highwayhash.Sum([]byte(strings.Join(keys, ":")), zeroKey[:]) // Get all the possible nodes for the services, and assign a hash-based score to each of them. for _, s := range services { for _, n := range s.Nodes { // Use the base key from above to calculate a derivative 64 bit hash number based off the instance ID. score := highwayhash.Sum64([]byte(n.Id), key[:]) scores = append(scores, score) possibleNodes = append(possibleNodes, n) } } return }
go
func ScoreNodes(keys []string, services []*registry.Service) (possibleNodes []*registry.Node, scores []uint64) { // Generate a base hashing key based off the supplied keys values. key := highwayhash.Sum([]byte(strings.Join(keys, ":")), zeroKey[:]) // Get all the possible nodes for the services, and assign a hash-based score to each of them. for _, s := range services { for _, n := range s.Nodes { // Use the base key from above to calculate a derivative 64 bit hash number based off the instance ID. score := highwayhash.Sum64([]byte(n.Id), key[:]) scores = append(scores, score) possibleNodes = append(possibleNodes, n) } } return }
[ "func", "ScoreNodes", "(", "keys", "[", "]", "string", ",", "services", "[", "]", "*", "registry", ".", "Service", ")", "(", "possibleNodes", "[", "]", "*", "registry", ".", "Node", ",", "scores", "[", "]", "uint64", ")", "{", "// Generate a base hashing key based off the supplied keys values.", "key", ":=", "highwayhash", ".", "Sum", "(", "[", "]", "byte", "(", "strings", ".", "Join", "(", "keys", ",", "\"", "\"", ")", ")", ",", "zeroKey", "[", ":", "]", ")", "\n\n", "// Get all the possible nodes for the services, and assign a hash-based score to each of them.", "for", "_", ",", "s", ":=", "range", "services", "{", "for", "_", ",", "n", ":=", "range", "s", ".", "Nodes", "{", "// Use the base key from above to calculate a derivative 64 bit hash number based off the instance ID.", "score", ":=", "highwayhash", ".", "Sum64", "(", "[", "]", "byte", "(", "n", ".", "Id", ")", ",", "key", "[", ":", "]", ")", "\n", "scores", "=", "append", "(", "scores", ",", "score", ")", "\n", "possibleNodes", "=", "append", "(", "possibleNodes", ",", "n", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// ScoreNodes returns a score for each node found in the given services.
[ "ScoreNodes", "returns", "a", "score", "for", "each", "node", "found", "in", "the", "given", "services", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/selector/shard/shard.go#L63-L77
train
micro/go-plugins
codec/msgpackrpc/codec.go
ReadHeader
func (c *msgpackCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error { c.mt = mt switch mt { case codec.Request: var h Request if err := msgp.Decode(c.rwc, &h); err != nil { return err } c.body = h.hasBody m.Id = h.ID m.Endpoint = h.Method case codec.Response: var h Response if err := msgp.Decode(c.rwc, &h); err != nil { return err } c.body = h.hasBody m.Id = h.ID m.Error = h.Error case codec.Publication: var h Notification if err := msgp.Decode(c.rwc, &h); err != nil { return err } c.body = h.hasBody m.Endpoint = h.Method default: return errors.New("Unrecognized message type") } return nil }
go
func (c *msgpackCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error { c.mt = mt switch mt { case codec.Request: var h Request if err := msgp.Decode(c.rwc, &h); err != nil { return err } c.body = h.hasBody m.Id = h.ID m.Endpoint = h.Method case codec.Response: var h Response if err := msgp.Decode(c.rwc, &h); err != nil { return err } c.body = h.hasBody m.Id = h.ID m.Error = h.Error case codec.Publication: var h Notification if err := msgp.Decode(c.rwc, &h); err != nil { return err } c.body = h.hasBody m.Endpoint = h.Method default: return errors.New("Unrecognized message type") } return nil }
[ "func", "(", "c", "*", "msgpackCodec", ")", "ReadHeader", "(", "m", "*", "codec", ".", "Message", ",", "mt", "codec", ".", "MessageType", ")", "error", "{", "c", ".", "mt", "=", "mt", "\n\n", "switch", "mt", "{", "case", "codec", ".", "Request", ":", "var", "h", "Request", "\n\n", "if", "err", ":=", "msgp", ".", "Decode", "(", "c", ".", "rwc", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "body", "=", "h", ".", "hasBody", "\n", "m", ".", "Id", "=", "h", ".", "ID", "\n", "m", ".", "Endpoint", "=", "h", ".", "Method", "\n\n", "case", "codec", ".", "Response", ":", "var", "h", "Response", "\n\n", "if", "err", ":=", "msgp", ".", "Decode", "(", "c", ".", "rwc", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "body", "=", "h", ".", "hasBody", "\n", "m", ".", "Id", "=", "h", ".", "ID", "\n", "m", ".", "Error", "=", "h", ".", "Error", "\n\n", "case", "codec", ".", "Publication", ":", "var", "h", "Notification", "\n\n", "if", "err", ":=", "msgp", ".", "Decode", "(", "c", ".", "rwc", ",", "&", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "body", "=", "h", ".", "hasBody", "\n", "m", ".", "Endpoint", "=", "h", ".", "Method", "\n\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ReadHeader reads the header from the wire.
[ "ReadHeader", "reads", "the", "header", "from", "the", "wire", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/msgpackrpc/codec.go#L27-L68
train
micro/go-plugins
codec/msgpackrpc/codec.go
ReadBody
func (c *msgpackCodec) ReadBody(v interface{}) error { if !c.body { return nil } r := msgp.NewReader(c.rwc) // Body is present, but no value to decode into. if v == nil { return r.Skip() } switch c.mt { case codec.Request, codec.Response, codec.Publication: return decodeBody(r, v) default: return fmt.Errorf("Unrecognized message type: %v", c.mt) } }
go
func (c *msgpackCodec) ReadBody(v interface{}) error { if !c.body { return nil } r := msgp.NewReader(c.rwc) // Body is present, but no value to decode into. if v == nil { return r.Skip() } switch c.mt { case codec.Request, codec.Response, codec.Publication: return decodeBody(r, v) default: return fmt.Errorf("Unrecognized message type: %v", c.mt) } }
[ "func", "(", "c", "*", "msgpackCodec", ")", "ReadBody", "(", "v", "interface", "{", "}", ")", "error", "{", "if", "!", "c", ".", "body", "{", "return", "nil", "\n", "}", "\n\n", "r", ":=", "msgp", ".", "NewReader", "(", "c", ".", "rwc", ")", "\n\n", "// Body is present, but no value to decode into.", "if", "v", "==", "nil", "{", "return", "r", ".", "Skip", "(", ")", "\n", "}", "\n\n", "switch", "c", ".", "mt", "{", "case", "codec", ".", "Request", ",", "codec", ".", "Response", ",", "codec", ".", "Publication", ":", "return", "decodeBody", "(", "r", ",", "v", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "mt", ")", "\n", "}", "\n", "}" ]
// ReadBody reads the body of the message. It is assumed the value being // decoded into is a satisfies the msgp.Decodable interface.
[ "ReadBody", "reads", "the", "body", "of", "the", "message", ".", "It", "is", "assumed", "the", "value", "being", "decoded", "into", "is", "a", "satisfies", "the", "msgp", ".", "Decodable", "interface", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/msgpackrpc/codec.go#L72-L90
train
micro/go-plugins
codec/msgpackrpc/codec.go
Write
func (c *msgpackCodec) Write(m *codec.Message, b interface{}) error { switch m.Type { case codec.Request: h := Request{ ID: m.Id, Method: m.Endpoint, Body: b, } return msgp.Encode(c.rwc, &h) case codec.Response: h := Response{ ID: m.Id, Body: b, } h.Error = m.Error return msgp.Encode(c.rwc, &h) case codec.Publication: h := Notification{ Method: m.Endpoint, Body: b, } return msgp.Encode(c.rwc, &h) default: return fmt.Errorf("Unrecognized message type: %v", m.Type) } }
go
func (c *msgpackCodec) Write(m *codec.Message, b interface{}) error { switch m.Type { case codec.Request: h := Request{ ID: m.Id, Method: m.Endpoint, Body: b, } return msgp.Encode(c.rwc, &h) case codec.Response: h := Response{ ID: m.Id, Body: b, } h.Error = m.Error return msgp.Encode(c.rwc, &h) case codec.Publication: h := Notification{ Method: m.Endpoint, Body: b, } return msgp.Encode(c.rwc, &h) default: return fmt.Errorf("Unrecognized message type: %v", m.Type) } }
[ "func", "(", "c", "*", "msgpackCodec", ")", "Write", "(", "m", "*", "codec", ".", "Message", ",", "b", "interface", "{", "}", ")", "error", "{", "switch", "m", ".", "Type", "{", "case", "codec", ".", "Request", ":", "h", ":=", "Request", "{", "ID", ":", "m", ".", "Id", ",", "Method", ":", "m", ".", "Endpoint", ",", "Body", ":", "b", ",", "}", "\n\n", "return", "msgp", ".", "Encode", "(", "c", ".", "rwc", ",", "&", "h", ")", "\n\n", "case", "codec", ".", "Response", ":", "h", ":=", "Response", "{", "ID", ":", "m", ".", "Id", ",", "Body", ":", "b", ",", "}", "\n\n", "h", ".", "Error", "=", "m", ".", "Error", "\n\n", "return", "msgp", ".", "Encode", "(", "c", ".", "rwc", ",", "&", "h", ")", "\n\n", "case", "codec", ".", "Publication", ":", "h", ":=", "Notification", "{", "Method", ":", "m", ".", "Endpoint", ",", "Body", ":", "b", ",", "}", "\n\n", "return", "msgp", ".", "Encode", "(", "c", ".", "rwc", ",", "&", "h", ")", "\n\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "m", ".", "Type", ")", "\n", "}", "\n", "}" ]
// Write writes a message to the wire which contains the header followed by the body. // The body is assumed to satisfy the msgp.Encodable interface.
[ "Write", "writes", "a", "message", "to", "the", "wire", "which", "contains", "the", "header", "followed", "by", "the", "body", ".", "The", "body", "is", "assumed", "to", "satisfy", "the", "msgp", ".", "Encodable", "interface", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/msgpackrpc/codec.go#L94-L126
train
micro/go-plugins
codec/jsonrpc2/errors.go
NewError
func NewError(code int, message string) *Error { return &Error{Code: code, Message: message} }
go
func NewError(code int, message string) *Error { return &Error{Code: code, Message: message} }
[ "func", "NewError", "(", "code", "int", ",", "message", "string", ")", "*", "Error", "{", "return", "&", "Error", "{", "Code", ":", "code", ",", "Message", ":", "message", "}", "\n", "}" ]
// NewError returns an Error with given code and message.
[ "NewError", "returns", "an", "Error", "with", "given", "code", "and", "message", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/jsonrpc2/errors.go#L28-L30
train
micro/go-plugins
codec/jsonrpc2/errors.go
newError
func newError(message string) *Error { switch { case strings.HasPrefix(message, "rpc: service/method request ill-formed"): return NewError(errMethod.Code, message) case strings.HasPrefix(message, "rpc: can't find service"): return NewError(errMethod.Code, message) case strings.HasPrefix(message, "rpc: can't find method"): return NewError(errMethod.Code, message) default: return NewError(errServer.Code, message) } }
go
func newError(message string) *Error { switch { case strings.HasPrefix(message, "rpc: service/method request ill-formed"): return NewError(errMethod.Code, message) case strings.HasPrefix(message, "rpc: can't find service"): return NewError(errMethod.Code, message) case strings.HasPrefix(message, "rpc: can't find method"): return NewError(errMethod.Code, message) default: return NewError(errServer.Code, message) } }
[ "func", "newError", "(", "message", "string", ")", "*", "Error", "{", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "message", ",", "\"", "\"", ")", ":", "return", "NewError", "(", "errMethod", ".", "Code", ",", "message", ")", "\n", "case", "strings", ".", "HasPrefix", "(", "message", ",", "\"", "\"", ")", ":", "return", "NewError", "(", "errMethod", ".", "Code", ",", "message", ")", "\n", "case", "strings", ".", "HasPrefix", "(", "message", ",", "\"", "\"", ")", ":", "return", "NewError", "(", "errMethod", ".", "Code", ",", "message", ")", "\n", "default", ":", "return", "NewError", "(", "errServer", ".", "Code", ",", "message", ")", "\n", "}", "\n", "}" ]
// newError returns an Error with auto-detected code for given message.
[ "newError", "returns", "an", "Error", "with", "auto", "-", "detected", "code", "for", "given", "message", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/jsonrpc2/errors.go#L33-L44
train
micro/go-plugins
codec/jsonrpc2/errors.go
Error
func (e *Error) Error() string { buf, err := json.Marshal(e) if err != nil { msg, err := json.Marshal(err.Error()) if err != nil { msg = []byte(`"` + errServerError.Message + `"`) } return fmt.Sprintf(`{"code":%d,"message":%s}`, errServerError.Code, string(msg)) } return string(buf) }
go
func (e *Error) Error() string { buf, err := json.Marshal(e) if err != nil { msg, err := json.Marshal(err.Error()) if err != nil { msg = []byte(`"` + errServerError.Message + `"`) } return fmt.Sprintf(`{"code":%d,"message":%s}`, errServerError.Code, string(msg)) } return string(buf) }
[ "func", "(", "e", "*", "Error", ")", "Error", "(", ")", "string", "{", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "e", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ",", "err", ":=", "json", ".", "Marshal", "(", "err", ".", "Error", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "msg", "=", "[", "]", "byte", "(", "`\"`", "+", "errServerError", ".", "Message", "+", "`\"`", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "`{\"code\":%d,\"message\":%s}`", ",", "errServerError", ".", "Code", ",", "string", "(", "msg", ")", ")", "\n", "}", "\n", "return", "string", "(", "buf", ")", "\n", "}" ]
// Error returns JSON representation of Error.
[ "Error", "returns", "JSON", "representation", "of", "Error", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/codec/jsonrpc2/errors.go#L82-L92
train
micro/go-plugins
registry/kubernetes/kubernetes.go
serviceName
func serviceName(name string) string { aname := make([]byte, len(name)) for i, r := range []byte(name) { if !labelRe.Match([]byte{r}) { aname[i] = '_' continue } aname[i] = r } return string(aname) }
go
func serviceName(name string) string { aname := make([]byte, len(name)) for i, r := range []byte(name) { if !labelRe.Match([]byte{r}) { aname[i] = '_' continue } aname[i] = r } return string(aname) }
[ "func", "serviceName", "(", "name", "string", ")", "string", "{", "aname", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "name", ")", ")", "\n\n", "for", "i", ",", "r", ":=", "range", "[", "]", "byte", "(", "name", ")", "{", "if", "!", "labelRe", ".", "Match", "(", "[", "]", "byte", "{", "r", "}", ")", "{", "aname", "[", "i", "]", "=", "'_'", "\n", "continue", "\n", "}", "\n", "aname", "[", "i", "]", "=", "r", "\n", "}", "\n\n", "return", "string", "(", "aname", ")", "\n", "}" ]
// serviceName generates a valid service name for k8s labels
[ "serviceName", "generates", "a", "valid", "service", "name", "for", "k8s", "labels" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L84-L96
train
micro/go-plugins
registry/kubernetes/kubernetes.go
Init
func (c *kregistry) Init(opts ...registry.Option) error { return configure(c, opts...) }
go
func (c *kregistry) Init(opts ...registry.Option) error { return configure(c, opts...) }
[ "func", "(", "c", "*", "kregistry", ")", "Init", "(", "opts", "...", "registry", ".", "Option", ")", "error", "{", "return", "configure", "(", "c", ",", "opts", "...", ")", "\n", "}" ]
// Init allows reconfig of options
[ "Init", "allows", "reconfig", "of", "options" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L99-L101
train
micro/go-plugins
registry/kubernetes/kubernetes.go
Register
func (c *kregistry) Register(s *registry.Service, opts ...registry.RegisterOption) error { if len(s.Nodes) == 0 { return errors.New("you must register at least one node") } // TODO: grab podname from somewhere better than this. podName := os.Getenv("HOSTNAME") svcName := s.Name // encode micro service b, err := json.Marshal(s) if err != nil { return err } svc := string(b) pod := &client.Pod{ Metadata: &client.Meta{ Labels: map[string]*string{ labelTypeKey: &labelTypeValueService, svcSelectorPrefix + serviceName(svcName): &svcSelectorValue, }, Annotations: map[string]*string{ annotationServiceKeyPrefix + serviceName(svcName): &svc, }, }, } if _, err := c.client.UpdatePod(podName, pod); err != nil { return err } return nil }
go
func (c *kregistry) Register(s *registry.Service, opts ...registry.RegisterOption) error { if len(s.Nodes) == 0 { return errors.New("you must register at least one node") } // TODO: grab podname from somewhere better than this. podName := os.Getenv("HOSTNAME") svcName := s.Name // encode micro service b, err := json.Marshal(s) if err != nil { return err } svc := string(b) pod := &client.Pod{ Metadata: &client.Meta{ Labels: map[string]*string{ labelTypeKey: &labelTypeValueService, svcSelectorPrefix + serviceName(svcName): &svcSelectorValue, }, Annotations: map[string]*string{ annotationServiceKeyPrefix + serviceName(svcName): &svc, }, }, } if _, err := c.client.UpdatePod(podName, pod); err != nil { return err } return nil }
[ "func", "(", "c", "*", "kregistry", ")", "Register", "(", "s", "*", "registry", ".", "Service", ",", "opts", "...", "registry", ".", "RegisterOption", ")", "error", "{", "if", "len", "(", "s", ".", "Nodes", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// TODO: grab podname from somewhere better than this.", "podName", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "svcName", ":=", "s", ".", "Name", "\n\n", "// encode micro service", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "svc", ":=", "string", "(", "b", ")", "\n\n", "pod", ":=", "&", "client", ".", "Pod", "{", "Metadata", ":", "&", "client", ".", "Meta", "{", "Labels", ":", "map", "[", "string", "]", "*", "string", "{", "labelTypeKey", ":", "&", "labelTypeValueService", ",", "svcSelectorPrefix", "+", "serviceName", "(", "svcName", ")", ":", "&", "svcSelectorValue", ",", "}", ",", "Annotations", ":", "map", "[", "string", "]", "*", "string", "{", "annotationServiceKeyPrefix", "+", "serviceName", "(", "svcName", ")", ":", "&", "svc", ",", "}", ",", "}", ",", "}", "\n\n", "if", "_", ",", "err", ":=", "c", ".", "client", ".", "UpdatePod", "(", "podName", ",", "pod", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n\n", "}" ]
// Register sets a service selector label and an annotation with a // serialised version of the service passed in.
[ "Register", "sets", "a", "service", "selector", "label", "and", "an", "annotation", "with", "a", "serialised", "version", "of", "the", "service", "passed", "in", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L110-L144
train
micro/go-plugins
registry/kubernetes/kubernetes.go
Deregister
func (c *kregistry) Deregister(s *registry.Service) error { if len(s.Nodes) == 0 { return errors.New("you must deregister at least one node") } // TODO: grab podname from somewhere better than this. podName := os.Getenv("HOSTNAME") svcName := s.Name pod := &client.Pod{ Metadata: &client.Meta{ Labels: map[string]*string{ svcSelectorPrefix + serviceName(svcName): nil, }, Annotations: map[string]*string{ annotationServiceKeyPrefix + serviceName(svcName): nil, }, }, } if _, err := c.client.UpdatePod(podName, pod); err != nil { return err } return nil }
go
func (c *kregistry) Deregister(s *registry.Service) error { if len(s.Nodes) == 0 { return errors.New("you must deregister at least one node") } // TODO: grab podname from somewhere better than this. podName := os.Getenv("HOSTNAME") svcName := s.Name pod := &client.Pod{ Metadata: &client.Meta{ Labels: map[string]*string{ svcSelectorPrefix + serviceName(svcName): nil, }, Annotations: map[string]*string{ annotationServiceKeyPrefix + serviceName(svcName): nil, }, }, } if _, err := c.client.UpdatePod(podName, pod); err != nil { return err } return nil }
[ "func", "(", "c", "*", "kregistry", ")", "Deregister", "(", "s", "*", "registry", ".", "Service", ")", "error", "{", "if", "len", "(", "s", ".", "Nodes", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// TODO: grab podname from somewhere better than this.", "podName", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "svcName", ":=", "s", ".", "Name", "\n\n", "pod", ":=", "&", "client", ".", "Pod", "{", "Metadata", ":", "&", "client", ".", "Meta", "{", "Labels", ":", "map", "[", "string", "]", "*", "string", "{", "svcSelectorPrefix", "+", "serviceName", "(", "svcName", ")", ":", "nil", ",", "}", ",", "Annotations", ":", "map", "[", "string", "]", "*", "string", "{", "annotationServiceKeyPrefix", "+", "serviceName", "(", "svcName", ")", ":", "nil", ",", "}", ",", "}", ",", "}", "\n\n", "if", "_", ",", "err", ":=", "c", ".", "client", ".", "UpdatePod", "(", "podName", ",", "pod", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n\n", "}" ]
// Deregister nils out any things set in Register
[ "Deregister", "nils", "out", "any", "things", "set", "in", "Register" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L147-L173
train
micro/go-plugins
registry/kubernetes/kubernetes.go
GetService
func (c *kregistry) GetService(name string) ([]*registry.Service, error) { pods, err := c.client.ListPods(map[string]string{ svcSelectorPrefix + serviceName(name): svcSelectorValue, }) if err != nil { return nil, err } if len(pods.Items) == 0 { return nil, registry.ErrNotFound } // svcs mapped by version svcs := make(map[string]*registry.Service) // loop through items for _, pod := range pods.Items { if pod.Status.Phase != podRunning { continue } // get serialised service from annotation svcStr, ok := pod.Metadata.Annotations[annotationServiceKeyPrefix+serviceName(name)] if !ok { continue } // unmarshal service string var svc registry.Service err := json.Unmarshal([]byte(*svcStr), &svc) if err != nil { return nil, fmt.Errorf("could not unmarshal service '%s' from pod annotation", name) } // merge up pod service & ip with versioned service. vs, ok := svcs[svc.Version] if !ok { svcs[svc.Version] = &svc continue } vs.Nodes = append(vs.Nodes, svc.Nodes...) } var list []*registry.Service for _, val := range svcs { list = append(list, val) } return list, nil }
go
func (c *kregistry) GetService(name string) ([]*registry.Service, error) { pods, err := c.client.ListPods(map[string]string{ svcSelectorPrefix + serviceName(name): svcSelectorValue, }) if err != nil { return nil, err } if len(pods.Items) == 0 { return nil, registry.ErrNotFound } // svcs mapped by version svcs := make(map[string]*registry.Service) // loop through items for _, pod := range pods.Items { if pod.Status.Phase != podRunning { continue } // get serialised service from annotation svcStr, ok := pod.Metadata.Annotations[annotationServiceKeyPrefix+serviceName(name)] if !ok { continue } // unmarshal service string var svc registry.Service err := json.Unmarshal([]byte(*svcStr), &svc) if err != nil { return nil, fmt.Errorf("could not unmarshal service '%s' from pod annotation", name) } // merge up pod service & ip with versioned service. vs, ok := svcs[svc.Version] if !ok { svcs[svc.Version] = &svc continue } vs.Nodes = append(vs.Nodes, svc.Nodes...) } var list []*registry.Service for _, val := range svcs { list = append(list, val) } return list, nil }
[ "func", "(", "c", "*", "kregistry", ")", "GetService", "(", "name", "string", ")", "(", "[", "]", "*", "registry", ".", "Service", ",", "error", ")", "{", "pods", ",", "err", ":=", "c", ".", "client", ".", "ListPods", "(", "map", "[", "string", "]", "string", "{", "svcSelectorPrefix", "+", "serviceName", "(", "name", ")", ":", "svcSelectorValue", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "pods", ".", "Items", ")", "==", "0", "{", "return", "nil", ",", "registry", ".", "ErrNotFound", "\n", "}", "\n\n", "// svcs mapped by version", "svcs", ":=", "make", "(", "map", "[", "string", "]", "*", "registry", ".", "Service", ")", "\n\n", "// loop through items", "for", "_", ",", "pod", ":=", "range", "pods", ".", "Items", "{", "if", "pod", ".", "Status", ".", "Phase", "!=", "podRunning", "{", "continue", "\n", "}", "\n", "// get serialised service from annotation", "svcStr", ",", "ok", ":=", "pod", ".", "Metadata", ".", "Annotations", "[", "annotationServiceKeyPrefix", "+", "serviceName", "(", "name", ")", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "// unmarshal service string", "var", "svc", "registry", ".", "Service", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "*", "svcStr", ")", ",", "&", "svc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "// merge up pod service & ip with versioned service.", "vs", ",", "ok", ":=", "svcs", "[", "svc", ".", "Version", "]", "\n", "if", "!", "ok", "{", "svcs", "[", "svc", ".", "Version", "]", "=", "&", "svc", "\n", "continue", "\n", "}", "\n\n", "vs", ".", "Nodes", "=", "append", "(", "vs", ".", "Nodes", ",", "svc", ".", "Nodes", "...", ")", "\n", "}", "\n\n", "var", "list", "[", "]", "*", "registry", ".", "Service", "\n", "for", "_", ",", "val", ":=", "range", "svcs", "{", "list", "=", "append", "(", "list", ",", "val", ")", "\n", "}", "\n", "return", "list", ",", "nil", "\n", "}" ]
// GetService will get all the pods with the given service selector, // and build services from the annotations.
[ "GetService", "will", "get", "all", "the", "pods", "with", "the", "given", "service", "selector", "and", "build", "services", "from", "the", "annotations", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L177-L225
train
micro/go-plugins
registry/kubernetes/kubernetes.go
ListServices
func (c *kregistry) ListServices() ([]*registry.Service, error) { pods, err := c.client.ListPods(podSelector) if err != nil { return nil, err } // svcs mapped by name svcs := make(map[string]bool) for _, pod := range pods.Items { if pod.Status.Phase != podRunning { continue } for k, v := range pod.Metadata.Annotations { if !strings.HasPrefix(k, annotationServiceKeyPrefix) { continue } // we have to unmarshal the annotation itself since the // key is encoded to match the regex restriction. var svc registry.Service if err := json.Unmarshal([]byte(*v), &svc); err != nil { continue } svcs[svc.Name] = true } } var list []*registry.Service for val := range svcs { list = append(list, &registry.Service{Name: val}) } return list, nil }
go
func (c *kregistry) ListServices() ([]*registry.Service, error) { pods, err := c.client.ListPods(podSelector) if err != nil { return nil, err } // svcs mapped by name svcs := make(map[string]bool) for _, pod := range pods.Items { if pod.Status.Phase != podRunning { continue } for k, v := range pod.Metadata.Annotations { if !strings.HasPrefix(k, annotationServiceKeyPrefix) { continue } // we have to unmarshal the annotation itself since the // key is encoded to match the regex restriction. var svc registry.Service if err := json.Unmarshal([]byte(*v), &svc); err != nil { continue } svcs[svc.Name] = true } } var list []*registry.Service for val := range svcs { list = append(list, &registry.Service{Name: val}) } return list, nil }
[ "func", "(", "c", "*", "kregistry", ")", "ListServices", "(", ")", "(", "[", "]", "*", "registry", ".", "Service", ",", "error", ")", "{", "pods", ",", "err", ":=", "c", ".", "client", ".", "ListPods", "(", "podSelector", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// svcs mapped by name", "svcs", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "for", "_", ",", "pod", ":=", "range", "pods", ".", "Items", "{", "if", "pod", ".", "Status", ".", "Phase", "!=", "podRunning", "{", "continue", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "pod", ".", "Metadata", ".", "Annotations", "{", "if", "!", "strings", ".", "HasPrefix", "(", "k", ",", "annotationServiceKeyPrefix", ")", "{", "continue", "\n", "}", "\n\n", "// we have to unmarshal the annotation itself since the", "// key is encoded to match the regex restriction.", "var", "svc", "registry", ".", "Service", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "*", "v", ")", ",", "&", "svc", ")", ";", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "svcs", "[", "svc", ".", "Name", "]", "=", "true", "\n", "}", "\n", "}", "\n\n", "var", "list", "[", "]", "*", "registry", ".", "Service", "\n", "for", "val", ":=", "range", "svcs", "{", "list", "=", "append", "(", "list", ",", "&", "registry", ".", "Service", "{", "Name", ":", "val", "}", ")", "\n", "}", "\n", "return", "list", ",", "nil", "\n", "}" ]
// ListServices will list all the service names
[ "ListServices", "will", "list", "all", "the", "service", "names" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L228-L261
train
micro/go-plugins
registry/kubernetes/kubernetes.go
Watch
func (c *kregistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) { return newWatcher(c, opts...) }
go
func (c *kregistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) { return newWatcher(c, opts...) }
[ "func", "(", "c", "*", "kregistry", ")", "Watch", "(", "opts", "...", "registry", ".", "WatchOption", ")", "(", "registry", ".", "Watcher", ",", "error", ")", "{", "return", "newWatcher", "(", "c", ",", "opts", "...", ")", "\n", "}" ]
// Watch returns a kubernetes watcher
[ "Watch", "returns", "a", "kubernetes", "watcher" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L264-L266
train
micro/go-plugins
registry/kubernetes/kubernetes.go
NewRegistry
func NewRegistry(opts ...registry.Option) registry.Registry { k := &kregistry{ options: registry.Options{}, } configure(k, opts...) return k }
go
func NewRegistry(opts ...registry.Option) registry.Registry { k := &kregistry{ options: registry.Options{}, } configure(k, opts...) return k }
[ "func", "NewRegistry", "(", "opts", "...", "registry", ".", "Option", ")", "registry", ".", "Registry", "{", "k", ":=", "&", "kregistry", "{", "options", ":", "registry", ".", "Options", "{", "}", ",", "}", "\n", "configure", "(", "k", ",", "opts", "...", ")", "\n", "return", "k", "\n", "}" ]
// NewRegistry creates a kubernetes registry
[ "NewRegistry", "creates", "a", "kubernetes", "registry" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/kubernetes.go#L273-L279
train
micro/go-plugins
micro/bot/input/discord/discord.go
CheckPrefixFactory
func CheckPrefixFactory(prefixes ...string) func(string) (string, bool) { return func(content string) (string, bool) { for _, prefix := range prefixes { if strings.HasPrefix(content, prefix) { return strings.TrimPrefix(content, prefix), true } } return "", false } }
go
func CheckPrefixFactory(prefixes ...string) func(string) (string, bool) { return func(content string) (string, bool) { for _, prefix := range prefixes { if strings.HasPrefix(content, prefix) { return strings.TrimPrefix(content, prefix), true } } return "", false } }
[ "func", "CheckPrefixFactory", "(", "prefixes", "...", "string", ")", "func", "(", "string", ")", "(", "string", ",", "bool", ")", "{", "return", "func", "(", "content", "string", ")", "(", "string", ",", "bool", ")", "{", "for", "_", ",", "prefix", ":=", "range", "prefixes", "{", "if", "strings", ".", "HasPrefix", "(", "content", ",", "prefix", ")", "{", "return", "strings", ".", "TrimPrefix", "(", "content", ",", "prefix", ")", ",", "true", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "}" ]
// CheckPrefixFactory Creates a prefix checking function and stuff.
[ "CheckPrefixFactory", "Creates", "a", "prefix", "checking", "function", "and", "stuff", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/bot/input/discord/discord.go#L141-L150
train
micro/go-plugins
registry/kubernetes/client/watch/body.go
Stop
func (wr *bodyWatcher) Stop() { select { case <-wr.stop: return default: close(wr.stop) close(wr.results) } }
go
func (wr *bodyWatcher) Stop() { select { case <-wr.stop: return default: close(wr.stop) close(wr.results) } }
[ "func", "(", "wr", "*", "bodyWatcher", ")", "Stop", "(", ")", "{", "select", "{", "case", "<-", "wr", ".", "stop", ":", "return", "\n", "default", ":", "close", "(", "wr", ".", "stop", ")", "\n", "close", "(", "wr", ".", "results", ")", "\n", "}", "\n", "}" ]
// Stop cancels the request
[ "Stop", "cancels", "the", "request" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/watch/body.go#L24-L32
train
micro/go-plugins
registry/kubernetes/client/watch/body.go
NewBodyWatcher
func NewBodyWatcher(req *http.Request, client *http.Client) (Watch, error) { stop := make(chan struct{}) req.Cancel = stop res, err := client.Do(req) if err != nil { return nil, err } wr := &bodyWatcher{ results: make(chan Event), stop: stop, req: req, res: res, } go wr.stream() return wr, nil }
go
func NewBodyWatcher(req *http.Request, client *http.Client) (Watch, error) { stop := make(chan struct{}) req.Cancel = stop res, err := client.Do(req) if err != nil { return nil, err } wr := &bodyWatcher{ results: make(chan Event), stop: stop, req: req, res: res, } go wr.stream() return wr, nil }
[ "func", "NewBodyWatcher", "(", "req", "*", "http", ".", "Request", ",", "client", "*", "http", ".", "Client", ")", "(", "Watch", ",", "error", ")", "{", "stop", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "req", ".", "Cancel", "=", "stop", "\n\n", "res", ",", "err", ":=", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "wr", ":=", "&", "bodyWatcher", "{", "results", ":", "make", "(", "chan", "Event", ")", ",", "stop", ":", "stop", ",", "req", ":", "req", ",", "res", ":", "res", ",", "}", "\n\n", "go", "wr", ".", "stream", "(", ")", "\n", "return", "wr", ",", "nil", "\n", "}" ]
// NewBodyWatcher creates a k8s body watcher for // a given http request
[ "NewBodyWatcher", "creates", "a", "k8s", "body", "watcher", "for", "a", "given", "http", "request" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/watch/body.go#L74-L92
train
micro/go-plugins
broker/gocloud/gocloud.go
NewBroker
func NewBroker(opts ...broker.Option) broker.Broker { options := broker.Options{ Context: context.Background(), } for _, o := range opts { o(&options) } var openTopic topicOpener var openSub subOpener var err error if projID, ok := options.Context.Value(gcpProjectIDKey{}).(gcp.ProjectID); ok { ts := options.Context.Value(gcpTokenSourceKey{}).(gcp.TokenSource) openTopic, openSub, err = setupGCP(options.Context, projID, ts) } else if rurl, ok := options.Context.Value(rabbitURLKey{}).(string); ok { openTopic, openSub, err = setupRabbit(options.Context, rurl) } else { openTopic, openSub, err = setupMem() } if err != nil { return &pubsubBroker{err: err} } return &pubsubBroker{ options: options, openTopic: openTopic, openSub: openSub, topics: map[string]*pubsub.Topic{}, subs: map[string]*pubsub.Subscription{}, } }
go
func NewBroker(opts ...broker.Option) broker.Broker { options := broker.Options{ Context: context.Background(), } for _, o := range opts { o(&options) } var openTopic topicOpener var openSub subOpener var err error if projID, ok := options.Context.Value(gcpProjectIDKey{}).(gcp.ProjectID); ok { ts := options.Context.Value(gcpTokenSourceKey{}).(gcp.TokenSource) openTopic, openSub, err = setupGCP(options.Context, projID, ts) } else if rurl, ok := options.Context.Value(rabbitURLKey{}).(string); ok { openTopic, openSub, err = setupRabbit(options.Context, rurl) } else { openTopic, openSub, err = setupMem() } if err != nil { return &pubsubBroker{err: err} } return &pubsubBroker{ options: options, openTopic: openTopic, openSub: openSub, topics: map[string]*pubsub.Topic{}, subs: map[string]*pubsub.Subscription{}, } }
[ "func", "NewBroker", "(", "opts", "...", "broker", ".", "Option", ")", "broker", ".", "Broker", "{", "options", ":=", "broker", ".", "Options", "{", "Context", ":", "context", ".", "Background", "(", ")", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "options", ")", "\n", "}", "\n", "var", "openTopic", "topicOpener", "\n", "var", "openSub", "subOpener", "\n", "var", "err", "error", "\n", "if", "projID", ",", "ok", ":=", "options", ".", "Context", ".", "Value", "(", "gcpProjectIDKey", "{", "}", ")", ".", "(", "gcp", ".", "ProjectID", ")", ";", "ok", "{", "ts", ":=", "options", ".", "Context", ".", "Value", "(", "gcpTokenSourceKey", "{", "}", ")", ".", "(", "gcp", ".", "TokenSource", ")", "\n", "openTopic", ",", "openSub", ",", "err", "=", "setupGCP", "(", "options", ".", "Context", ",", "projID", ",", "ts", ")", "\n", "}", "else", "if", "rurl", ",", "ok", ":=", "options", ".", "Context", ".", "Value", "(", "rabbitURLKey", "{", "}", ")", ".", "(", "string", ")", ";", "ok", "{", "openTopic", ",", "openSub", ",", "err", "=", "setupRabbit", "(", "options", ".", "Context", ",", "rurl", ")", "\n", "}", "else", "{", "openTopic", ",", "openSub", ",", "err", "=", "setupMem", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "&", "pubsubBroker", "{", "err", ":", "err", "}", "\n", "}", "\n", "return", "&", "pubsubBroker", "{", "options", ":", "options", ",", "openTopic", ":", "openTopic", ",", "openSub", ":", "openSub", ",", "topics", ":", "map", "[", "string", "]", "*", "pubsub", ".", "Topic", "{", "}", ",", "subs", ":", "map", "[", "string", "]", "*", "pubsub", ".", "Subscription", "{", "}", ",", "}", "\n", "}" ]
// NewBroker creates a new gocloud pubsubBroker. // If the GCPProjectID option is set, Go Cloud uses its Google Cloud PubSub implementation. // If the RabbitURL option is set, Go Cloud uses its RabbitMQ implementation. // Otherwise, Go Cloud uses its in-memory implementation.
[ "NewBroker", "creates", "a", "new", "gocloud", "pubsubBroker", ".", "If", "the", "GCPProjectID", "option", "is", "set", "Go", "Cloud", "uses", "its", "Google", "Cloud", "PubSub", "implementation", ".", "If", "the", "RabbitURL", "option", "is", "set", "Go", "Cloud", "uses", "its", "RabbitMQ", "implementation", ".", "Otherwise", "Go", "Cloud", "uses", "its", "in", "-", "memory", "implementation", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/gocloud/gocloud.go#L47-L76
train
micro/go-plugins
broker/gocloud/gocloud.go
Publish
func (b *pubsubBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { if b.err != nil { return b.err } t := b.topic(topic) return t.Send(context.Background(), &pubsub.Message{Metadata: msg.Header, Body: msg.Body}) }
go
func (b *pubsubBroker) Publish(topic string, msg *broker.Message, opts ...broker.PublishOption) error { if b.err != nil { return b.err } t := b.topic(topic) return t.Send(context.Background(), &pubsub.Message{Metadata: msg.Header, Body: msg.Body}) }
[ "func", "(", "b", "*", "pubsubBroker", ")", "Publish", "(", "topic", "string", ",", "msg", "*", "broker", ".", "Message", ",", "opts", "...", "broker", ".", "PublishOption", ")", "error", "{", "if", "b", ".", "err", "!=", "nil", "{", "return", "b", ".", "err", "\n", "}", "\n", "t", ":=", "b", ".", "topic", "(", "topic", ")", "\n", "return", "t", ".", "Send", "(", "context", ".", "Background", "(", ")", ",", "&", "pubsub", ".", "Message", "{", "Metadata", ":", "msg", ".", "Header", ",", "Body", ":", "msg", ".", "Body", "}", ")", "\n", "}" ]
// Publish opens the topic if it hasn't been already, then publishes the message.
[ "Publish", "opens", "the", "topic", "if", "it", "hasn", "t", "been", "already", "then", "publishes", "the", "message", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/gocloud/gocloud.go#L131-L137
train
micro/go-plugins
broker/gocloud/gocloud.go
topic
func (b *pubsubBroker) topic(name string) *pubsub.Topic { b.mu.Lock() defer b.mu.Unlock() t := b.topics[name] if t == nil { t = b.openTopic(name) b.topics[name] = t } return t }
go
func (b *pubsubBroker) topic(name string) *pubsub.Topic { b.mu.Lock() defer b.mu.Unlock() t := b.topics[name] if t == nil { t = b.openTopic(name) b.topics[name] = t } return t }
[ "func", "(", "b", "*", "pubsubBroker", ")", "topic", "(", "name", "string", ")", "*", "pubsub", ".", "Topic", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "t", ":=", "b", ".", "topics", "[", "name", "]", "\n", "if", "t", "==", "nil", "{", "t", "=", "b", ".", "openTopic", "(", "name", ")", "\n", "b", ".", "topics", "[", "name", "]", "=", "t", "\n", "}", "\n", "return", "t", "\n", "}" ]
// topic returns the topic with the given name if this broker has // seen it before. Otherwise it opens a new topic.
[ "topic", "returns", "the", "topic", "with", "the", "given", "name", "if", "this", "broker", "has", "seen", "it", "before", ".", "Otherwise", "it", "opens", "a", "new", "topic", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/broker/gocloud/gocloud.go#L181-L190
train
micro/go-plugins
wrapper/trace/opentracing/opentracing.go
NewClientWrapper
func NewClientWrapper(ot opentracing.Tracer) client.Wrapper { return func(c client.Client) client.Client { if ot == nil { ot = opentracing.GlobalTracer() } return &otWrapper{ot, c} } }
go
func NewClientWrapper(ot opentracing.Tracer) client.Wrapper { return func(c client.Client) client.Client { if ot == nil { ot = opentracing.GlobalTracer() } return &otWrapper{ot, c} } }
[ "func", "NewClientWrapper", "(", "ot", "opentracing", ".", "Tracer", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "if", "ot", "==", "nil", "{", "ot", "=", "opentracing", ".", "GlobalTracer", "(", ")", "\n", "}", "\n", "return", "&", "otWrapper", "{", "ot", ",", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper accepts an open tracing Trace and returns a Client Wrapper
[ "NewClientWrapper", "accepts", "an", "open", "tracing", "Trace", "and", "returns", "a", "Client", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opentracing/opentracing.go#L74-L81
train
micro/go-plugins
wrapper/trace/opentracing/opentracing.go
NewCallWrapper
func NewCallWrapper(ot opentracing.Tracer) client.CallWrapper { return func(cf client.CallFunc) client.CallFunc { return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { if ot == nil { ot = opentracing.GlobalTracer() } name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()) ctx, span, err := StartSpanFromContext(ctx, ot, name) if err != nil { return err } defer span.Finish() return cf(ctx, node, req, rsp, opts) } } }
go
func NewCallWrapper(ot opentracing.Tracer) client.CallWrapper { return func(cf client.CallFunc) client.CallFunc { return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { if ot == nil { ot = opentracing.GlobalTracer() } name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()) ctx, span, err := StartSpanFromContext(ctx, ot, name) if err != nil { return err } defer span.Finish() return cf(ctx, node, req, rsp, opts) } } }
[ "func", "NewCallWrapper", "(", "ot", "opentracing", ".", "Tracer", ")", "client", ".", "CallWrapper", "{", "return", "func", "(", "cf", "client", ".", "CallFunc", ")", "client", ".", "CallFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "node", "*", "registry", ".", "Node", ",", "req", "client", ".", "Request", ",", "rsp", "interface", "{", "}", ",", "opts", "client", ".", "CallOptions", ")", "error", "{", "if", "ot", "==", "nil", "{", "ot", "=", "opentracing", ".", "GlobalTracer", "(", ")", "\n", "}", "\n", "name", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "req", ".", "Service", "(", ")", ",", "req", ".", "Endpoint", "(", ")", ")", "\n", "ctx", ",", "span", ",", "err", ":=", "StartSpanFromContext", "(", "ctx", ",", "ot", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "span", ".", "Finish", "(", ")", "\n", "return", "cf", "(", "ctx", ",", "node", ",", "req", ",", "rsp", ",", "opts", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewCallWrapper accepts an opentracing Tracer and returns a Call Wrapper
[ "NewCallWrapper", "accepts", "an", "opentracing", "Tracer", "and", "returns", "a", "Call", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opentracing/opentracing.go#L84-L99
train
micro/go-plugins
wrapper/trace/opentracing/opentracing.go
NewHandlerWrapper
func NewHandlerWrapper(ot opentracing.Tracer) server.HandlerWrapper { return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { if ot == nil { ot = opentracing.GlobalTracer() } name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()) ctx, span, err := StartSpanFromContext(ctx, ot, name) if err != nil { return err } defer span.Finish() return h(ctx, req, rsp) } } }
go
func NewHandlerWrapper(ot opentracing.Tracer) server.HandlerWrapper { return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { if ot == nil { ot = opentracing.GlobalTracer() } name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint()) ctx, span, err := StartSpanFromContext(ctx, ot, name) if err != nil { return err } defer span.Finish() return h(ctx, req, rsp) } } }
[ "func", "NewHandlerWrapper", "(", "ot", "opentracing", ".", "Tracer", ")", "server", ".", "HandlerWrapper", "{", "return", "func", "(", "h", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "error", "{", "if", "ot", "==", "nil", "{", "ot", "=", "opentracing", ".", "GlobalTracer", "(", ")", "\n", "}", "\n", "name", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "req", ".", "Service", "(", ")", ",", "req", ".", "Endpoint", "(", ")", ")", "\n", "ctx", ",", "span", ",", "err", ":=", "StartSpanFromContext", "(", "ctx", ",", "ot", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "span", ".", "Finish", "(", ")", "\n", "return", "h", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper accepts an opentracing Tracer and returns a Handler Wrapper
[ "NewHandlerWrapper", "accepts", "an", "opentracing", "Tracer", "and", "returns", "a", "Handler", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opentracing/opentracing.go#L102-L117
train
micro/go-plugins
wrapper/trace/opentracing/opentracing.go
NewSubscriberWrapper
func NewSubscriberWrapper(ot opentracing.Tracer) server.SubscriberWrapper { return func(next server.SubscriberFunc) server.SubscriberFunc { return func(ctx context.Context, msg server.Message) error { name := "Pub to " + msg.Topic() if ot == nil { ot = opentracing.GlobalTracer() } ctx, span, err := StartSpanFromContext(ctx, ot, name) if err != nil { return err } defer span.Finish() return next(ctx, msg) } } }
go
func NewSubscriberWrapper(ot opentracing.Tracer) server.SubscriberWrapper { return func(next server.SubscriberFunc) server.SubscriberFunc { return func(ctx context.Context, msg server.Message) error { name := "Pub to " + msg.Topic() if ot == nil { ot = opentracing.GlobalTracer() } ctx, span, err := StartSpanFromContext(ctx, ot, name) if err != nil { return err } defer span.Finish() return next(ctx, msg) } } }
[ "func", "NewSubscriberWrapper", "(", "ot", "opentracing", ".", "Tracer", ")", "server", ".", "SubscriberWrapper", "{", "return", "func", "(", "next", "server", ".", "SubscriberFunc", ")", "server", ".", "SubscriberFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "msg", "server", ".", "Message", ")", "error", "{", "name", ":=", "\"", "\"", "+", "msg", ".", "Topic", "(", ")", "\n", "if", "ot", "==", "nil", "{", "ot", "=", "opentracing", ".", "GlobalTracer", "(", ")", "\n", "}", "\n", "ctx", ",", "span", ",", "err", ":=", "StartSpanFromContext", "(", "ctx", ",", "ot", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "span", ".", "Finish", "(", ")", "\n", "return", "next", "(", "ctx", ",", "msg", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewSubscriberWrapper accepts an opentracing Tracer and returns a Subscriber Wrapper
[ "NewSubscriberWrapper", "accepts", "an", "opentracing", "Tracer", "and", "returns", "a", "Subscriber", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opentracing/opentracing.go#L120-L135
train
micro/go-plugins
wrapper/ratelimiter/ratelimit/ratelimit.go
NewClientWrapper
func NewClientWrapper(b *ratelimit.Bucket, wait bool) client.Wrapper { fn := limit(b, wait, "go.micro.client") return func(c client.Client) client.Client { return &clientWrapper{fn, c} } }
go
func NewClientWrapper(b *ratelimit.Bucket, wait bool) client.Wrapper { fn := limit(b, wait, "go.micro.client") return func(c client.Client) client.Client { return &clientWrapper{fn, c} } }
[ "func", "NewClientWrapper", "(", "b", "*", "ratelimit", ".", "Bucket", ",", "wait", "bool", ")", "client", ".", "Wrapper", "{", "fn", ":=", "limit", "(", "b", ",", "wait", ",", "\"", "\"", ")", "\n\n", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "clientWrapper", "{", "fn", ",", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper takes a rate limiter and wait flag and returns a client Wrapper.
[ "NewClientWrapper", "takes", "a", "rate", "limiter", "and", "wait", "flag", "and", "returns", "a", "client", "Wrapper", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/ratelimiter/ratelimit/ratelimit.go#L38-L44
train
micro/go-plugins
wrapper/ratelimiter/ratelimit/ratelimit.go
NewHandlerWrapper
func NewHandlerWrapper(b *ratelimit.Bucket, wait bool) server.HandlerWrapper { fn := limit(b, wait, "go.micro.server") return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { if err := fn(); err != nil { return err } return h(ctx, req, rsp) } } }
go
func NewHandlerWrapper(b *ratelimit.Bucket, wait bool) server.HandlerWrapper { fn := limit(b, wait, "go.micro.server") return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) error { if err := fn(); err != nil { return err } return h(ctx, req, rsp) } } }
[ "func", "NewHandlerWrapper", "(", "b", "*", "ratelimit", ".", "Bucket", ",", "wait", "bool", ")", "server", ".", "HandlerWrapper", "{", "fn", ":=", "limit", "(", "b", ",", "wait", ",", "\"", "\"", ")", "\n\n", "return", "func", "(", "h", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "error", "{", "if", "err", ":=", "fn", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "h", "(", "ctx", ",", "req", ",", "rsp", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper takes a rate limiter and wait flag and returns a client Wrapper.
[ "NewHandlerWrapper", "takes", "a", "rate", "limiter", "and", "wait", "flag", "and", "returns", "a", "client", "Wrapper", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/ratelimiter/ratelimit/ratelimit.go#L47-L58
train
micro/go-plugins
micro/trace/awsxray/options.go
WithClient
func WithClient(x *xray.XRay) Option { return func(o *Options) { o.Client = x } }
go
func WithClient(x *xray.XRay) Option { return func(o *Options) { o.Client = x } }
[ "func", "WithClient", "(", "x", "*", "xray", ".", "XRay", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "Client", "=", "x", "\n", "}", "\n", "}" ]
// WithClient sets the XRay Client to use to send segments
[ "WithClient", "sets", "the", "XRay", "Client", "to", "use", "to", "send", "segments" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/micro/trace/awsxray/options.go#L26-L30
train
micro/go-plugins
wrapper/trace/opencensus/tracker.go
end
func (t *tracker) end(ctx context.Context, err error) { status := getResponseStatus(err) ctx, _ = tag.New(ctx, tag.Upsert(StatusCode, strconv.Itoa(int(status.Code)))) stats.Record(ctx, t.profile.LatencyMeasure.M(float64(time.Since(t.startedAt))/float64(time.Millisecond))) if t.span != nil { t.span.SetStatus(status) t.span.End() } }
go
func (t *tracker) end(ctx context.Context, err error) { status := getResponseStatus(err) ctx, _ = tag.New(ctx, tag.Upsert(StatusCode, strconv.Itoa(int(status.Code)))) stats.Record(ctx, t.profile.LatencyMeasure.M(float64(time.Since(t.startedAt))/float64(time.Millisecond))) if t.span != nil { t.span.SetStatus(status) t.span.End() } }
[ "func", "(", "t", "*", "tracker", ")", "end", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "{", "status", ":=", "getResponseStatus", "(", "err", ")", "\n\n", "ctx", ",", "_", "=", "tag", ".", "New", "(", "ctx", ",", "tag", ".", "Upsert", "(", "StatusCode", ",", "strconv", ".", "Itoa", "(", "int", "(", "status", ".", "Code", ")", ")", ")", ")", "\n", "stats", ".", "Record", "(", "ctx", ",", "t", ".", "profile", ".", "LatencyMeasure", ".", "M", "(", "float64", "(", "time", ".", "Since", "(", "t", ".", "startedAt", ")", ")", "/", "float64", "(", "time", ".", "Millisecond", ")", ")", ")", "\n\n", "if", "t", ".", "span", "!=", "nil", "{", "t", ".", "span", ".", "SetStatus", "(", "status", ")", "\n", "t", ".", "span", ".", "End", "(", ")", "\n", "}", "\n", "}" ]
// end a request's monitoring session. If there is a span ongoing, it will // be ended and metrics will be recorded.
[ "end", "a", "request", "s", "monitoring", "session", ".", "If", "there", "is", "a", "span", "ongoing", "it", "will", "be", "ended", "and", "metrics", "will", "be", "recorded", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/opencensus/tracker.go#L71-L81
train
micro/go-plugins
registry/eureka/marshalling.go
serviceToInstance
func serviceToInstance(service *registry.Service) (*fargo.Instance, error) { if len(service.Nodes) == 0 { return nil, errors.New("Require nodes") } node := service.Nodes[0] instance := &fargo.Instance{ App: service.Name, HostName: node.Address, IPAddr: node.Address, VipAddress: node.Address, SecureVipAddress: node.Address, Port: node.Port, Status: fargo.UP, UniqueID: func(i fargo.Instance) string { return fmt.Sprintf("%s:%s", node.Address, node.Id) }, DataCenterInfo: fargo.DataCenterInfo{Name: fargo.MyOwn}, } // set version instance.SetMetadataString("version", service.Version) // set instance ID instance.SetMetadataString("instanceId", node.Id) // set endpoints if b, err := json.Marshal(service.Endpoints); err == nil { instance.SetMetadataString("endpoints", string(b)) } // set metadata if b, err := json.Marshal(node.Metadata); err == nil { instance.SetMetadataString("metadata", string(b)) } return instance, nil }
go
func serviceToInstance(service *registry.Service) (*fargo.Instance, error) { if len(service.Nodes) == 0 { return nil, errors.New("Require nodes") } node := service.Nodes[0] instance := &fargo.Instance{ App: service.Name, HostName: node.Address, IPAddr: node.Address, VipAddress: node.Address, SecureVipAddress: node.Address, Port: node.Port, Status: fargo.UP, UniqueID: func(i fargo.Instance) string { return fmt.Sprintf("%s:%s", node.Address, node.Id) }, DataCenterInfo: fargo.DataCenterInfo{Name: fargo.MyOwn}, } // set version instance.SetMetadataString("version", service.Version) // set instance ID instance.SetMetadataString("instanceId", node.Id) // set endpoints if b, err := json.Marshal(service.Endpoints); err == nil { instance.SetMetadataString("endpoints", string(b)) } // set metadata if b, err := json.Marshal(node.Metadata); err == nil { instance.SetMetadataString("metadata", string(b)) } return instance, nil }
[ "func", "serviceToInstance", "(", "service", "*", "registry", ".", "Service", ")", "(", "*", "fargo", ".", "Instance", ",", "error", ")", "{", "if", "len", "(", "service", ".", "Nodes", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "node", ":=", "service", ".", "Nodes", "[", "0", "]", "\n\n", "instance", ":=", "&", "fargo", ".", "Instance", "{", "App", ":", "service", ".", "Name", ",", "HostName", ":", "node", ".", "Address", ",", "IPAddr", ":", "node", ".", "Address", ",", "VipAddress", ":", "node", ".", "Address", ",", "SecureVipAddress", ":", "node", ".", "Address", ",", "Port", ":", "node", ".", "Port", ",", "Status", ":", "fargo", ".", "UP", ",", "UniqueID", ":", "func", "(", "i", "fargo", ".", "Instance", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ".", "Address", ",", "node", ".", "Id", ")", "\n", "}", ",", "DataCenterInfo", ":", "fargo", ".", "DataCenterInfo", "{", "Name", ":", "fargo", ".", "MyOwn", "}", ",", "}", "\n\n", "// set version", "instance", ".", "SetMetadataString", "(", "\"", "\"", ",", "service", ".", "Version", ")", "\n\n", "// set instance ID", "instance", ".", "SetMetadataString", "(", "\"", "\"", ",", "node", ".", "Id", ")", "\n\n", "// set endpoints", "if", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "service", ".", "Endpoints", ")", ";", "err", "==", "nil", "{", "instance", ".", "SetMetadataString", "(", "\"", "\"", ",", "string", "(", "b", ")", ")", "\n", "}", "\n\n", "// set metadata", "if", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "node", ".", "Metadata", ")", ";", "err", "==", "nil", "{", "instance", ".", "SetMetadataString", "(", "\"", "\"", ",", "string", "(", "b", ")", ")", "\n", "}", "\n\n", "return", "instance", ",", "nil", "\n", "}" ]
// only parses first node
[ "only", "parses", "first", "node" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/eureka/marshalling.go#L74-L112
train
micro/go-plugins
registry/kubernetes/watcher.go
updateCache
func (k *k8sWatcher) updateCache() ([]*registry.Result, error) { podList, err := k.registry.client.ListPods(podSelector) if err != nil { return nil, err } k.RLock() k.RUnlock() var results []*registry.Result for _, pod := range podList.Items { rslts := k.buildPodResults(&pod, nil) for _, r := range rslts { results = append(results, r) } k.Lock() k.pods[pod.Metadata.Name] = &pod k.Unlock() } return results, nil }
go
func (k *k8sWatcher) updateCache() ([]*registry.Result, error) { podList, err := k.registry.client.ListPods(podSelector) if err != nil { return nil, err } k.RLock() k.RUnlock() var results []*registry.Result for _, pod := range podList.Items { rslts := k.buildPodResults(&pod, nil) for _, r := range rslts { results = append(results, r) } k.Lock() k.pods[pod.Metadata.Name] = &pod k.Unlock() } return results, nil }
[ "func", "(", "k", "*", "k8sWatcher", ")", "updateCache", "(", ")", "(", "[", "]", "*", "registry", ".", "Result", ",", "error", ")", "{", "podList", ",", "err", ":=", "k", ".", "registry", ".", "client", ".", "ListPods", "(", "podSelector", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "k", ".", "RLock", "(", ")", "\n", "k", ".", "RUnlock", "(", ")", "\n\n", "var", "results", "[", "]", "*", "registry", ".", "Result", "\n\n", "for", "_", ",", "pod", ":=", "range", "podList", ".", "Items", "{", "rslts", ":=", "k", ".", "buildPodResults", "(", "&", "pod", ",", "nil", ")", "\n\n", "for", "_", ",", "r", ":=", "range", "rslts", "{", "results", "=", "append", "(", "results", ",", "r", ")", "\n", "}", "\n\n", "k", ".", "Lock", "(", ")", "\n", "k", ".", "pods", "[", "pod", ".", "Metadata", ".", "Name", "]", "=", "&", "pod", "\n", "k", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "return", "results", ",", "nil", "\n", "}" ]
// build a cache of pods when the watcher starts.
[ "build", "a", "cache", "of", "pods", "when", "the", "watcher", "starts", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/watcher.go#L25-L49
train
micro/go-plugins
registry/kubernetes/watcher.go
buildPodResults
func (k *k8sWatcher) buildPodResults(pod *client.Pod, cache *client.Pod) []*registry.Result { var results []*registry.Result ignore := make(map[string]bool) if pod.Metadata != nil { for ak, av := range pod.Metadata.Annotations { // check this annotation kv is a service notation if !strings.HasPrefix(ak, annotationServiceKeyPrefix) { continue } if av == nil { continue } // ignore when we check the cached annotations // as we take care of it here ignore[ak] = true // compare aginst cache. var cacheExists bool var cav *string if cache != nil && cache.Metadata != nil { cav, cacheExists = cache.Metadata.Annotations[ak] if cacheExists && cav != nil && cav == av { // service notation exists and is identical - // no change result required. continue } } rslt := &registry.Result{} if cacheExists { rslt.Action = "update" } else { rslt.Action = "create" } // unmarshal service notation from annotation value err := json.Unmarshal([]byte(*av), &rslt.Service) if err != nil { continue } results = append(results, rslt) } } // loop through cache annotations to find services // not accounted for above, and "delete" them. if cache != nil && cache.Metadata != nil { for ak, av := range cache.Metadata.Annotations { if ignore[ak] { continue } // check this annotation kv is a service notation if !strings.HasPrefix(ak, annotationServiceKeyPrefix) { continue } rslt := &registry.Result{Action: "delete"} // unmarshal service notation from annotation value err := json.Unmarshal([]byte(*av), &rslt.Service) if err != nil { continue } results = append(results, rslt) } } return results }
go
func (k *k8sWatcher) buildPodResults(pod *client.Pod, cache *client.Pod) []*registry.Result { var results []*registry.Result ignore := make(map[string]bool) if pod.Metadata != nil { for ak, av := range pod.Metadata.Annotations { // check this annotation kv is a service notation if !strings.HasPrefix(ak, annotationServiceKeyPrefix) { continue } if av == nil { continue } // ignore when we check the cached annotations // as we take care of it here ignore[ak] = true // compare aginst cache. var cacheExists bool var cav *string if cache != nil && cache.Metadata != nil { cav, cacheExists = cache.Metadata.Annotations[ak] if cacheExists && cav != nil && cav == av { // service notation exists and is identical - // no change result required. continue } } rslt := &registry.Result{} if cacheExists { rslt.Action = "update" } else { rslt.Action = "create" } // unmarshal service notation from annotation value err := json.Unmarshal([]byte(*av), &rslt.Service) if err != nil { continue } results = append(results, rslt) } } // loop through cache annotations to find services // not accounted for above, and "delete" them. if cache != nil && cache.Metadata != nil { for ak, av := range cache.Metadata.Annotations { if ignore[ak] { continue } // check this annotation kv is a service notation if !strings.HasPrefix(ak, annotationServiceKeyPrefix) { continue } rslt := &registry.Result{Action: "delete"} // unmarshal service notation from annotation value err := json.Unmarshal([]byte(*av), &rslt.Service) if err != nil { continue } results = append(results, rslt) } } return results }
[ "func", "(", "k", "*", "k8sWatcher", ")", "buildPodResults", "(", "pod", "*", "client", ".", "Pod", ",", "cache", "*", "client", ".", "Pod", ")", "[", "]", "*", "registry", ".", "Result", "{", "var", "results", "[", "]", "*", "registry", ".", "Result", "\n", "ignore", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "if", "pod", ".", "Metadata", "!=", "nil", "{", "for", "ak", ",", "av", ":=", "range", "pod", ".", "Metadata", ".", "Annotations", "{", "// check this annotation kv is a service notation", "if", "!", "strings", ".", "HasPrefix", "(", "ak", ",", "annotationServiceKeyPrefix", ")", "{", "continue", "\n", "}", "\n\n", "if", "av", "==", "nil", "{", "continue", "\n", "}", "\n\n", "// ignore when we check the cached annotations", "// as we take care of it here", "ignore", "[", "ak", "]", "=", "true", "\n\n", "// compare aginst cache.", "var", "cacheExists", "bool", "\n", "var", "cav", "*", "string", "\n\n", "if", "cache", "!=", "nil", "&&", "cache", ".", "Metadata", "!=", "nil", "{", "cav", ",", "cacheExists", "=", "cache", ".", "Metadata", ".", "Annotations", "[", "ak", "]", "\n", "if", "cacheExists", "&&", "cav", "!=", "nil", "&&", "cav", "==", "av", "{", "// service notation exists and is identical -", "// no change result required.", "continue", "\n", "}", "\n", "}", "\n\n", "rslt", ":=", "&", "registry", ".", "Result", "{", "}", "\n", "if", "cacheExists", "{", "rslt", ".", "Action", "=", "\"", "\"", "\n", "}", "else", "{", "rslt", ".", "Action", "=", "\"", "\"", "\n", "}", "\n\n", "// unmarshal service notation from annotation value", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "*", "av", ")", ",", "&", "rslt", ".", "Service", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "results", "=", "append", "(", "results", ",", "rslt", ")", "\n", "}", "\n", "}", "\n\n", "// loop through cache annotations to find services", "// not accounted for above, and \"delete\" them.", "if", "cache", "!=", "nil", "&&", "cache", ".", "Metadata", "!=", "nil", "{", "for", "ak", ",", "av", ":=", "range", "cache", ".", "Metadata", ".", "Annotations", "{", "if", "ignore", "[", "ak", "]", "{", "continue", "\n", "}", "\n\n", "// check this annotation kv is a service notation", "if", "!", "strings", ".", "HasPrefix", "(", "ak", ",", "annotationServiceKeyPrefix", ")", "{", "continue", "\n", "}", "\n\n", "rslt", ":=", "&", "registry", ".", "Result", "{", "Action", ":", "\"", "\"", "}", "\n", "// unmarshal service notation from annotation value", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "*", "av", ")", ",", "&", "rslt", ".", "Service", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "results", "=", "append", "(", "results", ",", "rslt", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// look through pod annotations, compare against cache if present // and return a list of results to send down the wire.
[ "look", "through", "pod", "annotations", "compare", "against", "cache", "if", "present", "and", "return", "a", "list", "of", "results", "to", "send", "down", "the", "wire", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/watcher.go#L53-L127
train
micro/go-plugins
registry/kubernetes/watcher.go
handleEvent
func (k *k8sWatcher) handleEvent(event watch.Event) { var pod client.Pod if err := json.Unmarshal([]byte(event.Object), &pod); err != nil { log.Log("K8s Watcher: Couldnt unmarshal event object from pod") return } switch event.Type { case watch.Modified: // Pod was modified k.RLock() cache := k.pods[pod.Metadata.Name] k.RUnlock() // service could have been added, edited or removed. var results []*registry.Result if pod.Status.Phase == podRunning { results = k.buildPodResults(&pod, cache) } else { // passing in cache might not return all results results = k.buildPodResults(&pod, nil) } for _, result := range results { // pod isnt running if pod.Status.Phase != podRunning { result.Action = "delete" } k.next <- result } k.Lock() k.pods[pod.Metadata.Name] = &pod k.Unlock() return case watch.Deleted: // Pod was deleted // passing in cache might not return all results results := k.buildPodResults(&pod, nil) for _, result := range results { result.Action = "delete" k.next <- result } k.Lock() delete(k.pods, pod.Metadata.Name) k.Unlock() return } }
go
func (k *k8sWatcher) handleEvent(event watch.Event) { var pod client.Pod if err := json.Unmarshal([]byte(event.Object), &pod); err != nil { log.Log("K8s Watcher: Couldnt unmarshal event object from pod") return } switch event.Type { case watch.Modified: // Pod was modified k.RLock() cache := k.pods[pod.Metadata.Name] k.RUnlock() // service could have been added, edited or removed. var results []*registry.Result if pod.Status.Phase == podRunning { results = k.buildPodResults(&pod, cache) } else { // passing in cache might not return all results results = k.buildPodResults(&pod, nil) } for _, result := range results { // pod isnt running if pod.Status.Phase != podRunning { result.Action = "delete" } k.next <- result } k.Lock() k.pods[pod.Metadata.Name] = &pod k.Unlock() return case watch.Deleted: // Pod was deleted // passing in cache might not return all results results := k.buildPodResults(&pod, nil) for _, result := range results { result.Action = "delete" k.next <- result } k.Lock() delete(k.pods, pod.Metadata.Name) k.Unlock() return } }
[ "func", "(", "k", "*", "k8sWatcher", ")", "handleEvent", "(", "event", "watch", ".", "Event", ")", "{", "var", "pod", "client", ".", "Pod", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "event", ".", "Object", ")", ",", "&", "pod", ")", ";", "err", "!=", "nil", "{", "log", ".", "Log", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "switch", "event", ".", "Type", "{", "case", "watch", ".", "Modified", ":", "// Pod was modified", "k", ".", "RLock", "(", ")", "\n", "cache", ":=", "k", ".", "pods", "[", "pod", ".", "Metadata", ".", "Name", "]", "\n", "k", ".", "RUnlock", "(", ")", "\n\n", "// service could have been added, edited or removed.", "var", "results", "[", "]", "*", "registry", ".", "Result", "\n\n", "if", "pod", ".", "Status", ".", "Phase", "==", "podRunning", "{", "results", "=", "k", ".", "buildPodResults", "(", "&", "pod", ",", "cache", ")", "\n", "}", "else", "{", "// passing in cache might not return all results", "results", "=", "k", ".", "buildPodResults", "(", "&", "pod", ",", "nil", ")", "\n", "}", "\n\n", "for", "_", ",", "result", ":=", "range", "results", "{", "// pod isnt running", "if", "pod", ".", "Status", ".", "Phase", "!=", "podRunning", "{", "result", ".", "Action", "=", "\"", "\"", "\n", "}", "\n", "k", ".", "next", "<-", "result", "\n", "}", "\n\n", "k", ".", "Lock", "(", ")", "\n", "k", ".", "pods", "[", "pod", ".", "Metadata", ".", "Name", "]", "=", "&", "pod", "\n", "k", ".", "Unlock", "(", ")", "\n", "return", "\n\n", "case", "watch", ".", "Deleted", ":", "// Pod was deleted", "// passing in cache might not return all results", "results", ":=", "k", ".", "buildPodResults", "(", "&", "pod", ",", "nil", ")", "\n\n", "for", "_", ",", "result", ":=", "range", "results", "{", "result", ".", "Action", "=", "\"", "\"", "\n", "k", ".", "next", "<-", "result", "\n", "}", "\n\n", "k", ".", "Lock", "(", ")", "\n", "delete", "(", "k", ".", "pods", ",", "pod", ".", "Metadata", ".", "Name", ")", "\n", "k", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "}" ]
// handleEvent will taken an event from the k8s pods API and do the correct // things with the result, based on the local cache.
[ "handleEvent", "will", "taken", "an", "event", "from", "the", "k8s", "pods", "API", "and", "do", "the", "correct", "things", "with", "the", "result", "based", "on", "the", "local", "cache", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/watcher.go#L131-L185
train
micro/go-plugins
registry/kubernetes/watcher.go
Next
func (k *k8sWatcher) Next() (*registry.Result, error) { r, ok := <-k.next if !ok { return nil, errors.New("result chan closed") } return r, nil }
go
func (k *k8sWatcher) Next() (*registry.Result, error) { r, ok := <-k.next if !ok { return nil, errors.New("result chan closed") } return r, nil }
[ "func", "(", "k", "*", "k8sWatcher", ")", "Next", "(", ")", "(", "*", "registry", ".", "Result", ",", "error", ")", "{", "r", ",", "ok", ":=", "<-", "k", ".", "next", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// Next will block until a new result comes in
[ "Next", "will", "block", "until", "a", "new", "result", "comes", "in" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/watcher.go#L188-L194
train
micro/go-plugins
registry/kubernetes/watcher.go
Stop
func (k *k8sWatcher) Stop() { k.watcher.Stop() select { case <-k.next: return default: close(k.next) } }
go
func (k *k8sWatcher) Stop() { k.watcher.Stop() select { case <-k.next: return default: close(k.next) } }
[ "func", "(", "k", "*", "k8sWatcher", ")", "Stop", "(", ")", "{", "k", ".", "watcher", ".", "Stop", "(", ")", "\n\n", "select", "{", "case", "<-", "k", ".", "next", ":", "return", "\n", "default", ":", "close", "(", "k", ".", "next", ")", "\n", "}", "\n", "}" ]
// Stop will cancel any requests, and close channels
[ "Stop", "will", "cancel", "any", "requests", "and", "close", "channels" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/watcher.go#L197-L206
train
micro/go-plugins
wrapper/trace/datadog/datadog.go
NewClientWrapper
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { return &ddWrapper{c} } }
go
func NewClientWrapper() client.Wrapper { return func(c client.Client) client.Client { return &ddWrapper{c} } }
[ "func", "NewClientWrapper", "(", ")", "client", ".", "Wrapper", "{", "return", "func", "(", "c", "client", ".", "Client", ")", "client", ".", "Client", "{", "return", "&", "ddWrapper", "{", "c", "}", "\n", "}", "\n", "}" ]
// NewClientWrapper returns a Client wrapped in tracer
[ "NewClientWrapper", "returns", "a", "Client", "wrapped", "in", "tracer" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/datadog/datadog.go#L49-L53
train
micro/go-plugins
wrapper/trace/datadog/datadog.go
NewCallWrapper
func NewCallWrapper() client.CallWrapper { return func(cf client.CallFunc) client.CallFunc { return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { t := newRequestTracker(req, ClientProfile) ctx = t.StartSpanFromContext(ctx) defer func() { t.finishWithError(nil, noDebugStack) }() return cf(ctx, node, req, rsp, opts) } } }
go
func NewCallWrapper() client.CallWrapper { return func(cf client.CallFunc) client.CallFunc { return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error { t := newRequestTracker(req, ClientProfile) ctx = t.StartSpanFromContext(ctx) defer func() { t.finishWithError(nil, noDebugStack) }() return cf(ctx, node, req, rsp, opts) } } }
[ "func", "NewCallWrapper", "(", ")", "client", ".", "CallWrapper", "{", "return", "func", "(", "cf", "client", ".", "CallFunc", ")", "client", ".", "CallFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "node", "*", "registry", ".", "Node", ",", "req", "client", ".", "Request", ",", "rsp", "interface", "{", "}", ",", "opts", "client", ".", "CallOptions", ")", "error", "{", "t", ":=", "newRequestTracker", "(", "req", ",", "ClientProfile", ")", "\n", "ctx", "=", "t", ".", "StartSpanFromContext", "(", "ctx", ")", "\n\n", "defer", "func", "(", ")", "{", "t", ".", "finishWithError", "(", "nil", ",", "noDebugStack", ")", "\n", "}", "(", ")", "\n\n", "return", "cf", "(", "ctx", ",", "node", ",", "req", ",", "rsp", ",", "opts", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NewCallWrapper returns a Call Wrapper
[ "NewCallWrapper", "returns", "a", "Call", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/datadog/datadog.go#L56-L69
train
micro/go-plugins
wrapper/trace/datadog/datadog.go
NewHandlerWrapper
func NewHandlerWrapper() server.HandlerWrapper { return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) (err error) { if req.Endpoint() != "Debug.Health" { t := newRequestTracker(req, ServerProfile) ctx = t.StartSpanFromContext(ctx) defer func() { t.finishWithError(err, noDebugStack) }() } err = h(ctx, req, rsp) return } } }
go
func NewHandlerWrapper() server.HandlerWrapper { return func(h server.HandlerFunc) server.HandlerFunc { return func(ctx context.Context, req server.Request, rsp interface{}) (err error) { if req.Endpoint() != "Debug.Health" { t := newRequestTracker(req, ServerProfile) ctx = t.StartSpanFromContext(ctx) defer func() { t.finishWithError(err, noDebugStack) }() } err = h(ctx, req, rsp) return } } }
[ "func", "NewHandlerWrapper", "(", ")", "server", ".", "HandlerWrapper", "{", "return", "func", "(", "h", "server", ".", "HandlerFunc", ")", "server", ".", "HandlerFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "server", ".", "Request", ",", "rsp", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "if", "req", ".", "Endpoint", "(", ")", "!=", "\"", "\"", "{", "t", ":=", "newRequestTracker", "(", "req", ",", "ServerProfile", ")", "\n", "ctx", "=", "t", ".", "StartSpanFromContext", "(", "ctx", ")", "\n", "defer", "func", "(", ")", "{", "t", ".", "finishWithError", "(", "err", ",", "noDebugStack", ")", "\n", "}", "(", ")", "\n", "}", "\n\n", "err", "=", "h", "(", "ctx", ",", "req", ",", "rsp", ")", "\n\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// NewHandlerWrapper returns a Handler Wrapper
[ "NewHandlerWrapper", "returns", "a", "Handler", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/datadog/datadog.go#L72-L88
train
micro/go-plugins
wrapper/trace/datadog/datadog.go
NewSubscriberWrapper
func NewSubscriberWrapper() server.SubscriberWrapper { return func(next server.SubscriberFunc) server.SubscriberFunc { return func(ctx context.Context, msg server.Message) (err error) { t := newPublicationTracker(msg, ServerProfile) ctx = t.StartSpanFromContext(ctx) defer func() { t.finishWithError(err, noDebugStack) }() err = next(ctx, msg) return } } }
go
func NewSubscriberWrapper() server.SubscriberWrapper { return func(next server.SubscriberFunc) server.SubscriberFunc { return func(ctx context.Context, msg server.Message) (err error) { t := newPublicationTracker(msg, ServerProfile) ctx = t.StartSpanFromContext(ctx) defer func() { t.finishWithError(err, noDebugStack) }() err = next(ctx, msg) return } } }
[ "func", "NewSubscriberWrapper", "(", ")", "server", ".", "SubscriberWrapper", "{", "return", "func", "(", "next", "server", ".", "SubscriberFunc", ")", "server", ".", "SubscriberFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "msg", "server", ".", "Message", ")", "(", "err", "error", ")", "{", "t", ":=", "newPublicationTracker", "(", "msg", ",", "ServerProfile", ")", "\n", "ctx", "=", "t", ".", "StartSpanFromContext", "(", "ctx", ")", "\n", "defer", "func", "(", ")", "{", "t", ".", "finishWithError", "(", "err", ",", "noDebugStack", ")", "\n", "}", "(", ")", "\n\n", "err", "=", "next", "(", "ctx", ",", "msg", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// NewSubscriberWrapper returns a Subscriber Wrapper
[ "NewSubscriberWrapper", "returns", "a", "Subscriber", "Wrapper" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/wrapper/trace/datadog/datadog.go#L91-L104
train
micro/go-plugins
registry/kubernetes/client/api/response.go
Into
func (r *Response) Into(data interface{}) error { if r.err != nil { return r.err } defer r.res.Body.Close() decoder := json.NewDecoder(r.res.Body) err := decoder.Decode(&data) if err != nil { return ErrDecode } return r.err }
go
func (r *Response) Into(data interface{}) error { if r.err != nil { return r.err } defer r.res.Body.Close() decoder := json.NewDecoder(r.res.Body) err := decoder.Decode(&data) if err != nil { return ErrDecode } return r.err }
[ "func", "(", "r", "*", "Response", ")", "Into", "(", "data", "interface", "{", "}", ")", "error", "{", "if", "r", ".", "err", "!=", "nil", "{", "return", "r", ".", "err", "\n", "}", "\n\n", "defer", "r", ".", "res", ".", "Body", ".", "Close", "(", ")", "\n", "decoder", ":=", "json", ".", "NewDecoder", "(", "r", ".", "res", ".", "Body", ")", "\n", "err", ":=", "decoder", ".", "Decode", "(", "&", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ErrDecode", "\n", "}", "\n\n", "return", "r", ".", "err", "\n", "}" ]
// Into decode body into `data`
[ "Into", "decode", "body", "into", "data" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/api/response.go#L48-L61
train
micro/go-plugins
registry/nats/options.go
Options
func Options(nopts nats.Options) registry.Option { return func(o *registry.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, optionsKey{}, nopts) } }
go
func Options(nopts nats.Options) registry.Option { return func(o *registry.Options) { if o.Context == nil { o.Context = context.Background() } o.Context = context.WithValue(o.Context, optionsKey{}, nopts) } }
[ "func", "Options", "(", "nopts", "nats", ".", "Options", ")", "registry", ".", "Option", "{", "return", "func", "(", "o", "*", "registry", ".", "Options", ")", "{", "if", "o", ".", "Context", "==", "nil", "{", "o", ".", "Context", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "o", ".", "Context", "=", "context", ".", "WithValue", "(", "o", ".", "Context", ",", "optionsKey", "{", "}", ",", "nopts", ")", "\n", "}", "\n", "}" ]
// Options allow to inject a nats.Options struct for configuring // the nats connection
[ "Options", "allow", "to", "inject", "a", "nats", ".", "Options", "struct", "for", "configuring", "the", "nats", "connection" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/nats/options.go#L40-L47
train
micro/go-plugins
registry/kubernetes/client/client.go
NewClientByHost
func NewClientByHost(host string) Kubernetes { tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, DisableCompression: true, } c := &http.Client{ Transport: tr, } return &client{ opts: &api.Options{ Client: c, Host: host, Namespace: "default", }, } }
go
func NewClientByHost(host string) Kubernetes { tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, DisableCompression: true, } c := &http.Client{ Transport: tr, } return &client{ opts: &api.Options{ Client: c, Host: host, Namespace: "default", }, } }
[ "func", "NewClientByHost", "(", "host", "string", ")", "Kubernetes", "{", "tr", ":=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", ",", "}", ",", "DisableCompression", ":", "true", ",", "}", "\n\n", "c", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "tr", ",", "}", "\n\n", "return", "&", "client", "{", "opts", ":", "&", "api", ".", "Options", "{", "Client", ":", "c", ",", "Host", ":", "host", ",", "Namespace", ":", "\"", "\"", ",", "}", ",", "}", "\n", "}" ]
// NewClientByHost sets up a client by host
[ "NewClientByHost", "sets", "up", "a", "client", "by", "host" ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/client.go#L65-L84
train
micro/go-plugins
registry/kubernetes/client/client.go
NewClientInCluster
func NewClientInCluster() Kubernetes { host := "https://" + os.Getenv("KUBERNETES_SERVICE_HOST") + ":" + os.Getenv("KUBERNETES_SERVICE_PORT") s, err := os.Stat(serviceAccountPath) if err != nil { log.Fatal(err) } if s == nil || !s.IsDir() { log.Fatal(errors.New("no k8s service account found")) } token, err := ioutil.ReadFile(path.Join(serviceAccountPath, "token")) if err != nil { log.Fatal(err) } t := string(token) ns, err := detectNamespace() if err != nil { log.Fatal(err) } crt, err := CertPoolFromFile(path.Join(serviceAccountPath, "ca.crt")) if err != nil { log.Fatal(err) } c := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ RootCAs: crt, }, DisableCompression: true, }, } return &client{ opts: &api.Options{ Client: c, Host: host, Namespace: ns, BearerToken: &t, }, } }
go
func NewClientInCluster() Kubernetes { host := "https://" + os.Getenv("KUBERNETES_SERVICE_HOST") + ":" + os.Getenv("KUBERNETES_SERVICE_PORT") s, err := os.Stat(serviceAccountPath) if err != nil { log.Fatal(err) } if s == nil || !s.IsDir() { log.Fatal(errors.New("no k8s service account found")) } token, err := ioutil.ReadFile(path.Join(serviceAccountPath, "token")) if err != nil { log.Fatal(err) } t := string(token) ns, err := detectNamespace() if err != nil { log.Fatal(err) } crt, err := CertPoolFromFile(path.Join(serviceAccountPath, "ca.crt")) if err != nil { log.Fatal(err) } c := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ RootCAs: crt, }, DisableCompression: true, }, } return &client{ opts: &api.Options{ Client: c, Host: host, Namespace: ns, BearerToken: &t, }, } }
[ "func", "NewClientInCluster", "(", ")", "Kubernetes", "{", "host", ":=", "\"", "\"", "+", "os", ".", "Getenv", "(", "\"", "\"", ")", "+", "\"", "\"", "+", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n\n", "s", ",", "err", ":=", "os", ".", "Stat", "(", "serviceAccountPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "if", "s", "==", "nil", "||", "!", "s", ".", "IsDir", "(", ")", "{", "log", ".", "Fatal", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "token", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ".", "Join", "(", "serviceAccountPath", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "t", ":=", "string", "(", "token", ")", "\n\n", "ns", ",", "err", ":=", "detectNamespace", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "crt", ",", "err", ":=", "CertPoolFromFile", "(", "path", ".", "Join", "(", "serviceAccountPath", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "c", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "RootCAs", ":", "crt", ",", "}", ",", "DisableCompression", ":", "true", ",", "}", ",", "}", "\n\n", "return", "&", "client", "{", "opts", ":", "&", "api", ".", "Options", "{", "Client", ":", "c", ",", "Host", ":", "host", ",", "Namespace", ":", "ns", ",", "BearerToken", ":", "&", "t", ",", "}", ",", "}", "\n", "}" ]
// NewClientInCluster should work similarily to the official api // NewInClient by setting up a client configuration for use within // a k8s pod.
[ "NewClientInCluster", "should", "work", "similarily", "to", "the", "official", "api", "NewInClient", "by", "setting", "up", "a", "client", "configuration", "for", "use", "within", "a", "k8s", "pod", "." ]
d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0
https://github.com/micro/go-plugins/blob/d1cb339c5c5a3ab1e4be090c75a3cc03e38348e0/registry/kubernetes/client/client.go#L89-L133
train