id
int32 0
167k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
11,300 | optiopay/kafka | connection.go | readRespLoop | func (c *connection) readRespLoop() {
defer func() {
c.mu.Lock()
for _, cc := range c.respc {
close(cc)
}
c.respc = make(map[int32]chan []byte)
c.mu.Unlock()
}()
rd := bufio.NewReader(c.rw)
for {
if c.readTimeout > 0 {
err := c.rw.SetReadDeadline(time.Now().Add(c.readTimeout))
if err != nil {
c.logger.Error("msg", "SetReadDeadline failed",
"error", err)
}
}
correlationID, b, err := proto.ReadResp(rd)
if err != nil {
c.mu.Lock()
if c.stopErr == nil {
c.stopErr = err
close(c.stop)
}
c.mu.Unlock()
return
}
c.mu.Lock()
rc, ok := c.respc[correlationID]
delete(c.respc, correlationID)
c.mu.Unlock()
if !ok {
c.logger.Warn(
"msg", "response to unknown request",
"correlationID", correlationID)
continue
}
select {
case <-c.stop:
c.mu.Lock()
if c.stopErr == nil {
c.stopErr = ErrClosed
}
c.mu.Unlock()
case rc <- b:
}
close(rc)
}
} | go | func (c *connection) readRespLoop() {
defer func() {
c.mu.Lock()
for _, cc := range c.respc {
close(cc)
}
c.respc = make(map[int32]chan []byte)
c.mu.Unlock()
}()
rd := bufio.NewReader(c.rw)
for {
if c.readTimeout > 0 {
err := c.rw.SetReadDeadline(time.Now().Add(c.readTimeout))
if err != nil {
c.logger.Error("msg", "SetReadDeadline failed",
"error", err)
}
}
correlationID, b, err := proto.ReadResp(rd)
if err != nil {
c.mu.Lock()
if c.stopErr == nil {
c.stopErr = err
close(c.stop)
}
c.mu.Unlock()
return
}
c.mu.Lock()
rc, ok := c.respc[correlationID]
delete(c.respc, correlationID)
c.mu.Unlock()
if !ok {
c.logger.Warn(
"msg", "response to unknown request",
"correlationID", correlationID)
continue
}
select {
case <-c.stop:
c.mu.Lock()
if c.stopErr == nil {
c.stopErr = ErrClosed
}
c.mu.Unlock()
case rc <- b:
}
close(rc)
}
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"readRespLoop",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"cc",
":=",
"range",
"c",
".",
"respc",
"{",
"close",
"(",
"cc",
")",
"\n",
"}",
"\n",
"c",
".",
"respc",
"=",
"make",
"(",
"map",
"[",
"int32",
"]",
"chan",
"[",
"]",
"byte",
")",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"rd",
":=",
"bufio",
".",
"NewReader",
"(",
"c",
".",
"rw",
")",
"\n",
"for",
"{",
"if",
"c",
".",
"readTimeout",
">",
"0",
"{",
"err",
":=",
"c",
".",
"rw",
".",
"SetReadDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"c",
".",
"readTimeout",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"correlationID",
",",
"b",
",",
"err",
":=",
"proto",
".",
"ReadResp",
"(",
"rd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"stopErr",
"==",
"nil",
"{",
"c",
".",
"stopErr",
"=",
"err",
"\n",
"close",
"(",
"c",
".",
"stop",
")",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"rc",
",",
"ok",
":=",
"c",
".",
"respc",
"[",
"correlationID",
"]",
"\n",
"delete",
"(",
"c",
".",
"respc",
",",
"correlationID",
")",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"c",
".",
"logger",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"correlationID",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"c",
".",
"stop",
":",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"stopErr",
"==",
"nil",
"{",
"c",
".",
"stopErr",
"=",
"ErrClosed",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"case",
"rc",
"<-",
"b",
":",
"}",
"\n",
"close",
"(",
"rc",
")",
"\n",
"}",
"\n",
"}"
] | // readRespLoop constantly reading response messages from the socket and after
// partial parsing, sends byte representation of the whole message to request
// sending process. | [
"readRespLoop",
"constantly",
"reading",
"response",
"messages",
"from",
"the",
"socket",
"and",
"after",
"partial",
"parsing",
"sends",
"byte",
"representation",
"of",
"the",
"whole",
"message",
"to",
"request",
"sending",
"process",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L182-L234 |
11,301 | optiopay/kafka | connection.go | respWaiter | func (c *connection) respWaiter(correlationID int32) (respc chan []byte, err error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.stopErr != nil {
return nil, c.stopErr
}
if _, ok := c.respc[correlationID]; ok {
c.logger.Error("msg", "correlation conflict", "correlationID", correlationID)
return nil, fmt.Errorf("correlation conflict: %d", correlationID)
}
respc = make(chan []byte)
c.respc[correlationID] = respc
return respc, nil
} | go | func (c *connection) respWaiter(correlationID int32) (respc chan []byte, err error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.stopErr != nil {
return nil, c.stopErr
}
if _, ok := c.respc[correlationID]; ok {
c.logger.Error("msg", "correlation conflict", "correlationID", correlationID)
return nil, fmt.Errorf("correlation conflict: %d", correlationID)
}
respc = make(chan []byte)
c.respc[correlationID] = respc
return respc, nil
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"respWaiter",
"(",
"correlationID",
"int32",
")",
"(",
"respc",
"chan",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"c",
".",
"stopErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"c",
".",
"stopErr",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"respc",
"[",
"correlationID",
"]",
";",
"ok",
"{",
"c",
".",
"logger",
".",
"Error",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"correlationID",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"correlationID",
")",
"\n",
"}",
"\n",
"respc",
"=",
"make",
"(",
"chan",
"[",
"]",
"byte",
")",
"\n",
"c",
".",
"respc",
"[",
"correlationID",
"]",
"=",
"respc",
"\n",
"return",
"respc",
",",
"nil",
"\n",
"}"
] | // respWaiter register listener to response message with given correlationID
// and return channel that single response message will be pushed to once it
// will arrive.
// After pushing response message, channel is closed.
//
// Upon connection close, all unconsumed channels are closed. | [
"respWaiter",
"register",
"listener",
"to",
"response",
"message",
"with",
"given",
"correlationID",
"and",
"return",
"channel",
"that",
"single",
"response",
"message",
"will",
"be",
"pushed",
"to",
"once",
"it",
"will",
"arrive",
".",
"After",
"pushing",
"response",
"message",
"channel",
"is",
"closed",
".",
"Upon",
"connection",
"close",
"all",
"unconsumed",
"channels",
"are",
"closed",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L242-L256 |
11,302 | optiopay/kafka | connection.go | releaseWaiter | func (c *connection) releaseWaiter(correlationID int32) {
c.mu.Lock()
rc, ok := c.respc[correlationID]
if ok {
delete(c.respc, correlationID)
close(rc)
}
c.mu.Unlock()
} | go | func (c *connection) releaseWaiter(correlationID int32) {
c.mu.Lock()
rc, ok := c.respc[correlationID]
if ok {
delete(c.respc, correlationID)
close(rc)
}
c.mu.Unlock()
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"releaseWaiter",
"(",
"correlationID",
"int32",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"rc",
",",
"ok",
":=",
"c",
".",
"respc",
"[",
"correlationID",
"]",
"\n",
"if",
"ok",
"{",
"delete",
"(",
"c",
".",
"respc",
",",
"correlationID",
")",
"\n",
"close",
"(",
"rc",
")",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // releaseWaiter removes response channel from waiters pool and close it.
// Calling this method for unknown correlationID has no effect. | [
"releaseWaiter",
"removes",
"response",
"channel",
"from",
"waiters",
"pool",
"and",
"close",
"it",
".",
"Calling",
"this",
"method",
"for",
"unknown",
"correlationID",
"has",
"no",
"effect",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L260-L268 |
11,303 | optiopay/kafka | connection.go | Close | func (c *connection) Close() error {
c.mu.Lock()
if c.stopErr == nil {
c.stopErr = ErrClosed
close(c.stop)
}
c.mu.Unlock()
return c.rw.Close()
} | go | func (c *connection) Close() error {
c.mu.Lock()
if c.stopErr == nil {
c.stopErr = ErrClosed
close(c.stop)
}
c.mu.Unlock()
return c.rw.Close()
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"Close",
"(",
")",
"error",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"stopErr",
"==",
"nil",
"{",
"c",
".",
"stopErr",
"=",
"ErrClosed",
"\n",
"close",
"(",
"c",
".",
"stop",
")",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"c",
".",
"rw",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close close underlying transport connection and cancel all pending response
// waiters. | [
"Close",
"close",
"underlying",
"transport",
"connection",
"and",
"cancel",
"all",
"pending",
"response",
"waiters",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L272-L280 |
11,304 | optiopay/kafka | connection.go | APIVersions | func (c *connection) APIVersions(req *proto.APIVersionsReq) (*proto.APIVersionsResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedAPIVersionsResp(bytes.NewReader(b), req.GetVersion())
} | go | func (c *connection) APIVersions(req *proto.APIVersionsReq) (*proto.APIVersionsResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedAPIVersionsResp(bytes.NewReader(b), req.GetVersion())
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"APIVersions",
"(",
"req",
"*",
"proto",
".",
"APIVersionsReq",
")",
"(",
"*",
"proto",
".",
"APIVersionsResp",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"sendRequest",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"proto",
".",
"ReadVersionedAPIVersionsResp",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"req",
".",
"GetVersion",
"(",
")",
")",
"\n",
"}"
] | // APIVersions sends a request to fetch the supported versions for each API.
// Versioning is only supported in Kafka versions above 0.10.0.0 | [
"APIVersions",
"sends",
"a",
"request",
"to",
"fetch",
"the",
"supported",
"versions",
"for",
"each",
"API",
".",
"Versioning",
"is",
"only",
"supported",
"in",
"Kafka",
"versions",
"above",
"0",
".",
"10",
".",
"0",
".",
"0"
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L325-L331 |
11,305 | optiopay/kafka | connection.go | Metadata | func (c *connection) Metadata(req *proto.MetadataReq) (*proto.MetadataResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedMetadataResp(bytes.NewReader(b), req.GetVersion())
} | go | func (c *connection) Metadata(req *proto.MetadataReq) (*proto.MetadataResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedMetadataResp(bytes.NewReader(b), req.GetVersion())
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"Metadata",
"(",
"req",
"*",
"proto",
".",
"MetadataReq",
")",
"(",
"*",
"proto",
".",
"MetadataResp",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"sendRequest",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"proto",
".",
"ReadVersionedMetadataResp",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"req",
".",
"GetVersion",
"(",
")",
")",
"\n",
"}"
] | // Metadata sends given metadata request to kafka node and returns related
// metadata response.
// Calling this method on closed connection will always return ErrClosed. | [
"Metadata",
"sends",
"given",
"metadata",
"request",
"to",
"kafka",
"node",
"and",
"returns",
"related",
"metadata",
"response",
".",
"Calling",
"this",
"method",
"on",
"closed",
"connection",
"will",
"always",
"return",
"ErrClosed",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L336-L342 |
11,306 | optiopay/kafka | connection.go | CreateTopic | func (c *connection) CreateTopic(req *proto.CreateTopicsReq) (*proto.CreateTopicsResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadCreateTopicsResp(bytes.NewReader(b))
} | go | func (c *connection) CreateTopic(req *proto.CreateTopicsReq) (*proto.CreateTopicsResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadCreateTopicsResp(bytes.NewReader(b))
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"CreateTopic",
"(",
"req",
"*",
"proto",
".",
"CreateTopicsReq",
")",
"(",
"*",
"proto",
".",
"CreateTopicsResp",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"sendRequest",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"proto",
".",
"ReadCreateTopicsResp",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
")",
"\n",
"}"
] | // CreateTopic sends given createTopic request to kafka node and returns related
// response.
// Calling this method on closed connection will always return ErrClosed. | [
"CreateTopic",
"sends",
"given",
"createTopic",
"request",
"to",
"kafka",
"node",
"and",
"returns",
"related",
"response",
".",
"Calling",
"this",
"method",
"on",
"closed",
"connection",
"will",
"always",
"return",
"ErrClosed",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L347-L353 |
11,307 | optiopay/kafka | connection.go | Produce | func (c *connection) Produce(req *proto.ProduceReq) (*proto.ProduceResp, error) {
if req.RequiredAcks == proto.RequiredAcksNone {
return nil, c.sendRequestWithoutAcks(req)
}
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedProduceResp(bytes.NewReader(b), req.GetVersion())
} | go | func (c *connection) Produce(req *proto.ProduceReq) (*proto.ProduceResp, error) {
if req.RequiredAcks == proto.RequiredAcksNone {
return nil, c.sendRequestWithoutAcks(req)
}
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedProduceResp(bytes.NewReader(b), req.GetVersion())
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"Produce",
"(",
"req",
"*",
"proto",
".",
"ProduceReq",
")",
"(",
"*",
"proto",
".",
"ProduceResp",
",",
"error",
")",
"{",
"if",
"req",
".",
"RequiredAcks",
"==",
"proto",
".",
"RequiredAcksNone",
"{",
"return",
"nil",
",",
"c",
".",
"sendRequestWithoutAcks",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"c",
".",
"sendRequest",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"proto",
".",
"ReadVersionedProduceResp",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"req",
".",
"GetVersion",
"(",
")",
")",
"\n",
"}"
] | // Produce sends given produce request to kafka node and returns related
// response. Sending request with no ACKs flag will result with returning nil
// right after sending request, without waiting for response.
// Calling this method on closed connection will always return ErrClosed. | [
"Produce",
"sends",
"given",
"produce",
"request",
"to",
"kafka",
"node",
"and",
"returns",
"related",
"response",
".",
"Sending",
"request",
"with",
"no",
"ACKs",
"flag",
"will",
"result",
"with",
"returning",
"nil",
"right",
"after",
"sending",
"request",
"without",
"waiting",
"for",
"response",
".",
"Calling",
"this",
"method",
"on",
"closed",
"connection",
"will",
"always",
"return",
"ErrClosed",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L359-L371 |
11,308 | optiopay/kafka | connection.go | Fetch | func (c *connection) Fetch(req *proto.FetchReq) (*proto.FetchResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
resp, err := proto.ReadVersionedFetchResp(bytes.NewReader(b), req.GetVersion())
if err != nil {
return nil, err
}
// Compressed messages are returned in full batches for efficiency
// (the broker doesn't need to decompress).
// This means that it's possible to get some leading messages
// with a smaller offset than requested. Trim those.
for ti := range resp.Topics {
topic := &resp.Topics[ti]
reqTopic := &req.Topics[ti]
for pi := range topic.Partitions {
partition := &topic.Partitions[pi]
requestedOffset := reqTopic.Partitions[pi].FetchOffset
i := 0
if partition.MessageVersion < 2 {
for _, msg := range partition.Messages {
if msg.Offset >= requestedOffset {
break
}
i++
}
partition.Messages = partition.Messages[i:]
} else {
firstOffset := partition.RecordBatch.FirstOffset
for _, rec := range partition.RecordBatch.Records {
if firstOffset+rec.OffsetDelta >= requestedOffset {
break
}
i++
}
partition.RecordBatch.Records = partition.RecordBatch.Records[i:]
}
}
}
return resp, nil
} | go | func (c *connection) Fetch(req *proto.FetchReq) (*proto.FetchResp, error) {
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
resp, err := proto.ReadVersionedFetchResp(bytes.NewReader(b), req.GetVersion())
if err != nil {
return nil, err
}
// Compressed messages are returned in full batches for efficiency
// (the broker doesn't need to decompress).
// This means that it's possible to get some leading messages
// with a smaller offset than requested. Trim those.
for ti := range resp.Topics {
topic := &resp.Topics[ti]
reqTopic := &req.Topics[ti]
for pi := range topic.Partitions {
partition := &topic.Partitions[pi]
requestedOffset := reqTopic.Partitions[pi].FetchOffset
i := 0
if partition.MessageVersion < 2 {
for _, msg := range partition.Messages {
if msg.Offset >= requestedOffset {
break
}
i++
}
partition.Messages = partition.Messages[i:]
} else {
firstOffset := partition.RecordBatch.FirstOffset
for _, rec := range partition.RecordBatch.Records {
if firstOffset+rec.OffsetDelta >= requestedOffset {
break
}
i++
}
partition.RecordBatch.Records = partition.RecordBatch.Records[i:]
}
}
}
return resp, nil
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"Fetch",
"(",
"req",
"*",
"proto",
".",
"FetchReq",
")",
"(",
"*",
"proto",
".",
"FetchResp",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"sendRequest",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"proto",
".",
"ReadVersionedFetchResp",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"req",
".",
"GetVersion",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Compressed messages are returned in full batches for efficiency",
"// (the broker doesn't need to decompress).",
"// This means that it's possible to get some leading messages",
"// with a smaller offset than requested. Trim those.",
"for",
"ti",
":=",
"range",
"resp",
".",
"Topics",
"{",
"topic",
":=",
"&",
"resp",
".",
"Topics",
"[",
"ti",
"]",
"\n",
"reqTopic",
":=",
"&",
"req",
".",
"Topics",
"[",
"ti",
"]",
"\n",
"for",
"pi",
":=",
"range",
"topic",
".",
"Partitions",
"{",
"partition",
":=",
"&",
"topic",
".",
"Partitions",
"[",
"pi",
"]",
"\n",
"requestedOffset",
":=",
"reqTopic",
".",
"Partitions",
"[",
"pi",
"]",
".",
"FetchOffset",
"\n",
"i",
":=",
"0",
"\n",
"if",
"partition",
".",
"MessageVersion",
"<",
"2",
"{",
"for",
"_",
",",
"msg",
":=",
"range",
"partition",
".",
"Messages",
"{",
"if",
"msg",
".",
"Offset",
">=",
"requestedOffset",
"{",
"break",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"partition",
".",
"Messages",
"=",
"partition",
".",
"Messages",
"[",
"i",
":",
"]",
"\n",
"}",
"else",
"{",
"firstOffset",
":=",
"partition",
".",
"RecordBatch",
".",
"FirstOffset",
"\n",
"for",
"_",
",",
"rec",
":=",
"range",
"partition",
".",
"RecordBatch",
".",
"Records",
"{",
"if",
"firstOffset",
"+",
"rec",
".",
"OffsetDelta",
">=",
"requestedOffset",
"{",
"break",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"partition",
".",
"RecordBatch",
".",
"Records",
"=",
"partition",
".",
"RecordBatch",
".",
"Records",
"[",
"i",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"resp",
",",
"nil",
"\n",
"}"
] | // Fetch sends given fetch request to kafka node and returns related response.
// Calling this method on closed connection will always return ErrClosed. | [
"Fetch",
"sends",
"given",
"fetch",
"request",
"to",
"kafka",
"node",
"and",
"returns",
"related",
"response",
".",
"Calling",
"this",
"method",
"on",
"closed",
"connection",
"will",
"always",
"return",
"ErrClosed",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L375-L418 |
11,309 | optiopay/kafka | connection.go | Offset | func (c *connection) Offset(req *proto.OffsetReq) (*proto.OffsetResp, error) {
// TODO(husio) documentation is not mentioning this directly, but I assume
// -1 is for non node clients
req.ReplicaID = -1
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedOffsetResp(bytes.NewReader(b), req.GetVersion())
} | go | func (c *connection) Offset(req *proto.OffsetReq) (*proto.OffsetResp, error) {
// TODO(husio) documentation is not mentioning this directly, but I assume
// -1 is for non node clients
req.ReplicaID = -1
b, err := c.sendRequest(req)
if err != nil {
return nil, err
}
return proto.ReadVersionedOffsetResp(bytes.NewReader(b), req.GetVersion())
} | [
"func",
"(",
"c",
"*",
"connection",
")",
"Offset",
"(",
"req",
"*",
"proto",
".",
"OffsetReq",
")",
"(",
"*",
"proto",
".",
"OffsetResp",
",",
"error",
")",
"{",
"// TODO(husio) documentation is not mentioning this directly, but I assume",
"// -1 is for non node clients",
"req",
".",
"ReplicaID",
"=",
"-",
"1",
"\n\n",
"b",
",",
"err",
":=",
"c",
".",
"sendRequest",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"proto",
".",
"ReadVersionedOffsetResp",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"req",
".",
"GetVersion",
"(",
")",
")",
"\n",
"}"
] | // Offset sends given offset request to kafka node and returns related response.
// Calling this method on closed connection will always return ErrClosed. | [
"Offset",
"sends",
"given",
"offset",
"request",
"to",
"kafka",
"node",
"and",
"returns",
"related",
"response",
".",
"Calling",
"this",
"method",
"on",
"closed",
"connection",
"will",
"always",
"return",
"ErrClosed",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L422-L432 |
11,310 | optiopay/kafka | multiplexer.go | Merge | func Merge(consumers ...Consumer) *Mx {
p := &Mx{
errc: make(chan error),
msgc: make(chan *proto.Message),
stop: make(chan struct{}),
workers: len(consumers),
}
for _, consumer := range consumers {
go func(c Consumer) {
defer func() {
p.mu.Lock()
p.workers--
if p.workers == 0 && !p.closed {
close(p.stop)
p.closed = true
}
p.mu.Unlock()
}()
for {
msg, err := c.Consume()
if err != nil {
if err == ErrNoData {
return
}
select {
case p.errc <- err:
case <-p.stop:
return
}
} else {
select {
case p.msgc <- msg:
case <-p.stop:
return
}
}
}
}(consumer)
}
return p
} | go | func Merge(consumers ...Consumer) *Mx {
p := &Mx{
errc: make(chan error),
msgc: make(chan *proto.Message),
stop: make(chan struct{}),
workers: len(consumers),
}
for _, consumer := range consumers {
go func(c Consumer) {
defer func() {
p.mu.Lock()
p.workers--
if p.workers == 0 && !p.closed {
close(p.stop)
p.closed = true
}
p.mu.Unlock()
}()
for {
msg, err := c.Consume()
if err != nil {
if err == ErrNoData {
return
}
select {
case p.errc <- err:
case <-p.stop:
return
}
} else {
select {
case p.msgc <- msg:
case <-p.stop:
return
}
}
}
}(consumer)
}
return p
} | [
"func",
"Merge",
"(",
"consumers",
"...",
"Consumer",
")",
"*",
"Mx",
"{",
"p",
":=",
"&",
"Mx",
"{",
"errc",
":",
"make",
"(",
"chan",
"error",
")",
",",
"msgc",
":",
"make",
"(",
"chan",
"*",
"proto",
".",
"Message",
")",
",",
"stop",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"workers",
":",
"len",
"(",
"consumers",
")",
",",
"}",
"\n\n",
"for",
"_",
",",
"consumer",
":=",
"range",
"consumers",
"{",
"go",
"func",
"(",
"c",
"Consumer",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"p",
".",
"workers",
"--",
"\n",
"if",
"p",
".",
"workers",
"==",
"0",
"&&",
"!",
"p",
".",
"closed",
"{",
"close",
"(",
"p",
".",
"stop",
")",
"\n",
"p",
".",
"closed",
"=",
"true",
"\n",
"}",
"\n",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"for",
"{",
"msg",
",",
"err",
":=",
"c",
".",
"Consume",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"ErrNoData",
"{",
"return",
"\n",
"}",
"\n",
"select",
"{",
"case",
"p",
".",
"errc",
"<-",
"err",
":",
"case",
"<-",
"p",
".",
"stop",
":",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"select",
"{",
"case",
"p",
".",
"msgc",
"<-",
"msg",
":",
"case",
"<-",
"p",
".",
"stop",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
"consumer",
")",
"\n",
"}",
"\n\n",
"return",
"p",
"\n",
"}"
] | // Merge is merging consume result of any number of consumers into single stream
// and expose them through returned multiplexer. | [
"Merge",
"is",
"merging",
"consume",
"result",
"of",
"any",
"number",
"of",
"consumers",
"into",
"single",
"stream",
"and",
"expose",
"them",
"through",
"returned",
"multiplexer",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/multiplexer.go#L40-L83 |
11,311 | optiopay/kafka | multiplexer.go | Workers | func (p *Mx) Workers() int {
p.mu.Lock()
defer p.mu.Unlock()
return p.workers
} | go | func (p *Mx) Workers() int {
p.mu.Lock()
defer p.mu.Unlock()
return p.workers
} | [
"func",
"(",
"p",
"*",
"Mx",
")",
"Workers",
"(",
")",
"int",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"p",
".",
"workers",
"\n",
"}"
] | // Workers return number of active consumer workers that are pushing messages
// to multiplexer conumer queue. | [
"Workers",
"return",
"number",
"of",
"active",
"consumer",
"workers",
"that",
"are",
"pushing",
"messages",
"to",
"multiplexer",
"conumer",
"queue",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/multiplexer.go#L87-L91 |
11,312 | optiopay/kafka | multiplexer.go | Close | func (p *Mx) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if !p.closed {
p.closed = true
close(p.stop)
}
} | go | func (p *Mx) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if !p.closed {
p.closed = true
close(p.stop)
}
} | [
"func",
"(",
"p",
"*",
"Mx",
")",
"Close",
"(",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"p",
".",
"closed",
"{",
"p",
".",
"closed",
"=",
"true",
"\n",
"close",
"(",
"p",
".",
"stop",
")",
"\n",
"}",
"\n",
"}"
] | // Close is closing multiplexer and stopping all underlying workers.
//
// Closing multiplexer will stop all workers as soon as possible, but any
// consume-in-progress action performed by worker has to be finished first. Any
// consumption result received after closing multiplexer is ignored.
//
// Close is returning without waiting for all the workers to finish.
//
// Closing closed multiplexer has no effect. | [
"Close",
"is",
"closing",
"multiplexer",
"and",
"stopping",
"all",
"underlying",
"workers",
".",
"Closing",
"multiplexer",
"will",
"stop",
"all",
"workers",
"as",
"soon",
"as",
"possible",
"but",
"any",
"consume",
"-",
"in",
"-",
"progress",
"action",
"performed",
"by",
"worker",
"has",
"to",
"be",
"finished",
"first",
".",
"Any",
"consumption",
"result",
"received",
"after",
"closing",
"multiplexer",
"is",
"ignored",
".",
"Close",
"is",
"returning",
"without",
"waiting",
"for",
"all",
"the",
"workers",
"to",
"finish",
".",
"Closing",
"closed",
"multiplexer",
"has",
"no",
"effect",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/multiplexer.go#L102-L110 |
11,313 | optiopay/kafka | multiplexer.go | Consume | func (p *Mx) Consume() (*proto.Message, error) {
select {
case <-p.stop:
return nil, ErrMxClosed
case msg := <-p.msgc:
return msg, nil
case err := <-p.errc:
return nil, err
}
} | go | func (p *Mx) Consume() (*proto.Message, error) {
select {
case <-p.stop:
return nil, ErrMxClosed
case msg := <-p.msgc:
return msg, nil
case err := <-p.errc:
return nil, err
}
} | [
"func",
"(",
"p",
"*",
"Mx",
")",
"Consume",
"(",
")",
"(",
"*",
"proto",
".",
"Message",
",",
"error",
")",
"{",
"select",
"{",
"case",
"<-",
"p",
".",
"stop",
":",
"return",
"nil",
",",
"ErrMxClosed",
"\n",
"case",
"msg",
":=",
"<-",
"p",
".",
"msgc",
":",
"return",
"msg",
",",
"nil",
"\n",
"case",
"err",
":=",
"<-",
"p",
".",
"errc",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // Consume returns Consume result from any of the merged consumer. | [
"Consume",
"returns",
"Consume",
"result",
"from",
"any",
"of",
"the",
"merged",
"consumer",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/multiplexer.go#L113-L122 |
11,314 | optiopay/kafka | proto/utils.go | allocParseBuf | func allocParseBuf(size int) ([]byte, error) {
if size < 0 || size > maxParseBufSize {
return nil, messageSizeError(size)
}
return make([]byte, size), nil
} | go | func allocParseBuf(size int) ([]byte, error) {
if size < 0 || size > maxParseBufSize {
return nil, messageSizeError(size)
}
return make([]byte, size), nil
} | [
"func",
"allocParseBuf",
"(",
"size",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"size",
"<",
"0",
"||",
"size",
">",
"maxParseBufSize",
"{",
"return",
"nil",
",",
"messageSizeError",
"(",
"size",
")",
"\n",
"}",
"\n\n",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"size",
")",
",",
"nil",
"\n",
"}"
] | // allocParseBuf is used to allocate buffers used for parsing | [
"allocParseBuf",
"is",
"used",
"to",
"allocate",
"buffers",
"used",
"for",
"parsing"
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/proto/utils.go#L17-L23 |
11,315 | optiopay/kafka | proto/messages.go | ReadReq | func ReadReq(r io.Reader) (requestKind int16, b []byte, err error) {
dec := NewDecoder(r)
msgSize := dec.DecodeInt32()
requestKind = dec.DecodeInt16()
if err := dec.Err(); err != nil {
return 0, nil, err
}
// size of the message + size of the message itself
b, err = allocParseBuf(int(msgSize + 4))
if err != nil {
return 0, nil, err
}
binary.BigEndian.PutUint32(b, uint32(msgSize))
// only write back requestKind if it was included in messageSize
if len(b) >= 6 {
binary.BigEndian.PutUint16(b[4:], uint16(requestKind))
}
// read rest of request into allocated buffer if we allocated for it
if len(b) > 6 {
if _, err := io.ReadFull(r, b[6:]); err != nil {
return 0, nil, err
}
}
return requestKind, b, nil
} | go | func ReadReq(r io.Reader) (requestKind int16, b []byte, err error) {
dec := NewDecoder(r)
msgSize := dec.DecodeInt32()
requestKind = dec.DecodeInt16()
if err := dec.Err(); err != nil {
return 0, nil, err
}
// size of the message + size of the message itself
b, err = allocParseBuf(int(msgSize + 4))
if err != nil {
return 0, nil, err
}
binary.BigEndian.PutUint32(b, uint32(msgSize))
// only write back requestKind if it was included in messageSize
if len(b) >= 6 {
binary.BigEndian.PutUint16(b[4:], uint16(requestKind))
}
// read rest of request into allocated buffer if we allocated for it
if len(b) > 6 {
if _, err := io.ReadFull(r, b[6:]); err != nil {
return 0, nil, err
}
}
return requestKind, b, nil
} | [
"func",
"ReadReq",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"requestKind",
"int16",
",",
"b",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"dec",
":=",
"NewDecoder",
"(",
"r",
")",
"\n",
"msgSize",
":=",
"dec",
".",
"DecodeInt32",
"(",
")",
"\n",
"requestKind",
"=",
"dec",
".",
"DecodeInt16",
"(",
")",
"\n",
"if",
"err",
":=",
"dec",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// size of the message + size of the message itself",
"b",
",",
"err",
"=",
"allocParseBuf",
"(",
"int",
"(",
"msgSize",
"+",
"4",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"b",
",",
"uint32",
"(",
"msgSize",
")",
")",
"\n\n",
"// only write back requestKind if it was included in messageSize",
"if",
"len",
"(",
"b",
")",
">=",
"6",
"{",
"binary",
".",
"BigEndian",
".",
"PutUint16",
"(",
"b",
"[",
"4",
":",
"]",
",",
"uint16",
"(",
"requestKind",
")",
")",
"\n",
"}",
"\n\n",
"// read rest of request into allocated buffer if we allocated for it",
"if",
"len",
"(",
"b",
")",
">",
"6",
"{",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"b",
"[",
"6",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"requestKind",
",",
"b",
",",
"nil",
"\n",
"}"
] | // ReadReq returns request kind ID and byte representation of the whole message
// in wire protocol format. | [
"ReadReq",
"returns",
"request",
"kind",
"ID",
"and",
"byte",
"representation",
"of",
"the",
"whole",
"message",
"in",
"wire",
"protocol",
"format",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/proto/messages.go#L175-L203 |
11,316 | optiopay/kafka | proto/messages.go | ReadResp | func ReadResp(r io.Reader) (correlationID int32, b []byte, err error) {
dec := NewDecoder(r)
msgSize := dec.DecodeInt32()
correlationID = dec.DecodeInt32()
if err := dec.Err(); err != nil {
return 0, nil, err
}
// size of the message + size of the message itself
b, err = allocParseBuf(int(msgSize + 4))
if err != nil {
return 0, nil, err
}
binary.BigEndian.PutUint32(b, uint32(msgSize))
binary.BigEndian.PutUint32(b[4:], uint32(correlationID))
_, err = io.ReadFull(r, b[8:])
return correlationID, b, err
} | go | func ReadResp(r io.Reader) (correlationID int32, b []byte, err error) {
dec := NewDecoder(r)
msgSize := dec.DecodeInt32()
correlationID = dec.DecodeInt32()
if err := dec.Err(); err != nil {
return 0, nil, err
}
// size of the message + size of the message itself
b, err = allocParseBuf(int(msgSize + 4))
if err != nil {
return 0, nil, err
}
binary.BigEndian.PutUint32(b, uint32(msgSize))
binary.BigEndian.PutUint32(b[4:], uint32(correlationID))
_, err = io.ReadFull(r, b[8:])
return correlationID, b, err
} | [
"func",
"ReadResp",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"correlationID",
"int32",
",",
"b",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"dec",
":=",
"NewDecoder",
"(",
"r",
")",
"\n",
"msgSize",
":=",
"dec",
".",
"DecodeInt32",
"(",
")",
"\n",
"correlationID",
"=",
"dec",
".",
"DecodeInt32",
"(",
")",
"\n",
"if",
"err",
":=",
"dec",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// size of the message + size of the message itself",
"b",
",",
"err",
"=",
"allocParseBuf",
"(",
"int",
"(",
"msgSize",
"+",
"4",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"b",
",",
"uint32",
"(",
"msgSize",
")",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"b",
"[",
"4",
":",
"]",
",",
"uint32",
"(",
"correlationID",
")",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"b",
"[",
"8",
":",
"]",
")",
"\n",
"return",
"correlationID",
",",
"b",
",",
"err",
"\n",
"}"
] | // ReadResp returns message correlation ID and byte representation of the whole
// message in wire protocol that is returned when reading from given stream,
// including 4 bytes of message size itself.
// Byte representation returned by ReadResp can be parsed by all response
// reeaders to transform it into specialized response structure. | [
"ReadResp",
"returns",
"message",
"correlation",
"ID",
"and",
"byte",
"representation",
"of",
"the",
"whole",
"message",
"in",
"wire",
"protocol",
"that",
"is",
"returned",
"when",
"reading",
"from",
"given",
"stream",
"including",
"4",
"bytes",
"of",
"message",
"size",
"itself",
".",
"Byte",
"representation",
"returned",
"by",
"ReadResp",
"can",
"be",
"parsed",
"by",
"all",
"response",
"reeaders",
"to",
"transform",
"it",
"into",
"specialized",
"response",
"structure",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/proto/messages.go#L210-L227 |
11,317 | optiopay/kafka | proto/messages.go | ComputeCrc | func ComputeCrc(m *Message, compression Compression) uint32 {
var buf bytes.Buffer
enc := NewEncoder(&buf)
enc.EncodeInt8(0) // magic byte is always 0
enc.EncodeInt8(int8(compression))
enc.EncodeBytes(m.Key)
enc.EncodeBytes(m.Value)
return crc32.ChecksumIEEE(buf.Bytes())
} | go | func ComputeCrc(m *Message, compression Compression) uint32 {
var buf bytes.Buffer
enc := NewEncoder(&buf)
enc.EncodeInt8(0) // magic byte is always 0
enc.EncodeInt8(int8(compression))
enc.EncodeBytes(m.Key)
enc.EncodeBytes(m.Value)
return crc32.ChecksumIEEE(buf.Bytes())
} | [
"func",
"ComputeCrc",
"(",
"m",
"*",
"Message",
",",
"compression",
"Compression",
")",
"uint32",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"enc",
":=",
"NewEncoder",
"(",
"&",
"buf",
")",
"\n",
"enc",
".",
"EncodeInt8",
"(",
"0",
")",
"// magic byte is always 0",
"\n",
"enc",
".",
"EncodeInt8",
"(",
"int8",
"(",
"compression",
")",
")",
"\n",
"enc",
".",
"EncodeBytes",
"(",
"m",
".",
"Key",
")",
"\n",
"enc",
".",
"EncodeBytes",
"(",
"m",
".",
"Value",
")",
"\n",
"return",
"crc32",
".",
"ChecksumIEEE",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // ComputeCrc returns crc32 hash for given message content. | [
"ComputeCrc",
"returns",
"crc32",
"hash",
"for",
"given",
"message",
"content",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/proto/messages.go#L241-L249 |
11,318 | optiopay/kafka | proto/messages.go | writeMessageSet | func writeMessageSet(w io.Writer, messages []*Message, compression Compression) (int, error) {
if len(messages) == 0 {
return 0, nil
}
// NOTE(caleb): it doesn't appear to be documented, but I observed that the
// Java client sets the offset of the synthesized message set for a group of
// compressed messages to be the offset of the last message in the set.
compressOffset := messages[len(messages)-1].Offset
switch compression {
case CompressionGzip:
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err := writeMessageSet(gz, messages, CompressionNone); err != nil {
return 0, err
}
if err := gz.Close(); err != nil {
return 0, err
}
messages = []*Message{
{
Value: buf.Bytes(),
Offset: compressOffset,
},
}
case CompressionSnappy:
var buf bytes.Buffer
if _, err := writeMessageSet(&buf, messages, CompressionNone); err != nil {
return 0, err
}
messages = []*Message{
{
Value: snappy.Encode(nil, buf.Bytes()),
Offset: compressOffset,
},
}
}
totalSize := 0
b, err := newSliceWriter(0)
if err != nil {
return 0, err
}
for _, message := range messages {
bsize := 26 + len(message.Key) + len(message.Value)
if err := b.Reset(bsize); err != nil {
return 0, err
}
enc := NewEncoder(b)
enc.EncodeInt64(message.Offset)
msize := int32(14 + len(message.Key) + len(message.Value))
enc.EncodeInt32(msize)
enc.EncodeUint32(0) // crc32 placeholder
enc.EncodeInt8(0) // magic byte
enc.EncodeInt8(int8(compression))
enc.EncodeBytes(message.Key)
enc.EncodeBytes(message.Value)
if err := enc.Err(); err != nil {
return totalSize, err
}
const hsize = 8 + 4 + 4 // offset + message size + crc32
const crcoff = 8 + 4 // offset + message size
binary.BigEndian.PutUint32(b.buf[crcoff:crcoff+4], crc32.ChecksumIEEE(b.buf[hsize:bsize]))
if n, err := w.Write(b.Slice()); err != nil {
return totalSize, err
} else {
totalSize += n
}
}
return totalSize, nil
} | go | func writeMessageSet(w io.Writer, messages []*Message, compression Compression) (int, error) {
if len(messages) == 0 {
return 0, nil
}
// NOTE(caleb): it doesn't appear to be documented, but I observed that the
// Java client sets the offset of the synthesized message set for a group of
// compressed messages to be the offset of the last message in the set.
compressOffset := messages[len(messages)-1].Offset
switch compression {
case CompressionGzip:
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err := writeMessageSet(gz, messages, CompressionNone); err != nil {
return 0, err
}
if err := gz.Close(); err != nil {
return 0, err
}
messages = []*Message{
{
Value: buf.Bytes(),
Offset: compressOffset,
},
}
case CompressionSnappy:
var buf bytes.Buffer
if _, err := writeMessageSet(&buf, messages, CompressionNone); err != nil {
return 0, err
}
messages = []*Message{
{
Value: snappy.Encode(nil, buf.Bytes()),
Offset: compressOffset,
},
}
}
totalSize := 0
b, err := newSliceWriter(0)
if err != nil {
return 0, err
}
for _, message := range messages {
bsize := 26 + len(message.Key) + len(message.Value)
if err := b.Reset(bsize); err != nil {
return 0, err
}
enc := NewEncoder(b)
enc.EncodeInt64(message.Offset)
msize := int32(14 + len(message.Key) + len(message.Value))
enc.EncodeInt32(msize)
enc.EncodeUint32(0) // crc32 placeholder
enc.EncodeInt8(0) // magic byte
enc.EncodeInt8(int8(compression))
enc.EncodeBytes(message.Key)
enc.EncodeBytes(message.Value)
if err := enc.Err(); err != nil {
return totalSize, err
}
const hsize = 8 + 4 + 4 // offset + message size + crc32
const crcoff = 8 + 4 // offset + message size
binary.BigEndian.PutUint32(b.buf[crcoff:crcoff+4], crc32.ChecksumIEEE(b.buf[hsize:bsize]))
if n, err := w.Write(b.Slice()); err != nil {
return totalSize, err
} else {
totalSize += n
}
}
return totalSize, nil
} | [
"func",
"writeMessageSet",
"(",
"w",
"io",
".",
"Writer",
",",
"messages",
"[",
"]",
"*",
"Message",
",",
"compression",
"Compression",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"len",
"(",
"messages",
")",
"==",
"0",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n",
"// NOTE(caleb): it doesn't appear to be documented, but I observed that the",
"// Java client sets the offset of the synthesized message set for a group of",
"// compressed messages to be the offset of the last message in the set.",
"compressOffset",
":=",
"messages",
"[",
"len",
"(",
"messages",
")",
"-",
"1",
"]",
".",
"Offset",
"\n",
"switch",
"compression",
"{",
"case",
"CompressionGzip",
":",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"gz",
":=",
"gzip",
".",
"NewWriter",
"(",
"&",
"buf",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"writeMessageSet",
"(",
"gz",
",",
"messages",
",",
"CompressionNone",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gz",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"messages",
"=",
"[",
"]",
"*",
"Message",
"{",
"{",
"Value",
":",
"buf",
".",
"Bytes",
"(",
")",
",",
"Offset",
":",
"compressOffset",
",",
"}",
",",
"}",
"\n",
"case",
"CompressionSnappy",
":",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"_",
",",
"err",
":=",
"writeMessageSet",
"(",
"&",
"buf",
",",
"messages",
",",
"CompressionNone",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"messages",
"=",
"[",
"]",
"*",
"Message",
"{",
"{",
"Value",
":",
"snappy",
".",
"Encode",
"(",
"nil",
",",
"buf",
".",
"Bytes",
"(",
")",
")",
",",
"Offset",
":",
"compressOffset",
",",
"}",
",",
"}",
"\n",
"}",
"\n\n",
"totalSize",
":=",
"0",
"\n",
"b",
",",
"err",
":=",
"newSliceWriter",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"message",
":=",
"range",
"messages",
"{",
"bsize",
":=",
"26",
"+",
"len",
"(",
"message",
".",
"Key",
")",
"+",
"len",
"(",
"message",
".",
"Value",
")",
"\n",
"if",
"err",
":=",
"b",
".",
"Reset",
"(",
"bsize",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"enc",
":=",
"NewEncoder",
"(",
"b",
")",
"\n",
"enc",
".",
"EncodeInt64",
"(",
"message",
".",
"Offset",
")",
"\n",
"msize",
":=",
"int32",
"(",
"14",
"+",
"len",
"(",
"message",
".",
"Key",
")",
"+",
"len",
"(",
"message",
".",
"Value",
")",
")",
"\n",
"enc",
".",
"EncodeInt32",
"(",
"msize",
")",
"\n",
"enc",
".",
"EncodeUint32",
"(",
"0",
")",
"// crc32 placeholder",
"\n",
"enc",
".",
"EncodeInt8",
"(",
"0",
")",
"// magic byte",
"\n",
"enc",
".",
"EncodeInt8",
"(",
"int8",
"(",
"compression",
")",
")",
"\n",
"enc",
".",
"EncodeBytes",
"(",
"message",
".",
"Key",
")",
"\n",
"enc",
".",
"EncodeBytes",
"(",
"message",
".",
"Value",
")",
"\n\n",
"if",
"err",
":=",
"enc",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"totalSize",
",",
"err",
"\n",
"}",
"\n\n",
"const",
"hsize",
"=",
"8",
"+",
"4",
"+",
"4",
"// offset + message size + crc32",
"\n",
"const",
"crcoff",
"=",
"8",
"+",
"4",
"// offset + message size",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"b",
".",
"buf",
"[",
"crcoff",
":",
"crcoff",
"+",
"4",
"]",
",",
"crc32",
".",
"ChecksumIEEE",
"(",
"b",
".",
"buf",
"[",
"hsize",
":",
"bsize",
"]",
")",
")",
"\n\n",
"if",
"n",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"b",
".",
"Slice",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"totalSize",
",",
"err",
"\n",
"}",
"else",
"{",
"totalSize",
"+=",
"n",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"totalSize",
",",
"nil",
"\n",
"}"
] | // writeMessageSet writes a Message Set into w.
// It returns the number of bytes written and any error. | [
"writeMessageSet",
"writes",
"a",
"Message",
"Set",
"into",
"w",
".",
"It",
"returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/proto/messages.go#L253-L328 |
11,319 | optiopay/kafka | integration/cluster.go | Start | func (cluster *KafkaCluster) Start() error {
cluster.mu.Lock()
defer cluster.mu.Unlock()
// ensure cluster is not running
if err := cluster.Stop(); err != nil {
return fmt.Errorf("cannot ensure stop cluster: %s", err)
}
if err := cluster.removeStoppedContainers(); err != nil {
return fmt.Errorf("cannot cleanup dead containers: %s", err)
}
args := []string{"--no-ansi", "up", "-d", "--scale", fmt.Sprintf("kafka=%d", cluster.size)}
upCmd, _, stderr := cluster.cmd("docker-compose", args...)
err := upCmd.Run()
if err != nil {
return fmt.Errorf("docker-compose error: %s, %s", err, stderr)
}
containers, err := cluster.Containers()
if err != nil {
_ = cluster.Stop()
return fmt.Errorf("cannot get containers info: %s", err)
}
cluster.containers = containers
return nil
} | go | func (cluster *KafkaCluster) Start() error {
cluster.mu.Lock()
defer cluster.mu.Unlock()
// ensure cluster is not running
if err := cluster.Stop(); err != nil {
return fmt.Errorf("cannot ensure stop cluster: %s", err)
}
if err := cluster.removeStoppedContainers(); err != nil {
return fmt.Errorf("cannot cleanup dead containers: %s", err)
}
args := []string{"--no-ansi", "up", "-d", "--scale", fmt.Sprintf("kafka=%d", cluster.size)}
upCmd, _, stderr := cluster.cmd("docker-compose", args...)
err := upCmd.Run()
if err != nil {
return fmt.Errorf("docker-compose error: %s, %s", err, stderr)
}
containers, err := cluster.Containers()
if err != nil {
_ = cluster.Stop()
return fmt.Errorf("cannot get containers info: %s", err)
}
cluster.containers = containers
return nil
} | [
"func",
"(",
"cluster",
"*",
"KafkaCluster",
")",
"Start",
"(",
")",
"error",
"{",
"cluster",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cluster",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// ensure cluster is not running",
"if",
"err",
":=",
"cluster",
".",
"Stop",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cluster",
".",
"removeStoppedContainers",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"args",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cluster",
".",
"size",
")",
"}",
"\n",
"upCmd",
",",
"_",
",",
"stderr",
":=",
"cluster",
".",
"cmd",
"(",
"\"",
"\"",
",",
"args",
"...",
")",
"\n",
"err",
":=",
"upCmd",
".",
"Run",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"stderr",
")",
"\n",
"}",
"\n\n",
"containers",
",",
"err",
":=",
"cluster",
".",
"Containers",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"_",
"=",
"cluster",
".",
"Stop",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cluster",
".",
"containers",
"=",
"containers",
"\n",
"return",
"nil",
"\n",
"}"
] | // Start start zookeeper and kafka nodes using docker-compose command. Upon
// successful process spawn, cluster is scaled to required amount of nodes. | [
"Start",
"start",
"zookeeper",
"and",
"kafka",
"nodes",
"using",
"docker",
"-",
"compose",
"command",
".",
"Upon",
"successful",
"process",
"spawn",
"cluster",
"is",
"scaled",
"to",
"required",
"amount",
"of",
"nodes",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/integration/cluster.go#L64-L90 |
11,320 | optiopay/kafka | integration/cluster.go | Containers | func (cluster *KafkaCluster) Containers() ([]*Container, error) {
psCmd, stdout, stderr := cluster.cmd("docker-compose", "ps", "-q")
err := psCmd.Run()
if err != nil {
return nil, fmt.Errorf("Cannot list processes: %s, %s", err, stderr.String())
}
containerIDs := stdout.String()
var containers []*Container
endpoint := "unix:///var/run/docker.sock"
client, err := docker.NewClient(endpoint)
if err != nil {
return nil, fmt.Errorf("Cannot open connection to docker %s", err)
}
for _, containerID := range strings.Split(strings.TrimSpace(containerIDs), "\n") {
if containerID == "" {
continue
}
container, err := client.InspectContainer(containerID)
if err != nil {
return nil, fmt.Errorf("Cannot inspect docker container %s", err)
}
containers = append(containers, &Container{cluster: cluster, Container: container})
}
return containers, nil
} | go | func (cluster *KafkaCluster) Containers() ([]*Container, error) {
psCmd, stdout, stderr := cluster.cmd("docker-compose", "ps", "-q")
err := psCmd.Run()
if err != nil {
return nil, fmt.Errorf("Cannot list processes: %s, %s", err, stderr.String())
}
containerIDs := stdout.String()
var containers []*Container
endpoint := "unix:///var/run/docker.sock"
client, err := docker.NewClient(endpoint)
if err != nil {
return nil, fmt.Errorf("Cannot open connection to docker %s", err)
}
for _, containerID := range strings.Split(strings.TrimSpace(containerIDs), "\n") {
if containerID == "" {
continue
}
container, err := client.InspectContainer(containerID)
if err != nil {
return nil, fmt.Errorf("Cannot inspect docker container %s", err)
}
containers = append(containers, &Container{cluster: cluster, Container: container})
}
return containers, nil
} | [
"func",
"(",
"cluster",
"*",
"KafkaCluster",
")",
"Containers",
"(",
")",
"(",
"[",
"]",
"*",
"Container",
",",
"error",
")",
"{",
"psCmd",
",",
"stdout",
",",
"stderr",
":=",
"cluster",
".",
"cmd",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"err",
":=",
"psCmd",
".",
"Run",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"stderr",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"containerIDs",
":=",
"stdout",
".",
"String",
"(",
")",
"\n\n",
"var",
"containers",
"[",
"]",
"*",
"Container",
"\n\n",
"endpoint",
":=",
"\"",
"\"",
"\n",
"client",
",",
"err",
":=",
"docker",
".",
"NewClient",
"(",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"containerID",
":=",
"range",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"containerIDs",
")",
",",
"\"",
"\\n",
"\"",
")",
"{",
"if",
"containerID",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"container",
",",
"err",
":=",
"client",
".",
"InspectContainer",
"(",
"containerID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"containers",
"=",
"append",
"(",
"containers",
",",
"&",
"Container",
"{",
"cluster",
":",
"cluster",
",",
"Container",
":",
"container",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"containers",
",",
"nil",
"\n",
"}"
] | // Containers inspect all containers running within cluster and return
// information about them. | [
"Containers",
"inspect",
"all",
"containers",
"running",
"within",
"cluster",
"and",
"return",
"information",
"about",
"them",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/integration/cluster.go#L119-L147 |
11,321 | optiopay/kafka | distributing_producer.go | NewRandomProducer | func NewRandomProducer(p Producer, numPartitions int32) DistributingProducer {
return &randomProducer{
rand: saferand{r: rand.New(rand.NewSource(time.Now().UnixNano()))},
producer: p,
partitions: numPartitions,
}
} | go | func NewRandomProducer(p Producer, numPartitions int32) DistributingProducer {
return &randomProducer{
rand: saferand{r: rand.New(rand.NewSource(time.Now().UnixNano()))},
producer: p,
partitions: numPartitions,
}
} | [
"func",
"NewRandomProducer",
"(",
"p",
"Producer",
",",
"numPartitions",
"int32",
")",
"DistributingProducer",
"{",
"return",
"&",
"randomProducer",
"{",
"rand",
":",
"saferand",
"{",
"r",
":",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
"}",
",",
"producer",
":",
"p",
",",
"partitions",
":",
"numPartitions",
",",
"}",
"\n",
"}"
] | // NewRandomProducer wraps given producer and return DistributingProducer that
// publish messages to kafka, randomly picking partition number from range
// [0, numPartitions) | [
"NewRandomProducer",
"wraps",
"given",
"producer",
"and",
"return",
"DistributingProducer",
"that",
"publish",
"messages",
"to",
"kafka",
"randomly",
"picking",
"partition",
"number",
"from",
"range",
"[",
"0",
"numPartitions",
")"
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/distributing_producer.go#L47-L53 |
11,322 | optiopay/kafka | distributing_producer.go | Distribute | func (p *randomProducer) Distribute(topic string, messages ...*proto.Message) (offset int64, err error) {
// In the case there are no partitions, which may happen for new topics
// when AllowTopicCreation is passed, we will write to partition 0
// since rand.Intn panics with 0
part := 0
if p.partitions > 0 {
part = p.rand.Intn(int(p.partitions))
}
return p.producer.Produce(topic, int32(part), messages...)
} | go | func (p *randomProducer) Distribute(topic string, messages ...*proto.Message) (offset int64, err error) {
// In the case there are no partitions, which may happen for new topics
// when AllowTopicCreation is passed, we will write to partition 0
// since rand.Intn panics with 0
part := 0
if p.partitions > 0 {
part = p.rand.Intn(int(p.partitions))
}
return p.producer.Produce(topic, int32(part), messages...)
} | [
"func",
"(",
"p",
"*",
"randomProducer",
")",
"Distribute",
"(",
"topic",
"string",
",",
"messages",
"...",
"*",
"proto",
".",
"Message",
")",
"(",
"offset",
"int64",
",",
"err",
"error",
")",
"{",
"// In the case there are no partitions, which may happen for new topics",
"// when AllowTopicCreation is passed, we will write to partition 0",
"// since rand.Intn panics with 0",
"part",
":=",
"0",
"\n",
"if",
"p",
".",
"partitions",
">",
"0",
"{",
"part",
"=",
"p",
".",
"rand",
".",
"Intn",
"(",
"int",
"(",
"p",
".",
"partitions",
")",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"producer",
".",
"Produce",
"(",
"topic",
",",
"int32",
"(",
"part",
")",
",",
"messages",
"...",
")",
"\n",
"}"
] | // Distribute write messages to given kafka topic, randomly destination choosing
// partition. All messages written within single Produce call are atomically
// written to the same destination. | [
"Distribute",
"write",
"messages",
"to",
"given",
"kafka",
"topic",
"randomly",
"destination",
"choosing",
"partition",
".",
"All",
"messages",
"written",
"within",
"single",
"Produce",
"call",
"are",
"atomically",
"written",
"to",
"the",
"same",
"destination",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/distributing_producer.go#L58-L67 |
11,323 | optiopay/kafka | distributing_producer.go | NewRoundRobinProducer | func NewRoundRobinProducer(p Producer, numPartitions int32) DistributingProducer {
return &roundRobinProducer{
producer: p,
partitions: numPartitions,
next: 0,
}
} | go | func NewRoundRobinProducer(p Producer, numPartitions int32) DistributingProducer {
return &roundRobinProducer{
producer: p,
partitions: numPartitions,
next: 0,
}
} | [
"func",
"NewRoundRobinProducer",
"(",
"p",
"Producer",
",",
"numPartitions",
"int32",
")",
"DistributingProducer",
"{",
"return",
"&",
"roundRobinProducer",
"{",
"producer",
":",
"p",
",",
"partitions",
":",
"numPartitions",
",",
"next",
":",
"0",
",",
"}",
"\n",
"}"
] | // NewRoundRobinProducer wraps given producer and return DistributingProducer
// that publish messages to kafka, choosing destination partition from cycle
// build from [0, numPartitions) range. | [
"NewRoundRobinProducer",
"wraps",
"given",
"producer",
"and",
"return",
"DistributingProducer",
"that",
"publish",
"messages",
"to",
"kafka",
"choosing",
"destination",
"partition",
"from",
"cycle",
"build",
"from",
"[",
"0",
"numPartitions",
")",
"range",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/distributing_producer.go#L79-L85 |
11,324 | optiopay/kafka | distributing_producer.go | Distribute | func (p *roundRobinProducer) Distribute(topic string, messages ...*proto.Message) (offset int64, err error) {
p.mu.Lock()
part := p.next
p.next++
if p.next >= p.partitions {
p.next = 0
}
p.mu.Unlock()
return p.producer.Produce(topic, int32(part), messages...)
} | go | func (p *roundRobinProducer) Distribute(topic string, messages ...*proto.Message) (offset int64, err error) {
p.mu.Lock()
part := p.next
p.next++
if p.next >= p.partitions {
p.next = 0
}
p.mu.Unlock()
return p.producer.Produce(topic, int32(part), messages...)
} | [
"func",
"(",
"p",
"*",
"roundRobinProducer",
")",
"Distribute",
"(",
"topic",
"string",
",",
"messages",
"...",
"*",
"proto",
".",
"Message",
")",
"(",
"offset",
"int64",
",",
"err",
"error",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"part",
":=",
"p",
".",
"next",
"\n",
"p",
".",
"next",
"++",
"\n",
"if",
"p",
".",
"next",
">=",
"p",
".",
"partitions",
"{",
"p",
".",
"next",
"=",
"0",
"\n",
"}",
"\n",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"p",
".",
"producer",
".",
"Produce",
"(",
"topic",
",",
"int32",
"(",
"part",
")",
",",
"messages",
"...",
")",
"\n",
"}"
] | // Distribute write messages to given kafka topic, choosing next destination
// partition from internal cycle. All messages written within single Produce
// call are atomically written to the same destination. | [
"Distribute",
"write",
"messages",
"to",
"given",
"kafka",
"topic",
"choosing",
"next",
"destination",
"partition",
"from",
"internal",
"cycle",
".",
"All",
"messages",
"written",
"within",
"single",
"Produce",
"call",
"are",
"atomically",
"written",
"to",
"the",
"same",
"destination",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/distributing_producer.go#L90-L100 |
11,325 | optiopay/kafka | distributing_producer.go | NewHashProducer | func NewHashProducer(p Producer, numPartitions int32) DistributingProducer {
return &hashProducer{
producer: p,
partitions: numPartitions,
}
} | go | func NewHashProducer(p Producer, numPartitions int32) DistributingProducer {
return &hashProducer{
producer: p,
partitions: numPartitions,
}
} | [
"func",
"NewHashProducer",
"(",
"p",
"Producer",
",",
"numPartitions",
"int32",
")",
"DistributingProducer",
"{",
"return",
"&",
"hashProducer",
"{",
"producer",
":",
"p",
",",
"partitions",
":",
"numPartitions",
",",
"}",
"\n",
"}"
] | // NewHashProducer wraps given producer and return DistributingProducer that
// publish messages to kafka, computing partition number from message key hash,
// using fnv hash and [0, numPartitions) range. | [
"NewHashProducer",
"wraps",
"given",
"producer",
"and",
"return",
"DistributingProducer",
"that",
"publish",
"messages",
"to",
"kafka",
"computing",
"partition",
"number",
"from",
"message",
"key",
"hash",
"using",
"fnv",
"hash",
"and",
"[",
"0",
"numPartitions",
")",
"range",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/distributing_producer.go#L110-L115 |
11,326 | optiopay/kafka | distributing_producer.go | Distribute | func (p *hashProducer) Distribute(topic string, messages ...*proto.Message) (offset int64, err error) {
if len(messages) == 0 {
return 0, errors.New("no messages")
}
part, err := messageHashPartition(messages[0].Key, p.partitions)
if err != nil {
return 0, fmt.Errorf("cannot hash message: %s", err)
}
// make sure that all messages within single call are to the same destination
for i := 2; i < len(messages); i++ {
mp, err := messageHashPartition(messages[i].Key, p.partitions)
if err != nil {
return 0, fmt.Errorf("cannot hash message: %s", err)
}
if part != mp {
return 0, errors.New("cannot publish messages to different destinations")
}
}
return p.producer.Produce(topic, part, messages...)
} | go | func (p *hashProducer) Distribute(topic string, messages ...*proto.Message) (offset int64, err error) {
if len(messages) == 0 {
return 0, errors.New("no messages")
}
part, err := messageHashPartition(messages[0].Key, p.partitions)
if err != nil {
return 0, fmt.Errorf("cannot hash message: %s", err)
}
// make sure that all messages within single call are to the same destination
for i := 2; i < len(messages); i++ {
mp, err := messageHashPartition(messages[i].Key, p.partitions)
if err != nil {
return 0, fmt.Errorf("cannot hash message: %s", err)
}
if part != mp {
return 0, errors.New("cannot publish messages to different destinations")
}
}
return p.producer.Produce(topic, part, messages...)
} | [
"func",
"(",
"p",
"*",
"hashProducer",
")",
"Distribute",
"(",
"topic",
"string",
",",
"messages",
"...",
"*",
"proto",
".",
"Message",
")",
"(",
"offset",
"int64",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"messages",
")",
"==",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"part",
",",
"err",
":=",
"messageHashPartition",
"(",
"messages",
"[",
"0",
"]",
".",
"Key",
",",
"p",
".",
"partitions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// make sure that all messages within single call are to the same destination",
"for",
"i",
":=",
"2",
";",
"i",
"<",
"len",
"(",
"messages",
")",
";",
"i",
"++",
"{",
"mp",
",",
"err",
":=",
"messageHashPartition",
"(",
"messages",
"[",
"i",
"]",
".",
"Key",
",",
"p",
".",
"partitions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"part",
"!=",
"mp",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"p",
".",
"producer",
".",
"Produce",
"(",
"topic",
",",
"part",
",",
"messages",
"...",
")",
"\n",
"}"
] | // Distribute write messages to given kafka topic, computing partition number from
// the message key value. Message key must be not nil and all messages written
// within single Produce call are atomically written to the same destination.
//
// All messages passed within single Produce call must hash to the same
// destination, otherwise no message is written and error is returned. | [
"Distribute",
"write",
"messages",
"to",
"given",
"kafka",
"topic",
"computing",
"partition",
"number",
"from",
"the",
"message",
"key",
"value",
".",
"Message",
"key",
"must",
"be",
"not",
"nil",
"and",
"all",
"messages",
"written",
"within",
"single",
"Produce",
"call",
"are",
"atomically",
"written",
"to",
"the",
"same",
"destination",
".",
"All",
"messages",
"passed",
"within",
"single",
"Produce",
"call",
"must",
"hash",
"to",
"the",
"same",
"destination",
"otherwise",
"no",
"message",
"is",
"written",
"and",
"error",
"is",
"returned",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/distributing_producer.go#L123-L143 |
11,327 | optiopay/kafka | distributing_producer.go | messageHashPartition | func messageHashPartition(key []byte, partitions int32) (int32, error) {
if key == nil {
return 0, errors.New("no key")
}
hasher := fnv.New32a()
if _, err := hasher.Write(key); err != nil {
return 0, fmt.Errorf("cannot hash key: %s", err)
}
sum := int32(hasher.Sum32())
if sum < 0 {
sum = -sum
}
return sum % partitions, nil
} | go | func messageHashPartition(key []byte, partitions int32) (int32, error) {
if key == nil {
return 0, errors.New("no key")
}
hasher := fnv.New32a()
if _, err := hasher.Write(key); err != nil {
return 0, fmt.Errorf("cannot hash key: %s", err)
}
sum := int32(hasher.Sum32())
if sum < 0 {
sum = -sum
}
return sum % partitions, nil
} | [
"func",
"messageHashPartition",
"(",
"key",
"[",
"]",
"byte",
",",
"partitions",
"int32",
")",
"(",
"int32",
",",
"error",
")",
"{",
"if",
"key",
"==",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"hasher",
":=",
"fnv",
".",
"New32a",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"hasher",
".",
"Write",
"(",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"sum",
":=",
"int32",
"(",
"hasher",
".",
"Sum32",
"(",
")",
")",
"\n",
"if",
"sum",
"<",
"0",
"{",
"sum",
"=",
"-",
"sum",
"\n",
"}",
"\n",
"return",
"sum",
"%",
"partitions",
",",
"nil",
"\n",
"}"
] | // messageHashPartition compute destination partition number for given key
// value and total number of partitions. | [
"messageHashPartition",
"compute",
"destination",
"partition",
"number",
"for",
"given",
"key",
"value",
"and",
"total",
"number",
"of",
"partitions",
"."
] | 6c126522640ec5e8e232d0e219160b30a92814f8 | https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/distributing_producer.go#L147-L160 |
11,328 | starkandwayne/shield | tui/form.go | NewField | func (f *Form) NewField(label string, name string, value interface{}, showas string, fn FieldProcessor) (*Field, error) {
tmpField := Field{
Label: label,
Name: name,
ShowAs: showas,
Value: value,
Processor: fn,
Hidden: false,
}
f.Fields = append(f.Fields, &tmpField)
return &tmpField, nil
} | go | func (f *Form) NewField(label string, name string, value interface{}, showas string, fn FieldProcessor) (*Field, error) {
tmpField := Field{
Label: label,
Name: name,
ShowAs: showas,
Value: value,
Processor: fn,
Hidden: false,
}
f.Fields = append(f.Fields, &tmpField)
return &tmpField, nil
} | [
"func",
"(",
"f",
"*",
"Form",
")",
"NewField",
"(",
"label",
"string",
",",
"name",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"showas",
"string",
",",
"fn",
"FieldProcessor",
")",
"(",
"*",
"Field",
",",
"error",
")",
"{",
"tmpField",
":=",
"Field",
"{",
"Label",
":",
"label",
",",
"Name",
":",
"name",
",",
"ShowAs",
":",
"showas",
",",
"Value",
":",
"value",
",",
"Processor",
":",
"fn",
",",
"Hidden",
":",
"false",
",",
"}",
"\n",
"f",
".",
"Fields",
"=",
"append",
"(",
"f",
".",
"Fields",
",",
"&",
"tmpField",
")",
"\n",
"return",
"&",
"tmpField",
",",
"nil",
"\n",
"}"
] | // NewField appends a new Field to the Form. | [
"NewField",
"appends",
"a",
"new",
"Field",
"to",
"the",
"Form",
"."
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/tui/form.go#L50-L61 |
11,329 | starkandwayne/shield | tui/form.go | GetField | func (f *Form) GetField(name string) *Field {
for _, field := range f.Fields {
if field.Name == name {
return field
}
}
return nil
} | go | func (f *Form) GetField(name string) *Field {
for _, field := range f.Fields {
if field.Name == name {
return field
}
}
return nil
} | [
"func",
"(",
"f",
"*",
"Form",
")",
"GetField",
"(",
"name",
"string",
")",
"*",
"Field",
"{",
"for",
"_",
",",
"field",
":=",
"range",
"f",
".",
"Fields",
"{",
"if",
"field",
".",
"Name",
"==",
"name",
"{",
"return",
"field",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | //GetField retrieves the reference to the Field with the Name attribute given
//to this function. Returns nil if no such Field was found. | [
"GetField",
"retrieves",
"the",
"reference",
"to",
"the",
"Field",
"with",
"the",
"Name",
"attribute",
"given",
"to",
"this",
"function",
".",
"Returns",
"nil",
"if",
"no",
"such",
"Field",
"was",
"found",
"."
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/tui/form.go#L65-L72 |
11,330 | starkandwayne/shield | plugin/cassandra/plugin.go | hardLinkAll | func hardLinkAll(src_dir string, dst_dir string) (err error) {
dir, err := os.Open(src_dir)
if err != nil {
return err
}
defer func() {
dir.Close()
}()
entries, err := dir.Readdir(-1)
if err != nil {
return err
}
for _, tableDirInfo := range entries {
if tableDirInfo.IsDir() {
continue
}
src := filepath.Join(src_dir, tableDirInfo.Name())
dst := filepath.Join(dst_dir, tableDirInfo.Name())
err = os.Link(src, dst)
if err != nil {
return err
}
}
return nil
} | go | func hardLinkAll(src_dir string, dst_dir string) (err error) {
dir, err := os.Open(src_dir)
if err != nil {
return err
}
defer func() {
dir.Close()
}()
entries, err := dir.Readdir(-1)
if err != nil {
return err
}
for _, tableDirInfo := range entries {
if tableDirInfo.IsDir() {
continue
}
src := filepath.Join(src_dir, tableDirInfo.Name())
dst := filepath.Join(dst_dir, tableDirInfo.Name())
err = os.Link(src, dst)
if err != nil {
return err
}
}
return nil
} | [
"func",
"hardLinkAll",
"(",
"src_dir",
"string",
",",
"dst_dir",
"string",
")",
"(",
"err",
"error",
")",
"{",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"src_dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"dir",
".",
"Close",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"entries",
",",
"err",
":=",
"dir",
".",
"Readdir",
"(",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"tableDirInfo",
":=",
"range",
"entries",
"{",
"if",
"tableDirInfo",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"src",
":=",
"filepath",
".",
"Join",
"(",
"src_dir",
",",
"tableDirInfo",
".",
"Name",
"(",
")",
")",
"\n",
"dst",
":=",
"filepath",
".",
"Join",
"(",
"dst_dir",
",",
"tableDirInfo",
".",
"Name",
"(",
")",
")",
"\n\n",
"err",
"=",
"os",
".",
"Link",
"(",
"src",
",",
"dst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Hard-link all files from 'src_dir' to the 'dst_dir' | [
"Hard",
"-",
"link",
"all",
"files",
"from",
"src_dir",
"to",
"the",
"dst_dir"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/cassandra/plugin.go#L458-L486 |
11,331 | starkandwayne/shield | plugin/cassandra/plugin.go | Restore | func (p CassandraPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
cassandra, err := cassandraInfo(endpoint)
if err != nil {
return err
}
plugin.DEBUG("Creating directory '%s' with 0755 permissions", "/var/vcap/store/shield/cassandra")
err = os.MkdirAll("/var/vcap/store/shield/cassandra", 0755)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Create base temporary directory}\n")
return err
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Create base temporary directory}\n")
keyspaceDirPath := filepath.Join("/var/vcap/store/shield/cassandra", cassandra.Keyspace)
// Recursively remove /var/vcap/store/shield/cassandra/{cassandra.Keyspace}, if any
cmd := fmt.Sprintf("rm -rf \"%s\"", keyspaceDirPath)
plugin.DEBUG("Executing `%s`", cmd)
err = plugin.Exec(cmd, plugin.STDOUT)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Clear base temporary directory}\n")
return err
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Clear base temporary directory}\n")
defer func() {
// plugin.DEBUG("Skipping recursive deletion of directory '%s'", keyspaceDirPath)
// Recursively remove /var/vcap/store/shield/cassandra/{cassandra.Keyspace}, if any
cmd := fmt.Sprintf("rm -rf \"%s\"", keyspaceDirPath)
plugin.DEBUG("Executing `%s`", cmd)
err := plugin.Exec(cmd, plugin.STDOUT)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Clean base temporary directory}\n")
return
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Clean base temporary directory}\n")
}()
cmd = fmt.Sprintf("tar -x -C /var/vcap/store/shield/cassandra -f -")
plugin.DEBUG("Executing `%s`", cmd)
err = plugin.Exec(cmd, plugin.STDIN)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Extract tar to temporary directory}\n")
return err
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Extract tar to temporary directory}\n")
// Iterate through all table directories /var/vcap/store/shield/cassandra/{cassandra.Keyspace}/{tablename}
dir, err := os.Open(keyspaceDirPath)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Load all tables data}\n")
return err
}
defer dir.Close()
entries, err := dir.Readdir(-1)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Load all tables data}\n")
return err
}
for _, tableDirInfo := range entries {
if !tableDirInfo.IsDir() {
continue
}
// Run sstableloader on each sub-directory found, assuming it is a table backup
tableDirPath := filepath.Join(keyspaceDirPath, tableDirInfo.Name())
cmd := fmt.Sprintf("sstableloader -u \"%s\" -pw \"%s\" -d \"%s\" \"%s\"", cassandra.User, cassandra.Password, cassandra.Host, tableDirPath)
plugin.DEBUG("Executing: `%s`", cmd)
err = plugin.Exec(cmd, plugin.STDIN)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Load all tables data}\n")
return err
}
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Load all tables data}\n")
return nil
} | go | func (p CassandraPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
cassandra, err := cassandraInfo(endpoint)
if err != nil {
return err
}
plugin.DEBUG("Creating directory '%s' with 0755 permissions", "/var/vcap/store/shield/cassandra")
err = os.MkdirAll("/var/vcap/store/shield/cassandra", 0755)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Create base temporary directory}\n")
return err
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Create base temporary directory}\n")
keyspaceDirPath := filepath.Join("/var/vcap/store/shield/cassandra", cassandra.Keyspace)
// Recursively remove /var/vcap/store/shield/cassandra/{cassandra.Keyspace}, if any
cmd := fmt.Sprintf("rm -rf \"%s\"", keyspaceDirPath)
plugin.DEBUG("Executing `%s`", cmd)
err = plugin.Exec(cmd, plugin.STDOUT)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Clear base temporary directory}\n")
return err
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Clear base temporary directory}\n")
defer func() {
// plugin.DEBUG("Skipping recursive deletion of directory '%s'", keyspaceDirPath)
// Recursively remove /var/vcap/store/shield/cassandra/{cassandra.Keyspace}, if any
cmd := fmt.Sprintf("rm -rf \"%s\"", keyspaceDirPath)
plugin.DEBUG("Executing `%s`", cmd)
err := plugin.Exec(cmd, plugin.STDOUT)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Clean base temporary directory}\n")
return
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Clean base temporary directory}\n")
}()
cmd = fmt.Sprintf("tar -x -C /var/vcap/store/shield/cassandra -f -")
plugin.DEBUG("Executing `%s`", cmd)
err = plugin.Exec(cmd, plugin.STDIN)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Extract tar to temporary directory}\n")
return err
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Extract tar to temporary directory}\n")
// Iterate through all table directories /var/vcap/store/shield/cassandra/{cassandra.Keyspace}/{tablename}
dir, err := os.Open(keyspaceDirPath)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Load all tables data}\n")
return err
}
defer dir.Close()
entries, err := dir.Readdir(-1)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Load all tables data}\n")
return err
}
for _, tableDirInfo := range entries {
if !tableDirInfo.IsDir() {
continue
}
// Run sstableloader on each sub-directory found, assuming it is a table backup
tableDirPath := filepath.Join(keyspaceDirPath, tableDirInfo.Name())
cmd := fmt.Sprintf("sstableloader -u \"%s\" -pw \"%s\" -d \"%s\" \"%s\"", cassandra.User, cassandra.Password, cassandra.Host, tableDirPath)
plugin.DEBUG("Executing: `%s`", cmd)
err = plugin.Exec(cmd, plugin.STDIN)
if err != nil {
fmt.Fprintf(os.Stderr, "@R{\u2717 Load all tables data}\n")
return err
}
}
fmt.Fprintf(os.Stderr, "@G{\u2713 Load all tables data}\n")
return nil
} | [
"func",
"(",
"p",
"CassandraPlugin",
")",
"Restore",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"error",
"{",
"cassandra",
",",
"err",
":=",
"cassandraInfo",
"(",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"\"",
"\"",
",",
"0755",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2717",
"\\n",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2713",
"\\n",
"\"",
")",
"\n\n",
"keyspaceDirPath",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
",",
"cassandra",
".",
"Keyspace",
")",
"\n\n",
"// Recursively remove /var/vcap/store/shield/cassandra/{cassandra.Keyspace}, if any",
"cmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"keyspaceDirPath",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"err",
"=",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDOUT",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2717",
"\\n",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2713",
"\\n",
"\"",
")",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"// plugin.DEBUG(\"Skipping recursive deletion of directory '%s'\", keyspaceDirPath)",
"// Recursively remove /var/vcap/store/shield/cassandra/{cassandra.Keyspace}, if any",
"cmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"keyspaceDirPath",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"err",
":=",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDOUT",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2717",
"\\n",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2713",
"\\n",
"\"",
")",
"\n",
"}",
"(",
")",
"\n\n",
"cmd",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"err",
"=",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDIN",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2717",
"\\n",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2713",
"\\n",
"\"",
")",
"\n\n",
"// Iterate through all table directories /var/vcap/store/shield/cassandra/{cassandra.Keyspace}/{tablename}",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"keyspaceDirPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2717",
"\\n",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"dir",
".",
"Close",
"(",
")",
"\n\n",
"entries",
",",
"err",
":=",
"dir",
".",
"Readdir",
"(",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2717",
"\\n",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"tableDirInfo",
":=",
"range",
"entries",
"{",
"if",
"!",
"tableDirInfo",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"// Run sstableloader on each sub-directory found, assuming it is a table backup",
"tableDirPath",
":=",
"filepath",
".",
"Join",
"(",
"keyspaceDirPath",
",",
"tableDirInfo",
".",
"Name",
"(",
")",
")",
"\n",
"cmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"cassandra",
".",
"User",
",",
"cassandra",
".",
"Password",
",",
"cassandra",
".",
"Host",
",",
"tableDirPath",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"err",
"=",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDIN",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2717",
"\\n",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\u2713",
"\\n",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Restore one cassandra keyspace | [
"Restore",
"one",
"cassandra",
"keyspace"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/cassandra/plugin.go#L489-L568 |
11,332 | starkandwayne/shield | db/db.go | Connect | func Connect(file string) (*DB, error) {
db := &DB{
Driver: "sqlite3",
DSN: file,
}
connection, err := sqlx.Open(db.Driver, db.DSN)
if err != nil {
return nil, err
}
db.connection = connection
if db.cache == nil {
db.cache = make(map[string]*sql.Stmt)
}
return db, nil
} | go | func Connect(file string) (*DB, error) {
db := &DB{
Driver: "sqlite3",
DSN: file,
}
connection, err := sqlx.Open(db.Driver, db.DSN)
if err != nil {
return nil, err
}
db.connection = connection
if db.cache == nil {
db.cache = make(map[string]*sql.Stmt)
}
return db, nil
} | [
"func",
"Connect",
"(",
"file",
"string",
")",
"(",
"*",
"DB",
",",
"error",
")",
"{",
"db",
":=",
"&",
"DB",
"{",
"Driver",
":",
"\"",
"\"",
",",
"DSN",
":",
"file",
",",
"}",
"\n\n",
"connection",
",",
"err",
":=",
"sqlx",
".",
"Open",
"(",
"db",
".",
"Driver",
",",
"db",
".",
"DSN",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"db",
".",
"connection",
"=",
"connection",
"\n\n",
"if",
"db",
".",
"cache",
"==",
"nil",
"{",
"db",
".",
"cache",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"sql",
".",
"Stmt",
")",
"\n",
"}",
"\n\n",
"return",
"db",
",",
"nil",
"\n",
"}"
] | // Connect to the backend database | [
"Connect",
"to",
"the",
"backend",
"database"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/db/db.go#L28-L45 |
11,333 | starkandwayne/shield | db/db.go | Disconnect | func (db *DB) Disconnect() error {
if db.connection != nil {
if err := db.connection.Close(); err != nil {
return err
}
db.connection = nil
db.cache = make(map[string]*sql.Stmt)
}
return nil
} | go | func (db *DB) Disconnect() error {
if db.connection != nil {
if err := db.connection.Close(); err != nil {
return err
}
db.connection = nil
db.cache = make(map[string]*sql.Stmt)
}
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Disconnect",
"(",
")",
"error",
"{",
"if",
"db",
".",
"connection",
"!=",
"nil",
"{",
"if",
"err",
":=",
"db",
".",
"connection",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"db",
".",
"connection",
"=",
"nil",
"\n",
"db",
".",
"cache",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"sql",
".",
"Stmt",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Disconnect from the backend database | [
"Disconnect",
"from",
"the",
"backend",
"database"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/db/db.go#L53-L62 |
11,334 | starkandwayne/shield | db/db.go | statement | func (db *DB) statement(sql string) (*sql.Stmt, error) {
if db.connection == nil {
return nil, fmt.Errorf("Not connected to database")
}
sql = db.connection.Rebind(sql)
if _, ok := db.cache[sql]; !ok {
stmt, err := db.connection.Prepare(sql)
if err != nil {
return nil, err
}
db.cache[sql] = stmt
}
if q, ok := db.cache[sql]; ok {
return q, nil
}
return nil, fmt.Errorf("Weird bug: query '%s' is still not properly prepared", sql)
} | go | func (db *DB) statement(sql string) (*sql.Stmt, error) {
if db.connection == nil {
return nil, fmt.Errorf("Not connected to database")
}
sql = db.connection.Rebind(sql)
if _, ok := db.cache[sql]; !ok {
stmt, err := db.connection.Prepare(sql)
if err != nil {
return nil, err
}
db.cache[sql] = stmt
}
if q, ok := db.cache[sql]; ok {
return q, nil
}
return nil, fmt.Errorf("Weird bug: query '%s' is still not properly prepared", sql)
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"statement",
"(",
"sql",
"string",
")",
"(",
"*",
"sql",
".",
"Stmt",
",",
"error",
")",
"{",
"if",
"db",
".",
"connection",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"sql",
"=",
"db",
".",
"connection",
".",
"Rebind",
"(",
"sql",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"db",
".",
"cache",
"[",
"sql",
"]",
";",
"!",
"ok",
"{",
"stmt",
",",
"err",
":=",
"db",
".",
"connection",
".",
"Prepare",
"(",
"sql",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"db",
".",
"cache",
"[",
"sql",
"]",
"=",
"stmt",
"\n",
"}",
"\n\n",
"if",
"q",
",",
"ok",
":=",
"db",
".",
"cache",
"[",
"sql",
"]",
";",
"ok",
"{",
"return",
"q",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sql",
")",
"\n",
"}"
] | // Return the prepared statement for a given SQL query | [
"Return",
"the",
"prepared",
"statement",
"for",
"a",
"given",
"SQL",
"query"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/db/db.go#L124-L143 |
11,335 | starkandwayne/shield | db/memberships.go | GetTenantsForUser | func (db *DB) GetTenantsForUser(user string) ([]*Tenant, error) {
r, err := db.Query(`
SELECT t.uuid, t.name
FROM tenants t INNER JOIN memberships m ON m.tenant_uuid = t.uuid
WHERE m.user_uuid = ?`, user)
if err != nil {
return nil, err
}
defer r.Close()
l := make([]*Tenant, 0)
for r.Next() {
t := &Tenant{}
if err := r.Scan(&t.UUID, &t.Name); err != nil {
return l, err
}
l = append(l, t)
}
return l, nil
} | go | func (db *DB) GetTenantsForUser(user string) ([]*Tenant, error) {
r, err := db.Query(`
SELECT t.uuid, t.name
FROM tenants t INNER JOIN memberships m ON m.tenant_uuid = t.uuid
WHERE m.user_uuid = ?`, user)
if err != nil {
return nil, err
}
defer r.Close()
l := make([]*Tenant, 0)
for r.Next() {
t := &Tenant{}
if err := r.Scan(&t.UUID, &t.Name); err != nil {
return l, err
}
l = append(l, t)
}
return l, nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"GetTenantsForUser",
"(",
"user",
"string",
")",
"(",
"[",
"]",
"*",
"Tenant",
",",
"error",
")",
"{",
"r",
",",
"err",
":=",
"db",
".",
"Query",
"(",
"`\n\t SELECT t.uuid, t.name\n\t FROM tenants t INNER JOIN memberships m ON m.tenant_uuid = t.uuid\n\t WHERE m.user_uuid = ?`",
",",
"user",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"r",
".",
"Close",
"(",
")",
"\n\n",
"l",
":=",
"make",
"(",
"[",
"]",
"*",
"Tenant",
",",
"0",
")",
"\n",
"for",
"r",
".",
"Next",
"(",
")",
"{",
"t",
":=",
"&",
"Tenant",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"r",
".",
"Scan",
"(",
"&",
"t",
".",
"UUID",
",",
"&",
"t",
".",
"Name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"l",
",",
"err",
"\n",
"}",
"\n\n",
"l",
"=",
"append",
"(",
"l",
",",
"t",
")",
"\n",
"}",
"\n\n",
"return",
"l",
",",
"nil",
"\n",
"}"
] | //GetTenantsForUser given a user's uuid returns a slice of Tenants that the user has membership with | [
"GetTenantsForUser",
"given",
"a",
"user",
"s",
"uuid",
"returns",
"a",
"slice",
"of",
"Tenants",
"that",
"the",
"user",
"has",
"membership",
"with"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/db/memberships.go#L87-L109 |
11,336 | starkandwayne/shield | plugin/mysql/plugin.go | Backup | func (p MySQLPlugin) Backup(endpoint plugin.ShieldEndpoint) error {
mysql, err := mysqlConnectionInfo(endpoint)
if err != nil {
return err
}
if mysql.Replica != "" {
mysql.Host = mysql.Replica
}
cmd := fmt.Sprintf("%s/mysqldump %s %s", mysql.Bin, mysql.Options, connectionString(mysql, true))
plugin.DEBUG("Executing: `%s`", cmd)
fmt.Printf("SET SESSION SQL_LOG_BIN=0;\n")
return plugin.Exec(cmd, plugin.STDOUT)
} | go | func (p MySQLPlugin) Backup(endpoint plugin.ShieldEndpoint) error {
mysql, err := mysqlConnectionInfo(endpoint)
if err != nil {
return err
}
if mysql.Replica != "" {
mysql.Host = mysql.Replica
}
cmd := fmt.Sprintf("%s/mysqldump %s %s", mysql.Bin, mysql.Options, connectionString(mysql, true))
plugin.DEBUG("Executing: `%s`", cmd)
fmt.Printf("SET SESSION SQL_LOG_BIN=0;\n")
return plugin.Exec(cmd, plugin.STDOUT)
} | [
"func",
"(",
"p",
"MySQLPlugin",
")",
"Backup",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"error",
"{",
"mysql",
",",
"err",
":=",
"mysqlConnectionInfo",
"(",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"mysql",
".",
"Replica",
"!=",
"\"",
"\"",
"{",
"mysql",
".",
"Host",
"=",
"mysql",
".",
"Replica",
"\n",
"}",
"\n\n",
"cmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mysql",
".",
"Bin",
",",
"mysql",
".",
"Options",
",",
"connectionString",
"(",
"mysql",
",",
"true",
")",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"return",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDOUT",
")",
"\n",
"}"
] | // Backup mysql database | [
"Backup",
"mysql",
"database"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/mysql/plugin.go#L215-L229 |
11,337 | starkandwayne/shield | plugin/mysql/plugin.go | Restore | func (p MySQLPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
mysql, err := mysqlConnectionInfo(endpoint)
if err != nil {
return err
}
cmd := fmt.Sprintf("%s/mysql %s", mysql.Bin, connectionString(mysql, false))
dbname, err := endpoint.StringValueDefault("mysql_database", "")
if err != nil {
return err
} else if dbname == "" {
fmt.Fprintf(os.Stderr, "Restore Full Database \n")
return mysqlrestorefull(mysql, cmd)
} else {
fmt.Fprintf(os.Stderr, "Restore Database %s \n", dbname)
plugin.DEBUG("Exec: %s", cmd)
return plugin.Exec(cmd, plugin.STDIN)
}
} | go | func (p MySQLPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
mysql, err := mysqlConnectionInfo(endpoint)
if err != nil {
return err
}
cmd := fmt.Sprintf("%s/mysql %s", mysql.Bin, connectionString(mysql, false))
dbname, err := endpoint.StringValueDefault("mysql_database", "")
if err != nil {
return err
} else if dbname == "" {
fmt.Fprintf(os.Stderr, "Restore Full Database \n")
return mysqlrestorefull(mysql, cmd)
} else {
fmt.Fprintf(os.Stderr, "Restore Database %s \n", dbname)
plugin.DEBUG("Exec: %s", cmd)
return plugin.Exec(cmd, plugin.STDIN)
}
} | [
"func",
"(",
"p",
"MySQLPlugin",
")",
"Restore",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"error",
"{",
"mysql",
",",
"err",
":=",
"mysqlConnectionInfo",
"(",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mysql",
".",
"Bin",
",",
"connectionString",
"(",
"mysql",
",",
"false",
")",
")",
"\n",
"dbname",
",",
"err",
":=",
"endpoint",
".",
"StringValueDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"dbname",
"==",
"\"",
"\"",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"return",
"mysqlrestorefull",
"(",
"mysql",
",",
"cmd",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"dbname",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"return",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDIN",
")",
"\n",
"}",
"\n",
"}"
] | // Restore mysql database | [
"Restore",
"mysql",
"database"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/mysql/plugin.go#L232-L249 |
11,338 | starkandwayne/shield | plugin/mongo/plugin.go | Backup | func (p MongoPlugin) Backup(endpoint plugin.ShieldEndpoint) error {
mongo, err := mongoConnectionInfo(endpoint)
if err != nil {
return err
}
cmd := fmt.Sprintf("%s/mongodump %s", mongo.Bin, connectionString(mongo, true))
plugin.DEBUG("Executing: `%s`", cmd)
return plugin.Exec(cmd, plugin.STDOUT)
} | go | func (p MongoPlugin) Backup(endpoint plugin.ShieldEndpoint) error {
mongo, err := mongoConnectionInfo(endpoint)
if err != nil {
return err
}
cmd := fmt.Sprintf("%s/mongodump %s", mongo.Bin, connectionString(mongo, true))
plugin.DEBUG("Executing: `%s`", cmd)
return plugin.Exec(cmd, plugin.STDOUT)
} | [
"func",
"(",
"p",
"MongoPlugin",
")",
"Backup",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"error",
"{",
"mongo",
",",
"err",
":=",
"mongoConnectionInfo",
"(",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"cmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mongo",
".",
"Bin",
",",
"connectionString",
"(",
"mongo",
",",
"true",
")",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"return",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDOUT",
")",
"\n",
"}"
] | // Backup mongo database | [
"Backup",
"mongo",
"database"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/mongo/plugin.go#L174-L183 |
11,339 | starkandwayne/shield | plugin/mongo/plugin.go | Restore | func (p MongoPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
mongo, err := mongoConnectionInfo(endpoint)
if err != nil {
return err
}
cmd := fmt.Sprintf("%s/mongorestore %s", mongo.Bin, connectionString(mongo, false))
plugin.DEBUG("Exec: %s", cmd)
return plugin.Exec(cmd, plugin.STDIN)
} | go | func (p MongoPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
mongo, err := mongoConnectionInfo(endpoint)
if err != nil {
return err
}
cmd := fmt.Sprintf("%s/mongorestore %s", mongo.Bin, connectionString(mongo, false))
plugin.DEBUG("Exec: %s", cmd)
return plugin.Exec(cmd, plugin.STDIN)
} | [
"func",
"(",
"p",
"MongoPlugin",
")",
"Restore",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"error",
"{",
"mongo",
",",
"err",
":=",
"mongoConnectionInfo",
"(",
"endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"cmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mongo",
".",
"Bin",
",",
"connectionString",
"(",
"mongo",
",",
"false",
")",
")",
"\n",
"plugin",
".",
"DEBUG",
"(",
"\"",
"\"",
",",
"cmd",
")",
"\n",
"return",
"plugin",
".",
"Exec",
"(",
"cmd",
",",
"plugin",
".",
"STDIN",
")",
"\n",
"}"
] | // Restore mongo database | [
"Restore",
"mongo",
"database"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/mongo/plugin.go#L186-L195 |
11,340 | starkandwayne/shield | plugin/dummy/dummy.go | Backup | func (p DummyPlugin) Backup(endpoint plugin.ShieldEndpoint) error {
data, err := endpoint.StringValue("data")
if err != nil {
return err
}
return plugin.Exec(fmt.Sprintf("/bin/echo %s", data), plugin.STDOUT)
} | go | func (p DummyPlugin) Backup(endpoint plugin.ShieldEndpoint) error {
data, err := endpoint.StringValue("data")
if err != nil {
return err
}
return plugin.Exec(fmt.Sprintf("/bin/echo %s", data), plugin.STDOUT)
} | [
"func",
"(",
"p",
"DummyPlugin",
")",
"Backup",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"error",
"{",
"data",
",",
"err",
":=",
"endpoint",
".",
"StringValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"plugin",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"data",
")",
",",
"plugin",
".",
"STDOUT",
")",
"\n",
"}"
] | // Called when you want to back data up. Examine the ShieldEndpoint passed in, and perform actions accordingly | [
"Called",
"when",
"you",
"want",
"to",
"back",
"data",
"up",
".",
"Examine",
"the",
"ShieldEndpoint",
"passed",
"in",
"and",
"perform",
"actions",
"accordingly"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/dummy/dummy.go#L71-L78 |
11,341 | starkandwayne/shield | plugin/dummy/dummy.go | Restore | func (p DummyPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
file, err := endpoint.StringValue("file")
if err != nil {
return err
}
return plugin.Exec(fmt.Sprintf("/bin/sh -c \"/bin/cat > %s\"", file), plugin.STDIN)
} | go | func (p DummyPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
file, err := endpoint.StringValue("file")
if err != nil {
return err
}
return plugin.Exec(fmt.Sprintf("/bin/sh -c \"/bin/cat > %s\"", file), plugin.STDIN)
} | [
"func",
"(",
"p",
"DummyPlugin",
")",
"Restore",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"error",
"{",
"file",
",",
"err",
":=",
"endpoint",
".",
"StringValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"plugin",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"file",
")",
",",
"plugin",
".",
"STDIN",
")",
"\n",
"}"
] | // Called when you want to restore data Examine the ShieldEndpoint passed in, and perform actions accordingly | [
"Called",
"when",
"you",
"want",
"to",
"restore",
"data",
"Examine",
"the",
"ShieldEndpoint",
"passed",
"in",
"and",
"perform",
"actions",
"accordingly"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/dummy/dummy.go#L81-L88 |
11,342 | starkandwayne/shield | plugin/dummy/dummy.go | Store | func (p DummyPlugin) Store(endpoint plugin.ShieldEndpoint) (string, int64, error) {
directory, err := endpoint.StringValue("directory")
if err != nil {
return "", 0, err
}
file := plugin.GenUUID()
err = plugin.Exec(fmt.Sprintf("/bin/sh -c \"/bin/cat > %s/%s\"", directory, file), plugin.STDIN)
info, e := os.Stat(fmt.Sprintf("%s/%s", directory, file))
if e != nil {
return file, 0, e
}
return file, info.Size(), err
} | go | func (p DummyPlugin) Store(endpoint plugin.ShieldEndpoint) (string, int64, error) {
directory, err := endpoint.StringValue("directory")
if err != nil {
return "", 0, err
}
file := plugin.GenUUID()
err = plugin.Exec(fmt.Sprintf("/bin/sh -c \"/bin/cat > %s/%s\"", directory, file), plugin.STDIN)
info, e := os.Stat(fmt.Sprintf("%s/%s", directory, file))
if e != nil {
return file, 0, e
}
return file, info.Size(), err
} | [
"func",
"(",
"p",
"DummyPlugin",
")",
"Store",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
")",
"(",
"string",
",",
"int64",
",",
"error",
")",
"{",
"directory",
",",
"err",
":=",
"endpoint",
".",
"StringValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"file",
":=",
"plugin",
".",
"GenUUID",
"(",
")",
"\n\n",
"err",
"=",
"plugin",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"directory",
",",
"file",
")",
",",
"plugin",
".",
"STDIN",
")",
"\n",
"info",
",",
"e",
":=",
"os",
".",
"Stat",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"directory",
",",
"file",
")",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"file",
",",
"0",
",",
"e",
"\n",
"}",
"\n\n",
"return",
"file",
",",
"info",
".",
"Size",
"(",
")",
",",
"err",
"\n",
"}"
] | // Called when you want to store backup data. Examine the ShieldEndpoint passed in, and perform actions accordingly | [
"Called",
"when",
"you",
"want",
"to",
"store",
"backup",
"data",
".",
"Examine",
"the",
"ShieldEndpoint",
"passed",
"in",
"and",
"perform",
"actions",
"accordingly"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/dummy/dummy.go#L91-L106 |
11,343 | starkandwayne/shield | plugin/dummy/dummy.go | Retrieve | func (p DummyPlugin) Retrieve(endpoint plugin.ShieldEndpoint, file string) error {
directory, err := endpoint.StringValue("directory")
if err != nil {
return err
}
return plugin.Exec(fmt.Sprintf("/bin/cat %s/%s", directory, file), plugin.STDOUT)
} | go | func (p DummyPlugin) Retrieve(endpoint plugin.ShieldEndpoint, file string) error {
directory, err := endpoint.StringValue("directory")
if err != nil {
return err
}
return plugin.Exec(fmt.Sprintf("/bin/cat %s/%s", directory, file), plugin.STDOUT)
} | [
"func",
"(",
"p",
"DummyPlugin",
")",
"Retrieve",
"(",
"endpoint",
"plugin",
".",
"ShieldEndpoint",
",",
"file",
"string",
")",
"error",
"{",
"directory",
",",
"err",
":=",
"endpoint",
".",
"StringValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"plugin",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"directory",
",",
"file",
")",
",",
"plugin",
".",
"STDOUT",
")",
"\n",
"}"
] | // Called when you want to retreive backup data. Examine the ShieldEndpoint passed in, and perform actions accordingly | [
"Called",
"when",
"you",
"want",
"to",
"retreive",
"backup",
"data",
".",
"Examine",
"the",
"ShieldEndpoint",
"passed",
"in",
"and",
"perform",
"actions",
"accordingly"
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/plugin/dummy/dummy.go#L109-L116 |
11,344 | starkandwayne/shield | route/request.go | NewRequest | func NewRequest(w http.ResponseWriter, r *http.Request, debug bool) *Request {
return &Request{
Req: r,
w: w,
debug: debug,
}
} | go | func NewRequest(w http.ResponseWriter, r *http.Request, debug bool) *Request {
return &Request{
Req: r,
w: w,
debug: debug,
}
} | [
"func",
"NewRequest",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"debug",
"bool",
")",
"*",
"Request",
"{",
"return",
"&",
"Request",
"{",
"Req",
":",
"r",
",",
"w",
":",
"w",
",",
"debug",
":",
"debug",
",",
"}",
"\n",
"}"
] | //NewRequest initializes and returns a new request object. Setting debug to
// true will cause errors to be logged. | [
"NewRequest",
"initializes",
"and",
"returns",
"a",
"new",
"request",
"object",
".",
"Setting",
"debug",
"to",
"true",
"will",
"cause",
"errors",
"to",
"be",
"logged",
"."
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/route/request.go#L30-L36 |
11,345 | starkandwayne/shield | route/request.go | Payload | func (r *Request) Payload(v interface{}) bool {
if r.Req.Body == nil {
r.Fail(Bad(nil, "no JSON input payload present in request"))
return false
}
if err := json.NewDecoder(r.Req.Body).Decode(v); err != nil && err != io.EOF {
r.Fail(Bad(err, "invalid JSON input payload present in request"))
return false
}
return true
} | go | func (r *Request) Payload(v interface{}) bool {
if r.Req.Body == nil {
r.Fail(Bad(nil, "no JSON input payload present in request"))
return false
}
if err := json.NewDecoder(r.Req.Body).Decode(v); err != nil && err != io.EOF {
r.Fail(Bad(err, "invalid JSON input payload present in request"))
return false
}
return true
} | [
"func",
"(",
"r",
"*",
"Request",
")",
"Payload",
"(",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"if",
"r",
".",
"Req",
".",
"Body",
"==",
"nil",
"{",
"r",
".",
"Fail",
"(",
"Bad",
"(",
"nil",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Req",
".",
"Body",
")",
".",
"Decode",
"(",
"v",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"io",
".",
"EOF",
"{",
"r",
".",
"Fail",
"(",
"Bad",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] | //Payload unmarshals the JSON body of this request into the given interface.
// Returns true if successful and false otherwise. | [
"Payload",
"unmarshals",
"the",
"JSON",
"body",
"of",
"this",
"request",
"into",
"the",
"given",
"interface",
".",
"Returns",
"true",
"if",
"successful",
"and",
"false",
"otherwise",
"."
] | db2b428270a4dd1a9999dc1f3589ce0eef407bb2 | https://github.com/starkandwayne/shield/blob/db2b428270a4dd1a9999dc1f3589ce0eef407bb2/route/request.go#L133-L145 |
11,346 | benbjohnson/ego | parse.go | ParseFile | func ParseFile(path string) (*Template, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return Parse(f, path)
} | go | func ParseFile(path string) (*Template, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return Parse(f, path)
} | [
"func",
"ParseFile",
"(",
"path",
"string",
")",
"(",
"*",
"Template",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"return",
"Parse",
"(",
"f",
",",
"path",
")",
"\n",
"}"
] | // ParseFile parses an Ego template from a file. | [
"ParseFile",
"parses",
"an",
"Ego",
"template",
"from",
"a",
"file",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/parse.go#L9-L16 |
11,347 | benbjohnson/ego | parse.go | Parse | func Parse(r io.Reader, path string) (*Template, error) {
s := NewScanner(r, path)
t := &Template{Path: path}
for {
blk, err := s.Scan()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
switch blk := blk.(type) {
case *ComponentStartBlock:
if err := parseComponentBlock(s, blk); err != nil {
return nil, err
}
case *ComponentEndBlock:
return nil, NewSyntaxError(blk.Pos, "Component end block found without matching start block: %s", shortComponentBlockString(blk))
case *AttrStartBlock:
return nil, NewSyntaxError(blk.Pos, "Attribute start block found outside of component: %s", shortComponentBlockString(blk))
case *AttrEndBlock:
return nil, NewSyntaxError(blk.Pos, "Attribute end block found outside of component: %s", shortComponentBlockString(blk))
}
t.Blocks = append(t.Blocks, blk)
}
t.Blocks = normalizeBlocks(t.Blocks)
return t, nil
} | go | func Parse(r io.Reader, path string) (*Template, error) {
s := NewScanner(r, path)
t := &Template{Path: path}
for {
blk, err := s.Scan()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
switch blk := blk.(type) {
case *ComponentStartBlock:
if err := parseComponentBlock(s, blk); err != nil {
return nil, err
}
case *ComponentEndBlock:
return nil, NewSyntaxError(blk.Pos, "Component end block found without matching start block: %s", shortComponentBlockString(blk))
case *AttrStartBlock:
return nil, NewSyntaxError(blk.Pos, "Attribute start block found outside of component: %s", shortComponentBlockString(blk))
case *AttrEndBlock:
return nil, NewSyntaxError(blk.Pos, "Attribute end block found outside of component: %s", shortComponentBlockString(blk))
}
t.Blocks = append(t.Blocks, blk)
}
t.Blocks = normalizeBlocks(t.Blocks)
return t, nil
} | [
"func",
"Parse",
"(",
"r",
"io",
".",
"Reader",
",",
"path",
"string",
")",
"(",
"*",
"Template",
",",
"error",
")",
"{",
"s",
":=",
"NewScanner",
"(",
"r",
",",
"path",
")",
"\n",
"t",
":=",
"&",
"Template",
"{",
"Path",
":",
"path",
"}",
"\n",
"for",
"{",
"blk",
",",
"err",
":=",
"s",
".",
"Scan",
"(",
")",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"break",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"blk",
":=",
"blk",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ComponentStartBlock",
":",
"if",
"err",
":=",
"parseComponentBlock",
"(",
"s",
",",
"blk",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"*",
"ComponentEndBlock",
":",
"return",
"nil",
",",
"NewSyntaxError",
"(",
"blk",
".",
"Pos",
",",
"\"",
"\"",
",",
"shortComponentBlockString",
"(",
"blk",
")",
")",
"\n",
"case",
"*",
"AttrStartBlock",
":",
"return",
"nil",
",",
"NewSyntaxError",
"(",
"blk",
".",
"Pos",
",",
"\"",
"\"",
",",
"shortComponentBlockString",
"(",
"blk",
")",
")",
"\n",
"case",
"*",
"AttrEndBlock",
":",
"return",
"nil",
",",
"NewSyntaxError",
"(",
"blk",
".",
"Pos",
",",
"\"",
"\"",
",",
"shortComponentBlockString",
"(",
"blk",
")",
")",
"\n",
"}",
"\n\n",
"t",
".",
"Blocks",
"=",
"append",
"(",
"t",
".",
"Blocks",
",",
"blk",
")",
"\n",
"}",
"\n",
"t",
".",
"Blocks",
"=",
"normalizeBlocks",
"(",
"t",
".",
"Blocks",
")",
"\n",
"return",
"t",
",",
"nil",
"\n",
"}"
] | // Parse parses an Ego template from a reader.
// The path specifies the path name used in the compiled template's pragmas. | [
"Parse",
"parses",
"an",
"Ego",
"template",
"from",
"a",
"reader",
".",
"The",
"path",
"specifies",
"the",
"path",
"name",
"used",
"in",
"the",
"compiled",
"template",
"s",
"pragmas",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/parse.go#L20-L48 |
11,348 | benbjohnson/ego | scanner.go | NewScanner | func NewScanner(r io.Reader, path string) *Scanner {
return &Scanner{
r: r,
pos: Pos{
Path: path,
LineNo: 1,
},
}
} | go | func NewScanner(r io.Reader, path string) *Scanner {
return &Scanner{
r: r,
pos: Pos{
Path: path,
LineNo: 1,
},
}
} | [
"func",
"NewScanner",
"(",
"r",
"io",
".",
"Reader",
",",
"path",
"string",
")",
"*",
"Scanner",
"{",
"return",
"&",
"Scanner",
"{",
"r",
":",
"r",
",",
"pos",
":",
"Pos",
"{",
"Path",
":",
"path",
",",
"LineNo",
":",
"1",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewScanner initializes a new scanner with a given reader. | [
"NewScanner",
"initializes",
"a",
"new",
"scanner",
"with",
"a",
"given",
"reader",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L26-L34 |
11,349 | benbjohnson/ego | scanner.go | Scan | func (s *Scanner) Scan() (Block, error) {
if err := s.init(); err != nil {
return nil, err
}
switch s.peek() {
case '<':
// Special handling for component/attr blocks.
if s.peekComponentStartBlock() {
return s.scanComponentStartBlock()
} else if s.peekComponentEndBlock() {
return s.scanComponentEndBlock()
} else if s.peekAttrStartBlock() {
return s.scanAttrStartBlock()
} else if s.peekAttrEndBlock() {
return s.scanAttrEndBlock()
}
// Special handling for ego blocks.
if s.peekN(4) == "<%==" {
return s.scanRawPrintBlock()
} else if s.peekN(3) == "<%=" {
return s.scanPrintBlock()
} else if s.peekN(2) == "<%" {
return s.scanCodeBlock()
}
case eof:
return nil, io.EOF
}
return s.scanTextBlock()
} | go | func (s *Scanner) Scan() (Block, error) {
if err := s.init(); err != nil {
return nil, err
}
switch s.peek() {
case '<':
// Special handling for component/attr blocks.
if s.peekComponentStartBlock() {
return s.scanComponentStartBlock()
} else if s.peekComponentEndBlock() {
return s.scanComponentEndBlock()
} else if s.peekAttrStartBlock() {
return s.scanAttrStartBlock()
} else if s.peekAttrEndBlock() {
return s.scanAttrEndBlock()
}
// Special handling for ego blocks.
if s.peekN(4) == "<%==" {
return s.scanRawPrintBlock()
} else if s.peekN(3) == "<%=" {
return s.scanPrintBlock()
} else if s.peekN(2) == "<%" {
return s.scanCodeBlock()
}
case eof:
return nil, io.EOF
}
return s.scanTextBlock()
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"Scan",
"(",
")",
"(",
"Block",
",",
"error",
")",
"{",
"if",
"err",
":=",
"s",
".",
"init",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"s",
".",
"peek",
"(",
")",
"{",
"case",
"'<'",
":",
"// Special handling for component/attr blocks.",
"if",
"s",
".",
"peekComponentStartBlock",
"(",
")",
"{",
"return",
"s",
".",
"scanComponentStartBlock",
"(",
")",
"\n",
"}",
"else",
"if",
"s",
".",
"peekComponentEndBlock",
"(",
")",
"{",
"return",
"s",
".",
"scanComponentEndBlock",
"(",
")",
"\n",
"}",
"else",
"if",
"s",
".",
"peekAttrStartBlock",
"(",
")",
"{",
"return",
"s",
".",
"scanAttrStartBlock",
"(",
")",
"\n",
"}",
"else",
"if",
"s",
".",
"peekAttrEndBlock",
"(",
")",
"{",
"return",
"s",
".",
"scanAttrEndBlock",
"(",
")",
"\n",
"}",
"\n\n",
"// Special handling for ego blocks.",
"if",
"s",
".",
"peekN",
"(",
"4",
")",
"==",
"\"",
"\"",
"{",
"return",
"s",
".",
"scanRawPrintBlock",
"(",
")",
"\n",
"}",
"else",
"if",
"s",
".",
"peekN",
"(",
"3",
")",
"==",
"\"",
"\"",
"{",
"return",
"s",
".",
"scanPrintBlock",
"(",
")",
"\n",
"}",
"else",
"if",
"s",
".",
"peekN",
"(",
"2",
")",
"==",
"\"",
"\"",
"{",
"return",
"s",
".",
"scanCodeBlock",
"(",
")",
"\n",
"}",
"\n\n",
"case",
"eof",
":",
"return",
"nil",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"return",
"s",
".",
"scanTextBlock",
"(",
")",
"\n",
"}"
] | // Scan returns the next block from the reader. | [
"Scan",
"returns",
"the",
"next",
"block",
"from",
"the",
"reader",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L37-L68 |
11,350 | benbjohnson/ego | scanner.go | scanContent | func (s *Scanner) scanContent() (string, error) {
var buf bytes.Buffer
for {
ch := s.read()
if ch == eof {
return "", &SyntaxError{Message: "Expected close tag, found EOF", Pos: s.pos}
} else if ch == '%' {
ch := s.read()
if ch == eof {
return "", &SyntaxError{Message: "Expected close tag, found EOF", Pos: s.pos}
} else if ch == '>' {
break
} else {
buf.WriteRune('%')
buf.WriteRune(ch)
}
} else {
buf.WriteRune(ch)
}
}
return string(buf.Bytes()), nil
} | go | func (s *Scanner) scanContent() (string, error) {
var buf bytes.Buffer
for {
ch := s.read()
if ch == eof {
return "", &SyntaxError{Message: "Expected close tag, found EOF", Pos: s.pos}
} else if ch == '%' {
ch := s.read()
if ch == eof {
return "", &SyntaxError{Message: "Expected close tag, found EOF", Pos: s.pos}
} else if ch == '>' {
break
} else {
buf.WriteRune('%')
buf.WriteRune(ch)
}
} else {
buf.WriteRune(ch)
}
}
return string(buf.Bytes()), nil
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"scanContent",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"{",
"ch",
":=",
"s",
".",
"read",
"(",
")",
"\n",
"if",
"ch",
"==",
"eof",
"{",
"return",
"\"",
"\"",
",",
"&",
"SyntaxError",
"{",
"Message",
":",
"\"",
"\"",
",",
"Pos",
":",
"s",
".",
"pos",
"}",
"\n",
"}",
"else",
"if",
"ch",
"==",
"'%'",
"{",
"ch",
":=",
"s",
".",
"read",
"(",
")",
"\n",
"if",
"ch",
"==",
"eof",
"{",
"return",
"\"",
"\"",
",",
"&",
"SyntaxError",
"{",
"Message",
":",
"\"",
"\"",
",",
"Pos",
":",
"s",
".",
"pos",
"}",
"\n",
"}",
"else",
"if",
"ch",
"==",
"'>'",
"{",
"break",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteRune",
"(",
"'%'",
")",
"\n",
"buf",
".",
"WriteRune",
"(",
"ch",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteRune",
"(",
"ch",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"string",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
",",
"nil",
"\n",
"}"
] | // scans the reader until %> is reached. | [
"scans",
"the",
"reader",
"until",
"%",
">",
"is",
"reached",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L328-L349 |
11,351 | benbjohnson/ego | scanner.go | init | func (s *Scanner) init() (err error) {
if s.b != nil {
return nil
}
s.b, err = ioutil.ReadAll(s.r)
return err
} | go | func (s *Scanner) init() (err error) {
if s.b != nil {
return nil
}
s.b, err = ioutil.ReadAll(s.r)
return err
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"init",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"s",
".",
"b",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"s",
".",
"b",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"s",
".",
"r",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // init slurps the reader on first scan. | [
"init",
"slurps",
"the",
"reader",
"on",
"first",
"scan",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L513-L519 |
11,352 | benbjohnson/ego | scanner.go | read | func (s *Scanner) read() rune {
if s.i >= len(s.b) {
return eof
}
ch, n := utf8.DecodeRune(s.b[s.i:])
s.i += n
if ch == '\n' {
s.pos.LineNo++
}
return ch
} | go | func (s *Scanner) read() rune {
if s.i >= len(s.b) {
return eof
}
ch, n := utf8.DecodeRune(s.b[s.i:])
s.i += n
if ch == '\n' {
s.pos.LineNo++
}
return ch
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"read",
"(",
")",
"rune",
"{",
"if",
"s",
".",
"i",
">=",
"len",
"(",
"s",
".",
"b",
")",
"{",
"return",
"eof",
"\n",
"}",
"\n\n",
"ch",
",",
"n",
":=",
"utf8",
".",
"DecodeRune",
"(",
"s",
".",
"b",
"[",
"s",
".",
"i",
":",
"]",
")",
"\n",
"s",
".",
"i",
"+=",
"n",
"\n\n",
"if",
"ch",
"==",
"'\\n'",
"{",
"s",
".",
"pos",
".",
"LineNo",
"++",
"\n",
"}",
"\n",
"return",
"ch",
"\n",
"}"
] | // read reads the next rune and moves the position forward. | [
"read",
"reads",
"the",
"next",
"rune",
"and",
"moves",
"the",
"position",
"forward",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L522-L534 |
11,353 | benbjohnson/ego | scanner.go | readN | func (s *Scanner) readN(n int) string {
var buf bytes.Buffer
for i := 0; i < n; i++ {
ch := s.read()
if ch == eof {
break
}
buf.WriteRune(ch)
}
return buf.String()
} | go | func (s *Scanner) readN(n int) string {
var buf bytes.Buffer
for i := 0; i < n; i++ {
ch := s.read()
if ch == eof {
break
}
buf.WriteRune(ch)
}
return buf.String()
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"readN",
"(",
"n",
"int",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"ch",
":=",
"s",
".",
"read",
"(",
")",
"\n",
"if",
"ch",
"==",
"eof",
"{",
"break",
"\n",
"}",
"\n",
"buf",
".",
"WriteRune",
"(",
"ch",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // readN reads the next n characters and moves the position forward. | [
"readN",
"reads",
"the",
"next",
"n",
"characters",
"and",
"moves",
"the",
"position",
"forward",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L537-L547 |
11,354 | benbjohnson/ego | scanner.go | peek | func (s *Scanner) peek() rune {
if s.i >= len(s.b) {
return eof
}
ch, _ := utf8.DecodeRune(s.b[s.i:])
return ch
} | go | func (s *Scanner) peek() rune {
if s.i >= len(s.b) {
return eof
}
ch, _ := utf8.DecodeRune(s.b[s.i:])
return ch
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"peek",
"(",
")",
"rune",
"{",
"if",
"s",
".",
"i",
">=",
"len",
"(",
"s",
".",
"b",
")",
"{",
"return",
"eof",
"\n",
"}",
"\n",
"ch",
",",
"_",
":=",
"utf8",
".",
"DecodeRune",
"(",
"s",
".",
"b",
"[",
"s",
".",
"i",
":",
"]",
")",
"\n",
"return",
"ch",
"\n",
"}"
] | // peek reads the next rune but does not move the position forward. | [
"peek",
"reads",
"the",
"next",
"rune",
"but",
"does",
"not",
"move",
"the",
"position",
"forward",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L550-L556 |
11,355 | benbjohnson/ego | scanner.go | peekN | func (s *Scanner) peekN(n int) string {
if s.i >= len(s.b) {
return ""
}
b := s.b[s.i:]
var buf bytes.Buffer
for i := 0; i < n && len(b) > 0; i++ {
ch, sz := utf8.DecodeRune(b)
b = b[sz:]
buf.WriteRune(ch)
}
return buf.String()
} | go | func (s *Scanner) peekN(n int) string {
if s.i >= len(s.b) {
return ""
}
b := s.b[s.i:]
var buf bytes.Buffer
for i := 0; i < n && len(b) > 0; i++ {
ch, sz := utf8.DecodeRune(b)
b = b[sz:]
buf.WriteRune(ch)
}
return buf.String()
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"peekN",
"(",
"n",
"int",
")",
"string",
"{",
"if",
"s",
".",
"i",
">=",
"len",
"(",
"s",
".",
"b",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"b",
":=",
"s",
".",
"b",
"[",
"s",
".",
"i",
":",
"]",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
"&&",
"len",
"(",
"b",
")",
">",
"0",
";",
"i",
"++",
"{",
"ch",
",",
"sz",
":=",
"utf8",
".",
"DecodeRune",
"(",
"b",
")",
"\n",
"b",
"=",
"b",
"[",
"sz",
":",
"]",
"\n",
"buf",
".",
"WriteRune",
"(",
"ch",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // peekN reads the next n runes but does not move the position forward. | [
"peekN",
"reads",
"the",
"next",
"n",
"runes",
"but",
"does",
"not",
"move",
"the",
"position",
"forward",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L559-L572 |
11,356 | benbjohnson/ego | scanner.go | peekIgnoreWhitespace | func (s *Scanner) peekIgnoreWhitespace() rune {
var b []byte
if s.i < len(s.b) {
b = s.b[s.i:]
}
for i := 0; ; i++ {
if len(b) == 0 {
return eof
}
ch, sz := utf8.DecodeRune(b)
if !isWhitespace(ch) {
return ch
}
b = b[sz:]
}
} | go | func (s *Scanner) peekIgnoreWhitespace() rune {
var b []byte
if s.i < len(s.b) {
b = s.b[s.i:]
}
for i := 0; ; i++ {
if len(b) == 0 {
return eof
}
ch, sz := utf8.DecodeRune(b)
if !isWhitespace(ch) {
return ch
}
b = b[sz:]
}
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"peekIgnoreWhitespace",
"(",
")",
"rune",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"if",
"s",
".",
"i",
"<",
"len",
"(",
"s",
".",
"b",
")",
"{",
"b",
"=",
"s",
".",
"b",
"[",
"s",
".",
"i",
":",
"]",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
";",
"i",
"++",
"{",
"if",
"len",
"(",
"b",
")",
"==",
"0",
"{",
"return",
"eof",
"\n",
"}",
"\n\n",
"ch",
",",
"sz",
":=",
"utf8",
".",
"DecodeRune",
"(",
"b",
")",
"\n",
"if",
"!",
"isWhitespace",
"(",
"ch",
")",
"{",
"return",
"ch",
"\n",
"}",
"\n\n",
"b",
"=",
"b",
"[",
"sz",
":",
"]",
"\n",
"}",
"\n",
"}"
] | // peekIgnoreWhitespace reads the non-whitespace rune. | [
"peekIgnoreWhitespace",
"reads",
"the",
"non",
"-",
"whitespace",
"rune",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/scanner.go#L575-L593 |
11,357 | benbjohnson/ego | ego.go | WriteTo | func (t *Template) WriteTo(w io.Writer) (n int64, err error) {
var buf bytes.Buffer
// Write "generated" header comment.
buf.WriteString("// Generated by ego.\n")
buf.WriteString("// DO NOT EDIT\n\n")
// Write blocks.
writeBlocksTo(&buf, t.Blocks)
// Parse buffer as a Go file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", buf.Bytes(), parser.ParseComments)
if err != nil {
n, _ = buf.WriteTo(w)
return n, err
}
// Inject required packages.
injectImports(f)
// Attempt to gofmt.
var result bytes.Buffer
if err := format.Node(&result, fset, f); err != nil {
n, _ = buf.WriteTo(w)
return n, err
}
// Write to output writer.
return result.WriteTo(w)
} | go | func (t *Template) WriteTo(w io.Writer) (n int64, err error) {
var buf bytes.Buffer
// Write "generated" header comment.
buf.WriteString("// Generated by ego.\n")
buf.WriteString("// DO NOT EDIT\n\n")
// Write blocks.
writeBlocksTo(&buf, t.Blocks)
// Parse buffer as a Go file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", buf.Bytes(), parser.ParseComments)
if err != nil {
n, _ = buf.WriteTo(w)
return n, err
}
// Inject required packages.
injectImports(f)
// Attempt to gofmt.
var result bytes.Buffer
if err := format.Node(&result, fset, f); err != nil {
n, _ = buf.WriteTo(w)
return n, err
}
// Write to output writer.
return result.WriteTo(w)
} | [
"func",
"(",
"t",
"*",
"Template",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n\n",
"// Write \"generated\" header comment.",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n\n",
"// Write blocks.",
"writeBlocksTo",
"(",
"&",
"buf",
",",
"t",
".",
"Blocks",
")",
"\n\n",
"// Parse buffer as a Go file.",
"fset",
":=",
"token",
".",
"NewFileSet",
"(",
")",
"\n",
"f",
",",
"err",
":=",
"parser",
".",
"ParseFile",
"(",
"fset",
",",
"\"",
"\"",
",",
"buf",
".",
"Bytes",
"(",
")",
",",
"parser",
".",
"ParseComments",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"n",
",",
"_",
"=",
"buf",
".",
"WriteTo",
"(",
"w",
")",
"\n",
"return",
"n",
",",
"err",
"\n",
"}",
"\n\n",
"// Inject required packages.",
"injectImports",
"(",
"f",
")",
"\n\n",
"// Attempt to gofmt.",
"var",
"result",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"format",
".",
"Node",
"(",
"&",
"result",
",",
"fset",
",",
"f",
")",
";",
"err",
"!=",
"nil",
"{",
"n",
",",
"_",
"=",
"buf",
".",
"WriteTo",
"(",
"w",
")",
"\n",
"return",
"n",
",",
"err",
"\n",
"}",
"\n\n",
"// Write to output writer.",
"return",
"result",
".",
"WriteTo",
"(",
"w",
")",
"\n",
"}"
] | // WriteTo writes the template to a writer. | [
"WriteTo",
"writes",
"the",
"template",
"to",
"a",
"writer",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/ego.go#L24-L54 |
11,358 | benbjohnson/ego | ego.go | normalizeBlocks | func normalizeBlocks(a []Block) []Block {
a = joinAdjacentTextBlocks(a)
a = trimTrailingEmptyTextBlocks(a)
return a
} | go | func normalizeBlocks(a []Block) []Block {
a = joinAdjacentTextBlocks(a)
a = trimTrailingEmptyTextBlocks(a)
return a
} | [
"func",
"normalizeBlocks",
"(",
"a",
"[",
"]",
"Block",
")",
"[",
"]",
"Block",
"{",
"a",
"=",
"joinAdjacentTextBlocks",
"(",
"a",
")",
"\n",
"a",
"=",
"trimTrailingEmptyTextBlocks",
"(",
"a",
")",
"\n",
"return",
"a",
"\n",
"}"
] | // Normalize joins together adjacent text blocks. | [
"Normalize",
"joins",
"together",
"adjacent",
"text",
"blocks",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/ego.go#L114-L118 |
11,359 | benbjohnson/ego | ego.go | Position | func Position(blk Block) Pos {
switch blk := blk.(type) {
case *TextBlock:
return blk.Pos
case *CodeBlock:
return blk.Pos
case *PrintBlock:
return blk.Pos
case *RawPrintBlock:
return blk.Pos
case *ComponentStartBlock:
return blk.Pos
case *ComponentEndBlock:
return blk.Pos
case *AttrStartBlock:
return blk.Pos
case *AttrEndBlock:
return blk.Pos
default:
panic("unreachable")
}
} | go | func Position(blk Block) Pos {
switch blk := blk.(type) {
case *TextBlock:
return blk.Pos
case *CodeBlock:
return blk.Pos
case *PrintBlock:
return blk.Pos
case *RawPrintBlock:
return blk.Pos
case *ComponentStartBlock:
return blk.Pos
case *ComponentEndBlock:
return blk.Pos
case *AttrStartBlock:
return blk.Pos
case *AttrEndBlock:
return blk.Pos
default:
panic("unreachable")
}
} | [
"func",
"Position",
"(",
"blk",
"Block",
")",
"Pos",
"{",
"switch",
"blk",
":=",
"blk",
".",
"(",
"type",
")",
"{",
"case",
"*",
"TextBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"case",
"*",
"CodeBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"case",
"*",
"PrintBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"case",
"*",
"RawPrintBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"case",
"*",
"ComponentStartBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"case",
"*",
"ComponentEndBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"case",
"*",
"AttrStartBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"case",
"*",
"AttrEndBlock",
":",
"return",
"blk",
".",
"Pos",
"\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // Position returns the position of the block. | [
"Position",
"returns",
"the",
"position",
"of",
"the",
"block",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/ego.go#L370-L391 |
11,360 | benbjohnson/ego | ego.go | AttrNames | func AttrNames(attrs map[string]interface{}) []string {
a := make([]string, 0, len(attrs))
for k := range attrs {
a = append(a, k)
}
sort.Strings(a)
return a
} | go | func AttrNames(attrs map[string]interface{}) []string {
a := make([]string, 0, len(attrs))
for k := range attrs {
a = append(a, k)
}
sort.Strings(a)
return a
} | [
"func",
"AttrNames",
"(",
"attrs",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"[",
"]",
"string",
"{",
"a",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"attrs",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"attrs",
"{",
"a",
"=",
"append",
"(",
"a",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"a",
")",
"\n",
"return",
"a",
"\n",
"}"
] | // AttrNames returns a sorted list of names for an attribute set. | [
"AttrNames",
"returns",
"a",
"sorted",
"list",
"of",
"names",
"for",
"an",
"attribute",
"set",
"."
] | 02c2902eb0157c2ffab350390e373ca00e4e84a1 | https://github.com/benbjohnson/ego/blob/02c2902eb0157c2ffab350390e373ca00e4e84a1/ego.go#L414-L421 |
11,361 | codahale/hdrhistogram | window.go | NewWindowed | func NewWindowed(n int, minValue, maxValue int64, sigfigs int) *WindowedHistogram {
w := WindowedHistogram{
idx: -1,
h: make([]Histogram, n),
m: New(minValue, maxValue, sigfigs),
}
for i := range w.h {
w.h[i] = *New(minValue, maxValue, sigfigs)
}
w.Rotate()
return &w
} | go | func NewWindowed(n int, minValue, maxValue int64, sigfigs int) *WindowedHistogram {
w := WindowedHistogram{
idx: -1,
h: make([]Histogram, n),
m: New(minValue, maxValue, sigfigs),
}
for i := range w.h {
w.h[i] = *New(minValue, maxValue, sigfigs)
}
w.Rotate()
return &w
} | [
"func",
"NewWindowed",
"(",
"n",
"int",
",",
"minValue",
",",
"maxValue",
"int64",
",",
"sigfigs",
"int",
")",
"*",
"WindowedHistogram",
"{",
"w",
":=",
"WindowedHistogram",
"{",
"idx",
":",
"-",
"1",
",",
"h",
":",
"make",
"(",
"[",
"]",
"Histogram",
",",
"n",
")",
",",
"m",
":",
"New",
"(",
"minValue",
",",
"maxValue",
",",
"sigfigs",
")",
",",
"}",
"\n\n",
"for",
"i",
":=",
"range",
"w",
".",
"h",
"{",
"w",
".",
"h",
"[",
"i",
"]",
"=",
"*",
"New",
"(",
"minValue",
",",
"maxValue",
",",
"sigfigs",
")",
"\n",
"}",
"\n",
"w",
".",
"Rotate",
"(",
")",
"\n\n",
"return",
"&",
"w",
"\n",
"}"
] | // NewWindowed creates a new WindowedHistogram with N underlying histograms with
// the given parameters. | [
"NewWindowed",
"creates",
"a",
"new",
"WindowedHistogram",
"with",
"N",
"underlying",
"histograms",
"with",
"the",
"given",
"parameters",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/window.go#L14-L27 |
11,362 | codahale/hdrhistogram | window.go | Merge | func (w *WindowedHistogram) Merge() *Histogram {
w.m.Reset()
for _, h := range w.h {
w.m.Merge(&h)
}
return w.m
} | go | func (w *WindowedHistogram) Merge() *Histogram {
w.m.Reset()
for _, h := range w.h {
w.m.Merge(&h)
}
return w.m
} | [
"func",
"(",
"w",
"*",
"WindowedHistogram",
")",
"Merge",
"(",
")",
"*",
"Histogram",
"{",
"w",
".",
"m",
".",
"Reset",
"(",
")",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"w",
".",
"h",
"{",
"w",
".",
"m",
".",
"Merge",
"(",
"&",
"h",
")",
"\n",
"}",
"\n",
"return",
"w",
".",
"m",
"\n",
"}"
] | // Merge returns a histogram which includes the recorded values from all the
// sections of the window. | [
"Merge",
"returns",
"a",
"histogram",
"which",
"includes",
"the",
"recorded",
"values",
"from",
"all",
"the",
"sections",
"of",
"the",
"window",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/window.go#L31-L37 |
11,363 | codahale/hdrhistogram | window.go | Rotate | func (w *WindowedHistogram) Rotate() {
w.idx++
w.Current = &w.h[w.idx%len(w.h)]
w.Current.Reset()
} | go | func (w *WindowedHistogram) Rotate() {
w.idx++
w.Current = &w.h[w.idx%len(w.h)]
w.Current.Reset()
} | [
"func",
"(",
"w",
"*",
"WindowedHistogram",
")",
"Rotate",
"(",
")",
"{",
"w",
".",
"idx",
"++",
"\n",
"w",
".",
"Current",
"=",
"&",
"w",
".",
"h",
"[",
"w",
".",
"idx",
"%",
"len",
"(",
"w",
".",
"h",
")",
"]",
"\n",
"w",
".",
"Current",
".",
"Reset",
"(",
")",
"\n",
"}"
] | // Rotate resets the oldest histogram and rotates it to be used as the current
// histogram. | [
"Rotate",
"resets",
"the",
"oldest",
"histogram",
"and",
"rotates",
"it",
"to",
"be",
"used",
"as",
"the",
"current",
"histogram",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/window.go#L41-L45 |
11,364 | codahale/hdrhistogram | hdr.go | New | func New(minValue, maxValue int64, sigfigs int) *Histogram {
if sigfigs < 1 || 5 < sigfigs {
panic(fmt.Errorf("sigfigs must be [1,5] (was %d)", sigfigs))
}
largestValueWithSingleUnitResolution := 2 * math.Pow10(sigfigs)
subBucketCountMagnitude := int32(math.Ceil(math.Log2(float64(largestValueWithSingleUnitResolution))))
subBucketHalfCountMagnitude := subBucketCountMagnitude
if subBucketHalfCountMagnitude < 1 {
subBucketHalfCountMagnitude = 1
}
subBucketHalfCountMagnitude--
unitMagnitude := int32(math.Floor(math.Log2(float64(minValue))))
if unitMagnitude < 0 {
unitMagnitude = 0
}
subBucketCount := int32(math.Pow(2, float64(subBucketHalfCountMagnitude)+1))
subBucketHalfCount := subBucketCount / 2
subBucketMask := int64(subBucketCount-1) << uint(unitMagnitude)
// determine exponent range needed to support the trackable value with no
// overflow:
smallestUntrackableValue := int64(subBucketCount) << uint(unitMagnitude)
bucketsNeeded := int32(1)
for smallestUntrackableValue < maxValue {
smallestUntrackableValue <<= 1
bucketsNeeded++
}
bucketCount := bucketsNeeded
countsLen := (bucketCount + 1) * (subBucketCount / 2)
return &Histogram{
lowestTrackableValue: minValue,
highestTrackableValue: maxValue,
unitMagnitude: int64(unitMagnitude),
significantFigures: int64(sigfigs),
subBucketHalfCountMagnitude: subBucketHalfCountMagnitude,
subBucketHalfCount: subBucketHalfCount,
subBucketMask: subBucketMask,
subBucketCount: subBucketCount,
bucketCount: bucketCount,
countsLen: countsLen,
totalCount: 0,
counts: make([]int64, countsLen),
}
} | go | func New(minValue, maxValue int64, sigfigs int) *Histogram {
if sigfigs < 1 || 5 < sigfigs {
panic(fmt.Errorf("sigfigs must be [1,5] (was %d)", sigfigs))
}
largestValueWithSingleUnitResolution := 2 * math.Pow10(sigfigs)
subBucketCountMagnitude := int32(math.Ceil(math.Log2(float64(largestValueWithSingleUnitResolution))))
subBucketHalfCountMagnitude := subBucketCountMagnitude
if subBucketHalfCountMagnitude < 1 {
subBucketHalfCountMagnitude = 1
}
subBucketHalfCountMagnitude--
unitMagnitude := int32(math.Floor(math.Log2(float64(minValue))))
if unitMagnitude < 0 {
unitMagnitude = 0
}
subBucketCount := int32(math.Pow(2, float64(subBucketHalfCountMagnitude)+1))
subBucketHalfCount := subBucketCount / 2
subBucketMask := int64(subBucketCount-1) << uint(unitMagnitude)
// determine exponent range needed to support the trackable value with no
// overflow:
smallestUntrackableValue := int64(subBucketCount) << uint(unitMagnitude)
bucketsNeeded := int32(1)
for smallestUntrackableValue < maxValue {
smallestUntrackableValue <<= 1
bucketsNeeded++
}
bucketCount := bucketsNeeded
countsLen := (bucketCount + 1) * (subBucketCount / 2)
return &Histogram{
lowestTrackableValue: minValue,
highestTrackableValue: maxValue,
unitMagnitude: int64(unitMagnitude),
significantFigures: int64(sigfigs),
subBucketHalfCountMagnitude: subBucketHalfCountMagnitude,
subBucketHalfCount: subBucketHalfCount,
subBucketMask: subBucketMask,
subBucketCount: subBucketCount,
bucketCount: bucketCount,
countsLen: countsLen,
totalCount: 0,
counts: make([]int64, countsLen),
}
} | [
"func",
"New",
"(",
"minValue",
",",
"maxValue",
"int64",
",",
"sigfigs",
"int",
")",
"*",
"Histogram",
"{",
"if",
"sigfigs",
"<",
"1",
"||",
"5",
"<",
"sigfigs",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sigfigs",
")",
")",
"\n",
"}",
"\n\n",
"largestValueWithSingleUnitResolution",
":=",
"2",
"*",
"math",
".",
"Pow10",
"(",
"sigfigs",
")",
"\n",
"subBucketCountMagnitude",
":=",
"int32",
"(",
"math",
".",
"Ceil",
"(",
"math",
".",
"Log2",
"(",
"float64",
"(",
"largestValueWithSingleUnitResolution",
")",
")",
")",
")",
"\n\n",
"subBucketHalfCountMagnitude",
":=",
"subBucketCountMagnitude",
"\n",
"if",
"subBucketHalfCountMagnitude",
"<",
"1",
"{",
"subBucketHalfCountMagnitude",
"=",
"1",
"\n",
"}",
"\n",
"subBucketHalfCountMagnitude",
"--",
"\n\n",
"unitMagnitude",
":=",
"int32",
"(",
"math",
".",
"Floor",
"(",
"math",
".",
"Log2",
"(",
"float64",
"(",
"minValue",
")",
")",
")",
")",
"\n",
"if",
"unitMagnitude",
"<",
"0",
"{",
"unitMagnitude",
"=",
"0",
"\n",
"}",
"\n\n",
"subBucketCount",
":=",
"int32",
"(",
"math",
".",
"Pow",
"(",
"2",
",",
"float64",
"(",
"subBucketHalfCountMagnitude",
")",
"+",
"1",
")",
")",
"\n\n",
"subBucketHalfCount",
":=",
"subBucketCount",
"/",
"2",
"\n",
"subBucketMask",
":=",
"int64",
"(",
"subBucketCount",
"-",
"1",
")",
"<<",
"uint",
"(",
"unitMagnitude",
")",
"\n\n",
"// determine exponent range needed to support the trackable value with no",
"// overflow:",
"smallestUntrackableValue",
":=",
"int64",
"(",
"subBucketCount",
")",
"<<",
"uint",
"(",
"unitMagnitude",
")",
"\n",
"bucketsNeeded",
":=",
"int32",
"(",
"1",
")",
"\n",
"for",
"smallestUntrackableValue",
"<",
"maxValue",
"{",
"smallestUntrackableValue",
"<<=",
"1",
"\n",
"bucketsNeeded",
"++",
"\n",
"}",
"\n\n",
"bucketCount",
":=",
"bucketsNeeded",
"\n",
"countsLen",
":=",
"(",
"bucketCount",
"+",
"1",
")",
"*",
"(",
"subBucketCount",
"/",
"2",
")",
"\n\n",
"return",
"&",
"Histogram",
"{",
"lowestTrackableValue",
":",
"minValue",
",",
"highestTrackableValue",
":",
"maxValue",
",",
"unitMagnitude",
":",
"int64",
"(",
"unitMagnitude",
")",
",",
"significantFigures",
":",
"int64",
"(",
"sigfigs",
")",
",",
"subBucketHalfCountMagnitude",
":",
"subBucketHalfCountMagnitude",
",",
"subBucketHalfCount",
":",
"subBucketHalfCount",
",",
"subBucketMask",
":",
"subBucketMask",
",",
"subBucketCount",
":",
"subBucketCount",
",",
"bucketCount",
":",
"bucketCount",
",",
"countsLen",
":",
"countsLen",
",",
"totalCount",
":",
"0",
",",
"counts",
":",
"make",
"(",
"[",
"]",
"int64",
",",
"countsLen",
")",
",",
"}",
"\n",
"}"
] | // New returns a new Histogram instance capable of tracking values in the given
// range and with the given amount of precision. | [
"New",
"returns",
"a",
"new",
"Histogram",
"instance",
"capable",
"of",
"tracking",
"values",
"in",
"the",
"given",
"range",
"and",
"with",
"the",
"given",
"amount",
"of",
"precision",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L46-L96 |
11,365 | codahale/hdrhistogram | hdr.go | Merge | func (h *Histogram) Merge(from *Histogram) (dropped int64) {
i := from.rIterator()
for i.next() {
v := i.valueFromIdx
c := i.countAtIdx
if h.RecordValues(v, c) != nil {
dropped += c
}
}
return
} | go | func (h *Histogram) Merge(from *Histogram) (dropped int64) {
i := from.rIterator()
for i.next() {
v := i.valueFromIdx
c := i.countAtIdx
if h.RecordValues(v, c) != nil {
dropped += c
}
}
return
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Merge",
"(",
"from",
"*",
"Histogram",
")",
"(",
"dropped",
"int64",
")",
"{",
"i",
":=",
"from",
".",
"rIterator",
"(",
")",
"\n",
"for",
"i",
".",
"next",
"(",
")",
"{",
"v",
":=",
"i",
".",
"valueFromIdx",
"\n",
"c",
":=",
"i",
".",
"countAtIdx",
"\n\n",
"if",
"h",
".",
"RecordValues",
"(",
"v",
",",
"c",
")",
"!=",
"nil",
"{",
"dropped",
"+=",
"c",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Merge merges the data stored in the given histogram with the receiver,
// returning the number of recorded values which had to be dropped. | [
"Merge",
"merges",
"the",
"data",
"stored",
"in",
"the",
"given",
"histogram",
"with",
"the",
"receiver",
"returning",
"the",
"number",
"of",
"recorded",
"values",
"which",
"had",
"to",
"be",
"dropped",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L109-L121 |
11,366 | codahale/hdrhistogram | hdr.go | Max | func (h *Histogram) Max() int64 {
var max int64
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 {
max = i.highestEquivalentValue
}
}
return h.highestEquivalentValue(max)
} | go | func (h *Histogram) Max() int64 {
var max int64
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 {
max = i.highestEquivalentValue
}
}
return h.highestEquivalentValue(max)
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Max",
"(",
")",
"int64",
"{",
"var",
"max",
"int64",
"\n",
"i",
":=",
"h",
".",
"iterator",
"(",
")",
"\n",
"for",
"i",
".",
"next",
"(",
")",
"{",
"if",
"i",
".",
"countAtIdx",
"!=",
"0",
"{",
"max",
"=",
"i",
".",
"highestEquivalentValue",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"h",
".",
"highestEquivalentValue",
"(",
"max",
")",
"\n",
"}"
] | // Max returns the approximate maximum recorded value. | [
"Max",
"returns",
"the",
"approximate",
"maximum",
"recorded",
"value",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L129-L138 |
11,367 | codahale/hdrhistogram | hdr.go | Min | func (h *Histogram) Min() int64 {
var min int64
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 && min == 0 {
min = i.highestEquivalentValue
break
}
}
return h.lowestEquivalentValue(min)
} | go | func (h *Histogram) Min() int64 {
var min int64
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 && min == 0 {
min = i.highestEquivalentValue
break
}
}
return h.lowestEquivalentValue(min)
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Min",
"(",
")",
"int64",
"{",
"var",
"min",
"int64",
"\n",
"i",
":=",
"h",
".",
"iterator",
"(",
")",
"\n",
"for",
"i",
".",
"next",
"(",
")",
"{",
"if",
"i",
".",
"countAtIdx",
"!=",
"0",
"&&",
"min",
"==",
"0",
"{",
"min",
"=",
"i",
".",
"highestEquivalentValue",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"h",
".",
"lowestEquivalentValue",
"(",
"min",
")",
"\n",
"}"
] | // Min returns the approximate minimum recorded value. | [
"Min",
"returns",
"the",
"approximate",
"minimum",
"recorded",
"value",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L141-L151 |
11,368 | codahale/hdrhistogram | hdr.go | Mean | func (h *Histogram) Mean() float64 {
if h.totalCount == 0 {
return 0
}
var total int64
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 {
total += i.countAtIdx * h.medianEquivalentValue(i.valueFromIdx)
}
}
return float64(total) / float64(h.totalCount)
} | go | func (h *Histogram) Mean() float64 {
if h.totalCount == 0 {
return 0
}
var total int64
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 {
total += i.countAtIdx * h.medianEquivalentValue(i.valueFromIdx)
}
}
return float64(total) / float64(h.totalCount)
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Mean",
"(",
")",
"float64",
"{",
"if",
"h",
".",
"totalCount",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"var",
"total",
"int64",
"\n",
"i",
":=",
"h",
".",
"iterator",
"(",
")",
"\n",
"for",
"i",
".",
"next",
"(",
")",
"{",
"if",
"i",
".",
"countAtIdx",
"!=",
"0",
"{",
"total",
"+=",
"i",
".",
"countAtIdx",
"*",
"h",
".",
"medianEquivalentValue",
"(",
"i",
".",
"valueFromIdx",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"float64",
"(",
"total",
")",
"/",
"float64",
"(",
"h",
".",
"totalCount",
")",
"\n",
"}"
] | // Mean returns the approximate arithmetic mean of the recorded values. | [
"Mean",
"returns",
"the",
"approximate",
"arithmetic",
"mean",
"of",
"the",
"recorded",
"values",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L154-L166 |
11,369 | codahale/hdrhistogram | hdr.go | StdDev | func (h *Histogram) StdDev() float64 {
if h.totalCount == 0 {
return 0
}
mean := h.Mean()
geometricDevTotal := 0.0
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 {
dev := float64(h.medianEquivalentValue(i.valueFromIdx)) - mean
geometricDevTotal += (dev * dev) * float64(i.countAtIdx)
}
}
return math.Sqrt(geometricDevTotal / float64(h.totalCount))
} | go | func (h *Histogram) StdDev() float64 {
if h.totalCount == 0 {
return 0
}
mean := h.Mean()
geometricDevTotal := 0.0
i := h.iterator()
for i.next() {
if i.countAtIdx != 0 {
dev := float64(h.medianEquivalentValue(i.valueFromIdx)) - mean
geometricDevTotal += (dev * dev) * float64(i.countAtIdx)
}
}
return math.Sqrt(geometricDevTotal / float64(h.totalCount))
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"StdDev",
"(",
")",
"float64",
"{",
"if",
"h",
".",
"totalCount",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"mean",
":=",
"h",
".",
"Mean",
"(",
")",
"\n",
"geometricDevTotal",
":=",
"0.0",
"\n\n",
"i",
":=",
"h",
".",
"iterator",
"(",
")",
"\n",
"for",
"i",
".",
"next",
"(",
")",
"{",
"if",
"i",
".",
"countAtIdx",
"!=",
"0",
"{",
"dev",
":=",
"float64",
"(",
"h",
".",
"medianEquivalentValue",
"(",
"i",
".",
"valueFromIdx",
")",
")",
"-",
"mean",
"\n",
"geometricDevTotal",
"+=",
"(",
"dev",
"*",
"dev",
")",
"*",
"float64",
"(",
"i",
".",
"countAtIdx",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"math",
".",
"Sqrt",
"(",
"geometricDevTotal",
"/",
"float64",
"(",
"h",
".",
"totalCount",
")",
")",
"\n",
"}"
] | // StdDev returns the approximate standard deviation of the recorded values. | [
"StdDev",
"returns",
"the",
"approximate",
"standard",
"deviation",
"of",
"the",
"recorded",
"values",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L169-L186 |
11,370 | codahale/hdrhistogram | hdr.go | Reset | func (h *Histogram) Reset() {
h.totalCount = 0
for i := range h.counts {
h.counts[i] = 0
}
} | go | func (h *Histogram) Reset() {
h.totalCount = 0
for i := range h.counts {
h.counts[i] = 0
}
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Reset",
"(",
")",
"{",
"h",
".",
"totalCount",
"=",
"0",
"\n",
"for",
"i",
":=",
"range",
"h",
".",
"counts",
"{",
"h",
".",
"counts",
"[",
"i",
"]",
"=",
"0",
"\n",
"}",
"\n",
"}"
] | // Reset deletes all recorded values and restores the histogram to its original
// state. | [
"Reset",
"deletes",
"all",
"recorded",
"values",
"and",
"restores",
"the",
"histogram",
"to",
"its",
"original",
"state",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L190-L195 |
11,371 | codahale/hdrhistogram | hdr.go | CumulativeDistribution | func (h *Histogram) CumulativeDistribution() []Bracket {
var result []Bracket
i := h.pIterator(1)
for i.next() {
result = append(result, Bracket{
Quantile: i.percentile,
Count: i.countToIdx,
ValueAt: i.highestEquivalentValue,
})
}
return result
} | go | func (h *Histogram) CumulativeDistribution() []Bracket {
var result []Bracket
i := h.pIterator(1)
for i.next() {
result = append(result, Bracket{
Quantile: i.percentile,
Count: i.countToIdx,
ValueAt: i.highestEquivalentValue,
})
}
return result
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"CumulativeDistribution",
"(",
")",
"[",
"]",
"Bracket",
"{",
"var",
"result",
"[",
"]",
"Bracket",
"\n\n",
"i",
":=",
"h",
".",
"pIterator",
"(",
"1",
")",
"\n",
"for",
"i",
".",
"next",
"(",
")",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"Bracket",
"{",
"Quantile",
":",
"i",
".",
"percentile",
",",
"Count",
":",
"i",
".",
"countToIdx",
",",
"ValueAt",
":",
"i",
".",
"highestEquivalentValue",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] | // CumulativeDistribution returns an ordered list of brackets of the
// distribution of recorded values. | [
"CumulativeDistribution",
"returns",
"an",
"ordered",
"list",
"of",
"brackets",
"of",
"the",
"distribution",
"of",
"recorded",
"values",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L263-L276 |
11,372 | codahale/hdrhistogram | hdr.go | String | func (b Bar) String() string {
return fmt.Sprintf("%v, %v, %v\n", b.From, b.To, b.Count)
} | go | func (b Bar) String() string {
return fmt.Sprintf("%v, %v, %v\n", b.From, b.To, b.Count)
} | [
"func",
"(",
"b",
"Bar",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"b",
".",
"From",
",",
"b",
".",
"To",
",",
"b",
".",
"Count",
")",
"\n",
"}"
] | // Pretty print as csv for easy plotting | [
"Pretty",
"print",
"as",
"csv",
"for",
"easy",
"plotting"
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L302-L304 |
11,373 | codahale/hdrhistogram | hdr.go | Distribution | func (h *Histogram) Distribution() (result []Bar) {
i := h.iterator()
for i.next() {
result = append(result, Bar{
Count: i.countAtIdx,
From: h.lowestEquivalentValue(i.valueFromIdx),
To: i.highestEquivalentValue,
})
}
return result
} | go | func (h *Histogram) Distribution() (result []Bar) {
i := h.iterator()
for i.next() {
result = append(result, Bar{
Count: i.countAtIdx,
From: h.lowestEquivalentValue(i.valueFromIdx),
To: i.highestEquivalentValue,
})
}
return result
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Distribution",
"(",
")",
"(",
"result",
"[",
"]",
"Bar",
")",
"{",
"i",
":=",
"h",
".",
"iterator",
"(",
")",
"\n",
"for",
"i",
".",
"next",
"(",
")",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"Bar",
"{",
"Count",
":",
"i",
".",
"countAtIdx",
",",
"From",
":",
"h",
".",
"lowestEquivalentValue",
"(",
"i",
".",
"valueFromIdx",
")",
",",
"To",
":",
"i",
".",
"highestEquivalentValue",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] | // Distribution returns an ordered list of bars of the
// distribution of recorded values, counts can be normalized to a probability | [
"Distribution",
"returns",
"an",
"ordered",
"list",
"of",
"bars",
"of",
"the",
"distribution",
"of",
"recorded",
"values",
"counts",
"can",
"be",
"normalized",
"to",
"a",
"probability"
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L308-L319 |
11,374 | codahale/hdrhistogram | hdr.go | Export | func (h *Histogram) Export() *Snapshot {
return &Snapshot{
LowestTrackableValue: h.lowestTrackableValue,
HighestTrackableValue: h.highestTrackableValue,
SignificantFigures: h.significantFigures,
Counts: append([]int64(nil), h.counts...), // copy
}
} | go | func (h *Histogram) Export() *Snapshot {
return &Snapshot{
LowestTrackableValue: h.lowestTrackableValue,
HighestTrackableValue: h.highestTrackableValue,
SignificantFigures: h.significantFigures,
Counts: append([]int64(nil), h.counts...), // copy
}
} | [
"func",
"(",
"h",
"*",
"Histogram",
")",
"Export",
"(",
")",
"*",
"Snapshot",
"{",
"return",
"&",
"Snapshot",
"{",
"LowestTrackableValue",
":",
"h",
".",
"lowestTrackableValue",
",",
"HighestTrackableValue",
":",
"h",
".",
"highestTrackableValue",
",",
"SignificantFigures",
":",
"h",
".",
"significantFigures",
",",
"Counts",
":",
"append",
"(",
"[",
"]",
"int64",
"(",
"nil",
")",
",",
"h",
".",
"counts",
"...",
")",
",",
"// copy",
"}",
"\n",
"}"
] | // Export returns a snapshot view of the Histogram. This can be later passed to
// Import to construct a new Histogram with the same state. | [
"Export",
"returns",
"a",
"snapshot",
"view",
"of",
"the",
"Histogram",
".",
"This",
"can",
"be",
"later",
"passed",
"to",
"Import",
"to",
"construct",
"a",
"new",
"Histogram",
"with",
"the",
"same",
"state",
"."
] | 3a0bb77429bd3a61596f5e8a3172445844342120 | https://github.com/codahale/hdrhistogram/blob/3a0bb77429bd3a61596f5e8a3172445844342120/hdr.go#L349-L356 |
11,375 | gin-contrib/secure | policy.go | newPolicy | func newPolicy(config Config) *policy {
policy := &policy{}
policy.loadConfig(config)
return policy
} | go | func newPolicy(config Config) *policy {
policy := &policy{}
policy.loadConfig(config)
return policy
} | [
"func",
"newPolicy",
"(",
"config",
"Config",
")",
"*",
"policy",
"{",
"policy",
":=",
"&",
"policy",
"{",
"}",
"\n",
"policy",
".",
"loadConfig",
"(",
"config",
")",
"\n",
"return",
"policy",
"\n",
"}"
] | // Constructs a new Policy instance with supplied options. | [
"Constructs",
"a",
"new",
"Policy",
"instance",
"with",
"supplied",
"options",
"."
] | f9a5befa61069cfea68e8b54d92ac2a0433de46f | https://github.com/gin-contrib/secure/blob/f9a5befa61069cfea68e8b54d92ac2a0433de46f/policy.go#L27-L31 |
11,376 | messagebird/go-rest-api | hlr/hlr.go | Read | func Read(c *messagebird.Client, id string) (*HLR, error) {
hlr := &HLR{}
if err := c.Request(hlr, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return hlr, nil
} | go | func Read(c *messagebird.Client, id string) (*HLR, error) {
hlr := &HLR{}
if err := c.Request(hlr, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return hlr, nil
} | [
"func",
"Read",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"id",
"string",
")",
"(",
"*",
"HLR",
",",
"error",
")",
"{",
"hlr",
":=",
"&",
"HLR",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"hlr",
",",
"http",
".",
"MethodGet",
",",
"path",
"+",
"\"",
"\"",
"+",
"id",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"hlr",
",",
"nil",
"\n",
"}"
] | // Read looks up an existing HLR object for the specified id that was previously
// created by the NewHLR function. | [
"Read",
"looks",
"up",
"an",
"existing",
"HLR",
"object",
"for",
"the",
"specified",
"id",
"that",
"was",
"previously",
"created",
"by",
"the",
"NewHLR",
"function",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/hlr/hlr.go#L46-L53 |
11,377 | messagebird/go-rest-api | hlr/hlr.go | List | func List(c *messagebird.Client) (*HLRList, error) {
hlrList := &HLRList{}
if err := c.Request(hlrList, http.MethodGet, path, nil); err != nil {
return nil, err
}
return hlrList, nil
} | go | func List(c *messagebird.Client) (*HLRList, error) {
hlrList := &HLRList{}
if err := c.Request(hlrList, http.MethodGet, path, nil); err != nil {
return nil, err
}
return hlrList, nil
} | [
"func",
"List",
"(",
"c",
"*",
"messagebird",
".",
"Client",
")",
"(",
"*",
"HLRList",
",",
"error",
")",
"{",
"hlrList",
":=",
"&",
"HLRList",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"hlrList",
",",
"http",
".",
"MethodGet",
",",
"path",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"hlrList",
",",
"nil",
"\n",
"}"
] | // List all HLR objects that were previously created by the Create function. | [
"List",
"all",
"HLR",
"objects",
"that",
"were",
"previously",
"created",
"by",
"the",
"Create",
"function",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/hlr/hlr.go#L56-L63 |
11,378 | messagebird/go-rest-api | hlr/hlr.go | Create | func Create(c *messagebird.Client, msisdn string, reference string) (*HLR, error) {
requestData, err := requestDataForHLR(msisdn, reference)
if err != nil {
return nil, err
}
hlr := &HLR{}
if err := c.Request(hlr, http.MethodPost, path, requestData); err != nil {
return nil, err
}
return hlr, nil
} | go | func Create(c *messagebird.Client, msisdn string, reference string) (*HLR, error) {
requestData, err := requestDataForHLR(msisdn, reference)
if err != nil {
return nil, err
}
hlr := &HLR{}
if err := c.Request(hlr, http.MethodPost, path, requestData); err != nil {
return nil, err
}
return hlr, nil
} | [
"func",
"Create",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"msisdn",
"string",
",",
"reference",
"string",
")",
"(",
"*",
"HLR",
",",
"error",
")",
"{",
"requestData",
",",
"err",
":=",
"requestDataForHLR",
"(",
"msisdn",
",",
"reference",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"hlr",
":=",
"&",
"HLR",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"hlr",
",",
"http",
".",
"MethodPost",
",",
"path",
",",
"requestData",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"hlr",
",",
"nil",
"\n",
"}"
] | // Create creates a new HLR object. | [
"Create",
"creates",
"a",
"new",
"HLR",
"object",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/hlr/hlr.go#L66-L79 |
11,379 | messagebird/go-rest-api | balance/balance.go | Read | func Read(c *messagebird.Client) (*Balance, error) {
balance := &Balance{}
if err := c.Request(balance, http.MethodGet, path, nil); err != nil {
return nil, err
}
return balance, nil
} | go | func Read(c *messagebird.Client) (*Balance, error) {
balance := &Balance{}
if err := c.Request(balance, http.MethodGet, path, nil); err != nil {
return nil, err
}
return balance, nil
} | [
"func",
"Read",
"(",
"c",
"*",
"messagebird",
".",
"Client",
")",
"(",
"*",
"Balance",
",",
"error",
")",
"{",
"balance",
":=",
"&",
"Balance",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"balance",
",",
"http",
".",
"MethodGet",
",",
"path",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"balance",
",",
"nil",
"\n",
"}"
] | // Read returns the balance information for the account that is associated with
// the access key. | [
"Read",
"returns",
"the",
"balance",
"information",
"for",
"the",
"account",
"that",
"is",
"associated",
"with",
"the",
"access",
"key",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/balance/balance.go#L20-L27 |
11,380 | messagebird/go-rest-api | verify/verify.go | Create | func Create(c *messagebird.Client, recipient string, params *Params) (*Verify, error) {
requestData, err := requestDataForVerify(recipient, params)
if err != nil {
return nil, err
}
verify := &Verify{}
if err := c.Request(verify, http.MethodPost, path, requestData); err != nil {
return nil, err
}
return verify, nil
} | go | func Create(c *messagebird.Client, recipient string, params *Params) (*Verify, error) {
requestData, err := requestDataForVerify(recipient, params)
if err != nil {
return nil, err
}
verify := &Verify{}
if err := c.Request(verify, http.MethodPost, path, requestData); err != nil {
return nil, err
}
return verify, nil
} | [
"func",
"Create",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"recipient",
"string",
",",
"params",
"*",
"Params",
")",
"(",
"*",
"Verify",
",",
"error",
")",
"{",
"requestData",
",",
"err",
":=",
"requestDataForVerify",
"(",
"recipient",
",",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"verify",
":=",
"&",
"Verify",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"verify",
",",
"http",
".",
"MethodPost",
",",
"path",
",",
"requestData",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"verify",
",",
"nil",
"\n",
"}"
] | // Create generates a new One-Time-Password for one recipient. | [
"Create",
"generates",
"a",
"new",
"One",
"-",
"Time",
"-",
"Password",
"for",
"one",
"recipient",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/verify/verify.go#L56-L68 |
11,381 | messagebird/go-rest-api | verify/verify.go | Delete | func Delete(c *messagebird.Client, id string) error {
return c.Request(nil, http.MethodDelete, path+"/"+id, nil)
} | go | func Delete(c *messagebird.Client, id string) error {
return c.Request(nil, http.MethodDelete, path+"/"+id, nil)
} | [
"func",
"Delete",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"id",
"string",
")",
"error",
"{",
"return",
"c",
".",
"Request",
"(",
"nil",
",",
"http",
".",
"MethodDelete",
",",
"path",
"+",
"\"",
"\"",
"+",
"id",
",",
"nil",
")",
"\n",
"}"
] | // Delete deletes an existing Verify object by its ID. | [
"Delete",
"deletes",
"an",
"existing",
"Verify",
"object",
"by",
"its",
"ID",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/verify/verify.go#L71-L73 |
11,382 | messagebird/go-rest-api | verify/verify.go | Read | func Read(c *messagebird.Client, id string) (*Verify, error) {
verify := &Verify{}
if err := c.Request(verify, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return verify, nil
} | go | func Read(c *messagebird.Client, id string) (*Verify, error) {
verify := &Verify{}
if err := c.Request(verify, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return verify, nil
} | [
"func",
"Read",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"id",
"string",
")",
"(",
"*",
"Verify",
",",
"error",
")",
"{",
"verify",
":=",
"&",
"Verify",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"verify",
",",
"http",
".",
"MethodGet",
",",
"path",
"+",
"\"",
"\"",
"+",
"id",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"verify",
",",
"nil",
"\n",
"}"
] | // Read retrieves an existing Verify object by its ID. | [
"Read",
"retrieves",
"an",
"existing",
"Verify",
"object",
"by",
"its",
"ID",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/verify/verify.go#L76-L84 |
11,383 | messagebird/go-rest-api | verify/verify.go | VerifyToken | func VerifyToken(c *messagebird.Client, id, token string) (*Verify, error) {
params := &url.Values{}
params.Set("token", token)
pathWithParams := path + "/" + id + "?" + params.Encode()
verify := &Verify{}
if err := c.Request(verify, http.MethodGet, pathWithParams, nil); err != nil {
return nil, err
}
return verify, nil
} | go | func VerifyToken(c *messagebird.Client, id, token string) (*Verify, error) {
params := &url.Values{}
params.Set("token", token)
pathWithParams := path + "/" + id + "?" + params.Encode()
verify := &Verify{}
if err := c.Request(verify, http.MethodGet, pathWithParams, nil); err != nil {
return nil, err
}
return verify, nil
} | [
"func",
"VerifyToken",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"id",
",",
"token",
"string",
")",
"(",
"*",
"Verify",
",",
"error",
")",
"{",
"params",
":=",
"&",
"url",
".",
"Values",
"{",
"}",
"\n",
"params",
".",
"Set",
"(",
"\"",
"\"",
",",
"token",
")",
"\n\n",
"pathWithParams",
":=",
"path",
"+",
"\"",
"\"",
"+",
"id",
"+",
"\"",
"\"",
"+",
"params",
".",
"Encode",
"(",
")",
"\n\n",
"verify",
":=",
"&",
"Verify",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"verify",
",",
"http",
".",
"MethodGet",
",",
"pathWithParams",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"verify",
",",
"nil",
"\n",
"}"
] | // VerifyToken performs token value check against MessageBird API. | [
"VerifyToken",
"performs",
"token",
"value",
"check",
"against",
"MessageBird",
"API",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/verify/verify.go#L87-L99 |
11,384 | messagebird/go-rest-api | lookup/lookup.go | Read | func Read(c *messagebird.Client, phoneNumber string, params *Params) (*Lookup, error) {
urlParams := paramsForLookup(params)
path := lookupPath + "/" + phoneNumber + "?" + urlParams.Encode()
lookup := &Lookup{}
if err := c.Request(lookup, http.MethodGet, path, nil); err != nil {
return nil, err
}
return lookup, nil
} | go | func Read(c *messagebird.Client, phoneNumber string, params *Params) (*Lookup, error) {
urlParams := paramsForLookup(params)
path := lookupPath + "/" + phoneNumber + "?" + urlParams.Encode()
lookup := &Lookup{}
if err := c.Request(lookup, http.MethodGet, path, nil); err != nil {
return nil, err
}
return lookup, nil
} | [
"func",
"Read",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"phoneNumber",
"string",
",",
"params",
"*",
"Params",
")",
"(",
"*",
"Lookup",
",",
"error",
")",
"{",
"urlParams",
":=",
"paramsForLookup",
"(",
"params",
")",
"\n",
"path",
":=",
"lookupPath",
"+",
"\"",
"\"",
"+",
"phoneNumber",
"+",
"\"",
"\"",
"+",
"urlParams",
".",
"Encode",
"(",
")",
"\n\n",
"lookup",
":=",
"&",
"Lookup",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"lookup",
",",
"http",
".",
"MethodGet",
",",
"path",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"lookup",
",",
"nil",
"\n",
"}"
] | // Read performs a new lookup for the specified number. | [
"Read",
"performs",
"a",
"new",
"lookup",
"for",
"the",
"specified",
"number",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/lookup/lookup.go#L48-L58 |
11,385 | messagebird/go-rest-api | lookup/lookup.go | CreateHLR | func CreateHLR(c *messagebird.Client, phoneNumber string, params *Params) (*hlr.HLR, error) {
requestData := requestDataForLookup(params)
path := lookupPath + "/" + phoneNumber + "/" + hlrPath
hlr := &hlr.HLR{}
if err := c.Request(hlr, http.MethodPost, path, requestData); err != nil {
return nil, err
}
return hlr, nil
} | go | func CreateHLR(c *messagebird.Client, phoneNumber string, params *Params) (*hlr.HLR, error) {
requestData := requestDataForLookup(params)
path := lookupPath + "/" + phoneNumber + "/" + hlrPath
hlr := &hlr.HLR{}
if err := c.Request(hlr, http.MethodPost, path, requestData); err != nil {
return nil, err
}
return hlr, nil
} | [
"func",
"CreateHLR",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"phoneNumber",
"string",
",",
"params",
"*",
"Params",
")",
"(",
"*",
"hlr",
".",
"HLR",
",",
"error",
")",
"{",
"requestData",
":=",
"requestDataForLookup",
"(",
"params",
")",
"\n",
"path",
":=",
"lookupPath",
"+",
"\"",
"\"",
"+",
"phoneNumber",
"+",
"\"",
"\"",
"+",
"hlrPath",
"\n\n",
"hlr",
":=",
"&",
"hlr",
".",
"HLR",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"hlr",
",",
"http",
".",
"MethodPost",
",",
"path",
",",
"requestData",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"hlr",
",",
"nil",
"\n",
"}"
] | // CreateHLR creates a new HLR lookup for the specified number. | [
"CreateHLR",
"creates",
"a",
"new",
"HLR",
"lookup",
"for",
"the",
"specified",
"number",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/lookup/lookup.go#L61-L71 |
11,386 | messagebird/go-rest-api | lookup/lookup.go | ReadHLR | func ReadHLR(c *messagebird.Client, phoneNumber string, params *Params) (*hlr.HLR, error) {
urlParams := paramsForLookup(params)
path := lookupPath + "/" + phoneNumber + "/" + hlrPath + "?" + urlParams.Encode()
hlr := &hlr.HLR{}
if err := c.Request(hlr, http.MethodGet, path, nil); err != nil {
return nil, err
}
return hlr, nil
} | go | func ReadHLR(c *messagebird.Client, phoneNumber string, params *Params) (*hlr.HLR, error) {
urlParams := paramsForLookup(params)
path := lookupPath + "/" + phoneNumber + "/" + hlrPath + "?" + urlParams.Encode()
hlr := &hlr.HLR{}
if err := c.Request(hlr, http.MethodGet, path, nil); err != nil {
return nil, err
}
return hlr, nil
} | [
"func",
"ReadHLR",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"phoneNumber",
"string",
",",
"params",
"*",
"Params",
")",
"(",
"*",
"hlr",
".",
"HLR",
",",
"error",
")",
"{",
"urlParams",
":=",
"paramsForLookup",
"(",
"params",
")",
"\n",
"path",
":=",
"lookupPath",
"+",
"\"",
"\"",
"+",
"phoneNumber",
"+",
"\"",
"\"",
"+",
"hlrPath",
"+",
"\"",
"\"",
"+",
"urlParams",
".",
"Encode",
"(",
")",
"\n\n",
"hlr",
":=",
"&",
"hlr",
".",
"HLR",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"hlr",
",",
"http",
".",
"MethodGet",
",",
"path",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"hlr",
",",
"nil",
"\n",
"}"
] | // ReadHLR performs a HLR lookup for the specified number. | [
"ReadHLR",
"performs",
"a",
"HLR",
"lookup",
"for",
"the",
"specified",
"number",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/lookup/lookup.go#L74-L84 |
11,387 | messagebird/go-rest-api | voice/leg.go | Recordings | func (leg *Leg) Recordings(client *messagebird.Client) *Paginator {
return newPaginator(client, fmt.Sprintf("%s/calls/%s/legs/%s/recordings", apiRoot, leg.CallID, leg.ID), reflect.TypeOf(Recording{}))
} | go | func (leg *Leg) Recordings(client *messagebird.Client) *Paginator {
return newPaginator(client, fmt.Sprintf("%s/calls/%s/legs/%s/recordings", apiRoot, leg.CallID, leg.ID), reflect.TypeOf(Recording{}))
} | [
"func",
"(",
"leg",
"*",
"Leg",
")",
"Recordings",
"(",
"client",
"*",
"messagebird",
".",
"Client",
")",
"*",
"Paginator",
"{",
"return",
"newPaginator",
"(",
"client",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"apiRoot",
",",
"leg",
".",
"CallID",
",",
"leg",
".",
"ID",
")",
",",
"reflect",
".",
"TypeOf",
"(",
"Recording",
"{",
"}",
")",
")",
"\n",
"}"
] | // Recordings retrieves the Recording objects associated with a leg. | [
"Recordings",
"retrieves",
"the",
"Recording",
"objects",
"associated",
"with",
"a",
"leg",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/voice/leg.go#L152-L154 |
11,388 | messagebird/go-rest-api | contact/contact.go | List | func List(c *messagebird.Client, options *ListOptions) (*ContactList, error) {
query, err := listQuery(options)
if err != nil {
return nil, err
}
contactList := &ContactList{}
if err = c.Request(contactList, http.MethodGet, path+"?"+query, nil); err != nil {
return nil, err
}
return contactList, nil
} | go | func List(c *messagebird.Client, options *ListOptions) (*ContactList, error) {
query, err := listQuery(options)
if err != nil {
return nil, err
}
contactList := &ContactList{}
if err = c.Request(contactList, http.MethodGet, path+"?"+query, nil); err != nil {
return nil, err
}
return contactList, nil
} | [
"func",
"List",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"options",
"*",
"ListOptions",
")",
"(",
"*",
"ContactList",
",",
"error",
")",
"{",
"query",
",",
"err",
":=",
"listQuery",
"(",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"contactList",
":=",
"&",
"ContactList",
"{",
"}",
"\n",
"if",
"err",
"=",
"c",
".",
"Request",
"(",
"contactList",
",",
"http",
".",
"MethodGet",
",",
"path",
"+",
"\"",
"\"",
"+",
"query",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"contactList",
",",
"nil",
"\n",
"}"
] | // List retrieves a paginated list of contacts, based on the options provided.
// It's worth noting DefaultListOptions. | [
"List",
"retrieves",
"a",
"paginated",
"list",
"of",
"contacts",
"based",
"on",
"the",
"options",
"provided",
".",
"It",
"s",
"worth",
"noting",
"DefaultListOptions",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/contact/contact.go#L104-L116 |
11,389 | messagebird/go-rest-api | contact/contact.go | Read | func Read(c *messagebird.Client, id string) (*Contact, error) {
contact := &Contact{}
if err := c.Request(contact, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return contact, nil
} | go | func Read(c *messagebird.Client, id string) (*Contact, error) {
contact := &Contact{}
if err := c.Request(contact, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return contact, nil
} | [
"func",
"Read",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"id",
"string",
")",
"(",
"*",
"Contact",
",",
"error",
")",
"{",
"contact",
":=",
"&",
"Contact",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"contact",
",",
"http",
".",
"MethodGet",
",",
"path",
"+",
"\"",
"\"",
"+",
"id",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"contact",
",",
"nil",
"\n",
"}"
] | // Read retrieves the information of an existing contact. | [
"Read",
"retrieves",
"the",
"information",
"of",
"an",
"existing",
"contact",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/contact/contact.go#L136-L143 |
11,390 | messagebird/go-rest-api | contact/contact.go | Update | func Update(c *messagebird.Client, id string, contactRequest *Request) (*Contact, error) {
contact := &Contact{}
if err := c.Request(contact, http.MethodPatch, path+"/"+id, contactRequest); err != nil {
return nil, err
}
return contact, nil
} | go | func Update(c *messagebird.Client, id string, contactRequest *Request) (*Contact, error) {
contact := &Contact{}
if err := c.Request(contact, http.MethodPatch, path+"/"+id, contactRequest); err != nil {
return nil, err
}
return contact, nil
} | [
"func",
"Update",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"id",
"string",
",",
"contactRequest",
"*",
"Request",
")",
"(",
"*",
"Contact",
",",
"error",
")",
"{",
"contact",
":=",
"&",
"Contact",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"contact",
",",
"http",
".",
"MethodPatch",
",",
"path",
"+",
"\"",
"\"",
"+",
"id",
",",
"contactRequest",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"contact",
",",
"nil",
"\n",
"}"
] | // Update updates the record referenced by id with any values set in contactRequest.
// Do not set any values that should not be updated. | [
"Update",
"updates",
"the",
"record",
"referenced",
"by",
"id",
"with",
"any",
"values",
"set",
"in",
"contactRequest",
".",
"Do",
"not",
"set",
"any",
"values",
"that",
"should",
"not",
"be",
"updated",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/contact/contact.go#L147-L154 |
11,391 | messagebird/go-rest-api | conversation/conversation.go | List | func List(c *messagebird.Client, options *ListOptions) (*ConversationList, error) {
query := paginationQuery(options)
convList := &ConversationList{}
if err := request(c, convList, http.MethodGet, path+"?"+query, nil); err != nil {
return nil, err
}
return convList, nil
} | go | func List(c *messagebird.Client, options *ListOptions) (*ConversationList, error) {
query := paginationQuery(options)
convList := &ConversationList{}
if err := request(c, convList, http.MethodGet, path+"?"+query, nil); err != nil {
return nil, err
}
return convList, nil
} | [
"func",
"List",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"options",
"*",
"ListOptions",
")",
"(",
"*",
"ConversationList",
",",
"error",
")",
"{",
"query",
":=",
"paginationQuery",
"(",
"options",
")",
"\n\n",
"convList",
":=",
"&",
"ConversationList",
"{",
"}",
"\n",
"if",
"err",
":=",
"request",
"(",
"c",
",",
"convList",
",",
"http",
".",
"MethodGet",
",",
"path",
"+",
"\"",
"\"",
"+",
"query",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"convList",
",",
"nil",
"\n",
"}"
] | // List gets a collection of Conversations. Pagination can be set in options. | [
"List",
"gets",
"a",
"collection",
"of",
"Conversations",
".",
"Pagination",
"can",
"be",
"set",
"in",
"options",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/conversation/conversation.go#L31-L40 |
11,392 | messagebird/go-rest-api | conversation/conversation.go | Read | func Read(c *messagebird.Client, id string) (*Conversation, error) {
conv := &Conversation{}
if err := request(c, conv, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return conv, nil
} | go | func Read(c *messagebird.Client, id string) (*Conversation, error) {
conv := &Conversation{}
if err := request(c, conv, http.MethodGet, path+"/"+id, nil); err != nil {
return nil, err
}
return conv, nil
} | [
"func",
"Read",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"id",
"string",
")",
"(",
"*",
"Conversation",
",",
"error",
")",
"{",
"conv",
":=",
"&",
"Conversation",
"{",
"}",
"\n",
"if",
"err",
":=",
"request",
"(",
"c",
",",
"conv",
",",
"http",
".",
"MethodGet",
",",
"path",
"+",
"\"",
"\"",
"+",
"id",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"conv",
",",
"nil",
"\n",
"}"
] | // Read fetches a single Conversation based on its ID. | [
"Read",
"fetches",
"a",
"single",
"Conversation",
"based",
"on",
"its",
"ID",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/conversation/conversation.go#L43-L50 |
11,393 | messagebird/go-rest-api | conversation/conversation.go | Start | func Start(c *messagebird.Client, req *StartRequest) (*Conversation, error) {
conv := &Conversation{}
if err := request(c, conv, http.MethodPost, path+"/start", req); err != nil {
return nil, err
}
return conv, nil
} | go | func Start(c *messagebird.Client, req *StartRequest) (*Conversation, error) {
conv := &Conversation{}
if err := request(c, conv, http.MethodPost, path+"/start", req); err != nil {
return nil, err
}
return conv, nil
} | [
"func",
"Start",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"req",
"*",
"StartRequest",
")",
"(",
"*",
"Conversation",
",",
"error",
")",
"{",
"conv",
":=",
"&",
"Conversation",
"{",
"}",
"\n",
"if",
"err",
":=",
"request",
"(",
"c",
",",
"conv",
",",
"http",
".",
"MethodPost",
",",
"path",
"+",
"\"",
"\"",
",",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"conv",
",",
"nil",
"\n",
"}"
] | // Start creates a conversation by sending an initial message. If an active
// conversation exists for the recipient, it is resumed. | [
"Start",
"creates",
"a",
"conversation",
"by",
"sending",
"an",
"initial",
"message",
".",
"If",
"an",
"active",
"conversation",
"exists",
"for",
"the",
"recipient",
"it",
"is",
"resumed",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/conversation/conversation.go#L54-L61 |
11,394 | messagebird/go-rest-api | client.go | New | func New(accessKey string) *Client {
return &Client{
AccessKey: accessKey,
HTTPClient: &http.Client{
Timeout: httpClientTimeout,
},
}
} | go | func New(accessKey string) *Client {
return &Client{
AccessKey: accessKey,
HTTPClient: &http.Client{
Timeout: httpClientTimeout,
},
}
} | [
"func",
"New",
"(",
"accessKey",
"string",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"AccessKey",
":",
"accessKey",
",",
"HTTPClient",
":",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"httpClientTimeout",
",",
"}",
",",
"}",
"\n",
"}"
] | // New creates a new MessageBird client object. | [
"New",
"creates",
"a",
"new",
"MessageBird",
"client",
"object",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/client.go#L59-L66 |
11,395 | messagebird/go-rest-api | client.go | Request | func (c *Client) Request(v interface{}, method, path string, data interface{}) error {
if !strings.HasPrefix(path, "https://") && !strings.HasPrefix(path, "http://") {
path = fmt.Sprintf("%s/%s", Endpoint, path)
}
uri, err := url.Parse(path)
if err != nil {
return err
}
body, contentType, err := prepareRequestBody(data)
if err != nil {
return err
}
request, err := http.NewRequest(method, uri.String(), bytes.NewBuffer(body))
if err != nil {
return err
}
request.Header.Set("Accept", "application/json")
request.Header.Set("Authorization", "AccessKey "+c.AccessKey)
request.Header.Set("User-Agent", "MessageBird/ApiClient/"+ClientVersion+" Go/"+runtime.Version())
if contentType != contentTypeEmpty {
request.Header.Set("Content-Type", string(contentType))
}
if c.DebugLog != nil {
if data != nil {
c.DebugLog.Printf("HTTP REQUEST: %s %s %s", method, uri.String(), body)
} else {
c.DebugLog.Printf("HTTP REQUEST: %s %s", method, uri.String())
}
}
response, err := c.HTTPClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if c.DebugLog != nil {
c.DebugLog.Printf("HTTP RESPONSE: %s", string(responseBody))
}
switch response.StatusCode {
case http.StatusOK, http.StatusCreated:
// Status codes 200 and 201 are indicative of being able to convert the
// response body to the struct that was specified.
if err := json.Unmarshal(responseBody, &v); err != nil {
return fmt.Errorf("could not decode response JSON, %s: %v", string(responseBody), err)
}
return nil
case http.StatusNoContent:
// Status code 204 is returned for successful DELETE requests. Don't try to
// unmarshal the body: that would return errors.
return nil
case http.StatusInternalServerError:
// Status code 500 is a server error and means nothing can be done at this
// point.
return ErrUnexpectedResponse
default:
// Anything else than a 200/201/204/500 should be a JSON error.
var errorResponse ErrorResponse
if err := json.Unmarshal(responseBody, &errorResponse); err != nil {
return err
}
return errorResponse
}
} | go | func (c *Client) Request(v interface{}, method, path string, data interface{}) error {
if !strings.HasPrefix(path, "https://") && !strings.HasPrefix(path, "http://") {
path = fmt.Sprintf("%s/%s", Endpoint, path)
}
uri, err := url.Parse(path)
if err != nil {
return err
}
body, contentType, err := prepareRequestBody(data)
if err != nil {
return err
}
request, err := http.NewRequest(method, uri.String(), bytes.NewBuffer(body))
if err != nil {
return err
}
request.Header.Set("Accept", "application/json")
request.Header.Set("Authorization", "AccessKey "+c.AccessKey)
request.Header.Set("User-Agent", "MessageBird/ApiClient/"+ClientVersion+" Go/"+runtime.Version())
if contentType != contentTypeEmpty {
request.Header.Set("Content-Type", string(contentType))
}
if c.DebugLog != nil {
if data != nil {
c.DebugLog.Printf("HTTP REQUEST: %s %s %s", method, uri.String(), body)
} else {
c.DebugLog.Printf("HTTP REQUEST: %s %s", method, uri.String())
}
}
response, err := c.HTTPClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if c.DebugLog != nil {
c.DebugLog.Printf("HTTP RESPONSE: %s", string(responseBody))
}
switch response.StatusCode {
case http.StatusOK, http.StatusCreated:
// Status codes 200 and 201 are indicative of being able to convert the
// response body to the struct that was specified.
if err := json.Unmarshal(responseBody, &v); err != nil {
return fmt.Errorf("could not decode response JSON, %s: %v", string(responseBody), err)
}
return nil
case http.StatusNoContent:
// Status code 204 is returned for successful DELETE requests. Don't try to
// unmarshal the body: that would return errors.
return nil
case http.StatusInternalServerError:
// Status code 500 is a server error and means nothing can be done at this
// point.
return ErrUnexpectedResponse
default:
// Anything else than a 200/201/204/500 should be a JSON error.
var errorResponse ErrorResponse
if err := json.Unmarshal(responseBody, &errorResponse); err != nil {
return err
}
return errorResponse
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Request",
"(",
"v",
"interface",
"{",
"}",
",",
"method",
",",
"path",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"\"",
"\"",
")",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"\"",
"\"",
")",
"{",
"path",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"Endpoint",
",",
"path",
")",
"\n",
"}",
"\n",
"uri",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"body",
",",
"contentType",
",",
"err",
":=",
"prepareRequestBody",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"request",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"uri",
".",
"String",
"(",
")",
",",
"bytes",
".",
"NewBuffer",
"(",
"body",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"request",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"request",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"c",
".",
"AccessKey",
")",
"\n",
"request",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"ClientVersion",
"+",
"\"",
"\"",
"+",
"runtime",
".",
"Version",
"(",
")",
")",
"\n",
"if",
"contentType",
"!=",
"contentTypeEmpty",
"{",
"request",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"string",
"(",
"contentType",
")",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"DebugLog",
"!=",
"nil",
"{",
"if",
"data",
"!=",
"nil",
"{",
"c",
".",
"DebugLog",
".",
"Printf",
"(",
"\"",
"\"",
",",
"method",
",",
"uri",
".",
"String",
"(",
")",
",",
"body",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"DebugLog",
".",
"Printf",
"(",
"\"",
"\"",
",",
"method",
",",
"uri",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"response",
",",
"err",
":=",
"c",
".",
"HTTPClient",
".",
"Do",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"defer",
"response",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"responseBody",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"response",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"DebugLog",
"!=",
"nil",
"{",
"c",
".",
"DebugLog",
".",
"Printf",
"(",
"\"",
"\"",
",",
"string",
"(",
"responseBody",
")",
")",
"\n",
"}",
"\n\n",
"switch",
"response",
".",
"StatusCode",
"{",
"case",
"http",
".",
"StatusOK",
",",
"http",
".",
"StatusCreated",
":",
"// Status codes 200 and 201 are indicative of being able to convert the",
"// response body to the struct that was specified.",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"responseBody",
",",
"&",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"string",
"(",
"responseBody",
")",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"case",
"http",
".",
"StatusNoContent",
":",
"// Status code 204 is returned for successful DELETE requests. Don't try to",
"// unmarshal the body: that would return errors.",
"return",
"nil",
"\n",
"case",
"http",
".",
"StatusInternalServerError",
":",
"// Status code 500 is a server error and means nothing can be done at this",
"// point.",
"return",
"ErrUnexpectedResponse",
"\n",
"default",
":",
"// Anything else than a 200/201/204/500 should be a JSON error.",
"var",
"errorResponse",
"ErrorResponse",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"responseBody",
",",
"&",
"errorResponse",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"errorResponse",
"\n",
"}",
"\n",
"}"
] | // Request is for internal use only and unstable. | [
"Request",
"is",
"for",
"internal",
"use",
"only",
"and",
"unstable",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/client.go#L69-L145 |
11,396 | messagebird/go-rest-api | client.go | prepareRequestBody | func prepareRequestBody(data interface{}) ([]byte, contentType, error) {
switch data := data.(type) {
case nil:
// Nil bodies are accepted by `net/http`, so this is not an error.
return nil, contentTypeEmpty, nil
case string:
return []byte(data), contentTypeFormURLEncoded, nil
default:
b, err := json.Marshal(data)
if err != nil {
return nil, contentType(""), err
}
return b, contentTypeJSON, nil
}
} | go | func prepareRequestBody(data interface{}) ([]byte, contentType, error) {
switch data := data.(type) {
case nil:
// Nil bodies are accepted by `net/http`, so this is not an error.
return nil, contentTypeEmpty, nil
case string:
return []byte(data), contentTypeFormURLEncoded, nil
default:
b, err := json.Marshal(data)
if err != nil {
return nil, contentType(""), err
}
return b, contentTypeJSON, nil
}
} | [
"func",
"prepareRequestBody",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"contentType",
",",
"error",
")",
"{",
"switch",
"data",
":=",
"data",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"// Nil bodies are accepted by `net/http`, so this is not an error.",
"return",
"nil",
",",
"contentTypeEmpty",
",",
"nil",
"\n",
"case",
"string",
":",
"return",
"[",
"]",
"byte",
"(",
"data",
")",
",",
"contentTypeFormURLEncoded",
",",
"nil",
"\n",
"default",
":",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"contentType",
"(",
"\"",
"\"",
")",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"contentTypeJSON",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // prepareRequestBody takes untyped data and attempts constructing a meaningful
// request body from it. It also returns the appropriate Content-Type. | [
"prepareRequestBody",
"takes",
"untyped",
"data",
"and",
"attempts",
"constructing",
"a",
"meaningful",
"request",
"body",
"from",
"it",
".",
"It",
"also",
"returns",
"the",
"appropriate",
"Content",
"-",
"Type",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/client.go#L149-L164 |
11,397 | messagebird/go-rest-api | mms/message.go | Create | func Create(c *messagebird.Client, originator string, recipients []string, msgParams *Params) (*Message, error) {
params, err := paramsForMessage(msgParams)
if err != nil {
return nil, err
}
params.Set("originator", originator)
params.Set("recipients", strings.Join(recipients, ","))
mmsMessage := &Message{}
if err := c.Request(mmsMessage, http.MethodPost, path, params); err != nil {
return nil, err
}
return mmsMessage, nil
} | go | func Create(c *messagebird.Client, originator string, recipients []string, msgParams *Params) (*Message, error) {
params, err := paramsForMessage(msgParams)
if err != nil {
return nil, err
}
params.Set("originator", originator)
params.Set("recipients", strings.Join(recipients, ","))
mmsMessage := &Message{}
if err := c.Request(mmsMessage, http.MethodPost, path, params); err != nil {
return nil, err
}
return mmsMessage, nil
} | [
"func",
"Create",
"(",
"c",
"*",
"messagebird",
".",
"Client",
",",
"originator",
"string",
",",
"recipients",
"[",
"]",
"string",
",",
"msgParams",
"*",
"Params",
")",
"(",
"*",
"Message",
",",
"error",
")",
"{",
"params",
",",
"err",
":=",
"paramsForMessage",
"(",
"msgParams",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"params",
".",
"Set",
"(",
"\"",
"\"",
",",
"originator",
")",
"\n",
"params",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"recipients",
",",
"\"",
"\"",
")",
")",
"\n\n",
"mmsMessage",
":=",
"&",
"Message",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"Request",
"(",
"mmsMessage",
",",
"http",
".",
"MethodPost",
",",
"path",
",",
"params",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"mmsMessage",
",",
"nil",
"\n",
"}"
] | // Create creates a new MMS message for one or more recipients. | [
"Create",
"creates",
"a",
"new",
"MMS",
"message",
"for",
"one",
"or",
"more",
"recipients",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/mms/message.go#L52-L67 |
11,398 | messagebird/go-rest-api | mms/message.go | paramsForMessage | func paramsForMessage(params *Params) (*url.Values, error) {
urlParams := &url.Values{}
if params.Body == "" && params.MediaUrls == nil {
return nil, errors.New("Body or MediaUrls is required")
}
if params.Body != "" {
urlParams.Set("body", params.Body)
}
if params.MediaUrls != nil {
urlParams.Set("mediaUrls[]", strings.Join(params.MediaUrls, ","))
}
if params.Subject != "" {
urlParams.Set("subject", params.Subject)
}
if params.Reference != "" {
urlParams.Set("reference", params.Reference)
}
if params.ScheduledDatetime.Unix() > 0 {
urlParams.Set("scheduledDatetime", params.ScheduledDatetime.Format(time.RFC3339))
}
return urlParams, nil
} | go | func paramsForMessage(params *Params) (*url.Values, error) {
urlParams := &url.Values{}
if params.Body == "" && params.MediaUrls == nil {
return nil, errors.New("Body or MediaUrls is required")
}
if params.Body != "" {
urlParams.Set("body", params.Body)
}
if params.MediaUrls != nil {
urlParams.Set("mediaUrls[]", strings.Join(params.MediaUrls, ","))
}
if params.Subject != "" {
urlParams.Set("subject", params.Subject)
}
if params.Reference != "" {
urlParams.Set("reference", params.Reference)
}
if params.ScheduledDatetime.Unix() > 0 {
urlParams.Set("scheduledDatetime", params.ScheduledDatetime.Format(time.RFC3339))
}
return urlParams, nil
} | [
"func",
"paramsForMessage",
"(",
"params",
"*",
"Params",
")",
"(",
"*",
"url",
".",
"Values",
",",
"error",
")",
"{",
"urlParams",
":=",
"&",
"url",
".",
"Values",
"{",
"}",
"\n\n",
"if",
"params",
".",
"Body",
"==",
"\"",
"\"",
"&&",
"params",
".",
"MediaUrls",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"Body",
"!=",
"\"",
"\"",
"{",
"urlParams",
".",
"Set",
"(",
"\"",
"\"",
",",
"params",
".",
"Body",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"MediaUrls",
"!=",
"nil",
"{",
"urlParams",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"params",
".",
"MediaUrls",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"Subject",
"!=",
"\"",
"\"",
"{",
"urlParams",
".",
"Set",
"(",
"\"",
"\"",
",",
"params",
".",
"Subject",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"Reference",
"!=",
"\"",
"\"",
"{",
"urlParams",
".",
"Set",
"(",
"\"",
"\"",
",",
"params",
".",
"Reference",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"ScheduledDatetime",
".",
"Unix",
"(",
")",
">",
"0",
"{",
"urlParams",
".",
"Set",
"(",
"\"",
"\"",
",",
"params",
".",
"ScheduledDatetime",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n",
"}",
"\n\n",
"return",
"urlParams",
",",
"nil",
"\n",
"}"
] | // paramsForMessage converts the specified Parmas struct to a url.Values
// pointer and returns it. | [
"paramsForMessage",
"converts",
"the",
"specified",
"Parmas",
"struct",
"to",
"a",
"url",
".",
"Values",
"pointer",
"and",
"returns",
"it",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/mms/message.go#L71-L94 |
11,399 | messagebird/go-rest-api | conversation/api.go | paginationQuery | func paginationQuery(options *ListOptions) string {
query := url.Values{}
query.Set("limit", strconv.Itoa(options.Limit))
query.Set("offset", strconv.Itoa(options.Offset))
return query.Encode()
} | go | func paginationQuery(options *ListOptions) string {
query := url.Values{}
query.Set("limit", strconv.Itoa(options.Limit))
query.Set("offset", strconv.Itoa(options.Offset))
return query.Encode()
} | [
"func",
"paginationQuery",
"(",
"options",
"*",
"ListOptions",
")",
"string",
"{",
"query",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"options",
".",
"Limit",
")",
")",
"\n",
"query",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"options",
".",
"Offset",
")",
")",
"\n\n",
"return",
"query",
".",
"Encode",
"(",
")",
"\n",
"}"
] | // paginationQuery builds the query string for paginated endpoints. | [
"paginationQuery",
"builds",
"the",
"query",
"string",
"for",
"paginated",
"endpoints",
"."
] | fd48d63984e1cde9946be190d3a34e1a34e75e34 | https://github.com/messagebird/go-rest-api/blob/fd48d63984e1cde9946be190d3a34e1a34e75e34/conversation/api.go#L213-L219 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.