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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
18,100
instana/go-sensor
event.go
SendHostEvent
func SendHostEvent(title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Duration: int(duration / time.Millisecond), Severity: int(sev), }) }
go
func SendHostEvent(title string, text string, sev severity, duration time.Duration) { sendEvent(&EventData{ Title: title, Text: text, Duration: int(duration / time.Millisecond), Severity: int(sev), }) }
[ "func", "SendHostEvent", "(", "title", "string", ",", "text", "string", ",", "sev", "severity", ",", "duration", "time", ".", "Duration", ")", "{", "sendEvent", "(", "&", "EventData", "{", "Title", ":", "title", ",", "Text", ":", "text", ",", "Duration", ":", "int", "(", "duration", "/", "time", ".", "Millisecond", ")", ",", "Severity", ":", "int", "(", "sev", ")", ",", "}", ")", "\n", "}" ]
// SendHostEvent send an event on the current host
[ "SendHostEvent", "send", "an", "event", "on", "the", "current", "host" ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/event.go#L60-L67
18,101
instana/go-sensor
tracer.go
NewTracerWithOptions
func NewTracerWithOptions(options *Options) ot.Tracer { InitSensor(options) return NewTracerWithEverything(options, NewRecorder()) }
go
func NewTracerWithOptions(options *Options) ot.Tracer { InitSensor(options) return NewTracerWithEverything(options, NewRecorder()) }
[ "func", "NewTracerWithOptions", "(", "options", "*", "Options", ")", "ot", ".", "Tracer", "{", "InitSensor", "(", "options", ")", "\n\n", "return", "NewTracerWithEverything", "(", "options", ",", "NewRecorder", "(", ")", ")", "\n", "}" ]
// NewTracerWithOptions Get a new Tracer with the specified options.
[ "NewTracerWithOptions", "Get", "a", "new", "Tracer", "with", "the", "specified", "options", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/tracer.go#L103-L107
18,102
instana/go-sensor
tracer.go
NewTracerWithEverything
func NewTracerWithEverything(options *Options, recorder SpanRecorder) ot.Tracer { InitSensor(options) ret := &tracerS{options: TracerOptions{ Recorder: recorder, ShouldSample: shouldSample, MaxLogsPerSpan: MaxLogsPerSpan}} ret.textPropagator = &textMapPropagator{ret} return ret }
go
func NewTracerWithEverything(options *Options, recorder SpanRecorder) ot.Tracer { InitSensor(options) ret := &tracerS{options: TracerOptions{ Recorder: recorder, ShouldSample: shouldSample, MaxLogsPerSpan: MaxLogsPerSpan}} ret.textPropagator = &textMapPropagator{ret} return ret }
[ "func", "NewTracerWithEverything", "(", "options", "*", "Options", ",", "recorder", "SpanRecorder", ")", "ot", ".", "Tracer", "{", "InitSensor", "(", "options", ")", "\n", "ret", ":=", "&", "tracerS", "{", "options", ":", "TracerOptions", "{", "Recorder", ":", "recorder", ",", "ShouldSample", ":", "shouldSample", ",", "MaxLogsPerSpan", ":", "MaxLogsPerSpan", "}", "}", "\n", "ret", ".", "textPropagator", "=", "&", "textMapPropagator", "{", "ret", "}", "\n\n", "return", "ret", "\n", "}" ]
// NewTracerWithEverything Get a new Tracer with the works.
[ "NewTracerWithEverything", "Get", "a", "new", "Tracer", "with", "the", "works", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/tracer.go#L110-L119
18,103
instana/go-sensor
recorder.go
RecordSpan
func (r *Recorder) RecordSpan(span *spanS) { // If we're not announced and not in test mode then just // return if !r.testMode && !sensor.agent.canSend() { return } var data = &jsonData{} kindTag := span.getSpanKindTag() data.SDK = &jsonSDKData{ Name: span.Operation, Type: kindTag, Custom: &jsonCustomData{Tags: span.Tags, Logs: span.collectLogs()}} baggage := make(map[string]string) span.context.ForeachBaggageItem(func(k string, v string) bool { baggage[k] = v return true }) if len(baggage) > 0 { data.SDK.Custom.Baggage = baggage } data.Service = sensor.serviceName var parentID *int64 if span.ParentSpanID == 0 { parentID = nil } else { parentID = &span.ParentSpanID } r.Lock() defer r.Unlock() if len(r.spans) == sensor.options.MaxBufferedSpans { r.spans = r.spans[1:] } r.spans = append(r.spans, jsonSpan{ TraceID: span.context.TraceID, ParentID: parentID, SpanID: span.context.SpanID, Timestamp: uint64(span.Start.UnixNano()) / uint64(time.Millisecond), Duration: uint64(span.Duration) / uint64(time.Millisecond), Name: "sdk", Error: span.Error, Ec: span.Ec, Lang: "go", From: sensor.agent.from, Kind: span.getSpanKindInt(), Data: data}) if r.testMode || !sensor.agent.canSend() { return } if len(r.spans) >= sensor.options.ForceTransmissionStartingAt { log.debug("Forcing spans to agent. Count:", len(r.spans)) go r.send() } }
go
func (r *Recorder) RecordSpan(span *spanS) { // If we're not announced and not in test mode then just // return if !r.testMode && !sensor.agent.canSend() { return } var data = &jsonData{} kindTag := span.getSpanKindTag() data.SDK = &jsonSDKData{ Name: span.Operation, Type: kindTag, Custom: &jsonCustomData{Tags: span.Tags, Logs: span.collectLogs()}} baggage := make(map[string]string) span.context.ForeachBaggageItem(func(k string, v string) bool { baggage[k] = v return true }) if len(baggage) > 0 { data.SDK.Custom.Baggage = baggage } data.Service = sensor.serviceName var parentID *int64 if span.ParentSpanID == 0 { parentID = nil } else { parentID = &span.ParentSpanID } r.Lock() defer r.Unlock() if len(r.spans) == sensor.options.MaxBufferedSpans { r.spans = r.spans[1:] } r.spans = append(r.spans, jsonSpan{ TraceID: span.context.TraceID, ParentID: parentID, SpanID: span.context.SpanID, Timestamp: uint64(span.Start.UnixNano()) / uint64(time.Millisecond), Duration: uint64(span.Duration) / uint64(time.Millisecond), Name: "sdk", Error: span.Error, Ec: span.Ec, Lang: "go", From: sensor.agent.from, Kind: span.getSpanKindInt(), Data: data}) if r.testMode || !sensor.agent.canSend() { return } if len(r.spans) >= sensor.options.ForceTransmissionStartingAt { log.debug("Forcing spans to agent. Count:", len(r.spans)) go r.send() } }
[ "func", "(", "r", "*", "Recorder", ")", "RecordSpan", "(", "span", "*", "spanS", ")", "{", "// If we're not announced and not in test mode then just", "// return", "if", "!", "r", ".", "testMode", "&&", "!", "sensor", ".", "agent", ".", "canSend", "(", ")", "{", "return", "\n", "}", "\n\n", "var", "data", "=", "&", "jsonData", "{", "}", "\n", "kindTag", ":=", "span", ".", "getSpanKindTag", "(", ")", "\n\n", "data", ".", "SDK", "=", "&", "jsonSDKData", "{", "Name", ":", "span", ".", "Operation", ",", "Type", ":", "kindTag", ",", "Custom", ":", "&", "jsonCustomData", "{", "Tags", ":", "span", ".", "Tags", ",", "Logs", ":", "span", ".", "collectLogs", "(", ")", "}", "}", "\n\n", "baggage", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "span", ".", "context", ".", "ForeachBaggageItem", "(", "func", "(", "k", "string", ",", "v", "string", ")", "bool", "{", "baggage", "[", "k", "]", "=", "v", "\n\n", "return", "true", "\n", "}", ")", "\n\n", "if", "len", "(", "baggage", ")", ">", "0", "{", "data", ".", "SDK", ".", "Custom", ".", "Baggage", "=", "baggage", "\n", "}", "\n\n", "data", ".", "Service", "=", "sensor", ".", "serviceName", "\n\n", "var", "parentID", "*", "int64", "\n", "if", "span", ".", "ParentSpanID", "==", "0", "{", "parentID", "=", "nil", "\n", "}", "else", "{", "parentID", "=", "&", "span", ".", "ParentSpanID", "\n", "}", "\n\n", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "r", ".", "spans", ")", "==", "sensor", ".", "options", ".", "MaxBufferedSpans", "{", "r", ".", "spans", "=", "r", ".", "spans", "[", "1", ":", "]", "\n", "}", "\n\n", "r", ".", "spans", "=", "append", "(", "r", ".", "spans", ",", "jsonSpan", "{", "TraceID", ":", "span", ".", "context", ".", "TraceID", ",", "ParentID", ":", "parentID", ",", "SpanID", ":", "span", ".", "context", ".", "SpanID", ",", "Timestamp", ":", "uint64", "(", "span", ".", "Start", ".", "UnixNano", "(", ")", ")", "/", "uint64", "(", "time", ".", "Millisecond", ")", ",", "Duration", ":", "uint64", "(", "span", ".", "Duration", ")", "/", "uint64", "(", "time", ".", "Millisecond", ")", ",", "Name", ":", "\"", "\"", ",", "Error", ":", "span", ".", "Error", ",", "Ec", ":", "span", ".", "Ec", ",", "Lang", ":", "\"", "\"", ",", "From", ":", "sensor", ".", "agent", ".", "from", ",", "Kind", ":", "span", ".", "getSpanKindInt", "(", ")", ",", "Data", ":", "data", "}", ")", "\n\n", "if", "r", ".", "testMode", "||", "!", "sensor", ".", "agent", ".", "canSend", "(", ")", "{", "return", "\n", "}", "\n\n", "if", "len", "(", "r", ".", "spans", ")", ">=", "sensor", ".", "options", ".", "ForceTransmissionStartingAt", "{", "log", ".", "debug", "(", "\"", "\"", ",", "len", "(", "r", ".", "spans", ")", ")", "\n", "go", "r", ".", "send", "(", ")", "\n", "}", "\n", "}" ]
// RecordSpan accepts spans to be recorded and and added to the span queue // for eventual reporting to the host agent.
[ "RecordSpan", "accepts", "spans", "to", "be", "recorded", "and", "and", "added", "to", "the", "span", "queue", "for", "eventual", "reporting", "to", "the", "host", "agent", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/recorder.go#L58-L122
18,104
instana/go-sensor
recorder.go
QueuedSpansCount
func (r *Recorder) QueuedSpansCount() int { r.RLock() defer r.RUnlock() return len(r.spans) }
go
func (r *Recorder) QueuedSpansCount() int { r.RLock() defer r.RUnlock() return len(r.spans) }
[ "func", "(", "r", "*", "Recorder", ")", "QueuedSpansCount", "(", ")", "int", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "return", "len", "(", "r", ".", "spans", ")", "\n", "}" ]
// QueuedSpansCount returns the number of queued spans // Used only in tests currently.
[ "QueuedSpansCount", "returns", "the", "number", "of", "queued", "spans", "Used", "only", "in", "tests", "currently", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/recorder.go#L126-L130
18,105
instana/go-sensor
recorder.go
GetQueuedSpans
func (r *Recorder) GetQueuedSpans() []jsonSpan { r.Lock() defer r.Unlock() // Copy queued spans queuedSpans := make([]jsonSpan, len(r.spans)) copy(queuedSpans, r.spans) // and clear out the source r.clearQueuedSpans() return queuedSpans }
go
func (r *Recorder) GetQueuedSpans() []jsonSpan { r.Lock() defer r.Unlock() // Copy queued spans queuedSpans := make([]jsonSpan, len(r.spans)) copy(queuedSpans, r.spans) // and clear out the source r.clearQueuedSpans() return queuedSpans }
[ "func", "(", "r", "*", "Recorder", ")", "GetQueuedSpans", "(", ")", "[", "]", "jsonSpan", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n\n", "// Copy queued spans", "queuedSpans", ":=", "make", "(", "[", "]", "jsonSpan", ",", "len", "(", "r", ".", "spans", ")", ")", "\n", "copy", "(", "queuedSpans", ",", "r", ".", "spans", ")", "\n\n", "// and clear out the source", "r", ".", "clearQueuedSpans", "(", ")", "\n", "return", "queuedSpans", "\n", "}" ]
// GetQueuedSpans returns a copy of the queued spans and clears the queue.
[ "GetQueuedSpans", "returns", "a", "copy", "of", "the", "queued", "spans", "and", "clears", "the", "queue", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/recorder.go#L133-L144
18,106
instana/go-sensor
recorder.go
send
func (r *Recorder) send() { spansToSend := r.GetQueuedSpans() if len(spansToSend) > 0 { go func() { _, err := sensor.agent.request(sensor.agent.makeURL(agentTracesURL), "POST", spansToSend) if err != nil { log.debug("Posting traces failed in send(): ", err) sensor.agent.reset() } }() } }
go
func (r *Recorder) send() { spansToSend := r.GetQueuedSpans() if len(spansToSend) > 0 { go func() { _, err := sensor.agent.request(sensor.agent.makeURL(agentTracesURL), "POST", spansToSend) if err != nil { log.debug("Posting traces failed in send(): ", err) sensor.agent.reset() } }() } }
[ "func", "(", "r", "*", "Recorder", ")", "send", "(", ")", "{", "spansToSend", ":=", "r", ".", "GetQueuedSpans", "(", ")", "\n", "if", "len", "(", "spansToSend", ")", ">", "0", "{", "go", "func", "(", ")", "{", "_", ",", "err", ":=", "sensor", ".", "agent", ".", "request", "(", "sensor", ".", "agent", ".", "makeURL", "(", "agentTracesURL", ")", ",", "\"", "\"", ",", "spansToSend", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "debug", "(", "\"", "\"", ",", "err", ")", "\n", "sensor", ".", "agent", ".", "reset", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "}" ]
// Retrieve the queued spans and post them to the host agent asynchronously.
[ "Retrieve", "the", "queued", "spans", "and", "post", "them", "to", "the", "host", "agent", "asynchronously", "." ]
9854c6e5d3e8c264693416ef9ee0646fa89cdc18
https://github.com/instana/go-sensor/blob/9854c6e5d3e8c264693416ef9ee0646fa89cdc18/recorder.go#L165-L176
18,107
mitchellh/go-vnc
client.go
CutText
func (c *ClientConn) CutText(text string) error { var buf bytes.Buffer // This is the fixed size data we'll send fixedData := []interface{}{ uint8(6), uint8(0), uint8(0), uint8(0), uint32(len(text)), } for _, val := range fixedData { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } for _, char := range text { if char > unicode.MaxLatin1 { return fmt.Errorf("Character '%s' is not valid Latin-1", char) } if err := binary.Write(&buf, binary.BigEndian, uint8(char)); err != nil { return err } } dataLength := 8 + len(text) if _, err := c.c.Write(buf.Bytes()[0:dataLength]); err != nil { return err } return nil }
go
func (c *ClientConn) CutText(text string) error { var buf bytes.Buffer // This is the fixed size data we'll send fixedData := []interface{}{ uint8(6), uint8(0), uint8(0), uint8(0), uint32(len(text)), } for _, val := range fixedData { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } for _, char := range text { if char > unicode.MaxLatin1 { return fmt.Errorf("Character '%s' is not valid Latin-1", char) } if err := binary.Write(&buf, binary.BigEndian, uint8(char)); err != nil { return err } } dataLength := 8 + len(text) if _, err := c.c.Write(buf.Bytes()[0:dataLength]); err != nil { return err } return nil }
[ "func", "(", "c", "*", "ClientConn", ")", "CutText", "(", "text", "string", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n\n", "// This is the fixed size data we'll send", "fixedData", ":=", "[", "]", "interface", "{", "}", "{", "uint8", "(", "6", ")", ",", "uint8", "(", "0", ")", ",", "uint8", "(", "0", ")", ",", "uint8", "(", "0", ")", ",", "uint32", "(", "len", "(", "text", ")", ")", ",", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "fixedData", "{", "if", "err", ":=", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "val", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "char", ":=", "range", "text", "{", "if", "char", ">", "unicode", ".", "MaxLatin1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "char", ")", "\n", "}", "\n\n", "if", "err", ":=", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "uint8", "(", "char", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "dataLength", ":=", "8", "+", "len", "(", "text", ")", "\n", "if", "_", ",", "err", ":=", "c", ".", "c", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", "[", "0", ":", "dataLength", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CutText tells the server that the client has new text in its cut buffer. // The text string MUST only contain Latin-1 characters. This encoding // is compatible with Go's native string format, but can only use up to // unicode.MaxLatin values. // // See RFC 6143 Section 7.5.6
[ "CutText", "tells", "the", "server", "that", "the", "client", "has", "new", "text", "in", "its", "cut", "buffer", ".", "The", "text", "string", "MUST", "only", "contain", "Latin", "-", "1", "characters", ".", "This", "encoding", "is", "compatible", "with", "Go", "s", "native", "string", "format", "but", "can", "only", "use", "up", "to", "unicode", ".", "MaxLatin", "values", ".", "See", "RFC", "6143", "Section", "7", ".", "5", ".", "6" ]
723ed9867aed0f3209a81151e52ddc61681f0b01
https://github.com/mitchellh/go-vnc/blob/723ed9867aed0f3209a81151e52ddc61681f0b01/client.go#L95-L129
18,108
mitchellh/go-vnc
client.go
FramebufferUpdateRequest
func (c *ClientConn) FramebufferUpdateRequest(incremental bool, x, y, width, height uint16) error { var buf bytes.Buffer var incrementalByte uint8 = 0 if incremental { incrementalByte = 1 } data := []interface{}{ uint8(3), incrementalByte, x, y, width, height, } for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } if _, err := c.c.Write(buf.Bytes()[0:10]); err != nil { return err } return nil }
go
func (c *ClientConn) FramebufferUpdateRequest(incremental bool, x, y, width, height uint16) error { var buf bytes.Buffer var incrementalByte uint8 = 0 if incremental { incrementalByte = 1 } data := []interface{}{ uint8(3), incrementalByte, x, y, width, height, } for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } if _, err := c.c.Write(buf.Bytes()[0:10]); err != nil { return err } return nil }
[ "func", "(", "c", "*", "ClientConn", ")", "FramebufferUpdateRequest", "(", "incremental", "bool", ",", "x", ",", "y", ",", "width", ",", "height", "uint16", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "var", "incrementalByte", "uint8", "=", "0", "\n\n", "if", "incremental", "{", "incrementalByte", "=", "1", "\n", "}", "\n\n", "data", ":=", "[", "]", "interface", "{", "}", "{", "uint8", "(", "3", ")", ",", "incrementalByte", ",", "x", ",", "y", ",", "width", ",", "height", ",", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "data", "{", "if", "err", ":=", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "val", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "c", ".", "c", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", "[", "0", ":", "10", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Requests a framebuffer update from the server. There may be an indefinite // time between the request and the actual framebuffer update being // received. // // See RFC 6143 Section 7.5.3
[ "Requests", "a", "framebuffer", "update", "from", "the", "server", ".", "There", "may", "be", "an", "indefinite", "time", "between", "the", "request", "and", "the", "actual", "framebuffer", "update", "being", "received", ".", "See", "RFC", "6143", "Section", "7", ".", "5", ".", "3" ]
723ed9867aed0f3209a81151e52ddc61681f0b01
https://github.com/mitchellh/go-vnc/blob/723ed9867aed0f3209a81151e52ddc61681f0b01/client.go#L136-L161
18,109
mitchellh/go-vnc
client.go
KeyEvent
func (c *ClientConn) KeyEvent(keysym uint32, down bool) error { var downFlag uint8 = 0 if down { downFlag = 1 } data := []interface{}{ uint8(4), downFlag, uint8(0), uint8(0), keysym, } for _, val := range data { if err := binary.Write(c.c, binary.BigEndian, val); err != nil { return err } } return nil }
go
func (c *ClientConn) KeyEvent(keysym uint32, down bool) error { var downFlag uint8 = 0 if down { downFlag = 1 } data := []interface{}{ uint8(4), downFlag, uint8(0), uint8(0), keysym, } for _, val := range data { if err := binary.Write(c.c, binary.BigEndian, val); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "ClientConn", ")", "KeyEvent", "(", "keysym", "uint32", ",", "down", "bool", ")", "error", "{", "var", "downFlag", "uint8", "=", "0", "\n", "if", "down", "{", "downFlag", "=", "1", "\n", "}", "\n\n", "data", ":=", "[", "]", "interface", "{", "}", "{", "uint8", "(", "4", ")", ",", "downFlag", ",", "uint8", "(", "0", ")", ",", "uint8", "(", "0", ")", ",", "keysym", ",", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "data", "{", "if", "err", ":=", "binary", ".", "Write", "(", "c", ".", "c", ",", "binary", ".", "BigEndian", ",", "val", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// KeyEvent indiciates a key press or release and sends it to the server. // The key is indicated using the X Window System "keysym" value. Use // Google to find a reference of these values. To simulate a key press, // you must send a key with both a down event, and a non-down event. // // See 7.5.4.
[ "KeyEvent", "indiciates", "a", "key", "press", "or", "release", "and", "sends", "it", "to", "the", "server", ".", "The", "key", "is", "indicated", "using", "the", "X", "Window", "System", "keysym", "value", ".", "Use", "Google", "to", "find", "a", "reference", "of", "these", "values", ".", "To", "simulate", "a", "key", "press", "you", "must", "send", "a", "key", "with", "both", "a", "down", "event", "and", "a", "non", "-", "down", "event", ".", "See", "7", ".", "5", ".", "4", "." ]
723ed9867aed0f3209a81151e52ddc61681f0b01
https://github.com/mitchellh/go-vnc/blob/723ed9867aed0f3209a81151e52ddc61681f0b01/client.go#L169-L190
18,110
mitchellh/go-vnc
client.go
PointerEvent
func (c *ClientConn) PointerEvent(mask ButtonMask, x, y uint16) error { var buf bytes.Buffer data := []interface{}{ uint8(5), uint8(mask), x, y, } for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } if _, err := c.c.Write(buf.Bytes()[0:6]); err != nil { return err } return nil }
go
func (c *ClientConn) PointerEvent(mask ButtonMask, x, y uint16) error { var buf bytes.Buffer data := []interface{}{ uint8(5), uint8(mask), x, y, } for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } if _, err := c.c.Write(buf.Bytes()[0:6]); err != nil { return err } return nil }
[ "func", "(", "c", "*", "ClientConn", ")", "PointerEvent", "(", "mask", "ButtonMask", ",", "x", ",", "y", "uint16", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n\n", "data", ":=", "[", "]", "interface", "{", "}", "{", "uint8", "(", "5", ")", ",", "uint8", "(", "mask", ")", ",", "x", ",", "y", ",", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "data", "{", "if", "err", ":=", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "val", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "c", ".", "c", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", "[", "0", ":", "6", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PointerEvent indicates that pointer movement or a pointer button // press or release. // // The mask is a bitwise mask of various ButtonMask values. When a button // is set, it is pressed, when it is unset, it is released. // // See RFC 6143 Section 7.5.5
[ "PointerEvent", "indicates", "that", "pointer", "movement", "or", "a", "pointer", "button", "press", "or", "release", ".", "The", "mask", "is", "a", "bitwise", "mask", "of", "various", "ButtonMask", "values", ".", "When", "a", "button", "is", "set", "it", "is", "pressed", "when", "it", "is", "unset", "it", "is", "released", ".", "See", "RFC", "6143", "Section", "7", ".", "5", ".", "5" ]
723ed9867aed0f3209a81151e52ddc61681f0b01
https://github.com/mitchellh/go-vnc/blob/723ed9867aed0f3209a81151e52ddc61681f0b01/client.go#L199-L220
18,111
mitchellh/go-vnc
client.go
SetEncodings
func (c *ClientConn) SetEncodings(encs []Encoding) error { data := make([]interface{}, 3+len(encs)) data[0] = uint8(2) data[1] = uint8(0) data[2] = uint16(len(encs)) for i, enc := range encs { data[3+i] = int32(enc.Type()) } var buf bytes.Buffer for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } dataLength := 4 + (4 * len(encs)) if _, err := c.c.Write(buf.Bytes()[0:dataLength]); err != nil { return err } c.Encs = encs return nil }
go
func (c *ClientConn) SetEncodings(encs []Encoding) error { data := make([]interface{}, 3+len(encs)) data[0] = uint8(2) data[1] = uint8(0) data[2] = uint16(len(encs)) for i, enc := range encs { data[3+i] = int32(enc.Type()) } var buf bytes.Buffer for _, val := range data { if err := binary.Write(&buf, binary.BigEndian, val); err != nil { return err } } dataLength := 4 + (4 * len(encs)) if _, err := c.c.Write(buf.Bytes()[0:dataLength]); err != nil { return err } c.Encs = encs return nil }
[ "func", "(", "c", "*", "ClientConn", ")", "SetEncodings", "(", "encs", "[", "]", "Encoding", ")", "error", "{", "data", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "3", "+", "len", "(", "encs", ")", ")", "\n", "data", "[", "0", "]", "=", "uint8", "(", "2", ")", "\n", "data", "[", "1", "]", "=", "uint8", "(", "0", ")", "\n", "data", "[", "2", "]", "=", "uint16", "(", "len", "(", "encs", ")", ")", "\n\n", "for", "i", ",", "enc", ":=", "range", "encs", "{", "data", "[", "3", "+", "i", "]", "=", "int32", "(", "enc", ".", "Type", "(", ")", ")", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "val", ":=", "range", "data", "{", "if", "err", ":=", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "val", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "dataLength", ":=", "4", "+", "(", "4", "*", "len", "(", "encs", ")", ")", "\n", "if", "_", ",", "err", ":=", "c", ".", "c", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", "[", "0", ":", "dataLength", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "Encs", "=", "encs", "\n\n", "return", "nil", "\n", "}" ]
// SetEncodings sets the encoding types in which the pixel data can // be sent from the server. After calling this method, the encs slice // given should not be modified. // // See RFC 6143 Section 7.5.2
[ "SetEncodings", "sets", "the", "encoding", "types", "in", "which", "the", "pixel", "data", "can", "be", "sent", "from", "the", "server", ".", "After", "calling", "this", "method", "the", "encs", "slice", "given", "should", "not", "be", "modified", ".", "See", "RFC", "6143", "Section", "7", ".", "5", ".", "2" ]
723ed9867aed0f3209a81151e52ddc61681f0b01
https://github.com/mitchellh/go-vnc/blob/723ed9867aed0f3209a81151e52ddc61681f0b01/client.go#L227-L252
18,112
mitchellh/go-vnc
client.go
SetPixelFormat
func (c *ClientConn) SetPixelFormat(format *PixelFormat) error { var keyEvent [20]byte keyEvent[0] = 0 pfBytes, err := writePixelFormat(format) if err != nil { return err } // Copy the pixel format bytes into the proper slice location copy(keyEvent[4:], pfBytes) // Send the data down the connection if _, err := c.c.Write(keyEvent[:]); err != nil { return err } // Reset the color map as according to RFC. var newColorMap [256]Color c.ColorMap = newColorMap return nil }
go
func (c *ClientConn) SetPixelFormat(format *PixelFormat) error { var keyEvent [20]byte keyEvent[0] = 0 pfBytes, err := writePixelFormat(format) if err != nil { return err } // Copy the pixel format bytes into the proper slice location copy(keyEvent[4:], pfBytes) // Send the data down the connection if _, err := c.c.Write(keyEvent[:]); err != nil { return err } // Reset the color map as according to RFC. var newColorMap [256]Color c.ColorMap = newColorMap return nil }
[ "func", "(", "c", "*", "ClientConn", ")", "SetPixelFormat", "(", "format", "*", "PixelFormat", ")", "error", "{", "var", "keyEvent", "[", "20", "]", "byte", "\n", "keyEvent", "[", "0", "]", "=", "0", "\n\n", "pfBytes", ",", "err", ":=", "writePixelFormat", "(", "format", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Copy the pixel format bytes into the proper slice location", "copy", "(", "keyEvent", "[", "4", ":", "]", ",", "pfBytes", ")", "\n\n", "// Send the data down the connection", "if", "_", ",", "err", ":=", "c", ".", "c", ".", "Write", "(", "keyEvent", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Reset the color map as according to RFC.", "var", "newColorMap", "[", "256", "]", "Color", "\n", "c", ".", "ColorMap", "=", "newColorMap", "\n\n", "return", "nil", "\n", "}" ]
// SetPixelFormat sets the format in which pixel values should be sent // in FramebufferUpdate messages from the server. // // See RFC 6143 Section 7.5.1
[ "SetPixelFormat", "sets", "the", "format", "in", "which", "pixel", "values", "should", "be", "sent", "in", "FramebufferUpdate", "messages", "from", "the", "server", ".", "See", "RFC", "6143", "Section", "7", ".", "5", ".", "1" ]
723ed9867aed0f3209a81151e52ddc61681f0b01
https://github.com/mitchellh/go-vnc/blob/723ed9867aed0f3209a81151e52ddc61681f0b01/client.go#L258-L280
18,113
mitchellh/go-vnc
client.go
mainLoop
func (c *ClientConn) mainLoop() { defer c.Close() // Build the map of available server messages typeMap := make(map[uint8]ServerMessage) defaultMessages := []ServerMessage{ new(FramebufferUpdateMessage), new(SetColorMapEntriesMessage), new(BellMessage), new(ServerCutTextMessage), } for _, msg := range defaultMessages { typeMap[msg.Type()] = msg } if c.config.ServerMessages != nil { for _, msg := range c.config.ServerMessages { typeMap[msg.Type()] = msg } } for { var messageType uint8 if err := binary.Read(c.c, binary.BigEndian, &messageType); err != nil { break } msg, ok := typeMap[messageType] if !ok { // Unsupported message type! Bad! break } parsedMsg, err := msg.Read(c, c.c) if err != nil { break } if c.config.ServerMessageCh == nil { continue } c.config.ServerMessageCh <- parsedMsg } }
go
func (c *ClientConn) mainLoop() { defer c.Close() // Build the map of available server messages typeMap := make(map[uint8]ServerMessage) defaultMessages := []ServerMessage{ new(FramebufferUpdateMessage), new(SetColorMapEntriesMessage), new(BellMessage), new(ServerCutTextMessage), } for _, msg := range defaultMessages { typeMap[msg.Type()] = msg } if c.config.ServerMessages != nil { for _, msg := range c.config.ServerMessages { typeMap[msg.Type()] = msg } } for { var messageType uint8 if err := binary.Read(c.c, binary.BigEndian, &messageType); err != nil { break } msg, ok := typeMap[messageType] if !ok { // Unsupported message type! Bad! break } parsedMsg, err := msg.Read(c, c.c) if err != nil { break } if c.config.ServerMessageCh == nil { continue } c.config.ServerMessageCh <- parsedMsg } }
[ "func", "(", "c", "*", "ClientConn", ")", "mainLoop", "(", ")", "{", "defer", "c", ".", "Close", "(", ")", "\n\n", "// Build the map of available server messages", "typeMap", ":=", "make", "(", "map", "[", "uint8", "]", "ServerMessage", ")", "\n\n", "defaultMessages", ":=", "[", "]", "ServerMessage", "{", "new", "(", "FramebufferUpdateMessage", ")", ",", "new", "(", "SetColorMapEntriesMessage", ")", ",", "new", "(", "BellMessage", ")", ",", "new", "(", "ServerCutTextMessage", ")", ",", "}", "\n\n", "for", "_", ",", "msg", ":=", "range", "defaultMessages", "{", "typeMap", "[", "msg", ".", "Type", "(", ")", "]", "=", "msg", "\n", "}", "\n\n", "if", "c", ".", "config", ".", "ServerMessages", "!=", "nil", "{", "for", "_", ",", "msg", ":=", "range", "c", ".", "config", ".", "ServerMessages", "{", "typeMap", "[", "msg", ".", "Type", "(", ")", "]", "=", "msg", "\n", "}", "\n", "}", "\n\n", "for", "{", "var", "messageType", "uint8", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "c", ".", "c", ",", "binary", ".", "BigEndian", ",", "&", "messageType", ")", ";", "err", "!=", "nil", "{", "break", "\n", "}", "\n\n", "msg", ",", "ok", ":=", "typeMap", "[", "messageType", "]", "\n", "if", "!", "ok", "{", "// Unsupported message type! Bad!", "break", "\n", "}", "\n\n", "parsedMsg", ",", "err", ":=", "msg", ".", "Read", "(", "c", ",", "c", ".", "c", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n\n", "if", "c", ".", "config", ".", "ServerMessageCh", "==", "nil", "{", "continue", "\n", "}", "\n\n", "c", ".", "config", ".", "ServerMessageCh", "<-", "parsedMsg", "\n", "}", "\n", "}" ]
// mainLoop reads messages sent from the server and routes them to the // proper channels for users of the client to read.
[ "mainLoop", "reads", "messages", "sent", "from", "the", "server", "and", "routes", "them", "to", "the", "proper", "channels", "for", "users", "of", "the", "client", "to", "read", "." ]
723ed9867aed0f3209a81151e52ddc61681f0b01
https://github.com/mitchellh/go-vnc/blob/723ed9867aed0f3209a81151e52ddc61681f0b01/client.go#L422-L468
18,114
RackSec/srslog
dialer.go
unixDialer
func (w *Writer) unixDialer() (serverConn, string, error) { sc, err := unixSyslog() hostname := w.hostname if hostname == "" { hostname = "localhost" } return sc, hostname, err }
go
func (w *Writer) unixDialer() (serverConn, string, error) { sc, err := unixSyslog() hostname := w.hostname if hostname == "" { hostname = "localhost" } return sc, hostname, err }
[ "func", "(", "w", "*", "Writer", ")", "unixDialer", "(", ")", "(", "serverConn", ",", "string", ",", "error", ")", "{", "sc", ",", "err", ":=", "unixSyslog", "(", ")", "\n", "hostname", ":=", "w", ".", "hostname", "\n", "if", "hostname", "==", "\"", "\"", "{", "hostname", "=", "\"", "\"", "\n", "}", "\n", "return", "sc", ",", "hostname", ",", "err", "\n", "}" ]
// unixDialer uses the unixSyslog method to open a connection to the syslog // daemon running on the local machine.
[ "unixDialer", "uses", "the", "unixSyslog", "method", "to", "open", "a", "connection", "to", "the", "syslog", "daemon", "running", "on", "the", "local", "machine", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/dialer.go#L51-L58
18,115
RackSec/srslog
dialer.go
tlsDialer
func (w *Writer) tlsDialer() (serverConn, string, error) { c, err := tls.Dial("tcp", w.raddr, w.tlsConfig) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
go
func (w *Writer) tlsDialer() (serverConn, string, error) { c, err := tls.Dial("tcp", w.raddr, w.tlsConfig) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
[ "func", "(", "w", "*", "Writer", ")", "tlsDialer", "(", ")", "(", "serverConn", ",", "string", ",", "error", ")", "{", "c", ",", "err", ":=", "tls", ".", "Dial", "(", "\"", "\"", ",", "w", ".", "raddr", ",", "w", ".", "tlsConfig", ")", "\n", "var", "sc", "serverConn", "\n", "hostname", ":=", "w", ".", "hostname", "\n", "if", "err", "==", "nil", "{", "sc", "=", "&", "netConn", "{", "conn", ":", "c", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "hostname", "=", "c", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "return", "sc", ",", "hostname", ",", "err", "\n", "}" ]
// tlsDialer connects to TLS over TCP, and is used for the "tcp+tls" network // type.
[ "tlsDialer", "connects", "to", "TLS", "over", "TCP", "and", "is", "used", "for", "the", "tcp", "+", "tls", "network", "type", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/dialer.go#L62-L73
18,116
RackSec/srslog
dialer.go
basicDialer
func (w *Writer) basicDialer() (serverConn, string, error) { c, err := net.Dial(w.network, w.raddr) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
go
func (w *Writer) basicDialer() (serverConn, string, error) { c, err := net.Dial(w.network, w.raddr) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
[ "func", "(", "w", "*", "Writer", ")", "basicDialer", "(", ")", "(", "serverConn", ",", "string", ",", "error", ")", "{", "c", ",", "err", ":=", "net", ".", "Dial", "(", "w", ".", "network", ",", "w", ".", "raddr", ")", "\n", "var", "sc", "serverConn", "\n", "hostname", ":=", "w", ".", "hostname", "\n", "if", "err", "==", "nil", "{", "sc", "=", "&", "netConn", "{", "conn", ":", "c", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "hostname", "=", "c", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "return", "sc", ",", "hostname", ",", "err", "\n", "}" ]
// basicDialer is the most common dialer for syslog, and supports both TCP and // UDP connections.
[ "basicDialer", "is", "the", "most", "common", "dialer", "for", "syslog", "and", "supports", "both", "TCP", "and", "UDP", "connections", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/dialer.go#L77-L88
18,117
RackSec/srslog
dialer.go
customDialer
func (w *Writer) customDialer() (serverConn, string, error) { c, err := w.customDial(w.network, w.raddr) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
go
func (w *Writer) customDialer() (serverConn, string, error) { c, err := w.customDial(w.network, w.raddr) var sc serverConn hostname := w.hostname if err == nil { sc = &netConn{conn: c} if hostname == "" { hostname = c.LocalAddr().String() } } return sc, hostname, err }
[ "func", "(", "w", "*", "Writer", ")", "customDialer", "(", ")", "(", "serverConn", ",", "string", ",", "error", ")", "{", "c", ",", "err", ":=", "w", ".", "customDial", "(", "w", ".", "network", ",", "w", ".", "raddr", ")", "\n", "var", "sc", "serverConn", "\n", "hostname", ":=", "w", ".", "hostname", "\n", "if", "err", "==", "nil", "{", "sc", "=", "&", "netConn", "{", "conn", ":", "c", "}", "\n", "if", "hostname", "==", "\"", "\"", "{", "hostname", "=", "c", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "return", "sc", ",", "hostname", ",", "err", "\n", "}" ]
// customDialer uses the custom dialer when the Writer was created // giving developers total control over how connections are made and returned. // Note it does not check if cdialer is nil, as it should only be referenced from getDialer.
[ "customDialer", "uses", "the", "custom", "dialer", "when", "the", "Writer", "was", "created", "giving", "developers", "total", "control", "over", "how", "connections", "are", "made", "and", "returned", ".", "Note", "it", "does", "not", "check", "if", "cdialer", "is", "nil", "as", "it", "should", "only", "be", "referenced", "from", "getDialer", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/dialer.go#L93-L104
18,118
RackSec/srslog
writer.go
getConn
func (w *Writer) getConn() serverConn { w.mu.RLock() conn := w.conn w.mu.RUnlock() return conn }
go
func (w *Writer) getConn() serverConn { w.mu.RLock() conn := w.conn w.mu.RUnlock() return conn }
[ "func", "(", "w", "*", "Writer", ")", "getConn", "(", ")", "serverConn", "{", "w", ".", "mu", ".", "RLock", "(", ")", "\n", "conn", ":=", "w", ".", "conn", "\n", "w", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "conn", "\n", "}" ]
// getConn provides access to the internal conn, protected by a mutex. The // conn is threadsafe, so it can be used while unlocked, but we want to avoid // race conditions on grabbing a reference to it.
[ "getConn", "provides", "access", "to", "the", "internal", "conn", "protected", "by", "a", "mutex", ".", "The", "conn", "is", "threadsafe", "so", "it", "can", "be", "used", "while", "unlocked", "but", "we", "want", "to", "avoid", "race", "conditions", "on", "grabbing", "a", "reference", "to", "it", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/writer.go#L30-L35
18,119
RackSec/srslog
writer.go
setConn
func (w *Writer) setConn(c serverConn) { w.mu.Lock() w.conn = c w.mu.Unlock() }
go
func (w *Writer) setConn(c serverConn) { w.mu.Lock() w.conn = c w.mu.Unlock() }
[ "func", "(", "w", "*", "Writer", ")", "setConn", "(", "c", "serverConn", ")", "{", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "w", ".", "conn", "=", "c", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// setConn updates the internal conn, protected by a mutex.
[ "setConn", "updates", "the", "internal", "conn", "protected", "by", "a", "mutex", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/writer.go#L38-L42
18,120
RackSec/srslog
writer.go
connect
func (w *Writer) connect() (serverConn, error) { conn := w.getConn() if conn != nil { // ignore err from close, it makes sense to continue anyway conn.close() w.setConn(nil) } var hostname string var err error dialer := w.getDialer() conn, hostname, err = dialer.Call() if err == nil { w.setConn(conn) w.hostname = hostname return conn, nil } else { return nil, err } }
go
func (w *Writer) connect() (serverConn, error) { conn := w.getConn() if conn != nil { // ignore err from close, it makes sense to continue anyway conn.close() w.setConn(nil) } var hostname string var err error dialer := w.getDialer() conn, hostname, err = dialer.Call() if err == nil { w.setConn(conn) w.hostname = hostname return conn, nil } else { return nil, err } }
[ "func", "(", "w", "*", "Writer", ")", "connect", "(", ")", "(", "serverConn", ",", "error", ")", "{", "conn", ":=", "w", ".", "getConn", "(", ")", "\n", "if", "conn", "!=", "nil", "{", "// ignore err from close, it makes sense to continue anyway", "conn", ".", "close", "(", ")", "\n", "w", ".", "setConn", "(", "nil", ")", "\n", "}", "\n\n", "var", "hostname", "string", "\n", "var", "err", "error", "\n", "dialer", ":=", "w", ".", "getDialer", "(", ")", "\n", "conn", ",", "hostname", ",", "err", "=", "dialer", ".", "Call", "(", ")", "\n", "if", "err", "==", "nil", "{", "w", ".", "setConn", "(", "conn", ")", "\n", "w", ".", "hostname", "=", "hostname", "\n\n", "return", "conn", ",", "nil", "\n", "}", "else", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// connect makes a connection to the syslog server.
[ "connect", "makes", "a", "connection", "to", "the", "syslog", "server", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/writer.go#L45-L65
18,121
RackSec/srslog
writer.go
WriteWithPriority
func (w *Writer) WriteWithPriority(p Priority, b []byte) (int, error) { return w.writeAndRetryWithPriority(p, string(b)) }
go
func (w *Writer) WriteWithPriority(p Priority, b []byte) (int, error) { return w.writeAndRetryWithPriority(p, string(b)) }
[ "func", "(", "w", "*", "Writer", ")", "WriteWithPriority", "(", "p", "Priority", ",", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "w", ".", "writeAndRetryWithPriority", "(", "p", ",", "string", "(", "b", ")", ")", "\n", "}" ]
// WriteWithPriority sends a log message with a custom priority.
[ "WriteWithPriority", "sends", "a", "log", "message", "with", "a", "custom", "priority", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/writer.go#L89-L91
18,122
RackSec/srslog
writer.go
writeAndRetry
func (w *Writer) writeAndRetry(severity Priority, s string) (int, error) { pr := (w.priority & facilityMask) | (severity & severityMask) return w.writeAndRetryWithPriority(pr, s) }
go
func (w *Writer) writeAndRetry(severity Priority, s string) (int, error) { pr := (w.priority & facilityMask) | (severity & severityMask) return w.writeAndRetryWithPriority(pr, s) }
[ "func", "(", "w", "*", "Writer", ")", "writeAndRetry", "(", "severity", "Priority", ",", "s", "string", ")", "(", "int", ",", "error", ")", "{", "pr", ":=", "(", "w", ".", "priority", "&", "facilityMask", ")", "|", "(", "severity", "&", "severityMask", ")", "\n\n", "return", "w", ".", "writeAndRetryWithPriority", "(", "pr", ",", "s", ")", "\n", "}" ]
// writeAndRetry takes a severity and the string to write. Any facility passed to // it as part of the severity Priority will be ignored.
[ "writeAndRetry", "takes", "a", "severity", "and", "the", "string", "to", "write", ".", "Any", "facility", "passed", "to", "it", "as", "part", "of", "the", "severity", "Priority", "will", "be", "ignored", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/writer.go#L162-L166
18,123
RackSec/srslog
writer.go
writeAndRetryWithPriority
func (w *Writer) writeAndRetryWithPriority(p Priority, s string) (int, error) { conn := w.getConn() if conn != nil { if n, err := w.write(conn, p, s); err == nil { return n, err } } var err error if conn, err = w.connect(); err != nil { return 0, err } return w.write(conn, p, s) }
go
func (w *Writer) writeAndRetryWithPriority(p Priority, s string) (int, error) { conn := w.getConn() if conn != nil { if n, err := w.write(conn, p, s); err == nil { return n, err } } var err error if conn, err = w.connect(); err != nil { return 0, err } return w.write(conn, p, s) }
[ "func", "(", "w", "*", "Writer", ")", "writeAndRetryWithPriority", "(", "p", "Priority", ",", "s", "string", ")", "(", "int", ",", "error", ")", "{", "conn", ":=", "w", ".", "getConn", "(", ")", "\n", "if", "conn", "!=", "nil", "{", "if", "n", ",", "err", ":=", "w", ".", "write", "(", "conn", ",", "p", ",", "s", ")", ";", "err", "==", "nil", "{", "return", "n", ",", "err", "\n", "}", "\n", "}", "\n\n", "var", "err", "error", "\n", "if", "conn", ",", "err", "=", "w", ".", "connect", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "w", ".", "write", "(", "conn", ",", "p", ",", "s", ")", "\n", "}" ]
// writeAndRetryWithPriority differs from writeAndRetry in that it allows setting // of both the facility and the severity.
[ "writeAndRetryWithPriority", "differs", "from", "writeAndRetry", "in", "that", "it", "allows", "setting", "of", "both", "the", "facility", "and", "the", "severity", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/writer.go#L170-L183
18,124
RackSec/srslog
writer.go
write
func (w *Writer) write(conn serverConn, p Priority, msg string) (int, error) { // ensure it ends in a \n if !strings.HasSuffix(msg, "\n") { msg += "\n" } err := conn.writeString(w.framer, w.formatter, p, w.hostname, w.tag, msg) if err != nil { return 0, err } // Note: return the length of the input, not the number of // bytes printed by Fprintf, because this must behave like // an io.Writer. return len(msg), nil }
go
func (w *Writer) write(conn serverConn, p Priority, msg string) (int, error) { // ensure it ends in a \n if !strings.HasSuffix(msg, "\n") { msg += "\n" } err := conn.writeString(w.framer, w.formatter, p, w.hostname, w.tag, msg) if err != nil { return 0, err } // Note: return the length of the input, not the number of // bytes printed by Fprintf, because this must behave like // an io.Writer. return len(msg), nil }
[ "func", "(", "w", "*", "Writer", ")", "write", "(", "conn", "serverConn", ",", "p", "Priority", ",", "msg", "string", ")", "(", "int", ",", "error", ")", "{", "// ensure it ends in a \\n", "if", "!", "strings", ".", "HasSuffix", "(", "msg", ",", "\"", "\\n", "\"", ")", "{", "msg", "+=", "\"", "\\n", "\"", "\n", "}", "\n\n", "err", ":=", "conn", ".", "writeString", "(", "w", ".", "framer", ",", "w", ".", "formatter", ",", "p", ",", "w", ".", "hostname", ",", "w", ".", "tag", ",", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "// Note: return the length of the input, not the number of", "// bytes printed by Fprintf, because this must behave like", "// an io.Writer.", "return", "len", "(", "msg", ")", ",", "nil", "\n", "}" ]
// write generates and writes a syslog formatted string. It formats the // message based on the current Formatter and Framer.
[ "write", "generates", "and", "writes", "a", "syslog", "formatted", "string", ".", "It", "formats", "the", "message", "based", "on", "the", "current", "Formatter", "and", "Framer", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/writer.go#L187-L201
18,125
RackSec/srslog
net_conn.go
writeString
func (n *netConn) writeString(framer Framer, formatter Formatter, p Priority, hostname, tag, msg string) error { if framer == nil { framer = DefaultFramer } if formatter == nil { formatter = DefaultFormatter } formattedMessage := framer(formatter(p, hostname, tag, msg)) _, err := n.conn.Write([]byte(formattedMessage)) return err }
go
func (n *netConn) writeString(framer Framer, formatter Formatter, p Priority, hostname, tag, msg string) error { if framer == nil { framer = DefaultFramer } if formatter == nil { formatter = DefaultFormatter } formattedMessage := framer(formatter(p, hostname, tag, msg)) _, err := n.conn.Write([]byte(formattedMessage)) return err }
[ "func", "(", "n", "*", "netConn", ")", "writeString", "(", "framer", "Framer", ",", "formatter", "Formatter", ",", "p", "Priority", ",", "hostname", ",", "tag", ",", "msg", "string", ")", "error", "{", "if", "framer", "==", "nil", "{", "framer", "=", "DefaultFramer", "\n", "}", "\n", "if", "formatter", "==", "nil", "{", "formatter", "=", "DefaultFormatter", "\n", "}", "\n", "formattedMessage", ":=", "framer", "(", "formatter", "(", "p", ",", "hostname", ",", "tag", ",", "msg", ")", ")", "\n", "_", ",", "err", ":=", "n", ".", "conn", ".", "Write", "(", "[", "]", "byte", "(", "formattedMessage", ")", ")", "\n", "return", "err", "\n", "}" ]
// writeString formats syslog messages using time.RFC3339 and includes the // hostname, and sends the message to the connection.
[ "writeString", "formats", "syslog", "messages", "using", "time", ".", "RFC3339", "and", "includes", "the", "hostname", "and", "sends", "the", "message", "to", "the", "connection", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/net_conn.go#L15-L25
18,126
RackSec/srslog
formatter.go
UnixFormatter
func UnixFormatter(p Priority, hostname, tag, content string) string { timestamp := time.Now().Format(time.Stamp) msg := fmt.Sprintf("<%d>%s %s[%d]: %s", p, timestamp, tag, os.Getpid(), content) return msg }
go
func UnixFormatter(p Priority, hostname, tag, content string) string { timestamp := time.Now().Format(time.Stamp) msg := fmt.Sprintf("<%d>%s %s[%d]: %s", p, timestamp, tag, os.Getpid(), content) return msg }
[ "func", "UnixFormatter", "(", "p", "Priority", ",", "hostname", ",", "tag", ",", "content", "string", ")", "string", "{", "timestamp", ":=", "time", ".", "Now", "(", ")", ".", "Format", "(", "time", ".", "Stamp", ")", "\n", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ",", "timestamp", ",", "tag", ",", "os", ".", "Getpid", "(", ")", ",", "content", ")", "\n", "return", "msg", "\n", "}" ]
// UnixFormatter omits the hostname, because it is only used locally.
[ "UnixFormatter", "omits", "the", "hostname", "because", "it", "is", "only", "used", "locally", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/formatter.go#L27-L32
18,127
RackSec/srslog
formatter.go
truncateStartStr
func truncateStartStr(s string, max int) string { if (len(s) > max) { return s[len(s) - max:] } return s }
go
func truncateStartStr(s string, max int) string { if (len(s) > max) { return s[len(s) - max:] } return s }
[ "func", "truncateStartStr", "(", "s", "string", ",", "max", "int", ")", "string", "{", "if", "(", "len", "(", "s", ")", ">", "max", ")", "{", "return", "s", "[", "len", "(", "s", ")", "-", "max", ":", "]", "\n", "}", "\n", "return", "s", "\n", "}" ]
// if string's length is greater than max, then use the last part
[ "if", "string", "s", "length", "is", "greater", "than", "max", "then", "use", "the", "last", "part" ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/formatter.go#L43-L48
18,128
RackSec/srslog
formatter.go
RFC5424Formatter
func RFC5424Formatter(p Priority, hostname, tag, content string) string { timestamp := time.Now().Format(time.RFC3339) pid := os.Getpid() appName := truncateStartStr(os.Args[0], appNameMaxLength) msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s", p, 1, timestamp, hostname, appName, pid, tag, content) return msg }
go
func RFC5424Formatter(p Priority, hostname, tag, content string) string { timestamp := time.Now().Format(time.RFC3339) pid := os.Getpid() appName := truncateStartStr(os.Args[0], appNameMaxLength) msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s", p, 1, timestamp, hostname, appName, pid, tag, content) return msg }
[ "func", "RFC5424Formatter", "(", "p", "Priority", ",", "hostname", ",", "tag", ",", "content", "string", ")", "string", "{", "timestamp", ":=", "time", ".", "Now", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", "\n", "pid", ":=", "os", ".", "Getpid", "(", ")", "\n", "appName", ":=", "truncateStartStr", "(", "os", ".", "Args", "[", "0", "]", ",", "appNameMaxLength", ")", "\n", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ",", "1", ",", "timestamp", ",", "hostname", ",", "appName", ",", "pid", ",", "tag", ",", "content", ")", "\n", "return", "msg", "\n", "}" ]
// RFC5424Formatter provides an RFC 5424 compliant message.
[ "RFC5424Formatter", "provides", "an", "RFC", "5424", "compliant", "message", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/formatter.go#L51-L58
18,129
RackSec/srslog
srslog.go
Dial
func Dial(network, raddr string, priority Priority, tag string) (*Writer, error) { return DialWithTLSConfig(network, raddr, priority, tag, nil) }
go
func Dial(network, raddr string, priority Priority, tag string) (*Writer, error) { return DialWithTLSConfig(network, raddr, priority, tag, nil) }
[ "func", "Dial", "(", "network", ",", "raddr", "string", ",", "priority", "Priority", ",", "tag", "string", ")", "(", "*", "Writer", ",", "error", ")", "{", "return", "DialWithTLSConfig", "(", "network", ",", "raddr", ",", "priority", ",", "tag", ",", "nil", ")", "\n", "}" ]
// Dial establishes a connection to a log daemon by connecting to // address raddr on the specified network. Each write to the returned // Writer sends a log message with the given facility, severity and // tag. // If network is empty, Dial will connect to the local syslog server.
[ "Dial", "establishes", "a", "connection", "to", "a", "log", "daemon", "by", "connecting", "to", "address", "raddr", "on", "the", "specified", "network", ".", "Each", "write", "to", "the", "returned", "Writer", "sends", "a", "log", "message", "with", "the", "given", "facility", "severity", "and", "tag", ".", "If", "network", "is", "empty", "Dial", "will", "connect", "to", "the", "local", "syslog", "server", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog.go#L36-L38
18,130
RackSec/srslog
srslog.go
DialWithCustomDialer
func DialWithCustomDialer(network, raddr string, priority Priority, tag string, customDial DialFunc) (*Writer, error) { if customDial == nil { return nil, ErrNilDialFunc } return dialAllParameters(network, raddr, priority, tag, nil, customDial) }
go
func DialWithCustomDialer(network, raddr string, priority Priority, tag string, customDial DialFunc) (*Writer, error) { if customDial == nil { return nil, ErrNilDialFunc } return dialAllParameters(network, raddr, priority, tag, nil, customDial) }
[ "func", "DialWithCustomDialer", "(", "network", ",", "raddr", "string", ",", "priority", "Priority", ",", "tag", "string", ",", "customDial", "DialFunc", ")", "(", "*", "Writer", ",", "error", ")", "{", "if", "customDial", "==", "nil", "{", "return", "nil", ",", "ErrNilDialFunc", "\n", "}", "\n", "return", "dialAllParameters", "(", "network", ",", "raddr", ",", "priority", ",", "tag", ",", "nil", ",", "customDial", ")", "\n", "}" ]
// DialWithCustomDialer establishes a connection by calling customDial. // Each write to the returned Writer sends a log message with the given facility, severity and tag. // Network must be "custom" in order for this package to use customDial. // While network and raddr will be passed to customDial, it is allowed for customDial to ignore them. // If customDial is nil, this function returns ErrNilDialFunc.
[ "DialWithCustomDialer", "establishes", "a", "connection", "by", "calling", "customDial", ".", "Each", "write", "to", "the", "returned", "Writer", "sends", "a", "log", "message", "with", "the", "given", "facility", "severity", "and", "tag", ".", "Network", "must", "be", "custom", "in", "order", "for", "this", "package", "to", "use", "customDial", ".", "While", "network", "and", "raddr", "will", "be", "passed", "to", "customDial", "it", "is", "allowed", "for", "customDial", "to", "ignore", "them", ".", "If", "customDial", "is", "nil", "this", "function", "returns", "ErrNilDialFunc", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog.go#L49-L54
18,131
RackSec/srslog
srslog.go
DialWithTLSCertPath
func DialWithTLSCertPath(network, raddr string, priority Priority, tag, certPath string) (*Writer, error) { serverCert, err := ioutil.ReadFile(certPath) if err != nil { return nil, err } return DialWithTLSCert(network, raddr, priority, tag, serverCert) }
go
func DialWithTLSCertPath(network, raddr string, priority Priority, tag, certPath string) (*Writer, error) { serverCert, err := ioutil.ReadFile(certPath) if err != nil { return nil, err } return DialWithTLSCert(network, raddr, priority, tag, serverCert) }
[ "func", "DialWithTLSCertPath", "(", "network", ",", "raddr", "string", ",", "priority", "Priority", ",", "tag", ",", "certPath", "string", ")", "(", "*", "Writer", ",", "error", ")", "{", "serverCert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "certPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "DialWithTLSCert", "(", "network", ",", "raddr", ",", "priority", ",", "tag", ",", "serverCert", ")", "\n", "}" ]
// DialWithTLSCertPath establishes a secure connection to a log daemon by connecting to // address raddr on the specified network. It uses certPath to load TLS certificates and configure // the secure connection.
[ "DialWithTLSCertPath", "establishes", "a", "secure", "connection", "to", "a", "log", "daemon", "by", "connecting", "to", "address", "raddr", "on", "the", "specified", "network", ".", "It", "uses", "certPath", "to", "load", "TLS", "certificates", "and", "configure", "the", "secure", "connection", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog.go#L59-L66
18,132
RackSec/srslog
srslog.go
DialWithTLSCert
func DialWithTLSCert(network, raddr string, priority Priority, tag string, serverCert []byte) (*Writer, error) { pool := x509.NewCertPool() pool.AppendCertsFromPEM(serverCert) config := tls.Config{ RootCAs: pool, } return DialWithTLSConfig(network, raddr, priority, tag, &config) }
go
func DialWithTLSCert(network, raddr string, priority Priority, tag string, serverCert []byte) (*Writer, error) { pool := x509.NewCertPool() pool.AppendCertsFromPEM(serverCert) config := tls.Config{ RootCAs: pool, } return DialWithTLSConfig(network, raddr, priority, tag, &config) }
[ "func", "DialWithTLSCert", "(", "network", ",", "raddr", "string", ",", "priority", "Priority", ",", "tag", "string", ",", "serverCert", "[", "]", "byte", ")", "(", "*", "Writer", ",", "error", ")", "{", "pool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "pool", ".", "AppendCertsFromPEM", "(", "serverCert", ")", "\n", "config", ":=", "tls", ".", "Config", "{", "RootCAs", ":", "pool", ",", "}", "\n\n", "return", "DialWithTLSConfig", "(", "network", ",", "raddr", ",", "priority", ",", "tag", ",", "&", "config", ")", "\n", "}" ]
// DialWIthTLSCert establishes a secure connection to a log daemon by connecting to // address raddr on the specified network. It uses serverCert to load a TLS certificate // and configure the secure connection.
[ "DialWIthTLSCert", "establishes", "a", "secure", "connection", "to", "a", "log", "daemon", "by", "connecting", "to", "address", "raddr", "on", "the", "specified", "network", ".", "It", "uses", "serverCert", "to", "load", "a", "TLS", "certificate", "and", "configure", "the", "secure", "connection", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog.go#L71-L79
18,133
RackSec/srslog
srslog.go
DialWithTLSConfig
func DialWithTLSConfig(network, raddr string, priority Priority, tag string, tlsConfig *tls.Config) (*Writer, error) { return dialAllParameters(network, raddr, priority, tag, tlsConfig, nil) }
go
func DialWithTLSConfig(network, raddr string, priority Priority, tag string, tlsConfig *tls.Config) (*Writer, error) { return dialAllParameters(network, raddr, priority, tag, tlsConfig, nil) }
[ "func", "DialWithTLSConfig", "(", "network", ",", "raddr", "string", ",", "priority", "Priority", ",", "tag", "string", ",", "tlsConfig", "*", "tls", ".", "Config", ")", "(", "*", "Writer", ",", "error", ")", "{", "return", "dialAllParameters", "(", "network", ",", "raddr", ",", "priority", ",", "tag", ",", "tlsConfig", ",", "nil", ")", "\n", "}" ]
// DialWithTLSConfig establishes a secure connection to a log daemon by connecting to // address raddr on the specified network. It uses tlsConfig to configure the secure connection.
[ "DialWithTLSConfig", "establishes", "a", "secure", "connection", "to", "a", "log", "daemon", "by", "connecting", "to", "address", "raddr", "on", "the", "specified", "network", ".", "It", "uses", "tlsConfig", "to", "configure", "the", "secure", "connection", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog.go#L83-L85
18,134
RackSec/srslog
srslog.go
dialAllParameters
func dialAllParameters(network, raddr string, priority Priority, tag string, tlsConfig *tls.Config, customDial DialFunc) (*Writer, error) { if err := validatePriority(priority); err != nil { return nil, err } if tag == "" { tag = os.Args[0] } hostname, _ := os.Hostname() w := &Writer{ priority: priority, tag: tag, hostname: hostname, network: network, raddr: raddr, tlsConfig: tlsConfig, customDial: customDial, } _, err := w.connect() if err != nil { return nil, err } return w, err }
go
func dialAllParameters(network, raddr string, priority Priority, tag string, tlsConfig *tls.Config, customDial DialFunc) (*Writer, error) { if err := validatePriority(priority); err != nil { return nil, err } if tag == "" { tag = os.Args[0] } hostname, _ := os.Hostname() w := &Writer{ priority: priority, tag: tag, hostname: hostname, network: network, raddr: raddr, tlsConfig: tlsConfig, customDial: customDial, } _, err := w.connect() if err != nil { return nil, err } return w, err }
[ "func", "dialAllParameters", "(", "network", ",", "raddr", "string", ",", "priority", "Priority", ",", "tag", "string", ",", "tlsConfig", "*", "tls", ".", "Config", ",", "customDial", "DialFunc", ")", "(", "*", "Writer", ",", "error", ")", "{", "if", "err", ":=", "validatePriority", "(", "priority", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "tag", "==", "\"", "\"", "{", "tag", "=", "os", ".", "Args", "[", "0", "]", "\n", "}", "\n", "hostname", ",", "_", ":=", "os", ".", "Hostname", "(", ")", "\n\n", "w", ":=", "&", "Writer", "{", "priority", ":", "priority", ",", "tag", ":", "tag", ",", "hostname", ":", "hostname", ",", "network", ":", "network", ",", "raddr", ":", "raddr", ",", "tlsConfig", ":", "tlsConfig", ",", "customDial", ":", "customDial", ",", "}", "\n\n", "_", ",", "err", ":=", "w", ".", "connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "w", ",", "err", "\n", "}" ]
// implementation of the various functions above
[ "implementation", "of", "the", "various", "functions", "above" ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog.go#L88-L113
18,135
RackSec/srslog
srslog.go
NewLogger
func NewLogger(p Priority, logFlag int) (*log.Logger, error) { s, err := New(p, "") if err != nil { return nil, err } return log.New(s, "", logFlag), nil }
go
func NewLogger(p Priority, logFlag int) (*log.Logger, error) { s, err := New(p, "") if err != nil { return nil, err } return log.New(s, "", logFlag), nil }
[ "func", "NewLogger", "(", "p", "Priority", ",", "logFlag", "int", ")", "(", "*", "log", ".", "Logger", ",", "error", ")", "{", "s", ",", "err", ":=", "New", "(", "p", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "log", ".", "New", "(", "s", ",", "\"", "\"", ",", "logFlag", ")", ",", "nil", "\n", "}" ]
// NewLogger creates a log.Logger whose output is written to // the system log service with the specified priority. The logFlag // argument is the flag set passed through to log.New to create // the Logger.
[ "NewLogger", "creates", "a", "log", ".", "Logger", "whose", "output", "is", "written", "to", "the", "system", "log", "service", "with", "the", "specified", "priority", ".", "The", "logFlag", "argument", "is", "the", "flag", "set", "passed", "through", "to", "log", ".", "New", "to", "create", "the", "Logger", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog.go#L119-L125
18,136
RackSec/srslog
srslog_unix.go
unixSyslog
func unixSyslog() (conn serverConn, err error) { logTypes := []string{"unixgram", "unix"} logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"} for _, network := range logTypes { for _, path := range logPaths { conn, err := net.Dial(network, path) if err != nil { continue } else { return &localConn{conn: conn}, nil } } } return nil, errors.New("Unix syslog delivery error") }
go
func unixSyslog() (conn serverConn, err error) { logTypes := []string{"unixgram", "unix"} logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"} for _, network := range logTypes { for _, path := range logPaths { conn, err := net.Dial(network, path) if err != nil { continue } else { return &localConn{conn: conn}, nil } } } return nil, errors.New("Unix syslog delivery error") }
[ "func", "unixSyslog", "(", ")", "(", "conn", "serverConn", ",", "err", "error", ")", "{", "logTypes", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "\n", "logPaths", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "for", "_", ",", "network", ":=", "range", "logTypes", "{", "for", "_", ",", "path", ":=", "range", "logPaths", "{", "conn", ",", "err", ":=", "net", ".", "Dial", "(", "network", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "else", "{", "return", "&", "localConn", "{", "conn", ":", "conn", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// unixSyslog opens a connection to the syslog daemon running on the // local machine using a Unix domain socket. This function exists because of // Solaris support as implemented by gccgo. On Solaris you can not // simply open a TCP connection to the syslog daemon. The gccgo // sources have a syslog_solaris.go file that implements unixSyslog to // return a type that satisfies the serverConn interface and simply calls the C // library syslog function.
[ "unixSyslog", "opens", "a", "connection", "to", "the", "syslog", "daemon", "running", "on", "the", "local", "machine", "using", "a", "Unix", "domain", "socket", ".", "This", "function", "exists", "because", "of", "Solaris", "support", "as", "implemented", "by", "gccgo", ".", "On", "Solaris", "you", "can", "not", "simply", "open", "a", "TCP", "connection", "to", "the", "syslog", "daemon", ".", "The", "gccgo", "sources", "have", "a", "syslog_solaris", ".", "go", "file", "that", "implements", "unixSyslog", "to", "return", "a", "type", "that", "satisfies", "the", "serverConn", "interface", "and", "simply", "calls", "the", "C", "library", "syslog", "function", "." ]
a4725f04ec91af1a91b380da679d6e0c2f061e59
https://github.com/RackSec/srslog/blob/a4725f04ec91af1a91b380da679d6e0c2f061e59/srslog_unix.go#L16-L30
18,137
percona/go-mysql
dsn/dsn.go
GetSocketFromTCPConnection
func GetSocketFromTCPConnection(ctx context.Context, dsn string) (socket string, err error) { db, err := sql.Open("mysql", dsn) if err != nil { return "", ErrNoSocket } defer db.Close() err = db.QueryRowContext(ctx, "SELECT @@socket").Scan(socket) if err != nil { return "", ErrNoSocket } if !path.IsAbs(socket) { return "", ErrNoSocket } if socket != "" { return socket, nil } return "", ErrNoSocket }
go
func GetSocketFromTCPConnection(ctx context.Context, dsn string) (socket string, err error) { db, err := sql.Open("mysql", dsn) if err != nil { return "", ErrNoSocket } defer db.Close() err = db.QueryRowContext(ctx, "SELECT @@socket").Scan(socket) if err != nil { return "", ErrNoSocket } if !path.IsAbs(socket) { return "", ErrNoSocket } if socket != "" { return socket, nil } return "", ErrNoSocket }
[ "func", "GetSocketFromTCPConnection", "(", "ctx", "context", ".", "Context", ",", "dsn", "string", ")", "(", "socket", "string", ",", "err", "error", ")", "{", "db", ",", "err", ":=", "sql", ".", "Open", "(", "\"", "\"", ",", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "ErrNoSocket", "\n", "}", "\n", "defer", "db", ".", "Close", "(", ")", "\n\n", "err", "=", "db", ".", "QueryRowContext", "(", "ctx", ",", "\"", "\"", ")", ".", "Scan", "(", "socket", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "ErrNoSocket", "\n", "}", "\n", "if", "!", "path", ".", "IsAbs", "(", "socket", ")", "{", "return", "\"", "\"", ",", "ErrNoSocket", "\n", "}", "\n", "if", "socket", "!=", "\"", "\"", "{", "return", "socket", ",", "nil", "\n", "}", "\n\n", "return", "\"", "\"", ",", "ErrNoSocket", "\n", "}" ]
// GetSocketFromTCPConnection will try to get socket path by connecting to MySQL localhost TCP port. // This is not reliable as TCP connections may be not allowed.
[ "GetSocketFromTCPConnection", "will", "try", "to", "get", "socket", "path", "by", "connecting", "to", "MySQL", "localhost", "TCP", "port", ".", "This", "is", "not", "reliable", "as", "TCP", "connections", "may", "be", "not", "allowed", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/dsn/dsn.go#L209-L228
18,138
percona/go-mysql
dsn/dsn.go
GetSocket
func GetSocket(ctx context.Context, dsn string) (string, error) { var socket string var err error socket, err = GetSocketFromTCPConnection(ctx, dsn) if err != nil { socket, err = GetSocketFromProcessList(ctx) if err != nil { socket, err = GetSocketFromNetstat(ctx) } } return socket, err }
go
func GetSocket(ctx context.Context, dsn string) (string, error) { var socket string var err error socket, err = GetSocketFromTCPConnection(ctx, dsn) if err != nil { socket, err = GetSocketFromProcessList(ctx) if err != nil { socket, err = GetSocketFromNetstat(ctx) } } return socket, err }
[ "func", "GetSocket", "(", "ctx", "context", ".", "Context", ",", "dsn", "string", ")", "(", "string", ",", "error", ")", "{", "var", "socket", "string", "\n", "var", "err", "error", "\n", "socket", ",", "err", "=", "GetSocketFromTCPConnection", "(", "ctx", ",", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "socket", ",", "err", "=", "GetSocketFromProcessList", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "socket", ",", "err", "=", "GetSocketFromNetstat", "(", "ctx", ")", "\n", "}", "\n", "}", "\n", "return", "socket", ",", "err", "\n", "}" ]
// GetSocket tries to detect and return path to the MySQL socket.
[ "GetSocket", "tries", "to", "detect", "and", "return", "path", "to", "the", "MySQL", "socket", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/dsn/dsn.go#L330-L341
18,139
percona/go-mysql
event/aggregator.go
AddEvent
func (a *Aggregator) AddEvent(event *log.Event, id, fingerprint string) { if a.rateLimit != event.RateLimit { a.rateLimit = event.RateLimit } outlier := false if a.outlierTime > 0 && event.TimeMetrics["Query_time"] > a.outlierTime { outlier = true } a.global.AddEvent(event, outlier) class, ok := a.classes[id] if !ok { class = NewClass(id, fingerprint, a.samples) a.classes[id] = class } class.AddEvent(event, outlier) }
go
func (a *Aggregator) AddEvent(event *log.Event, id, fingerprint string) { if a.rateLimit != event.RateLimit { a.rateLimit = event.RateLimit } outlier := false if a.outlierTime > 0 && event.TimeMetrics["Query_time"] > a.outlierTime { outlier = true } a.global.AddEvent(event, outlier) class, ok := a.classes[id] if !ok { class = NewClass(id, fingerprint, a.samples) a.classes[id] = class } class.AddEvent(event, outlier) }
[ "func", "(", "a", "*", "Aggregator", ")", "AddEvent", "(", "event", "*", "log", ".", "Event", ",", "id", ",", "fingerprint", "string", ")", "{", "if", "a", ".", "rateLimit", "!=", "event", ".", "RateLimit", "{", "a", ".", "rateLimit", "=", "event", ".", "RateLimit", "\n", "}", "\n\n", "outlier", ":=", "false", "\n", "if", "a", ".", "outlierTime", ">", "0", "&&", "event", ".", "TimeMetrics", "[", "\"", "\"", "]", ">", "a", ".", "outlierTime", "{", "outlier", "=", "true", "\n", "}", "\n\n", "a", ".", "global", ".", "AddEvent", "(", "event", ",", "outlier", ")", "\n\n", "class", ",", "ok", ":=", "a", ".", "classes", "[", "id", "]", "\n", "if", "!", "ok", "{", "class", "=", "NewClass", "(", "id", ",", "fingerprint", ",", "a", ".", "samples", ")", "\n", "a", ".", "classes", "[", "id", "]", "=", "class", "\n", "}", "\n", "class", ".", "AddEvent", "(", "event", ",", "outlier", ")", "\n", "}" ]
// AddEvent adds the event to the aggregator, automatically creating new classes // as needed.
[ "AddEvent", "adds", "the", "event", "to", "the", "aggregator", "automatically", "creating", "new", "classes", "as", "needed", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/aggregator.go#L63-L81
18,140
percona/go-mysql
event/aggregator.go
Finalize
func (a *Aggregator) Finalize() Result { a.global.Finalize(a.rateLimit) a.global.UniqueQueries = uint(len(a.classes)) for _, class := range a.classes { class.Finalize(a.rateLimit) class.UniqueQueries = 1 if class.Example != nil && class.Example.Ts != "" { if t, err := time.Parse("2006-01-02 15:04:05", class.Example.Ts); err != nil { class.Example.Ts = "" } else { class.Example.Ts = t.Add(a.utcOffset).Format("2006-01-02 15:04:05") } } } return Result{ Global: a.global, Class: a.classes, RateLimit: a.rateLimit, } }
go
func (a *Aggregator) Finalize() Result { a.global.Finalize(a.rateLimit) a.global.UniqueQueries = uint(len(a.classes)) for _, class := range a.classes { class.Finalize(a.rateLimit) class.UniqueQueries = 1 if class.Example != nil && class.Example.Ts != "" { if t, err := time.Parse("2006-01-02 15:04:05", class.Example.Ts); err != nil { class.Example.Ts = "" } else { class.Example.Ts = t.Add(a.utcOffset).Format("2006-01-02 15:04:05") } } } return Result{ Global: a.global, Class: a.classes, RateLimit: a.rateLimit, } }
[ "func", "(", "a", "*", "Aggregator", ")", "Finalize", "(", ")", "Result", "{", "a", ".", "global", ".", "Finalize", "(", "a", ".", "rateLimit", ")", "\n", "a", ".", "global", ".", "UniqueQueries", "=", "uint", "(", "len", "(", "a", ".", "classes", ")", ")", "\n", "for", "_", ",", "class", ":=", "range", "a", ".", "classes", "{", "class", ".", "Finalize", "(", "a", ".", "rateLimit", ")", "\n", "class", ".", "UniqueQueries", "=", "1", "\n", "if", "class", ".", "Example", "!=", "nil", "&&", "class", ".", "Example", ".", "Ts", "!=", "\"", "\"", "{", "if", "t", ",", "err", ":=", "time", ".", "Parse", "(", "\"", "\"", ",", "class", ".", "Example", ".", "Ts", ")", ";", "err", "!=", "nil", "{", "class", ".", "Example", ".", "Ts", "=", "\"", "\"", "\n", "}", "else", "{", "class", ".", "Example", ".", "Ts", "=", "t", ".", "Add", "(", "a", ".", "utcOffset", ")", ".", "Format", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "Result", "{", "Global", ":", "a", ".", "global", ",", "Class", ":", "a", ".", "classes", ",", "RateLimit", ":", "a", ".", "rateLimit", ",", "}", "\n", "}" ]
// Finalize calculates all metric statistics and returns a Result. // Call this function when done adding events to the aggregator.
[ "Finalize", "calculates", "all", "metric", "statistics", "and", "returns", "a", "Result", ".", "Call", "this", "function", "when", "done", "adding", "events", "to", "the", "aggregator", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/aggregator.go#L85-L104
18,141
percona/go-mysql
log/slow/parser.go
NewSlowLogParser
func NewSlowLogParser(file *os.File, opt log.Options) *SlowLogParser { if opt.DefaultLocation == nil { // Old MySQL format assumes time is taken from SYSTEM. opt.DefaultLocation = time.Local } p := &SlowLogParser{ file: file, opt: opt, // -- stopChan: make(chan bool, 1), eventChan: make(chan *log.Event), inHeader: false, inQuery: false, headerLines: 0, queryLines: 0, lineOffset: 0, bytesRead: opt.StartOffset, event: log.NewEvent(), } return p }
go
func NewSlowLogParser(file *os.File, opt log.Options) *SlowLogParser { if opt.DefaultLocation == nil { // Old MySQL format assumes time is taken from SYSTEM. opt.DefaultLocation = time.Local } p := &SlowLogParser{ file: file, opt: opt, // -- stopChan: make(chan bool, 1), eventChan: make(chan *log.Event), inHeader: false, inQuery: false, headerLines: 0, queryLines: 0, lineOffset: 0, bytesRead: opt.StartOffset, event: log.NewEvent(), } return p }
[ "func", "NewSlowLogParser", "(", "file", "*", "os", ".", "File", ",", "opt", "log", ".", "Options", ")", "*", "SlowLogParser", "{", "if", "opt", ".", "DefaultLocation", "==", "nil", "{", "// Old MySQL format assumes time is taken from SYSTEM.", "opt", ".", "DefaultLocation", "=", "time", ".", "Local", "\n", "}", "\n", "p", ":=", "&", "SlowLogParser", "{", "file", ":", "file", ",", "opt", ":", "opt", ",", "// --", "stopChan", ":", "make", "(", "chan", "bool", ",", "1", ")", ",", "eventChan", ":", "make", "(", "chan", "*", "log", ".", "Event", ")", ",", "inHeader", ":", "false", ",", "inQuery", ":", "false", ",", "headerLines", ":", "0", ",", "queryLines", ":", "0", ",", "lineOffset", ":", "0", ",", "bytesRead", ":", "opt", ".", "StartOffset", ",", "event", ":", "log", ".", "NewEvent", "(", ")", ",", "}", "\n", "return", "p", "\n", "}" ]
// NewSlowLogParser returns a new SlowLogParser that reads from the open file.
[ "NewSlowLogParser", "returns", "a", "new", "SlowLogParser", "that", "reads", "from", "the", "open", "file", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/log/slow/parser.go#L67-L87
18,142
percona/go-mysql
log/slow/parser.go
Stop
func (p *SlowLogParser) Stop() { if p.opt.Debug { l.Println("stopping") } p.stopChan <- true return }
go
func (p *SlowLogParser) Stop() { if p.opt.Debug { l.Println("stopping") } p.stopChan <- true return }
[ "func", "(", "p", "*", "SlowLogParser", ")", "Stop", "(", ")", "{", "if", "p", ".", "opt", ".", "Debug", "{", "l", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "stopChan", "<-", "true", "\n", "return", "\n", "}" ]
// Stop stops the parser before parsing the next event or while blocked on // sending the current event to the event channel.
[ "Stop", "stops", "the", "parser", "before", "parsing", "the", "next", "event", "or", "while", "blocked", "on", "sending", "the", "current", "event", "to", "the", "event", "channel", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/log/slow/parser.go#L97-L103
18,143
percona/go-mysql
log/slow/parser.go
Start
func (p *SlowLogParser) Start() error { if p.opt.Debug { l.SetFlags(l.Ltime | l.Lmicroseconds) fmt.Println() l.Println("parsing " + p.file.Name()) } // Seek to the offset, if any. // @todo error if start off > file size if p.opt.StartOffset > 0 { if _, err := p.file.Seek(int64(p.opt.StartOffset), os.SEEK_SET); err != nil { return err } } defer close(p.eventChan) r := bufio.NewReader(p.file) SCANNER_LOOP: for !p.stopped { select { case <-p.stopChan: p.stopped = true break SCANNER_LOOP default: } line, err := r.ReadString('\n') if err != nil { if err != io.EOF { return err } break SCANNER_LOOP } lineLen := uint64(len(line)) p.bytesRead += lineLen p.lineOffset = p.bytesRead - lineLen if p.opt.Debug { fmt.Println() l.Printf("+%d line: %s", p.lineOffset, line) } // Filter out meta lines: // /usr/local/bin/mysqld, Version: 5.6.15-62.0-tokudb-7.1.0-tokudb-log (binary). started with: // Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock // Time Id Command Argument if lineLen >= 20 && ((line[0] == '/' && line[lineLen-6:lineLen] == "with:\n") || (line[0:5] == "Time ") || (line[0:4] == "Tcp ") || (line[0:4] == "TCP ")) { if p.opt.Debug { l.Println("meta") } continue } // PMM-1834: Filter out empty comments and MariaDB explain: if line == "#\n" || strings.HasPrefix(line, "# explain:") { continue } // Remove \n. line = line[0 : lineLen-1] if p.inHeader { p.parseHeader(line) } else if p.inQuery { p.parseQuery(line) } else if headerRe.MatchString(line) { p.inHeader = true p.inQuery = false p.parseHeader(line) } } if !p.stopped && p.queryLines > 0 { p.endOffset = p.bytesRead p.sendEvent(false, false) } if p.opt.Debug { l.Printf("\ndone") } return nil }
go
func (p *SlowLogParser) Start() error { if p.opt.Debug { l.SetFlags(l.Ltime | l.Lmicroseconds) fmt.Println() l.Println("parsing " + p.file.Name()) } // Seek to the offset, if any. // @todo error if start off > file size if p.opt.StartOffset > 0 { if _, err := p.file.Seek(int64(p.opt.StartOffset), os.SEEK_SET); err != nil { return err } } defer close(p.eventChan) r := bufio.NewReader(p.file) SCANNER_LOOP: for !p.stopped { select { case <-p.stopChan: p.stopped = true break SCANNER_LOOP default: } line, err := r.ReadString('\n') if err != nil { if err != io.EOF { return err } break SCANNER_LOOP } lineLen := uint64(len(line)) p.bytesRead += lineLen p.lineOffset = p.bytesRead - lineLen if p.opt.Debug { fmt.Println() l.Printf("+%d line: %s", p.lineOffset, line) } // Filter out meta lines: // /usr/local/bin/mysqld, Version: 5.6.15-62.0-tokudb-7.1.0-tokudb-log (binary). started with: // Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock // Time Id Command Argument if lineLen >= 20 && ((line[0] == '/' && line[lineLen-6:lineLen] == "with:\n") || (line[0:5] == "Time ") || (line[0:4] == "Tcp ") || (line[0:4] == "TCP ")) { if p.opt.Debug { l.Println("meta") } continue } // PMM-1834: Filter out empty comments and MariaDB explain: if line == "#\n" || strings.HasPrefix(line, "# explain:") { continue } // Remove \n. line = line[0 : lineLen-1] if p.inHeader { p.parseHeader(line) } else if p.inQuery { p.parseQuery(line) } else if headerRe.MatchString(line) { p.inHeader = true p.inQuery = false p.parseHeader(line) } } if !p.stopped && p.queryLines > 0 { p.endOffset = p.bytesRead p.sendEvent(false, false) } if p.opt.Debug { l.Printf("\ndone") } return nil }
[ "func", "(", "p", "*", "SlowLogParser", ")", "Start", "(", ")", "error", "{", "if", "p", ".", "opt", ".", "Debug", "{", "l", ".", "SetFlags", "(", "l", ".", "Ltime", "|", "l", ".", "Lmicroseconds", ")", "\n", "fmt", ".", "Println", "(", ")", "\n", "l", ".", "Println", "(", "\"", "\"", "+", "p", ".", "file", ".", "Name", "(", ")", ")", "\n", "}", "\n\n", "// Seek to the offset, if any.", "// @todo error if start off > file size", "if", "p", ".", "opt", ".", "StartOffset", ">", "0", "{", "if", "_", ",", "err", ":=", "p", ".", "file", ".", "Seek", "(", "int64", "(", "p", ".", "opt", ".", "StartOffset", ")", ",", "os", ".", "SEEK_SET", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "defer", "close", "(", "p", ".", "eventChan", ")", "\n\n", "r", ":=", "bufio", ".", "NewReader", "(", "p", ".", "file", ")", "\n\n", "SCANNER_LOOP", ":", "for", "!", "p", ".", "stopped", "{", "select", "{", "case", "<-", "p", ".", "stopChan", ":", "p", ".", "stopped", "=", "true", "\n", "break", "SCANNER_LOOP", "\n", "default", ":", "}", "\n\n", "line", ",", "err", ":=", "r", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "return", "err", "\n", "}", "\n", "break", "SCANNER_LOOP", "\n", "}", "\n\n", "lineLen", ":=", "uint64", "(", "len", "(", "line", ")", ")", "\n", "p", ".", "bytesRead", "+=", "lineLen", "\n", "p", ".", "lineOffset", "=", "p", ".", "bytesRead", "-", "lineLen", "\n", "if", "p", ".", "opt", ".", "Debug", "{", "fmt", ".", "Println", "(", ")", "\n", "l", ".", "Printf", "(", "\"", "\"", ",", "p", ".", "lineOffset", ",", "line", ")", "\n", "}", "\n\n", "// Filter out meta lines:", "// /usr/local/bin/mysqld, Version: 5.6.15-62.0-tokudb-7.1.0-tokudb-log (binary). started with:", "// Tcp port: 3306 Unix socket: /var/lib/mysql/mysql.sock", "// Time Id Command Argument", "if", "lineLen", ">=", "20", "&&", "(", "(", "line", "[", "0", "]", "==", "'/'", "&&", "line", "[", "lineLen", "-", "6", ":", "lineLen", "]", "==", "\"", "\\n", "\"", ")", "||", "(", "line", "[", "0", ":", "5", "]", "==", "\"", "\"", ")", "||", "(", "line", "[", "0", ":", "4", "]", "==", "\"", "\"", ")", "||", "(", "line", "[", "0", ":", "4", "]", "==", "\"", "\"", ")", ")", "{", "if", "p", ".", "opt", ".", "Debug", "{", "l", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// PMM-1834: Filter out empty comments and MariaDB explain:", "if", "line", "==", "\"", "\\n", "\"", "||", "strings", ".", "HasPrefix", "(", "line", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n\n", "// Remove \\n.", "line", "=", "line", "[", "0", ":", "lineLen", "-", "1", "]", "\n\n", "if", "p", ".", "inHeader", "{", "p", ".", "parseHeader", "(", "line", ")", "\n", "}", "else", "if", "p", ".", "inQuery", "{", "p", ".", "parseQuery", "(", "line", ")", "\n", "}", "else", "if", "headerRe", ".", "MatchString", "(", "line", ")", "{", "p", ".", "inHeader", "=", "true", "\n", "p", ".", "inQuery", "=", "false", "\n", "p", ".", "parseHeader", "(", "line", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "p", ".", "stopped", "&&", "p", ".", "queryLines", ">", "0", "{", "p", ".", "endOffset", "=", "p", ".", "bytesRead", "\n", "p", ".", "sendEvent", "(", "false", ",", "false", ")", "\n", "}", "\n\n", "if", "p", ".", "opt", ".", "Debug", "{", "l", ".", "Printf", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Start starts the parser. Events are sent to the unbuffered event channel. // Parsing stops on EOF, error, or call to Stop. The event channel is closed // when parsing stops. The file is not closed.
[ "Start", "starts", "the", "parser", ".", "Events", "are", "sent", "to", "the", "unbuffered", "event", "channel", ".", "Parsing", "stops", "on", "EOF", "error", "or", "call", "to", "Stop", ".", "The", "event", "channel", "is", "closed", "when", "parsing", "stops", ".", "The", "file", "is", "not", "closed", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/log/slow/parser.go#L108-L194
18,144
percona/go-mysql
event/class.go
NewClass
func NewClass(id, fingerprint string, sample bool) *Class { class := &Class{ Id: id, Fingerprint: fingerprint, Metrics: NewMetrics(), TotalQueries: 0, Example: &Example{}, sample: sample, } return class }
go
func NewClass(id, fingerprint string, sample bool) *Class { class := &Class{ Id: id, Fingerprint: fingerprint, Metrics: NewMetrics(), TotalQueries: 0, Example: &Example{}, sample: sample, } return class }
[ "func", "NewClass", "(", "id", ",", "fingerprint", "string", ",", "sample", "bool", ")", "*", "Class", "{", "class", ":=", "&", "Class", "{", "Id", ":", "id", ",", "Fingerprint", ":", "fingerprint", ",", "Metrics", ":", "NewMetrics", "(", ")", ",", "TotalQueries", ":", "0", ",", "Example", ":", "&", "Example", "{", "}", ",", "sample", ":", "sample", ",", "}", "\n", "return", "class", "\n", "}" ]
// NewClass returns a new Class for the class ID and fingerprint. // If sample is true, the query with the greatest Query_time is saved.
[ "NewClass", "returns", "a", "new", "Class", "for", "the", "class", "ID", "and", "fingerprint", ".", "If", "sample", "is", "true", "the", "query", "with", "the", "greatest", "Query_time", "is", "saved", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/class.go#L61-L71
18,145
percona/go-mysql
event/class.go
AddEvent
func (c *Class) AddEvent(e *log.Event, outlier bool) { if outlier { c.outliers++ } else { c.TotalQueries++ } c.Metrics.AddEvent(e, outlier) // Save last db seen for this query. This helps ensure the sample query // has a db. if e.Db != "" { c.lastDb = e.Db } if c.sample { if n, ok := e.TimeMetrics["Query_time"]; ok { if float64(n) > c.Example.QueryTime { c.Example.QueryTime = float64(n) c.Example.Size = len(e.Query) if e.Db != "" { c.Example.Db = e.Db } else { c.Example.Db = c.lastDb } if len(e.Query) > MaxExampleBytes { c.Example.Query = e.Query[0:MaxExampleBytes-len(TruncatedExampleSuffix)] + TruncatedExampleSuffix } else { c.Example.Query = e.Query } if !e.Ts.IsZero() { // todo use time.RFC3339Nano instead c.Example.Ts = e.Ts.UTC().Format("2006-01-02 15:04:05") } } } } }
go
func (c *Class) AddEvent(e *log.Event, outlier bool) { if outlier { c.outliers++ } else { c.TotalQueries++ } c.Metrics.AddEvent(e, outlier) // Save last db seen for this query. This helps ensure the sample query // has a db. if e.Db != "" { c.lastDb = e.Db } if c.sample { if n, ok := e.TimeMetrics["Query_time"]; ok { if float64(n) > c.Example.QueryTime { c.Example.QueryTime = float64(n) c.Example.Size = len(e.Query) if e.Db != "" { c.Example.Db = e.Db } else { c.Example.Db = c.lastDb } if len(e.Query) > MaxExampleBytes { c.Example.Query = e.Query[0:MaxExampleBytes-len(TruncatedExampleSuffix)] + TruncatedExampleSuffix } else { c.Example.Query = e.Query } if !e.Ts.IsZero() { // todo use time.RFC3339Nano instead c.Example.Ts = e.Ts.UTC().Format("2006-01-02 15:04:05") } } } } }
[ "func", "(", "c", "*", "Class", ")", "AddEvent", "(", "e", "*", "log", ".", "Event", ",", "outlier", "bool", ")", "{", "if", "outlier", "{", "c", ".", "outliers", "++", "\n", "}", "else", "{", "c", ".", "TotalQueries", "++", "\n", "}", "\n\n", "c", ".", "Metrics", ".", "AddEvent", "(", "e", ",", "outlier", ")", "\n\n", "// Save last db seen for this query. This helps ensure the sample query", "// has a db.", "if", "e", ".", "Db", "!=", "\"", "\"", "{", "c", ".", "lastDb", "=", "e", ".", "Db", "\n", "}", "\n", "if", "c", ".", "sample", "{", "if", "n", ",", "ok", ":=", "e", ".", "TimeMetrics", "[", "\"", "\"", "]", ";", "ok", "{", "if", "float64", "(", "n", ")", ">", "c", ".", "Example", ".", "QueryTime", "{", "c", ".", "Example", ".", "QueryTime", "=", "float64", "(", "n", ")", "\n", "c", ".", "Example", ".", "Size", "=", "len", "(", "e", ".", "Query", ")", "\n", "if", "e", ".", "Db", "!=", "\"", "\"", "{", "c", ".", "Example", ".", "Db", "=", "e", ".", "Db", "\n", "}", "else", "{", "c", ".", "Example", ".", "Db", "=", "c", ".", "lastDb", "\n", "}", "\n", "if", "len", "(", "e", ".", "Query", ")", ">", "MaxExampleBytes", "{", "c", ".", "Example", ".", "Query", "=", "e", ".", "Query", "[", "0", ":", "MaxExampleBytes", "-", "len", "(", "TruncatedExampleSuffix", ")", "]", "+", "TruncatedExampleSuffix", "\n", "}", "else", "{", "c", ".", "Example", ".", "Query", "=", "e", ".", "Query", "\n", "}", "\n", "if", "!", "e", ".", "Ts", ".", "IsZero", "(", ")", "{", "// todo use time.RFC3339Nano instead", "c", ".", "Example", ".", "Ts", "=", "e", ".", "Ts", ".", "UTC", "(", ")", ".", "Format", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// AddEvent adds an event to the query class.
[ "AddEvent", "adds", "an", "event", "to", "the", "query", "class", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/class.go#L74-L110
18,146
percona/go-mysql
event/class.go
AddClass
func (c *Class) AddClass(newClass *Class) { c.UniqueQueries++ c.TotalQueries += newClass.TotalQueries c.Example = nil for newMetric, newStats := range newClass.Metrics.TimeMetrics { stats, ok := c.Metrics.TimeMetrics[newMetric] if !ok { m := *newStats c.Metrics.TimeMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum stats.Avg = Float64(stats.Sum / float64(c.TotalQueries)) if Float64Value(newStats.Min) < Float64Value(stats.Min) || stats.Min == nil { stats.Min = newStats.Min } if Float64Value(newStats.Max) > Float64Value(stats.Max) || stats.Max == nil { stats.Max = newStats.Max } } } for newMetric, newStats := range newClass.Metrics.NumberMetrics { stats, ok := c.Metrics.NumberMetrics[newMetric] if !ok { m := *newStats c.Metrics.NumberMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum stats.Avg = Uint64(stats.Sum / uint64(c.TotalQueries)) if Uint64Value(newStats.Min) < Uint64Value(stats.Min) || stats.Min == nil { stats.Min = newStats.Min } if Uint64Value(newStats.Max) > Uint64Value(stats.Max) || stats.Max == nil { stats.Max = newStats.Max } } } for newMetric, newStats := range newClass.Metrics.BoolMetrics { stats, ok := c.Metrics.BoolMetrics[newMetric] if !ok { m := *newStats c.Metrics.BoolMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum } } }
go
func (c *Class) AddClass(newClass *Class) { c.UniqueQueries++ c.TotalQueries += newClass.TotalQueries c.Example = nil for newMetric, newStats := range newClass.Metrics.TimeMetrics { stats, ok := c.Metrics.TimeMetrics[newMetric] if !ok { m := *newStats c.Metrics.TimeMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum stats.Avg = Float64(stats.Sum / float64(c.TotalQueries)) if Float64Value(newStats.Min) < Float64Value(stats.Min) || stats.Min == nil { stats.Min = newStats.Min } if Float64Value(newStats.Max) > Float64Value(stats.Max) || stats.Max == nil { stats.Max = newStats.Max } } } for newMetric, newStats := range newClass.Metrics.NumberMetrics { stats, ok := c.Metrics.NumberMetrics[newMetric] if !ok { m := *newStats c.Metrics.NumberMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum stats.Avg = Uint64(stats.Sum / uint64(c.TotalQueries)) if Uint64Value(newStats.Min) < Uint64Value(stats.Min) || stats.Min == nil { stats.Min = newStats.Min } if Uint64Value(newStats.Max) > Uint64Value(stats.Max) || stats.Max == nil { stats.Max = newStats.Max } } } for newMetric, newStats := range newClass.Metrics.BoolMetrics { stats, ok := c.Metrics.BoolMetrics[newMetric] if !ok { m := *newStats c.Metrics.BoolMetrics[newMetric] = &m } else { stats.Sum += newStats.Sum } } }
[ "func", "(", "c", "*", "Class", ")", "AddClass", "(", "newClass", "*", "Class", ")", "{", "c", ".", "UniqueQueries", "++", "\n", "c", ".", "TotalQueries", "+=", "newClass", ".", "TotalQueries", "\n", "c", ".", "Example", "=", "nil", "\n\n", "for", "newMetric", ",", "newStats", ":=", "range", "newClass", ".", "Metrics", ".", "TimeMetrics", "{", "stats", ",", "ok", ":=", "c", ".", "Metrics", ".", "TimeMetrics", "[", "newMetric", "]", "\n", "if", "!", "ok", "{", "m", ":=", "*", "newStats", "\n", "c", ".", "Metrics", ".", "TimeMetrics", "[", "newMetric", "]", "=", "&", "m", "\n", "}", "else", "{", "stats", ".", "Sum", "+=", "newStats", ".", "Sum", "\n", "stats", ".", "Avg", "=", "Float64", "(", "stats", ".", "Sum", "/", "float64", "(", "c", ".", "TotalQueries", ")", ")", "\n", "if", "Float64Value", "(", "newStats", ".", "Min", ")", "<", "Float64Value", "(", "stats", ".", "Min", ")", "||", "stats", ".", "Min", "==", "nil", "{", "stats", ".", "Min", "=", "newStats", ".", "Min", "\n", "}", "\n", "if", "Float64Value", "(", "newStats", ".", "Max", ")", ">", "Float64Value", "(", "stats", ".", "Max", ")", "||", "stats", ".", "Max", "==", "nil", "{", "stats", ".", "Max", "=", "newStats", ".", "Max", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "newMetric", ",", "newStats", ":=", "range", "newClass", ".", "Metrics", ".", "NumberMetrics", "{", "stats", ",", "ok", ":=", "c", ".", "Metrics", ".", "NumberMetrics", "[", "newMetric", "]", "\n", "if", "!", "ok", "{", "m", ":=", "*", "newStats", "\n", "c", ".", "Metrics", ".", "NumberMetrics", "[", "newMetric", "]", "=", "&", "m", "\n", "}", "else", "{", "stats", ".", "Sum", "+=", "newStats", ".", "Sum", "\n", "stats", ".", "Avg", "=", "Uint64", "(", "stats", ".", "Sum", "/", "uint64", "(", "c", ".", "TotalQueries", ")", ")", "\n", "if", "Uint64Value", "(", "newStats", ".", "Min", ")", "<", "Uint64Value", "(", "stats", ".", "Min", ")", "||", "stats", ".", "Min", "==", "nil", "{", "stats", ".", "Min", "=", "newStats", ".", "Min", "\n", "}", "\n", "if", "Uint64Value", "(", "newStats", ".", "Max", ")", ">", "Uint64Value", "(", "stats", ".", "Max", ")", "||", "stats", ".", "Max", "==", "nil", "{", "stats", ".", "Max", "=", "newStats", ".", "Max", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "newMetric", ",", "newStats", ":=", "range", "newClass", ".", "Metrics", ".", "BoolMetrics", "{", "stats", ",", "ok", ":=", "c", ".", "Metrics", ".", "BoolMetrics", "[", "newMetric", "]", "\n", "if", "!", "ok", "{", "m", ":=", "*", "newStats", "\n", "c", ".", "Metrics", ".", "BoolMetrics", "[", "newMetric", "]", "=", "&", "m", "\n", "}", "else", "{", "stats", ".", "Sum", "+=", "newStats", ".", "Sum", "\n", "}", "\n", "}", "\n", "}" ]
// AddClass adds a Class to the current class. This is used with Performance // Schema which returns pre-aggregated classes instead of events.
[ "AddClass", "adds", "a", "Class", "to", "the", "current", "class", ".", "This", "is", "used", "with", "Performance", "Schema", "which", "returns", "pre", "-", "aggregated", "classes", "instead", "of", "events", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/class.go#L114-L162
18,147
percona/go-mysql
event/class.go
Finalize
func (c *Class) Finalize(rateLimit uint) { if rateLimit == 0 { rateLimit = 1 } c.TotalQueries = (c.TotalQueries * rateLimit) + c.outliers c.Metrics.Finalize(rateLimit, c.TotalQueries) if c.Example.QueryTime == 0 { c.Example = nil } }
go
func (c *Class) Finalize(rateLimit uint) { if rateLimit == 0 { rateLimit = 1 } c.TotalQueries = (c.TotalQueries * rateLimit) + c.outliers c.Metrics.Finalize(rateLimit, c.TotalQueries) if c.Example.QueryTime == 0 { c.Example = nil } }
[ "func", "(", "c", "*", "Class", ")", "Finalize", "(", "rateLimit", "uint", ")", "{", "if", "rateLimit", "==", "0", "{", "rateLimit", "=", "1", "\n", "}", "\n", "c", ".", "TotalQueries", "=", "(", "c", ".", "TotalQueries", "*", "rateLimit", ")", "+", "c", ".", "outliers", "\n", "c", ".", "Metrics", ".", "Finalize", "(", "rateLimit", ",", "c", ".", "TotalQueries", ")", "\n", "if", "c", ".", "Example", ".", "QueryTime", "==", "0", "{", "c", ".", "Example", "=", "nil", "\n", "}", "\n", "}" ]
// Finalize calculates all metric statistics. Call this function when done // adding events to the class.
[ "Finalize", "calculates", "all", "metric", "statistics", ".", "Call", "this", "function", "when", "done", "adding", "events", "to", "the", "class", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/class.go#L166-L175
18,148
percona/go-mysql
log/log.go
NewEvent
func NewEvent() *Event { event := new(Event) event.TimeMetrics = make(map[string]float64) event.NumberMetrics = make(map[string]uint64) event.BoolMetrics = make(map[string]bool) return event }
go
func NewEvent() *Event { event := new(Event) event.TimeMetrics = make(map[string]float64) event.NumberMetrics = make(map[string]uint64) event.BoolMetrics = make(map[string]bool) return event }
[ "func", "NewEvent", "(", ")", "*", "Event", "{", "event", ":=", "new", "(", "Event", ")", "\n", "event", ".", "TimeMetrics", "=", "make", "(", "map", "[", "string", "]", "float64", ")", "\n", "event", ".", "NumberMetrics", "=", "make", "(", "map", "[", "string", "]", "uint64", ")", "\n", "event", ".", "BoolMetrics", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "return", "event", "\n", "}" ]
// NewEvent returns a new Event with initialized metric maps.
[ "NewEvent", "returns", "a", "new", "Event", "with", "initialized", "metric", "maps", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/log/log.go#L50-L56
18,149
percona/go-mysql
query/query.go
Id
func Id(fingerprint string) string { id := md5.New() io.WriteString(id, fingerprint) h := fmt.Sprintf("%x", id.Sum(nil)) return strings.ToUpper(h[16:32]) }
go
func Id(fingerprint string) string { id := md5.New() io.WriteString(id, fingerprint) h := fmt.Sprintf("%x", id.Sum(nil)) return strings.ToUpper(h[16:32]) }
[ "func", "Id", "(", "fingerprint", "string", ")", "string", "{", "id", ":=", "md5", ".", "New", "(", ")", "\n", "io", ".", "WriteString", "(", "id", ",", "fingerprint", ")", "\n", "h", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ".", "Sum", "(", "nil", ")", ")", "\n", "return", "strings", ".", "ToUpper", "(", "h", "[", "16", ":", "32", "]", ")", "\n", "}" ]
// Id returns the right-most 16 characters of the MD5 checksum of fingerprint. // Query IDs are the shortest way to uniquely identify queries.
[ "Id", "returns", "the", "right", "-", "most", "16", "characters", "of", "the", "MD5", "checksum", "of", "fingerprint", ".", "Query", "IDs", "are", "the", "shortest", "way", "to", "uniquely", "identify", "queries", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/query/query.go#L800-L805
18,150
percona/go-mysql
event/metrics.go
NewMetrics
func NewMetrics() *Metrics { m := &Metrics{ TimeMetrics: make(map[string]*TimeStats), NumberMetrics: make(map[string]*NumberStats), BoolMetrics: make(map[string]*BoolStats), } return m }
go
func NewMetrics() *Metrics { m := &Metrics{ TimeMetrics: make(map[string]*TimeStats), NumberMetrics: make(map[string]*NumberStats), BoolMetrics: make(map[string]*BoolStats), } return m }
[ "func", "NewMetrics", "(", ")", "*", "Metrics", "{", "m", ":=", "&", "Metrics", "{", "TimeMetrics", ":", "make", "(", "map", "[", "string", "]", "*", "TimeStats", ")", ",", "NumberMetrics", ":", "make", "(", "map", "[", "string", "]", "*", "NumberStats", ")", ",", "BoolMetrics", ":", "make", "(", "map", "[", "string", "]", "*", "BoolStats", ")", ",", "}", "\n", "return", "m", "\n", "}" ]
// NewMetrics returns a pointer to an initialized Metrics structure.
[ "NewMetrics", "returns", "a", "pointer", "to", "an", "initialized", "Metrics", "structure", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/metrics.go#L64-L71
18,151
percona/go-mysql
event/metrics.go
AddEvent
func (m *Metrics) AddEvent(e *log.Event, outlier bool) { for metric, val := range e.TimeMetrics { stats, seenMetric := m.TimeMetrics[metric] if !seenMetric { m.TimeMetrics[metric] = &TimeStats{ vals: []float64{}, } stats = m.TimeMetrics[metric] } if outlier { stats.outlierSum += val } else { stats.Sum += val } stats.vals = append(stats.vals, float64(val)) } for metric, val := range e.NumberMetrics { stats, seenMetric := m.NumberMetrics[metric] if !seenMetric { m.NumberMetrics[metric] = &NumberStats{ vals: []uint64{}, } stats = m.NumberMetrics[metric] } if outlier { stats.outlierSum += val } else { stats.Sum += val } stats.vals = append(stats.vals, val) } for metric, val := range e.BoolMetrics { stats, seenMetric := m.BoolMetrics[metric] if !seenMetric { stats = &BoolStats{} m.BoolMetrics[metric] = stats } if val { if outlier { stats.outlierSum += 1 } else { stats.Sum += 1 } } } }
go
func (m *Metrics) AddEvent(e *log.Event, outlier bool) { for metric, val := range e.TimeMetrics { stats, seenMetric := m.TimeMetrics[metric] if !seenMetric { m.TimeMetrics[metric] = &TimeStats{ vals: []float64{}, } stats = m.TimeMetrics[metric] } if outlier { stats.outlierSum += val } else { stats.Sum += val } stats.vals = append(stats.vals, float64(val)) } for metric, val := range e.NumberMetrics { stats, seenMetric := m.NumberMetrics[metric] if !seenMetric { m.NumberMetrics[metric] = &NumberStats{ vals: []uint64{}, } stats = m.NumberMetrics[metric] } if outlier { stats.outlierSum += val } else { stats.Sum += val } stats.vals = append(stats.vals, val) } for metric, val := range e.BoolMetrics { stats, seenMetric := m.BoolMetrics[metric] if !seenMetric { stats = &BoolStats{} m.BoolMetrics[metric] = stats } if val { if outlier { stats.outlierSum += 1 } else { stats.Sum += 1 } } } }
[ "func", "(", "m", "*", "Metrics", ")", "AddEvent", "(", "e", "*", "log", ".", "Event", ",", "outlier", "bool", ")", "{", "for", "metric", ",", "val", ":=", "range", "e", ".", "TimeMetrics", "{", "stats", ",", "seenMetric", ":=", "m", ".", "TimeMetrics", "[", "metric", "]", "\n", "if", "!", "seenMetric", "{", "m", ".", "TimeMetrics", "[", "metric", "]", "=", "&", "TimeStats", "{", "vals", ":", "[", "]", "float64", "{", "}", ",", "}", "\n", "stats", "=", "m", ".", "TimeMetrics", "[", "metric", "]", "\n", "}", "\n", "if", "outlier", "{", "stats", ".", "outlierSum", "+=", "val", "\n", "}", "else", "{", "stats", ".", "Sum", "+=", "val", "\n", "}", "\n", "stats", ".", "vals", "=", "append", "(", "stats", ".", "vals", ",", "float64", "(", "val", ")", ")", "\n", "}", "\n\n", "for", "metric", ",", "val", ":=", "range", "e", ".", "NumberMetrics", "{", "stats", ",", "seenMetric", ":=", "m", ".", "NumberMetrics", "[", "metric", "]", "\n", "if", "!", "seenMetric", "{", "m", ".", "NumberMetrics", "[", "metric", "]", "=", "&", "NumberStats", "{", "vals", ":", "[", "]", "uint64", "{", "}", ",", "}", "\n", "stats", "=", "m", ".", "NumberMetrics", "[", "metric", "]", "\n", "}", "\n", "if", "outlier", "{", "stats", ".", "outlierSum", "+=", "val", "\n", "}", "else", "{", "stats", ".", "Sum", "+=", "val", "\n", "}", "\n", "stats", ".", "vals", "=", "append", "(", "stats", ".", "vals", ",", "val", ")", "\n", "}", "\n\n", "for", "metric", ",", "val", ":=", "range", "e", ".", "BoolMetrics", "{", "stats", ",", "seenMetric", ":=", "m", ".", "BoolMetrics", "[", "metric", "]", "\n", "if", "!", "seenMetric", "{", "stats", "=", "&", "BoolStats", "{", "}", "\n", "m", ".", "BoolMetrics", "[", "metric", "]", "=", "stats", "\n", "}", "\n", "if", "val", "{", "if", "outlier", "{", "stats", ".", "outlierSum", "+=", "1", "\n", "}", "else", "{", "stats", ".", "Sum", "+=", "1", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// AddEvent saves all the metrics of the event.
[ "AddEvent", "saves", "all", "the", "metrics", "of", "the", "event", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/metrics.go#L74-L122
18,152
percona/go-mysql
event/metrics.go
Finalize
func (m *Metrics) Finalize(rateLimit uint, totalQueries uint) { if rateLimit == 0 { rateLimit = 1 } for _, s := range m.TimeMetrics { sort.Float64s(s.vals) cnt := len(s.vals) s.Min = Float64(s.vals[0]) s.Med = Float64(s.vals[(50*cnt)/100]) // median = 50th percentile s.P95 = Float64(s.vals[(95*cnt)/100]) s.Max = Float64(s.vals[cnt-1]) s.Sum = (s.Sum * float64(rateLimit)) + s.outlierSum s.Avg = Float64(s.Sum / float64(totalQueries)) } for _, s := range m.NumberMetrics { sort.Sort(byUint64(s.vals)) cnt := len(s.vals) s.Min = Uint64(s.vals[0]) s.Med = Uint64(s.vals[(50*cnt)/100]) // median = 50th percentile s.P95 = Uint64(s.vals[(95*cnt)/100]) s.Max = Uint64(s.vals[cnt-1]) s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum s.Avg = Uint64(s.Sum / uint64(totalQueries)) } for _, s := range m.BoolMetrics { s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum } }
go
func (m *Metrics) Finalize(rateLimit uint, totalQueries uint) { if rateLimit == 0 { rateLimit = 1 } for _, s := range m.TimeMetrics { sort.Float64s(s.vals) cnt := len(s.vals) s.Min = Float64(s.vals[0]) s.Med = Float64(s.vals[(50*cnt)/100]) // median = 50th percentile s.P95 = Float64(s.vals[(95*cnt)/100]) s.Max = Float64(s.vals[cnt-1]) s.Sum = (s.Sum * float64(rateLimit)) + s.outlierSum s.Avg = Float64(s.Sum / float64(totalQueries)) } for _, s := range m.NumberMetrics { sort.Sort(byUint64(s.vals)) cnt := len(s.vals) s.Min = Uint64(s.vals[0]) s.Med = Uint64(s.vals[(50*cnt)/100]) // median = 50th percentile s.P95 = Uint64(s.vals[(95*cnt)/100]) s.Max = Uint64(s.vals[cnt-1]) s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum s.Avg = Uint64(s.Sum / uint64(totalQueries)) } for _, s := range m.BoolMetrics { s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum } }
[ "func", "(", "m", "*", "Metrics", ")", "Finalize", "(", "rateLimit", "uint", ",", "totalQueries", "uint", ")", "{", "if", "rateLimit", "==", "0", "{", "rateLimit", "=", "1", "\n", "}", "\n\n", "for", "_", ",", "s", ":=", "range", "m", ".", "TimeMetrics", "{", "sort", ".", "Float64s", "(", "s", ".", "vals", ")", "\n", "cnt", ":=", "len", "(", "s", ".", "vals", ")", "\n\n", "s", ".", "Min", "=", "Float64", "(", "s", ".", "vals", "[", "0", "]", ")", "\n", "s", ".", "Med", "=", "Float64", "(", "s", ".", "vals", "[", "(", "50", "*", "cnt", ")", "/", "100", "]", ")", "// median = 50th percentile", "\n", "s", ".", "P95", "=", "Float64", "(", "s", ".", "vals", "[", "(", "95", "*", "cnt", ")", "/", "100", "]", ")", "\n", "s", ".", "Max", "=", "Float64", "(", "s", ".", "vals", "[", "cnt", "-", "1", "]", ")", "\n", "s", ".", "Sum", "=", "(", "s", ".", "Sum", "*", "float64", "(", "rateLimit", ")", ")", "+", "s", ".", "outlierSum", "\n", "s", ".", "Avg", "=", "Float64", "(", "s", ".", "Sum", "/", "float64", "(", "totalQueries", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "s", ":=", "range", "m", ".", "NumberMetrics", "{", "sort", ".", "Sort", "(", "byUint64", "(", "s", ".", "vals", ")", ")", "\n", "cnt", ":=", "len", "(", "s", ".", "vals", ")", "\n\n", "s", ".", "Min", "=", "Uint64", "(", "s", ".", "vals", "[", "0", "]", ")", "\n", "s", ".", "Med", "=", "Uint64", "(", "s", ".", "vals", "[", "(", "50", "*", "cnt", ")", "/", "100", "]", ")", "// median = 50th percentile", "\n", "s", ".", "P95", "=", "Uint64", "(", "s", ".", "vals", "[", "(", "95", "*", "cnt", ")", "/", "100", "]", ")", "\n", "s", ".", "Max", "=", "Uint64", "(", "s", ".", "vals", "[", "cnt", "-", "1", "]", ")", "\n", "s", ".", "Sum", "=", "(", "s", ".", "Sum", "*", "uint64", "(", "rateLimit", ")", ")", "+", "s", ".", "outlierSum", "\n", "s", ".", "Avg", "=", "Uint64", "(", "s", ".", "Sum", "/", "uint64", "(", "totalQueries", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "s", ":=", "range", "m", ".", "BoolMetrics", "{", "s", ".", "Sum", "=", "(", "s", ".", "Sum", "*", "uint64", "(", "rateLimit", ")", ")", "+", "s", ".", "outlierSum", "\n", "}", "\n", "}" ]
// Finalize calculates the statistics of the added metrics. Call this function // when done adding events.
[ "Finalize", "calculates", "the", "statistics", "of", "the", "added", "metrics", ".", "Call", "this", "function", "when", "done", "adding", "events", "." ]
f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6
https://github.com/percona/go-mysql/blob/f5cfaf6a5e55b754b7b106f4488e1bc24cb8c2d6/event/metrics.go#L134-L166
18,153
d2r2/go-dht
dht.go
String
func (v SensorType) String() string { if v == DHT11 { return "DHT11" } else if v == DHT12 { return "DHT12" } else if v == DHT22 || v == AM2302 { return "DHT22|AM2302" } else { return "!!! unknown !!!" } }
go
func (v SensorType) String() string { if v == DHT11 { return "DHT11" } else if v == DHT12 { return "DHT12" } else if v == DHT22 || v == AM2302 { return "DHT22|AM2302" } else { return "!!! unknown !!!" } }
[ "func", "(", "v", "SensorType", ")", "String", "(", ")", "string", "{", "if", "v", "==", "DHT11", "{", "return", "\"", "\"", "\n", "}", "else", "if", "v", "==", "DHT12", "{", "return", "\"", "\"", "\n", "}", "else", "if", "v", "==", "DHT22", "||", "v", "==", "AM2302", "{", "return", "\"", "\"", "\n", "}", "else", "{", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// String implement Stringer interface.
[ "String", "implement", "Stringer", "interface", "." ]
b6103ae97a4b34d2876c04261ed37fce8cbbcc2d
https://github.com/d2r2/go-dht/blob/b6103ae97a4b34d2876c04261ed37fce8cbbcc2d/dht.go#L45-L55
18,154
d2r2/go-dht
dht.go
GetHandshakeDuration
func (v SensorType) GetHandshakeDuration() time.Duration { if v == DHT11 { return 18 * time.Millisecond } else if v == DHT12 { return 200 * time.Millisecond } else if v == DHT22 || v == AM2302 { return 18 * time.Millisecond } else { return 0 } }
go
func (v SensorType) GetHandshakeDuration() time.Duration { if v == DHT11 { return 18 * time.Millisecond } else if v == DHT12 { return 200 * time.Millisecond } else if v == DHT22 || v == AM2302 { return 18 * time.Millisecond } else { return 0 } }
[ "func", "(", "v", "SensorType", ")", "GetHandshakeDuration", "(", ")", "time", ".", "Duration", "{", "if", "v", "==", "DHT11", "{", "return", "18", "*", "time", ".", "Millisecond", "\n", "}", "else", "if", "v", "==", "DHT12", "{", "return", "200", "*", "time", ".", "Millisecond", "\n", "}", "else", "if", "v", "==", "DHT22", "||", "v", "==", "AM2302", "{", "return", "18", "*", "time", ".", "Millisecond", "\n", "}", "else", "{", "return", "0", "\n", "}", "\n", "}" ]
// GetHandshakeDuration specify signal duration necessary // to initiate sensor response.
[ "GetHandshakeDuration", "specify", "signal", "duration", "necessary", "to", "initiate", "sensor", "response", "." ]
b6103ae97a4b34d2876c04261ed37fce8cbbcc2d
https://github.com/d2r2/go-dht/blob/b6103ae97a4b34d2876c04261ed37fce8cbbcc2d/dht.go#L59-L69
18,155
d2r2/go-dht
dht.go
dialDHTxxAndGetResponse
func dialDHTxxAndGetResponse(pin int, handshakeDur time.Duration, boostPerfFlag bool) ([]Pulse, error) { var arr *C.int32_t var arrLen C.int32_t var list []int32 var hsDurUsec C.int32_t = C.int32_t(handshakeDur / time.Microsecond) var boost C.int32_t = 0 var err2 *C.Error if boostPerfFlag { boost = 1 } // return array: [pulse, duration, pulse, duration, ...] r := C.dial_DHTxx_and_read(C.int32_t(pin), hsDurUsec, boost, &arr, &arrLen, &err2) if r == -1 { var err error if err2 != nil { msg := C.GoString(err2.message) err = errors.New(spew.Sprintf("Error during call C.dial_DHTxx_and_read(): %v", msg)) C.free_error(err2) } else { err = errors.New(spew.Sprintf("Error during call C.dial_DHTxx_and_read()")) } return nil, err } defer C.free(unsafe.Pointer(arr)) // convert original C array arr to Go slice list h := (*reflect.SliceHeader)(unsafe.Pointer(&list)) h.Data = uintptr(unsafe.Pointer(arr)) h.Len = int(arrLen) h.Cap = int(arrLen) pulses := make([]Pulse, len(list)/2) // convert original int array ([pulse, duration, pulse, duration, ...]) // to Pulse struct array for i := 0; i < len(list)/2; i++ { var value byte = 0 if list[i*2] != 0 { value = 1 } pulses[i] = Pulse{Value: value, Duration: time.Duration(list[i*2+1]) * time.Microsecond} } return pulses, nil }
go
func dialDHTxxAndGetResponse(pin int, handshakeDur time.Duration, boostPerfFlag bool) ([]Pulse, error) { var arr *C.int32_t var arrLen C.int32_t var list []int32 var hsDurUsec C.int32_t = C.int32_t(handshakeDur / time.Microsecond) var boost C.int32_t = 0 var err2 *C.Error if boostPerfFlag { boost = 1 } // return array: [pulse, duration, pulse, duration, ...] r := C.dial_DHTxx_and_read(C.int32_t(pin), hsDurUsec, boost, &arr, &arrLen, &err2) if r == -1 { var err error if err2 != nil { msg := C.GoString(err2.message) err = errors.New(spew.Sprintf("Error during call C.dial_DHTxx_and_read(): %v", msg)) C.free_error(err2) } else { err = errors.New(spew.Sprintf("Error during call C.dial_DHTxx_and_read()")) } return nil, err } defer C.free(unsafe.Pointer(arr)) // convert original C array arr to Go slice list h := (*reflect.SliceHeader)(unsafe.Pointer(&list)) h.Data = uintptr(unsafe.Pointer(arr)) h.Len = int(arrLen) h.Cap = int(arrLen) pulses := make([]Pulse, len(list)/2) // convert original int array ([pulse, duration, pulse, duration, ...]) // to Pulse struct array for i := 0; i < len(list)/2; i++ { var value byte = 0 if list[i*2] != 0 { value = 1 } pulses[i] = Pulse{Value: value, Duration: time.Duration(list[i*2+1]) * time.Microsecond} } return pulses, nil }
[ "func", "dialDHTxxAndGetResponse", "(", "pin", "int", ",", "handshakeDur", "time", ".", "Duration", ",", "boostPerfFlag", "bool", ")", "(", "[", "]", "Pulse", ",", "error", ")", "{", "var", "arr", "*", "C", ".", "int32_t", "\n", "var", "arrLen", "C", ".", "int32_t", "\n", "var", "list", "[", "]", "int32", "\n", "var", "hsDurUsec", "C", ".", "int32_t", "=", "C", ".", "int32_t", "(", "handshakeDur", "/", "time", ".", "Microsecond", ")", "\n", "var", "boost", "C", ".", "int32_t", "=", "0", "\n", "var", "err2", "*", "C", ".", "Error", "\n", "if", "boostPerfFlag", "{", "boost", "=", "1", "\n", "}", "\n", "// return array: [pulse, duration, pulse, duration, ...]", "r", ":=", "C", ".", "dial_DHTxx_and_read", "(", "C", ".", "int32_t", "(", "pin", ")", ",", "hsDurUsec", ",", "boost", ",", "&", "arr", ",", "&", "arrLen", ",", "&", "err2", ")", "\n", "if", "r", "==", "-", "1", "{", "var", "err", "error", "\n", "if", "err2", "!=", "nil", "{", "msg", ":=", "C", ".", "GoString", "(", "err2", ".", "message", ")", "\n", "err", "=", "errors", ".", "New", "(", "spew", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ")", ")", "\n", "C", ".", "free_error", "(", "err2", ")", "\n", "}", "else", "{", "err", "=", "errors", ".", "New", "(", "spew", ".", "Sprintf", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "arr", ")", ")", "\n", "// convert original C array arr to Go slice list", "h", ":=", "(", "*", "reflect", ".", "SliceHeader", ")", "(", "unsafe", ".", "Pointer", "(", "&", "list", ")", ")", "\n", "h", ".", "Data", "=", "uintptr", "(", "unsafe", ".", "Pointer", "(", "arr", ")", ")", "\n", "h", ".", "Len", "=", "int", "(", "arrLen", ")", "\n", "h", ".", "Cap", "=", "int", "(", "arrLen", ")", "\n", "pulses", ":=", "make", "(", "[", "]", "Pulse", ",", "len", "(", "list", ")", "/", "2", ")", "\n", "// convert original int array ([pulse, duration, pulse, duration, ...])", "// to Pulse struct array", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", "/", "2", ";", "i", "++", "{", "var", "value", "byte", "=", "0", "\n", "if", "list", "[", "i", "*", "2", "]", "!=", "0", "{", "value", "=", "1", "\n", "}", "\n", "pulses", "[", "i", "]", "=", "Pulse", "{", "Value", ":", "value", ",", "Duration", ":", "time", ".", "Duration", "(", "list", "[", "i", "*", "2", "+", "1", "]", ")", "*", "time", ".", "Microsecond", "}", "\n", "}", "\n", "return", "pulses", ",", "nil", "\n", "}" ]
// Activate sensor and get back bunch of pulses for further decoding. // C function call wrapper.
[ "Activate", "sensor", "and", "get", "back", "bunch", "of", "pulses", "for", "further", "decoding", ".", "C", "function", "call", "wrapper", "." ]
b6103ae97a4b34d2876c04261ed37fce8cbbcc2d
https://github.com/d2r2/go-dht/blob/b6103ae97a4b34d2876c04261ed37fce8cbbcc2d/dht.go#L96-L140
18,156
d2r2/go-dht
dht.go
decodeByte
func decodeByte(tLow, tHigh0, tHigh1 time.Duration, start int, pulses []Pulse) (byte, error) { if len(pulses)-start < 16 { return 0, fmt.Errorf("Can't decode byte, since range between "+ "index and array length is less than 16: %d, %d", start, len(pulses)) } HIGH_DUR_MAX := tLow + tHigh1 HIGH_LOW_DUR_AVG := ((tLow+tHigh1)/2 + (tLow+tHigh0)/2) / 2 var b int = 0 for i := 0; i < 8; i++ { pulseL := pulses[start+i*2] pulseH := pulses[start+i*2+1] if pulseL.Value != 0 { return 0, fmt.Errorf("Low edge value expected at index %d", start+i*2) } if pulseH.Value == 0 { return 0, fmt.Errorf("High edge value expected at index %d", start+i*2+1) } // const HIGH_DUR_MAX = (70 + (70 + 54)) / 2 * time.Microsecond // Calc average value between 24us (bit 0) and 70us (bit 1). // Everything that less than this param is bit 0, bigger - bit 1. // const HIGH_LOW_DUR_AVG = (24 + (70-24)/2) * time.Microsecond if pulseH.Duration > HIGH_DUR_MAX { return 0, fmt.Errorf("High edge value duration %v exceed "+ "maximum expected %v", pulseH.Duration, HIGH_DUR_MAX) } if pulseH.Duration > HIGH_LOW_DUR_AVG { //fmt.Printf("bit %d is high\n", 7-i) b = b | (1 << uint(7-i)) } } return byte(b), nil }
go
func decodeByte(tLow, tHigh0, tHigh1 time.Duration, start int, pulses []Pulse) (byte, error) { if len(pulses)-start < 16 { return 0, fmt.Errorf("Can't decode byte, since range between "+ "index and array length is less than 16: %d, %d", start, len(pulses)) } HIGH_DUR_MAX := tLow + tHigh1 HIGH_LOW_DUR_AVG := ((tLow+tHigh1)/2 + (tLow+tHigh0)/2) / 2 var b int = 0 for i := 0; i < 8; i++ { pulseL := pulses[start+i*2] pulseH := pulses[start+i*2+1] if pulseL.Value != 0 { return 0, fmt.Errorf("Low edge value expected at index %d", start+i*2) } if pulseH.Value == 0 { return 0, fmt.Errorf("High edge value expected at index %d", start+i*2+1) } // const HIGH_DUR_MAX = (70 + (70 + 54)) / 2 * time.Microsecond // Calc average value between 24us (bit 0) and 70us (bit 1). // Everything that less than this param is bit 0, bigger - bit 1. // const HIGH_LOW_DUR_AVG = (24 + (70-24)/2) * time.Microsecond if pulseH.Duration > HIGH_DUR_MAX { return 0, fmt.Errorf("High edge value duration %v exceed "+ "maximum expected %v", pulseH.Duration, HIGH_DUR_MAX) } if pulseH.Duration > HIGH_LOW_DUR_AVG { //fmt.Printf("bit %d is high\n", 7-i) b = b | (1 << uint(7-i)) } } return byte(b), nil }
[ "func", "decodeByte", "(", "tLow", ",", "tHigh0", ",", "tHigh1", "time", ".", "Duration", ",", "start", "int", ",", "pulses", "[", "]", "Pulse", ")", "(", "byte", ",", "error", ")", "{", "if", "len", "(", "pulses", ")", "-", "start", "<", "16", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "start", ",", "len", "(", "pulses", ")", ")", "\n", "}", "\n", "HIGH_DUR_MAX", ":=", "tLow", "+", "tHigh1", "\n", "HIGH_LOW_DUR_AVG", ":=", "(", "(", "tLow", "+", "tHigh1", ")", "/", "2", "+", "(", "tLow", "+", "tHigh0", ")", "/", "2", ")", "/", "2", "\n", "var", "b", "int", "=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "8", ";", "i", "++", "{", "pulseL", ":=", "pulses", "[", "start", "+", "i", "*", "2", "]", "\n", "pulseH", ":=", "pulses", "[", "start", "+", "i", "*", "2", "+", "1", "]", "\n", "if", "pulseL", ".", "Value", "!=", "0", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "start", "+", "i", "*", "2", ")", "\n", "}", "\n", "if", "pulseH", ".", "Value", "==", "0", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "start", "+", "i", "*", "2", "+", "1", ")", "\n", "}", "\n", "// const HIGH_DUR_MAX = (70 + (70 + 54)) / 2 * time.Microsecond", "// Calc average value between 24us (bit 0) and 70us (bit 1).", "// Everything that less than this param is bit 0, bigger - bit 1.", "// const HIGH_LOW_DUR_AVG = (24 + (70-24)/2) * time.Microsecond", "if", "pulseH", ".", "Duration", ">", "HIGH_DUR_MAX", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "pulseH", ".", "Duration", ",", "HIGH_DUR_MAX", ")", "\n", "}", "\n", "if", "pulseH", ".", "Duration", ">", "HIGH_LOW_DUR_AVG", "{", "//fmt.Printf(\"bit %d is high\\n\", 7-i)", "b", "=", "b", "|", "(", "1", "<<", "uint", "(", "7", "-", "i", ")", ")", "\n", "}", "\n", "}", "\n", "return", "byte", "(", "b", ")", ",", "nil", "\n", "}" ]
// decodeByte decode data byte from specific pulse array position.
[ "decodeByte", "decode", "data", "byte", "from", "specific", "pulse", "array", "position", "." ]
b6103ae97a4b34d2876c04261ed37fce8cbbcc2d
https://github.com/d2r2/go-dht/blob/b6103ae97a4b34d2876c04261ed37fce8cbbcc2d/dht.go#L143-L174
18,157
sebest/xff
xff.go
toMasks
func toMasks(ips []string) (masks []net.IPNet, err error) { for _, cidr := range ips { var network *net.IPNet _, network, err = net.ParseCIDR(cidr) if err != nil { return } masks = append(masks, *network) } return }
go
func toMasks(ips []string) (masks []net.IPNet, err error) { for _, cidr := range ips { var network *net.IPNet _, network, err = net.ParseCIDR(cidr) if err != nil { return } masks = append(masks, *network) } return }
[ "func", "toMasks", "(", "ips", "[", "]", "string", ")", "(", "masks", "[", "]", "net", ".", "IPNet", ",", "err", "error", ")", "{", "for", "_", ",", "cidr", ":=", "range", "ips", "{", "var", "network", "*", "net", ".", "IPNet", "\n", "_", ",", "network", ",", "err", "=", "net", ".", "ParseCIDR", "(", "cidr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "masks", "=", "append", "(", "masks", ",", "*", "network", ")", "\n", "}", "\n", "return", "\n", "}" ]
// converts a list of subnets' string to a list of net.IPNet.
[ "converts", "a", "list", "of", "subnets", "string", "to", "a", "list", "of", "net", ".", "IPNet", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L21-L31
18,158
sebest/xff
xff.go
ipInMasks
func ipInMasks(ip net.IP, masks []net.IPNet) bool { for _, mask := range masks { if mask.Contains(ip) { return true } } return false }
go
func ipInMasks(ip net.IP, masks []net.IPNet) bool { for _, mask := range masks { if mask.Contains(ip) { return true } } return false }
[ "func", "ipInMasks", "(", "ip", "net", ".", "IP", ",", "masks", "[", "]", "net", ".", "IPNet", ")", "bool", "{", "for", "_", ",", "mask", ":=", "range", "masks", "{", "if", "mask", ".", "Contains", "(", "ip", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// checks if a net.IP is in a list of net.IPNet
[ "checks", "if", "a", "net", ".", "IP", "is", "in", "a", "list", "of", "net", ".", "IPNet" ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L34-L41
18,159
sebest/xff
xff.go
IsPublicIP
func IsPublicIP(ip net.IP) bool { if !ip.IsGlobalUnicast() { return false } return !ipInMasks(ip, privateMasks) }
go
func IsPublicIP(ip net.IP) bool { if !ip.IsGlobalUnicast() { return false } return !ipInMasks(ip, privateMasks) }
[ "func", "IsPublicIP", "(", "ip", "net", ".", "IP", ")", "bool", "{", "if", "!", "ip", ".", "IsGlobalUnicast", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "!", "ipInMasks", "(", "ip", ",", "privateMasks", ")", "\n", "}" ]
// IsPublicIP returns true if the given IP can be routed on the Internet.
[ "IsPublicIP", "returns", "true", "if", "the", "given", "IP", "can", "be", "routed", "on", "the", "Internet", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L44-L49
18,160
sebest/xff
xff.go
Parse
func Parse(ipList string) string { for _, ip := range strings.Split(ipList, ",") { ip = strings.TrimSpace(ip) if IP := net.ParseIP(ip); IP != nil && IsPublicIP(IP) { return ip } } return "" }
go
func Parse(ipList string) string { for _, ip := range strings.Split(ipList, ",") { ip = strings.TrimSpace(ip) if IP := net.ParseIP(ip); IP != nil && IsPublicIP(IP) { return ip } } return "" }
[ "func", "Parse", "(", "ipList", "string", ")", "string", "{", "for", "_", ",", "ip", ":=", "range", "strings", ".", "Split", "(", "ipList", ",", "\"", "\"", ")", "{", "ip", "=", "strings", ".", "TrimSpace", "(", "ip", ")", "\n", "if", "IP", ":=", "net", ".", "ParseIP", "(", "ip", ")", ";", "IP", "!=", "nil", "&&", "IsPublicIP", "(", "IP", ")", "{", "return", "ip", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Parse parses the value of the X-Forwarded-For Header and returns the IP address.
[ "Parse", "parses", "the", "value", "of", "the", "X", "-", "Forwarded", "-", "For", "Header", "and", "returns", "the", "IP", "address", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L52-L60
18,161
sebest/xff
xff.go
GetRemoteAddr
func GetRemoteAddr(r *http.Request) string { return GetRemoteAddrIfAllowed(r, func(sip string) bool { return true }) }
go
func GetRemoteAddr(r *http.Request) string { return GetRemoteAddrIfAllowed(r, func(sip string) bool { return true }) }
[ "func", "GetRemoteAddr", "(", "r", "*", "http", ".", "Request", ")", "string", "{", "return", "GetRemoteAddrIfAllowed", "(", "r", ",", "func", "(", "sip", "string", ")", "bool", "{", "return", "true", "}", ")", "\n", "}" ]
// GetRemoteAddr parses the given request, resolves the X-Forwarded-For header // and returns the resolved remote address.
[ "GetRemoteAddr", "parses", "the", "given", "request", "resolves", "the", "X", "-", "Forwarded", "-", "For", "header", "and", "returns", "the", "resolved", "remote", "address", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L64-L66
18,162
sebest/xff
xff.go
GetRemoteAddrIfAllowed
func GetRemoteAddrIfAllowed(r *http.Request, allowed func(sip string) bool) string { if xffh := r.Header.Get("X-Forwarded-For"); xffh != "" { if sip, sport, err := net.SplitHostPort(r.RemoteAddr); err == nil && sip != "" { if allowed(sip) { if xip := Parse(xffh); xip != "" { return net.JoinHostPort(xip, sport) } } } } return r.RemoteAddr }
go
func GetRemoteAddrIfAllowed(r *http.Request, allowed func(sip string) bool) string { if xffh := r.Header.Get("X-Forwarded-For"); xffh != "" { if sip, sport, err := net.SplitHostPort(r.RemoteAddr); err == nil && sip != "" { if allowed(sip) { if xip := Parse(xffh); xip != "" { return net.JoinHostPort(xip, sport) } } } } return r.RemoteAddr }
[ "func", "GetRemoteAddrIfAllowed", "(", "r", "*", "http", ".", "Request", ",", "allowed", "func", "(", "sip", "string", ")", "bool", ")", "string", "{", "if", "xffh", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "xffh", "!=", "\"", "\"", "{", "if", "sip", ",", "sport", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "r", ".", "RemoteAddr", ")", ";", "err", "==", "nil", "&&", "sip", "!=", "\"", "\"", "{", "if", "allowed", "(", "sip", ")", "{", "if", "xip", ":=", "Parse", "(", "xffh", ")", ";", "xip", "!=", "\"", "\"", "{", "return", "net", ".", "JoinHostPort", "(", "xip", ",", "sport", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "r", ".", "RemoteAddr", "\n", "}" ]
// GetRemoteAddrIfAllowed parses the given request, resolves the X-Forwarded-For header // and returns the resolved remote address if allowed.
[ "GetRemoteAddrIfAllowed", "parses", "the", "given", "request", "resolves", "the", "X", "-", "Forwarded", "-", "For", "header", "and", "returns", "the", "resolved", "remote", "address", "if", "allowed", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L70-L81
18,163
sebest/xff
xff.go
New
func New(options Options) (*XFF, error) { allowedMasks, err := toMasks(options.AllowedSubnets) if err != nil { return nil, err } xff := &XFF{ allowAll: len(options.AllowedSubnets) == 0, allowedMasks: allowedMasks, } if options.Debug { xff.Log = log.New(os.Stdout, "[xff] ", log.LstdFlags) } return xff, nil }
go
func New(options Options) (*XFF, error) { allowedMasks, err := toMasks(options.AllowedSubnets) if err != nil { return nil, err } xff := &XFF{ allowAll: len(options.AllowedSubnets) == 0, allowedMasks: allowedMasks, } if options.Debug { xff.Log = log.New(os.Stdout, "[xff] ", log.LstdFlags) } return xff, nil }
[ "func", "New", "(", "options", "Options", ")", "(", "*", "XFF", ",", "error", ")", "{", "allowedMasks", ",", "err", ":=", "toMasks", "(", "options", ".", "AllowedSubnets", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "xff", ":=", "&", "XFF", "{", "allowAll", ":", "len", "(", "options", ".", "AllowedSubnets", ")", "==", "0", ",", "allowedMasks", ":", "allowedMasks", ",", "}", "\n", "if", "options", ".", "Debug", "{", "xff", ".", "Log", "=", "log", ".", "New", "(", "os", ".", "Stdout", ",", "\"", "\"", ",", "log", ".", "LstdFlags", ")", "\n", "}", "\n", "return", "xff", ",", "nil", "\n", "}" ]
// New creates a new XFF handler with the provided options.
[ "New", "creates", "a", "new", "XFF", "handler", "with", "the", "provided", "options", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L104-L117
18,164
sebest/xff
xff.go
Handler
func (xff *XFF) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.RemoteAddr = GetRemoteAddrIfAllowed(r, xff.allowed) h.ServeHTTP(w, r) }) }
go
func (xff *XFF) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.RemoteAddr = GetRemoteAddrIfAllowed(r, xff.allowed) h.ServeHTTP(w, r) }) }
[ "func", "(", "xff", "*", "XFF", ")", "Handler", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "r", ".", "RemoteAddr", "=", "GetRemoteAddrIfAllowed", "(", "r", ",", "xff", ".", "allowed", ")", "\n", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// Handler updates RemoteAdd from X-Fowarded-For Headers.
[ "Handler", "updates", "RemoteAdd", "from", "X", "-", "Fowarded", "-", "For", "Headers", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L125-L130
18,165
sebest/xff
xff.go
ServeHTTP
func (xff *XFF) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { r.RemoteAddr = GetRemoteAddrIfAllowed(r, xff.allowed) next(w, r) }
go
func (xff *XFF) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { r.RemoteAddr = GetRemoteAddrIfAllowed(r, xff.allowed) next(w, r) }
[ "func", "(", "xff", "*", "XFF", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "next", "http", ".", "HandlerFunc", ")", "{", "r", ".", "RemoteAddr", "=", "GetRemoteAddrIfAllowed", "(", "r", ",", "xff", ".", "allowed", ")", "\n", "next", "(", "w", ",", "r", ")", "\n", "}" ]
// Negroni compatible interface
[ "Negroni", "compatible", "interface" ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L133-L136
18,166
sebest/xff
xff.go
allowed
func (xff *XFF) allowed(sip string) bool { if xff.allowAll { return true } else if ip := net.ParseIP(sip); ip != nil && ipInMasks(ip, xff.allowedMasks) { return true } return false }
go
func (xff *XFF) allowed(sip string) bool { if xff.allowAll { return true } else if ip := net.ParseIP(sip); ip != nil && ipInMasks(ip, xff.allowedMasks) { return true } return false }
[ "func", "(", "xff", "*", "XFF", ")", "allowed", "(", "sip", "string", ")", "bool", "{", "if", "xff", ".", "allowAll", "{", "return", "true", "\n", "}", "else", "if", "ip", ":=", "net", ".", "ParseIP", "(", "sip", ")", ";", "ip", "!=", "nil", "&&", "ipInMasks", "(", "ip", ",", "xff", ".", "allowedMasks", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// checks that the IP is allowed.
[ "checks", "that", "the", "IP", "is", "allowed", "." ]
6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f
https://github.com/sebest/xff/blob/6c115e0ffa35d6a2e3f7a9e797c9cf07f0da4b9f/xff.go#L144-L151
18,167
emicklei/forest
error_color.go
Errorf
func Errorf(t *testing.T, format string, args ...interface{}) { t.Error(Scolorf(ErrorColorSyntaxCode, format, args...)) }
go
func Errorf(t *testing.T, format string, args ...interface{}) { t.Error(Scolorf(ErrorColorSyntaxCode, format, args...)) }
[ "func", "Errorf", "(", "t", "*", "testing", ".", "T", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "t", ".", "Error", "(", "Scolorf", "(", "ErrorColorSyntaxCode", ",", "format", ",", "args", "...", ")", ")", "\n", "}" ]
// Errorf calls Error on t with a colorized message
[ "Errorf", "calls", "Error", "on", "t", "with", "a", "colorized", "message" ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/error_color.go#L54-L56
18,168
emicklei/forest
error_color.go
Fatalf
func Fatalf(t *testing.T, format string, args ...interface{}) { t.Fatal(Scolorf(FatalColorSyntaxCode, format, args...)) }
go
func Fatalf(t *testing.T, format string, args ...interface{}) { t.Fatal(Scolorf(FatalColorSyntaxCode, format, args...)) }
[ "func", "Fatalf", "(", "t", "*", "testing", ".", "T", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "t", ".", "Fatal", "(", "Scolorf", "(", "FatalColorSyntaxCode", ",", "format", ",", "args", "...", ")", ")", "\n", "}" ]
// Fatalf calls Fatal on t with a colorized message
[ "Fatalf", "calls", "Fatal", "on", "t", "with", "a", "colorized", "message" ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/error_color.go#L59-L61
18,169
emicklei/forest
helpers.go
Dump
func Dump(t T, resp *http.Response) { // dump request var buffer bytes.Buffer buffer.WriteString("\n") buffer.WriteString(fmt.Sprintf("%v %v\n", resp.Request.Method, resp.Request.URL)) for k, v := range resp.Request.Header { if IsMaskedHeader(k) { v = []string{strings.Repeat(MaskChar, len(v[0]))} } if len(k) > 0 { buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ","))) } } // dump request payload, only available is there is a Body. if resp != nil && resp.Request != nil && resp.Request.Body != nil { rc, err := resp.Request.GetBody() body, err := ioutil.ReadAll(rc) if err != nil { buffer.WriteString(fmt.Sprintf("unable to read request body:%v", err)) } else { if len(body) > 0 { buffer.WriteString("\n") } buffer.WriteString(string(body)) buffer.WriteString("\n") } } // dump response payload if resp == nil { buffer.WriteString("-- no response --") Logf(t, buffer.String()) return } buffer.WriteString(fmt.Sprintf("\n%s\n", resp.Status)) for k, v := range resp.Header { if len(k) > 0 { buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ","))) } } if resp.Body != nil { body, err := ioutil.ReadAll(resp.Body) if err != nil { if resp.StatusCode/100 == 3 { // redirect closes body ; nothing to read buffer.WriteString("\n") } else { buffer.WriteString(fmt.Sprintf("unable to read response body:%v", err)) } } else { if len(body) > 0 { buffer.WriteString("\n") } buffer.WriteString(string(body)) } resp.Body.Close() // put the body back for re-reads resp.Body = ioutil.NopCloser(bytes.NewReader(body)) } buffer.WriteString("\n") Logf(t, buffer.String()) }
go
func Dump(t T, resp *http.Response) { // dump request var buffer bytes.Buffer buffer.WriteString("\n") buffer.WriteString(fmt.Sprintf("%v %v\n", resp.Request.Method, resp.Request.URL)) for k, v := range resp.Request.Header { if IsMaskedHeader(k) { v = []string{strings.Repeat(MaskChar, len(v[0]))} } if len(k) > 0 { buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ","))) } } // dump request payload, only available is there is a Body. if resp != nil && resp.Request != nil && resp.Request.Body != nil { rc, err := resp.Request.GetBody() body, err := ioutil.ReadAll(rc) if err != nil { buffer.WriteString(fmt.Sprintf("unable to read request body:%v", err)) } else { if len(body) > 0 { buffer.WriteString("\n") } buffer.WriteString(string(body)) buffer.WriteString("\n") } } // dump response payload if resp == nil { buffer.WriteString("-- no response --") Logf(t, buffer.String()) return } buffer.WriteString(fmt.Sprintf("\n%s\n", resp.Status)) for k, v := range resp.Header { if len(k) > 0 { buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ","))) } } if resp.Body != nil { body, err := ioutil.ReadAll(resp.Body) if err != nil { if resp.StatusCode/100 == 3 { // redirect closes body ; nothing to read buffer.WriteString("\n") } else { buffer.WriteString(fmt.Sprintf("unable to read response body:%v", err)) } } else { if len(body) > 0 { buffer.WriteString("\n") } buffer.WriteString(string(body)) } resp.Body.Close() // put the body back for re-reads resp.Body = ioutil.NopCloser(bytes.NewReader(body)) } buffer.WriteString("\n") Logf(t, buffer.String()) }
[ "func", "Dump", "(", "t", "T", ",", "resp", "*", "http", ".", "Response", ")", "{", "// dump request", "var", "buffer", "bytes", ".", "Buffer", "\n", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "resp", ".", "Request", ".", "Method", ",", "resp", ".", "Request", ".", "URL", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "resp", ".", "Request", ".", "Header", "{", "if", "IsMaskedHeader", "(", "k", ")", "{", "v", "=", "[", "]", "string", "{", "strings", ".", "Repeat", "(", "MaskChar", ",", "len", "(", "v", "[", "0", "]", ")", ")", "}", "\n", "}", "\n", "if", "len", "(", "k", ")", ">", "0", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "k", ",", "strings", ".", "Join", "(", "v", ",", "\"", "\"", ")", ")", ")", "\n", "}", "\n", "}", "\n", "// dump request payload, only available is there is a Body.", "if", "resp", "!=", "nil", "&&", "resp", ".", "Request", "!=", "nil", "&&", "resp", ".", "Request", ".", "Body", "!=", "nil", "{", "rc", ",", "err", ":=", "resp", ".", "Request", ".", "GetBody", "(", ")", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "rc", ")", "\n", "if", "err", "!=", "nil", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "else", "{", "if", "len", "(", "body", ")", ">", "0", "{", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "string", "(", "body", ")", ")", "\n", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "}", "\n", "// dump response payload", "if", "resp", "==", "nil", "{", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "Logf", "(", "t", ",", "buffer", ".", "String", "(", ")", ")", "\n", "return", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "resp", ".", "Status", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "resp", ".", "Header", "{", "if", "len", "(", "k", ")", ">", "0", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "k", ",", "strings", ".", "Join", "(", "v", ",", "\"", "\"", ")", ")", ")", "\n", "}", "\n", "}", "\n", "if", "resp", ".", "Body", "!=", "nil", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "/", "100", "==", "3", "{", "// redirect closes body ; nothing to read", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "else", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "}", "else", "{", "if", "len", "(", "body", ")", ">", "0", "{", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "string", "(", "body", ")", ")", "\n", "}", "\n", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "// put the body back for re-reads", "resp", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "body", ")", ")", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "Logf", "(", "t", ",", "buffer", ".", "String", "(", ")", ")", "\n", "}" ]
// Dump is a convenient method to log the full contents of a request and its response.
[ "Dump", "is", "a", "convenient", "method", "to", "log", "the", "full", "contents", "of", "a", "request", "and", "its", "response", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/helpers.go#L34-L94
18,170
emicklei/forest
helpers.go
SkipUnless
func SkipUnless(t skippeable, labels ...string) { env := strings.Split(os.Getenv("LABELS"), ",") for _, each := range labels { for _, other := range env { if each == other { return } } } t.Skipf("skipped because provided LABELS=%v does not include any of %v", env, labels) }
go
func SkipUnless(t skippeable, labels ...string) { env := strings.Split(os.Getenv("LABELS"), ",") for _, each := range labels { for _, other := range env { if each == other { return } } } t.Skipf("skipped because provided LABELS=%v does not include any of %v", env, labels) }
[ "func", "SkipUnless", "(", "t", "skippeable", ",", "labels", "...", "string", ")", "{", "env", ":=", "strings", ".", "Split", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "for", "_", ",", "each", ":=", "range", "labels", "{", "for", "_", ",", "other", ":=", "range", "env", "{", "if", "each", "==", "other", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "t", ".", "Skipf", "(", "\"", "\"", ",", "env", ",", "labels", ")", "\n", "}" ]
// SkipUnless will Skip the test unless the LABELS environment variable includes any of the provided labels. // // LABELS=integration,nightly go test -v //
[ "SkipUnless", "will", "Skip", "the", "test", "unless", "the", "LABELS", "environment", "variable", "includes", "any", "of", "the", "provided", "labels", ".", "LABELS", "=", "integration", "nightly", "go", "test", "-", "v" ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/helpers.go#L104-L114
18,171
emicklei/forest
logger.go
Logf
func (l Logger) Logf(format string, args ...interface{}) { if l.InfoEnabled { LoggingPrintf("\tinfo : "+tabify(format)+"\n", args...) } }
go
func (l Logger) Logf(format string, args ...interface{}) { if l.InfoEnabled { LoggingPrintf("\tinfo : "+tabify(format)+"\n", args...) } }
[ "func", "(", "l", "Logger", ")", "Logf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "l", ".", "InfoEnabled", "{", "LoggingPrintf", "(", "\"", "\\t", "\"", "+", "tabify", "(", "format", ")", "+", "\"", "\\n", "\"", ",", "args", "...", ")", "\n", "}", "\n", "}" ]
// Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log. // The text will be printed only if the test fails or the -test.v flag is set.
[ "Logf", "formats", "its", "arguments", "according", "to", "the", "format", "analogous", "to", "Printf", "and", "records", "the", "text", "in", "the", "error", "log", ".", "The", "text", "will", "be", "printed", "only", "if", "the", "test", "fails", "or", "the", "-", "test", ".", "v", "flag", "is", "set", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/logger.go#L18-L22
18,172
emicklei/forest
logger.go
Fatal
func (l Logger) Fatal(args ...interface{}) { if l.ErrorEnabled { LoggingPrintf("\tfatal: "+tabify("%s")+"\n", args...) } if l.ExitOnFatal { os.Exit(1) } }
go
func (l Logger) Fatal(args ...interface{}) { if l.ErrorEnabled { LoggingPrintf("\tfatal: "+tabify("%s")+"\n", args...) } if l.ExitOnFatal { os.Exit(1) } }
[ "func", "(", "l", "Logger", ")", "Fatal", "(", "args", "...", "interface", "{", "}", ")", "{", "if", "l", ".", "ErrorEnabled", "{", "LoggingPrintf", "(", "\"", "\\t", "\"", "+", "tabify", "(", "\"", "\"", ")", "+", "\"", "\\n", "\"", ",", "args", "...", ")", "\n", "}", "\n", "if", "l", ".", "ExitOnFatal", "{", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}" ]
// Fatal is equivalent to Log followed by FailNow.
[ "Fatal", "is", "equivalent", "to", "Log", "followed", "by", "FailNow", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/logger.go#L32-L39
18,173
emicklei/forest
expectations.go
CheckError
func CheckError(t T, err error) bool { if err != nil { logerror(t, serrorf("CheckError: did not expect to receive err: %v", err)) } return err != nil }
go
func CheckError(t T, err error) bool { if err != nil { logerror(t, serrorf("CheckError: did not expect to receive err: %v", err)) } return err != nil }
[ "func", "CheckError", "(", "t", "T", ",", "err", "error", ")", "bool", "{", "if", "err", "!=", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "err", "!=", "nil", "\n", "}" ]
// CheckError simply tests the error and fail is not undefined. // This is implicity called after sending a Http request. // Return true if there was an error.
[ "CheckError", "simply", "tests", "the", "error", "and", "fail", "is", "not", "undefined", ".", "This", "is", "implicity", "called", "after", "sending", "a", "Http", "request", ".", "Return", "true", "if", "there", "was", "an", "error", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/expectations.go#L40-L45
18,174
emicklei/forest
expectations.go
ExpectHeader
func ExpectHeader(t T, r *http.Response, name, value string) bool { if r == nil { logerror(t, serrorf("ExpectHeader: got nil but want a Http response")) return false } rname := r.Header.Get(name) if rname != value { logerror(t, serrorf("ExpectHeader: got header %s=%s but want %s", name, rname, value)) } return rname == value }
go
func ExpectHeader(t T, r *http.Response, name, value string) bool { if r == nil { logerror(t, serrorf("ExpectHeader: got nil but want a Http response")) return false } rname := r.Header.Get(name) if rname != value { logerror(t, serrorf("ExpectHeader: got header %s=%s but want %s", name, rname, value)) } return rname == value }
[ "func", "ExpectHeader", "(", "t", "T", ",", "r", "*", "http", ".", "Response", ",", "name", ",", "value", "string", ")", "bool", "{", "if", "r", "==", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ")", ")", "\n", "return", "false", "\n", "}", "\n", "rname", ":=", "r", ".", "Header", ".", "Get", "(", "name", ")", "\n", "if", "rname", "!=", "value", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ",", "name", ",", "rname", ",", "value", ")", ")", "\n", "}", "\n", "return", "rname", "==", "value", "\n", "}" ]
// ExpectHeader inspects the header of the response. // Return true if the header matches.
[ "ExpectHeader", "inspects", "the", "header", "of", "the", "response", ".", "Return", "true", "if", "the", "header", "matches", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/expectations.go#L49-L59
18,175
emicklei/forest
expectations.go
ExpectJSONHash
func ExpectJSONHash(t T, r *http.Response, callback func(hash map[string]interface{})) bool { if r == nil { logerror(t, serrorf("ExpectJSONHash: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectJSONHash: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONHash: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) dict := map[string]interface{}{} err = json.Unmarshal(data, &dict) if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONHash: unable to unmarshal Json:%v", err)) return false } callback(dict) return true }
go
func ExpectJSONHash(t T, r *http.Response, callback func(hash map[string]interface{})) bool { if r == nil { logerror(t, serrorf("ExpectJSONHash: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectJSONHash: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONHash: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) dict := map[string]interface{}{} err = json.Unmarshal(data, &dict) if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONHash: unable to unmarshal Json:%v", err)) return false } callback(dict) return true }
[ "func", "ExpectJSONHash", "(", "t", "T", ",", "r", "*", "http", ".", "Response", ",", "callback", "func", "(", "hash", "map", "[", "string", "]", "interface", "{", "}", ")", ")", "bool", "{", "if", "r", "==", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "r", ".", "Body", "==", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ")", ")", "\n", "return", "false", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "verboseOnFailure", "{", "Dump", "(", "t", ",", "r", ")", "\n", "}", "\n", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", "\n", "}", "\n", "// put the body back for re-reads", "r", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n\n", "dict", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "dict", ")", "\n", "if", "err", "!=", "nil", "{", "if", "verboseOnFailure", "{", "Dump", "(", "t", ",", "r", ")", "\n", "}", "\n", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", "\n", "}", "\n", "callback", "(", "dict", ")", "\n", "return", "true", "\n", "}" ]
// ExpectJSONHash tries to unmarshal the response body into a Go map callback parameter. // Fail if the body could not be read or if unmarshalling was not possible. // Returns true if the callback was executed with a map.
[ "ExpectJSONHash", "tries", "to", "unmarshal", "the", "response", "body", "into", "a", "Go", "map", "callback", "parameter", ".", "Fail", "if", "the", "body", "could", "not", "be", "read", "or", "if", "unmarshalling", "was", "not", "possible", ".", "Returns", "true", "if", "the", "callback", "was", "executed", "with", "a", "map", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/expectations.go#L64-L96
18,176
emicklei/forest
expectations.go
ExpectJSONArray
func ExpectJSONArray(t T, r *http.Response, callback func(array []interface{})) bool { if r == nil { logerror(t, serrorf("ExpectJSONArray: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectJSONArray: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONArray: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) slice := []interface{}{} err = json.Unmarshal(data, &slice) if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONArray: unable to unmarshal Json:%v", err)) return false } callback(slice) return true }
go
func ExpectJSONArray(t T, r *http.Response, callback func(array []interface{})) bool { if r == nil { logerror(t, serrorf("ExpectJSONArray: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectJSONArray: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONArray: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) slice := []interface{}{} err = json.Unmarshal(data, &slice) if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectJSONArray: unable to unmarshal Json:%v", err)) return false } callback(slice) return true }
[ "func", "ExpectJSONArray", "(", "t", "T", ",", "r", "*", "http", ".", "Response", ",", "callback", "func", "(", "array", "[", "]", "interface", "{", "}", ")", ")", "bool", "{", "if", "r", "==", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "r", ".", "Body", "==", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ")", ")", "\n", "return", "false", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "verboseOnFailure", "{", "Dump", "(", "t", ",", "r", ")", "\n", "}", "\n", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", "\n", "}", "\n", "// put the body back for re-reads", "r", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n\n", "slice", ":=", "[", "]", "interface", "{", "}", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "slice", ")", "\n", "if", "err", "!=", "nil", "{", "if", "verboseOnFailure", "{", "Dump", "(", "t", ",", "r", ")", "\n", "}", "\n", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", "\n", "}", "\n", "callback", "(", "slice", ")", "\n", "return", "true", "\n", "}" ]
// ExpectJSONArray tries to unmarshal the response body into a Go slice callback parameter. // Fail if the body could not be read or if unmarshalling was not possible. // Returns true if the callback was executed with an array.
[ "ExpectJSONArray", "tries", "to", "unmarshal", "the", "response", "body", "into", "a", "Go", "slice", "callback", "parameter", ".", "Fail", "if", "the", "body", "could", "not", "be", "read", "or", "if", "unmarshalling", "was", "not", "possible", ".", "Returns", "true", "if", "the", "callback", "was", "executed", "with", "an", "array", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/expectations.go#L101-L133
18,177
emicklei/forest
expectations.go
ExpectString
func ExpectString(t T, r *http.Response, callback func(content string)) bool { if r == nil { logerror(t, serrorf("ExpectString: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectString: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectString: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) callback(string(data)) return true }
go
func ExpectString(t T, r *http.Response, callback func(content string)) bool { if r == nil { logerror(t, serrorf("ExpectString: no response available")) return false } if r.Body == nil { logerror(t, serrorf("ExpectString: no body to read")) return false } data, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { if verboseOnFailure { Dump(t, r) } logerror(t, serrorf("ExpectString: unable to read response body:%v", err)) return false } // put the body back for re-reads r.Body = ioutil.NopCloser(bytes.NewReader(data)) callback(string(data)) return true }
[ "func", "ExpectString", "(", "t", "T", ",", "r", "*", "http", ".", "Response", ",", "callback", "func", "(", "content", "string", ")", ")", "bool", "{", "if", "r", "==", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "r", ".", "Body", "==", "nil", "{", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ")", ")", "\n", "return", "false", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "defer", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "verboseOnFailure", "{", "Dump", "(", "t", ",", "r", ")", "\n", "}", "\n", "logerror", "(", "t", ",", "serrorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "false", "\n", "}", "\n", "// put the body back for re-reads", "r", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n\n", "callback", "(", "string", "(", "data", ")", ")", "\n", "return", "true", "\n", "}" ]
// ExpectString reads the response body into a Go string callback parameter. // Fail if the body could not be read or unmarshalled. // Returns true if a response body was read.
[ "ExpectString", "reads", "the", "response", "body", "into", "a", "Go", "string", "callback", "parameter", ".", "Fail", "if", "the", "body", "could", "not", "be", "read", "or", "unmarshalled", ".", "Returns", "true", "if", "a", "response", "body", "was", "read", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/expectations.go#L138-L161
18,178
emicklei/forest
request_config.go
NewConfig
func NewConfig(pathTemplate string, pathParams ...interface{}) *RequestConfig { cfg := &RequestConfig{ HeaderMap: http.Header{}, Values: url.Values{}, } cfg.Path(pathTemplate, pathParams...) return cfg }
go
func NewConfig(pathTemplate string, pathParams ...interface{}) *RequestConfig { cfg := &RequestConfig{ HeaderMap: http.Header{}, Values: url.Values{}, } cfg.Path(pathTemplate, pathParams...) return cfg }
[ "func", "NewConfig", "(", "pathTemplate", "string", ",", "pathParams", "...", "interface", "{", "}", ")", "*", "RequestConfig", "{", "cfg", ":=", "&", "RequestConfig", "{", "HeaderMap", ":", "http", ".", "Header", "{", "}", ",", "Values", ":", "url", ".", "Values", "{", "}", ",", "}", "\n", "cfg", ".", "Path", "(", "pathTemplate", ",", "pathParams", "...", ")", "\n", "return", "cfg", "\n", "}" ]
// NewConfig returns a new RequestConfig with initialized empty headers and query parameters. // See Path for an explanation of the function parameters.
[ "NewConfig", "returns", "a", "new", "RequestConfig", "with", "initialized", "empty", "headers", "and", "query", "parameters", ".", "See", "Path", "for", "an", "explanation", "of", "the", "function", "parameters", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/request_config.go#L30-L37
18,179
emicklei/forest
request_config.go
Do
func (r *RequestConfig) Do(block func(config *RequestConfig)) *RequestConfig { block(r) return r }
go
func (r *RequestConfig) Do(block func(config *RequestConfig)) *RequestConfig { block(r) return r }
[ "func", "(", "r", "*", "RequestConfig", ")", "Do", "(", "block", "func", "(", "config", "*", "RequestConfig", ")", ")", "*", "RequestConfig", "{", "block", "(", "r", ")", "\n", "return", "r", "\n", "}" ]
// Do calls the one-argument function parameter with the receiver. // This allows for custom convenience functions without breaking the fluent programming style.
[ "Do", "calls", "the", "one", "-", "argument", "function", "parameter", "with", "the", "receiver", ".", "This", "allows", "for", "custom", "convenience", "functions", "without", "breaking", "the", "fluent", "programming", "style", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/request_config.go#L41-L44
18,180
emicklei/forest
request_config.go
Query
func (r *RequestConfig) Query(name string, value interface{}) *RequestConfig { r.Values.Add(name, fmt.Sprintf("%v", value)) return r }
go
func (r *RequestConfig) Query(name string, value interface{}) *RequestConfig { r.Values.Add(name, fmt.Sprintf("%v", value)) return r }
[ "func", "(", "r", "*", "RequestConfig", ")", "Query", "(", "name", "string", ",", "value", "interface", "{", "}", ")", "*", "RequestConfig", "{", "r", ".", "Values", ".", "Add", "(", "name", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "value", ")", ")", "\n", "return", "r", "\n", "}" ]
// Query adds a name=value pair to the list of query parameters.
[ "Query", "adds", "a", "name", "=", "value", "pair", "to", "the", "list", "of", "query", "parameters", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/request_config.go#L92-L95
18,181
emicklei/forest
request_config.go
Header
func (r *RequestConfig) Header(name, value string) *RequestConfig { r.HeaderMap.Add(name, value) return r }
go
func (r *RequestConfig) Header(name, value string) *RequestConfig { r.HeaderMap.Add(name, value) return r }
[ "func", "(", "r", "*", "RequestConfig", ")", "Header", "(", "name", ",", "value", "string", ")", "*", "RequestConfig", "{", "r", ".", "HeaderMap", ".", "Add", "(", "name", ",", "value", ")", "\n", "return", "r", "\n", "}" ]
// Header adds a name=value pair to the list of header parameters.
[ "Header", "adds", "a", "name", "=", "value", "pair", "to", "the", "list", "of", "header", "parameters", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/request_config.go#L98-L101
18,182
emicklei/forest
request_config.go
Body
func (r *RequestConfig) Body(body string) *RequestConfig { r.BodyReader = strings.NewReader(body) return r }
go
func (r *RequestConfig) Body(body string) *RequestConfig { r.BodyReader = strings.NewReader(body) return r }
[ "func", "(", "r", "*", "RequestConfig", ")", "Body", "(", "body", "string", ")", "*", "RequestConfig", "{", "r", ".", "BodyReader", "=", "strings", ".", "NewReader", "(", "body", ")", "\n", "return", "r", "\n", "}" ]
// Body sets the playload as is. No content type is set. // It sets the BodyReader field of the RequestConfig.
[ "Body", "sets", "the", "playload", "as", "is", ".", "No", "content", "type", "is", "set", ".", "It", "sets", "the", "BodyReader", "field", "of", "the", "RequestConfig", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/request_config.go#L105-L108
18,183
emicklei/forest
request_config.go
Read
func (r *RequestConfig) Read(bodyReader io.Reader) *RequestConfig { r.BodyReader = bodyReader return r }
go
func (r *RequestConfig) Read(bodyReader io.Reader) *RequestConfig { r.BodyReader = bodyReader return r }
[ "func", "(", "r", "*", "RequestConfig", ")", "Read", "(", "bodyReader", "io", ".", "Reader", ")", "*", "RequestConfig", "{", "r", ".", "BodyReader", "=", "bodyReader", "\n", "return", "r", "\n", "}" ]
// Read sets the BodyReader for content to send with the request.
[ "Read", "sets", "the", "BodyReader", "for", "content", "to", "send", "with", "the", "request", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/request_config.go#L165-L168
18,184
emicklei/forest
template.go
ProcessTemplate
func ProcessTemplate(t T, templateContent string, value interface{}) string { tmp, err := template.New("temporary").Parse(templateContent) if err != nil { logfatal(t, sfatalf("failed to parse:%v", err)) return "" } var buf bytes.Buffer err = tmp.Execute(&buf, value) if err != nil { logfatal(t, sfatalf("failed to execute template:%v", err)) return "" } return buf.String() }
go
func ProcessTemplate(t T, templateContent string, value interface{}) string { tmp, err := template.New("temporary").Parse(templateContent) if err != nil { logfatal(t, sfatalf("failed to parse:%v", err)) return "" } var buf bytes.Buffer err = tmp.Execute(&buf, value) if err != nil { logfatal(t, sfatalf("failed to execute template:%v", err)) return "" } return buf.String() }
[ "func", "ProcessTemplate", "(", "t", "T", ",", "templateContent", "string", ",", "value", "interface", "{", "}", ")", "string", "{", "tmp", ",", "err", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "templateContent", ")", "\n", "if", "err", "!=", "nil", "{", "logfatal", "(", "t", ",", "sfatalf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "err", "=", "tmp", ".", "Execute", "(", "&", "buf", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "logfatal", "(", "t", ",", "sfatalf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// ProcessTemplate creates a new text Template and executes it using the provided value. // Returns the string result of applying this template. // Failures in the template are reported using t.
[ "ProcessTemplate", "creates", "a", "new", "text", "Template", "and", "executes", "it", "using", "the", "provided", "value", ".", "Returns", "the", "string", "result", "of", "applying", "this", "template", ".", "Failures", "in", "the", "template", "are", "reported", "using", "t", "." ]
dc111550dbc4ef569b15c0766f1cd69a8c218f6d
https://github.com/emicklei/forest/blob/dc111550dbc4ef569b15c0766f1cd69a8c218f6d/template.go#L11-L24
18,185
subosito/twilio
util.go
structToMapString
func structToMapString(i interface{}) map[string][]string { ms := map[string][]string{} iv := reflect.ValueOf(i).Elem() tp := iv.Type() for i := 0; i < iv.NumField(); i++ { k := tp.Field(i).Name f := iv.Field(i) ms[k] = valueToString(f) } return ms }
go
func structToMapString(i interface{}) map[string][]string { ms := map[string][]string{} iv := reflect.ValueOf(i).Elem() tp := iv.Type() for i := 0; i < iv.NumField(); i++ { k := tp.Field(i).Name f := iv.Field(i) ms[k] = valueToString(f) } return ms }
[ "func", "structToMapString", "(", "i", "interface", "{", "}", ")", "map", "[", "string", "]", "[", "]", "string", "{", "ms", ":=", "map", "[", "string", "]", "[", "]", "string", "{", "}", "\n", "iv", ":=", "reflect", ".", "ValueOf", "(", "i", ")", ".", "Elem", "(", ")", "\n", "tp", ":=", "iv", ".", "Type", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "iv", ".", "NumField", "(", ")", ";", "i", "++", "{", "k", ":=", "tp", ".", "Field", "(", "i", ")", ".", "Name", "\n", "f", ":=", "iv", ".", "Field", "(", "i", ")", "\n", "ms", "[", "k", "]", "=", "valueToString", "(", "f", ")", "\n", "}", "\n\n", "return", "ms", "\n", "}" ]
// structToMapString converts struct as map string
[ "structToMapString", "converts", "struct", "as", "map", "string" ]
ef2f13504366093ed052627008181166612c646d
https://github.com/subosito/twilio/blob/ef2f13504366093ed052627008181166612c646d/util.go#L44-L56
18,186
subosito/twilio
util.go
valueToString
func valueToString(f reflect.Value) []string { var v []string switch reflect.TypeOf(f.Interface()).Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: v = []string{strconv.FormatInt(f.Int(), 10)} case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: v = []string{strconv.FormatUint(f.Uint(), 10)} case reflect.Float32: v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 32)} case reflect.Float64: v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 64)} case reflect.Bool: v = []string{strconv.FormatBool(f.Bool())} case reflect.Slice: for i := 0; i < f.Len(); i++ { if s := valueToString(f.Index(i)); len(s) == 1 { v = append(v, s[0]) } } case reflect.String: v = []string{f.String()} } return v }
go
func valueToString(f reflect.Value) []string { var v []string switch reflect.TypeOf(f.Interface()).Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: v = []string{strconv.FormatInt(f.Int(), 10)} case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: v = []string{strconv.FormatUint(f.Uint(), 10)} case reflect.Float32: v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 32)} case reflect.Float64: v = []string{strconv.FormatFloat(f.Float(), 'f', 4, 64)} case reflect.Bool: v = []string{strconv.FormatBool(f.Bool())} case reflect.Slice: for i := 0; i < f.Len(); i++ { if s := valueToString(f.Index(i)); len(s) == 1 { v = append(v, s[0]) } } case reflect.String: v = []string{f.String()} } return v }
[ "func", "valueToString", "(", "f", "reflect", ".", "Value", ")", "[", "]", "string", "{", "var", "v", "[", "]", "string", "\n\n", "switch", "reflect", ".", "TypeOf", "(", "f", ".", "Interface", "(", ")", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ":", "v", "=", "[", "]", "string", "{", "strconv", ".", "FormatInt", "(", "f", ".", "Int", "(", ")", ",", "10", ")", "}", "\n", "case", "reflect", ".", "Uint", ",", "reflect", ".", "Uint8", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ":", "v", "=", "[", "]", "string", "{", "strconv", ".", "FormatUint", "(", "f", ".", "Uint", "(", ")", ",", "10", ")", "}", "\n", "case", "reflect", ".", "Float32", ":", "v", "=", "[", "]", "string", "{", "strconv", ".", "FormatFloat", "(", "f", ".", "Float", "(", ")", ",", "'f'", ",", "4", ",", "32", ")", "}", "\n", "case", "reflect", ".", "Float64", ":", "v", "=", "[", "]", "string", "{", "strconv", ".", "FormatFloat", "(", "f", ".", "Float", "(", ")", ",", "'f'", ",", "4", ",", "64", ")", "}", "\n", "case", "reflect", ".", "Bool", ":", "v", "=", "[", "]", "string", "{", "strconv", ".", "FormatBool", "(", "f", ".", "Bool", "(", ")", ")", "}", "\n", "case", "reflect", ".", "Slice", ":", "for", "i", ":=", "0", ";", "i", "<", "f", ".", "Len", "(", ")", ";", "i", "++", "{", "if", "s", ":=", "valueToString", "(", "f", ".", "Index", "(", "i", ")", ")", ";", "len", "(", "s", ")", "==", "1", "{", "v", "=", "append", "(", "v", ",", "s", "[", "0", "]", ")", "\n", "}", "\n", "}", "\n", "case", "reflect", ".", "String", ":", "v", "=", "[", "]", "string", "{", "f", ".", "String", "(", ")", "}", "\n", "}", "\n\n", "return", "v", "\n", "}" ]
// valueToString converts supported type of f as slice string
[ "valueToString", "converts", "supported", "type", "of", "f", "as", "slice", "string" ]
ef2f13504366093ed052627008181166612c646d
https://github.com/subosito/twilio/blob/ef2f13504366093ed052627008181166612c646d/util.go#L59-L84
18,187
subosito/twilio
message.go
SendSMS
func (s *MessageService) SendSMS(from, to, body string) (*Message, *Response, error) { return s.Send(from, to, MessageParams{Body: body}) }
go
func (s *MessageService) SendSMS(from, to, body string) (*Message, *Response, error) { return s.Send(from, to, MessageParams{Body: body}) }
[ "func", "(", "s", "*", "MessageService", ")", "SendSMS", "(", "from", ",", "to", ",", "body", "string", ")", "(", "*", "Message", ",", "*", "Response", ",", "error", ")", "{", "return", "s", ".", "Send", "(", "from", ",", "to", ",", "MessageParams", "{", "Body", ":", "body", "}", ")", "\n", "}" ]
// Shortcut for sending SMS with no optional parameters support.
[ "Shortcut", "for", "sending", "SMS", "with", "no", "optional", "parameters", "support", "." ]
ef2f13504366093ed052627008181166612c646d
https://github.com/subosito/twilio/blob/ef2f13504366093ed052627008181166612c646d/message.go#L69-L71
18,188
subosito/twilio
client.go
NewClient
func NewClient(accountSid, authToken string, httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } baseURL, _ := url.Parse(apiBaseURL) c := &Client{ client: httpClient, UserAgent: userAgent, BaseURL: baseURL, AccountSid: accountSid, AuthToken: authToken, } c.Messages = &MessageService{client: c} return c }
go
func NewClient(accountSid, authToken string, httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } baseURL, _ := url.Parse(apiBaseURL) c := &Client{ client: httpClient, UserAgent: userAgent, BaseURL: baseURL, AccountSid: accountSid, AuthToken: authToken, } c.Messages = &MessageService{client: c} return c }
[ "func", "NewClient", "(", "accountSid", ",", "authToken", "string", ",", "httpClient", "*", "http", ".", "Client", ")", "*", "Client", "{", "if", "httpClient", "==", "nil", "{", "httpClient", "=", "http", ".", "DefaultClient", "\n", "}", "\n\n", "baseURL", ",", "_", ":=", "url", ".", "Parse", "(", "apiBaseURL", ")", "\n\n", "c", ":=", "&", "Client", "{", "client", ":", "httpClient", ",", "UserAgent", ":", "userAgent", ",", "BaseURL", ":", "baseURL", ",", "AccountSid", ":", "accountSid", ",", "AuthToken", ":", "authToken", ",", "}", "\n\n", "c", ".", "Messages", "=", "&", "MessageService", "{", "client", ":", "c", "}", "\n\n", "return", "c", "\n", "}" ]
// NewClient returns a new Twilio API client. This will load default http.Client if httpClient is nil.
[ "NewClient", "returns", "a", "new", "Twilio", "API", "client", ".", "This", "will", "load", "default", "http", ".", "Client", "if", "httpClient", "is", "nil", "." ]
ef2f13504366093ed052627008181166612c646d
https://github.com/subosito/twilio/blob/ef2f13504366093ed052627008181166612c646d/client.go#L32-L50
18,189
sassoftware/go-rpmutils
header.go
getInts
func (hdr *rpmHeader) getInts(tag int) (buf interface{}, n int, err error) { ent, ok := hdr.entries[tag] if !ok { return nil, 0, NewNoSuchTagError(tag) } n = len(ent.contents) switch ent.dataType { case RPM_INT8_TYPE: buf = make([]uint8, n) case RPM_INT16_TYPE: n >>= 1 buf = make([]uint16, n) case RPM_INT32_TYPE: n >>= 2 buf = make([]uint32, n) case RPM_INT64_TYPE: n >>= 3 buf = make([]uint64, n) default: return nil, 0, fmt.Errorf("tag %d isn't an int type", tag) } if err := binary.Read(bytes.NewReader(ent.contents), binary.BigEndian, buf); err != nil { return nil, 0, err } return }
go
func (hdr *rpmHeader) getInts(tag int) (buf interface{}, n int, err error) { ent, ok := hdr.entries[tag] if !ok { return nil, 0, NewNoSuchTagError(tag) } n = len(ent.contents) switch ent.dataType { case RPM_INT8_TYPE: buf = make([]uint8, n) case RPM_INT16_TYPE: n >>= 1 buf = make([]uint16, n) case RPM_INT32_TYPE: n >>= 2 buf = make([]uint32, n) case RPM_INT64_TYPE: n >>= 3 buf = make([]uint64, n) default: return nil, 0, fmt.Errorf("tag %d isn't an int type", tag) } if err := binary.Read(bytes.NewReader(ent.contents), binary.BigEndian, buf); err != nil { return nil, 0, err } return }
[ "func", "(", "hdr", "*", "rpmHeader", ")", "getInts", "(", "tag", "int", ")", "(", "buf", "interface", "{", "}", ",", "n", "int", ",", "err", "error", ")", "{", "ent", ",", "ok", ":=", "hdr", ".", "entries", "[", "tag", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "0", ",", "NewNoSuchTagError", "(", "tag", ")", "\n", "}", "\n", "n", "=", "len", "(", "ent", ".", "contents", ")", "\n", "switch", "ent", ".", "dataType", "{", "case", "RPM_INT8_TYPE", ":", "buf", "=", "make", "(", "[", "]", "uint8", ",", "n", ")", "\n", "case", "RPM_INT16_TYPE", ":", "n", ">>=", "1", "\n", "buf", "=", "make", "(", "[", "]", "uint16", ",", "n", ")", "\n", "case", "RPM_INT32_TYPE", ":", "n", ">>=", "2", "\n", "buf", "=", "make", "(", "[", "]", "uint32", ",", "n", ")", "\n", "case", "RPM_INT64_TYPE", ":", "n", ">>=", "3", "\n", "buf", "=", "make", "(", "[", "]", "uint64", ",", "n", ")", "\n", "default", ":", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "if", "err", ":=", "binary", ".", "Read", "(", "bytes", ".", "NewReader", "(", "ent", ".", "contents", ")", ",", "binary", ".", "BigEndian", ",", "buf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "return", "\n", "}" ]
// get an int array using whatever the appropriate sized type is
[ "get", "an", "int", "array", "using", "whatever", "the", "appropriate", "sized", "type", "is" ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/header.go#L201-L226
18,190
sassoftware/go-rpmutils
header.go
GetInts
func (hdr *rpmHeader) GetInts(tag int) ([]int, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } out := make([]int, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = int(v) } case []uint16: for i, v := range bvals { out[i] = int(v) } case []uint32: for i, v := range bvals { if v > (1<<31)-1 { return nil, fmt.Errorf("value %d out of range for int32 array in tag %d", i, tag) } out[i] = int(v) } default: return nil, fmt.Errorf("tag %d is too big for int type", tag) } return out, nil }
go
func (hdr *rpmHeader) GetInts(tag int) ([]int, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } out := make([]int, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = int(v) } case []uint16: for i, v := range bvals { out[i] = int(v) } case []uint32: for i, v := range bvals { if v > (1<<31)-1 { return nil, fmt.Errorf("value %d out of range for int32 array in tag %d", i, tag) } out[i] = int(v) } default: return nil, fmt.Errorf("tag %d is too big for int type", tag) } return out, nil }
[ "func", "(", "hdr", "*", "rpmHeader", ")", "GetInts", "(", "tag", "int", ")", "(", "[", "]", "int", ",", "error", ")", "{", "buf", ",", "n", ",", "err", ":=", "hdr", ".", "getInts", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "int", ",", "n", ")", "\n", "switch", "bvals", ":=", "buf", ".", "(", "type", ")", "{", "case", "[", "]", "uint8", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "out", "[", "i", "]", "=", "int", "(", "v", ")", "\n", "}", "\n", "case", "[", "]", "uint16", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "out", "[", "i", "]", "=", "int", "(", "v", ")", "\n", "}", "\n", "case", "[", "]", "uint32", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "if", "v", ">", "(", "1", "<<", "31", ")", "-", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ",", "tag", ")", "\n", "}", "\n", "out", "[", "i", "]", "=", "int", "(", "v", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Get an int array using the default 'int' type. DEPRECATED because all rpm // integers are unsigned, so some int32 values might not fit. Returns an error // in case of overflow.
[ "Get", "an", "int", "array", "using", "the", "default", "int", "type", ".", "DEPRECATED", "because", "all", "rpm", "integers", "are", "unsigned", "so", "some", "int32", "values", "might", "not", "fit", ".", "Returns", "an", "error", "in", "case", "of", "overflow", "." ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/header.go#L231-L257
18,191
sassoftware/go-rpmutils
header.go
GetUint32s
func (hdr *rpmHeader) GetUint32s(tag int) ([]uint32, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } if out, ok := buf.([]uint32); ok { return out, nil } out := make([]uint32, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = uint32(v) } case []uint16: for i, v := range bvals { out[i] = uint32(v) } default: return nil, fmt.Errorf("tag %d is too big for int type", tag) } return out, nil }
go
func (hdr *rpmHeader) GetUint32s(tag int) ([]uint32, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } if out, ok := buf.([]uint32); ok { return out, nil } out := make([]uint32, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = uint32(v) } case []uint16: for i, v := range bvals { out[i] = uint32(v) } default: return nil, fmt.Errorf("tag %d is too big for int type", tag) } return out, nil }
[ "func", "(", "hdr", "*", "rpmHeader", ")", "GetUint32s", "(", "tag", "int", ")", "(", "[", "]", "uint32", ",", "error", ")", "{", "buf", ",", "n", ",", "err", ":=", "hdr", ".", "getInts", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "out", ",", "ok", ":=", "buf", ".", "(", "[", "]", "uint32", ")", ";", "ok", "{", "return", "out", ",", "nil", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "uint32", ",", "n", ")", "\n", "switch", "bvals", ":=", "buf", ".", "(", "type", ")", "{", "case", "[", "]", "uint8", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "out", "[", "i", "]", "=", "uint32", "(", "v", ")", "\n", "}", "\n", "case", "[", "]", "uint16", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "out", "[", "i", "]", "=", "uint32", "(", "v", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Get an int array as a uint32 slice. This can accomodate any int type other // than INT64.
[ "Get", "an", "int", "array", "as", "a", "uint32", "slice", ".", "This", "can", "accomodate", "any", "int", "type", "other", "than", "INT64", "." ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/header.go#L261-L283
18,192
sassoftware/go-rpmutils
header.go
GetUint64s
func (hdr *rpmHeader) GetUint64s(tag int) ([]uint64, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } if out, ok := buf.([]uint64); ok { return out, nil } out := make([]uint64, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = uint64(v) } case []uint16: for i, v := range bvals { out[i] = uint64(v) } case []uint32: for i, v := range bvals { out[i] = uint64(v) } } return out, nil }
go
func (hdr *rpmHeader) GetUint64s(tag int) ([]uint64, error) { buf, n, err := hdr.getInts(tag) if err != nil { return nil, err } if out, ok := buf.([]uint64); ok { return out, nil } out := make([]uint64, n) switch bvals := buf.(type) { case []uint8: for i, v := range bvals { out[i] = uint64(v) } case []uint16: for i, v := range bvals { out[i] = uint64(v) } case []uint32: for i, v := range bvals { out[i] = uint64(v) } } return out, nil }
[ "func", "(", "hdr", "*", "rpmHeader", ")", "GetUint64s", "(", "tag", "int", ")", "(", "[", "]", "uint64", ",", "error", ")", "{", "buf", ",", "n", ",", "err", ":=", "hdr", ".", "getInts", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "out", ",", "ok", ":=", "buf", ".", "(", "[", "]", "uint64", ")", ";", "ok", "{", "return", "out", ",", "nil", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "uint64", ",", "n", ")", "\n", "switch", "bvals", ":=", "buf", ".", "(", "type", ")", "{", "case", "[", "]", "uint8", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "out", "[", "i", "]", "=", "uint64", "(", "v", ")", "\n", "}", "\n", "case", "[", "]", "uint16", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "out", "[", "i", "]", "=", "uint64", "(", "v", ")", "\n", "}", "\n", "case", "[", "]", "uint32", ":", "for", "i", ",", "v", ":=", "range", "bvals", "{", "out", "[", "i", "]", "=", "uint64", "(", "v", ")", "\n", "}", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Get an int array as a uint64 slice. This can accomodate all int types.
[ "Get", "an", "int", "array", "as", "a", "uint64", "slice", ".", "This", "can", "accomodate", "all", "int", "types", "." ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/header.go#L286-L310
18,193
sassoftware/go-rpmutils
header.go
GetUint64Fallback
func (hdr *rpmHeader) GetUint64Fallback(intTag, longTag int) ([]uint64, error) { if _, ok := hdr.entries[longTag]; ok { return hdr.GetUint64s(longTag) } else { return hdr.GetUint64s(intTag) } }
go
func (hdr *rpmHeader) GetUint64Fallback(intTag, longTag int) ([]uint64, error) { if _, ok := hdr.entries[longTag]; ok { return hdr.GetUint64s(longTag) } else { return hdr.GetUint64s(intTag) } }
[ "func", "(", "hdr", "*", "rpmHeader", ")", "GetUint64Fallback", "(", "intTag", ",", "longTag", "int", ")", "(", "[", "]", "uint64", ",", "error", ")", "{", "if", "_", ",", "ok", ":=", "hdr", ".", "entries", "[", "longTag", "]", ";", "ok", "{", "return", "hdr", ".", "GetUint64s", "(", "longTag", ")", "\n", "}", "else", "{", "return", "hdr", ".", "GetUint64s", "(", "intTag", ")", "\n", "}", "\n", "}" ]
// Get longTag if it exists, otherwise intTag
[ "Get", "longTag", "if", "it", "exists", "otherwise", "intTag" ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/header.go#L313-L319
18,194
sassoftware/go-rpmutils
rpmutils.go
InstalledSize
func (hdr *RpmHeader) InstalledSize() (int64, error) { u, err := hdr.GetUint64Fallback(SIZE, LONGSIZE) if err != nil { return -1, err } return int64(u), nil }
go
func (hdr *RpmHeader) InstalledSize() (int64, error) { u, err := hdr.GetUint64Fallback(SIZE, LONGSIZE) if err != nil { return -1, err } return int64(u), nil }
[ "func", "(", "hdr", "*", "RpmHeader", ")", "InstalledSize", "(", ")", "(", "int64", ",", "error", ")", "{", "u", ",", "err", ":=", "hdr", ".", "GetUint64Fallback", "(", "SIZE", ",", "LONGSIZE", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "return", "int64", "(", "u", ")", ",", "nil", "\n", "}" ]
// Return the approximate disk space needed to install the package
[ "Return", "the", "approximate", "disk", "space", "needed", "to", "install", "the", "package" ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/rpmutils.go#L201-L207
18,195
sassoftware/go-rpmutils
rpmutils.go
PayloadSize
func (hdr *RpmHeader) PayloadSize() (int64, error) { u, err := hdr.sigHeader.GetUint64Fallback(SIG_PAYLOADSIZE-_SIGHEADER_TAG_BASE, SIG_LONGARCHIVESIZE) if err != nil { return -1, err } else if len(u) != 1 { return -1, errors.New("incorrect number of values") } return int64(u[0]), err }
go
func (hdr *RpmHeader) PayloadSize() (int64, error) { u, err := hdr.sigHeader.GetUint64Fallback(SIG_PAYLOADSIZE-_SIGHEADER_TAG_BASE, SIG_LONGARCHIVESIZE) if err != nil { return -1, err } else if len(u) != 1 { return -1, errors.New("incorrect number of values") } return int64(u[0]), err }
[ "func", "(", "hdr", "*", "RpmHeader", ")", "PayloadSize", "(", ")", "(", "int64", ",", "error", ")", "{", "u", ",", "err", ":=", "hdr", ".", "sigHeader", ".", "GetUint64Fallback", "(", "SIG_PAYLOADSIZE", "-", "_SIGHEADER_TAG_BASE", ",", "SIG_LONGARCHIVESIZE", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "else", "if", "len", "(", "u", ")", "!=", "1", "{", "return", "-", "1", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "int64", "(", "u", "[", "0", "]", ")", ",", "err", "\n", "}" ]
// Return the size of the uncompressed payload in bytes
[ "Return", "the", "size", "of", "the", "uncompressed", "payload", "in", "bytes" ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/rpmutils.go#L210-L218
18,196
sassoftware/go-rpmutils
signatures.go
SignRpmStream
func SignRpmStream(stream io.Reader, key *packet.PrivateKey, opts *SignatureOptions) (header *RpmHeader, err error) { lead, sigHeader, err := readSignatureHeader(stream) if err != nil { return } // parse the general header and also tee it into a buffer genHeaderBuf := new(bytes.Buffer) headerTee := io.TeeReader(stream, genHeaderBuf) genHeader, err := readHeader(headerTee, getSha1(sigHeader), sigHeader.isSource, false) if err != nil { return } genHeaderBlob := genHeaderBuf.Bytes() // chain the buffered general header to the rest of the payload, and digest the whole lot of it genHeaderAndPayload := io.MultiReader(bytes.NewReader(genHeaderBlob), stream) payloadDigest := md5.New() payloadTee := io.TeeReader(genHeaderAndPayload, payloadDigest) sigPgp, err := makeSignature(payloadTee, key, opts) if err != nil { return } if !checkMd5(sigHeader, payloadDigest) { return nil, errors.New("md5 digest mismatch") } sigRsa, err := makeSignature(bytes.NewReader(genHeaderBlob), key, opts) if err != nil { return } insertSignatures(sigHeader, sigPgp, sigRsa) return &RpmHeader{ lead: lead, sigHeader: sigHeader, genHeader: genHeader, isSource: sigHeader.isSource, }, nil }
go
func SignRpmStream(stream io.Reader, key *packet.PrivateKey, opts *SignatureOptions) (header *RpmHeader, err error) { lead, sigHeader, err := readSignatureHeader(stream) if err != nil { return } // parse the general header and also tee it into a buffer genHeaderBuf := new(bytes.Buffer) headerTee := io.TeeReader(stream, genHeaderBuf) genHeader, err := readHeader(headerTee, getSha1(sigHeader), sigHeader.isSource, false) if err != nil { return } genHeaderBlob := genHeaderBuf.Bytes() // chain the buffered general header to the rest of the payload, and digest the whole lot of it genHeaderAndPayload := io.MultiReader(bytes.NewReader(genHeaderBlob), stream) payloadDigest := md5.New() payloadTee := io.TeeReader(genHeaderAndPayload, payloadDigest) sigPgp, err := makeSignature(payloadTee, key, opts) if err != nil { return } if !checkMd5(sigHeader, payloadDigest) { return nil, errors.New("md5 digest mismatch") } sigRsa, err := makeSignature(bytes.NewReader(genHeaderBlob), key, opts) if err != nil { return } insertSignatures(sigHeader, sigPgp, sigRsa) return &RpmHeader{ lead: lead, sigHeader: sigHeader, genHeader: genHeader, isSource: sigHeader.isSource, }, nil }
[ "func", "SignRpmStream", "(", "stream", "io", ".", "Reader", ",", "key", "*", "packet", ".", "PrivateKey", ",", "opts", "*", "SignatureOptions", ")", "(", "header", "*", "RpmHeader", ",", "err", "error", ")", "{", "lead", ",", "sigHeader", ",", "err", ":=", "readSignatureHeader", "(", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// parse the general header and also tee it into a buffer", "genHeaderBuf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "headerTee", ":=", "io", ".", "TeeReader", "(", "stream", ",", "genHeaderBuf", ")", "\n", "genHeader", ",", "err", ":=", "readHeader", "(", "headerTee", ",", "getSha1", "(", "sigHeader", ")", ",", "sigHeader", ".", "isSource", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "genHeaderBlob", ":=", "genHeaderBuf", ".", "Bytes", "(", ")", "\n", "// chain the buffered general header to the rest of the payload, and digest the whole lot of it", "genHeaderAndPayload", ":=", "io", ".", "MultiReader", "(", "bytes", ".", "NewReader", "(", "genHeaderBlob", ")", ",", "stream", ")", "\n", "payloadDigest", ":=", "md5", ".", "New", "(", ")", "\n", "payloadTee", ":=", "io", ".", "TeeReader", "(", "genHeaderAndPayload", ",", "payloadDigest", ")", "\n", "sigPgp", ",", "err", ":=", "makeSignature", "(", "payloadTee", ",", "key", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "!", "checkMd5", "(", "sigHeader", ",", "payloadDigest", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "sigRsa", ",", "err", ":=", "makeSignature", "(", "bytes", ".", "NewReader", "(", "genHeaderBlob", ")", ",", "key", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "insertSignatures", "(", "sigHeader", ",", "sigPgp", ",", "sigRsa", ")", "\n", "return", "&", "RpmHeader", "{", "lead", ":", "lead", ",", "sigHeader", ":", "sigHeader", ",", "genHeader", ":", "genHeader", ",", "isSource", ":", "sigHeader", ".", "isSource", ",", "}", ",", "nil", "\n", "}" ]
// Read an RPM and sign it, returning the set of headers updated with the new signature.
[ "Read", "an", "RPM", "and", "sign", "it", "returning", "the", "set", "of", "headers", "updated", "with", "the", "new", "signature", "." ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/signatures.go#L114-L149
18,197
sassoftware/go-rpmutils
signatures.go
SignRpmFileIntoStream
func SignRpmFileIntoStream(outstream io.Writer, infile io.ReadSeeker, key *packet.PrivateKey, opts *SignatureOptions) error { header, err := SignRpmStream(infile, key, opts) if err != nil { return err } delete(header.sigHeader.entries, SIG_RESERVEDSPACE-_SIGHEADER_TAG_BASE) return writeRpm(infile, outstream, header.sigHeader) }
go
func SignRpmFileIntoStream(outstream io.Writer, infile io.ReadSeeker, key *packet.PrivateKey, opts *SignatureOptions) error { header, err := SignRpmStream(infile, key, opts) if err != nil { return err } delete(header.sigHeader.entries, SIG_RESERVEDSPACE-_SIGHEADER_TAG_BASE) return writeRpm(infile, outstream, header.sigHeader) }
[ "func", "SignRpmFileIntoStream", "(", "outstream", "io", ".", "Writer", ",", "infile", "io", ".", "ReadSeeker", ",", "key", "*", "packet", ".", "PrivateKey", ",", "opts", "*", "SignatureOptions", ")", "error", "{", "header", ",", "err", ":=", "SignRpmStream", "(", "infile", ",", "key", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "delete", "(", "header", ".", "sigHeader", ".", "entries", ",", "SIG_RESERVEDSPACE", "-", "_SIGHEADER_TAG_BASE", ")", "\n", "return", "writeRpm", "(", "infile", ",", "outstream", ",", "header", ".", "sigHeader", ")", "\n", "}" ]
// SignRpmFileIntoStream signs the rpmfile represented by infile with the // provided private key and sig options. The entire signed RPM file is then // written to the outstream.
[ "SignRpmFileIntoStream", "signs", "the", "rpmfile", "represented", "by", "infile", "with", "the", "provided", "private", "key", "and", "sig", "options", ".", "The", "entire", "signed", "RPM", "file", "is", "then", "written", "to", "the", "outstream", "." ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/signatures.go#L175-L182
18,198
sassoftware/go-rpmutils
uncompress.go
uncompressRpmPayloadReader
func uncompressRpmPayloadReader(r io.Reader, hdr *RpmHeader) (io.Reader, error) { // Check to make sure payload format is a cpio archive. If the tag does // not exist, assume archive is cpio. if hdr.HasTag(PAYLOADFORMAT) { val, err := hdr.GetString(PAYLOADFORMAT) if err != nil { return nil, err } if val != "cpio" { return nil, fmt.Errorf("Unknown payload format %s", val) } } // Check to see how the payload was compressed. If the tag does not // exist, check if it is gzip, if not it is uncompressed. var compression string if hdr.HasTag(PAYLOADCOMPRESSOR) { val, err := hdr.GetString(PAYLOADCOMPRESSOR) if err != nil { return nil, err } compression = val } else { b := make([]byte, 4096) _, err := r.Read(b) if err != nil { return nil, err } if len(b) > 2 && b[0] == 0x1f && b[1] == 0x8b { compression = "gzip" } else { compression = "uncompressed" } } switch compression { case "gzip": return gzip.NewReader(r) case "bzip2": return bzip2.NewReader(r), nil case "lzma", "xz": return xz.NewReader(r, 0) case "uncompressed": return r, nil default: return nil, fmt.Errorf("Unknown compression type %s", compression) } }
go
func uncompressRpmPayloadReader(r io.Reader, hdr *RpmHeader) (io.Reader, error) { // Check to make sure payload format is a cpio archive. If the tag does // not exist, assume archive is cpio. if hdr.HasTag(PAYLOADFORMAT) { val, err := hdr.GetString(PAYLOADFORMAT) if err != nil { return nil, err } if val != "cpio" { return nil, fmt.Errorf("Unknown payload format %s", val) } } // Check to see how the payload was compressed. If the tag does not // exist, check if it is gzip, if not it is uncompressed. var compression string if hdr.HasTag(PAYLOADCOMPRESSOR) { val, err := hdr.GetString(PAYLOADCOMPRESSOR) if err != nil { return nil, err } compression = val } else { b := make([]byte, 4096) _, err := r.Read(b) if err != nil { return nil, err } if len(b) > 2 && b[0] == 0x1f && b[1] == 0x8b { compression = "gzip" } else { compression = "uncompressed" } } switch compression { case "gzip": return gzip.NewReader(r) case "bzip2": return bzip2.NewReader(r), nil case "lzma", "xz": return xz.NewReader(r, 0) case "uncompressed": return r, nil default: return nil, fmt.Errorf("Unknown compression type %s", compression) } }
[ "func", "uncompressRpmPayloadReader", "(", "r", "io", ".", "Reader", ",", "hdr", "*", "RpmHeader", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "// Check to make sure payload format is a cpio archive. If the tag does", "// not exist, assume archive is cpio.", "if", "hdr", ".", "HasTag", "(", "PAYLOADFORMAT", ")", "{", "val", ",", "err", ":=", "hdr", ".", "GetString", "(", "PAYLOADFORMAT", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "val", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "val", ")", "\n", "}", "\n", "}", "\n\n", "// Check to see how the payload was compressed. If the tag does not", "// exist, check if it is gzip, if not it is uncompressed.", "var", "compression", "string", "\n", "if", "hdr", ".", "HasTag", "(", "PAYLOADCOMPRESSOR", ")", "{", "val", ",", "err", ":=", "hdr", ".", "GetString", "(", "PAYLOADCOMPRESSOR", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "compression", "=", "val", "\n", "}", "else", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "4096", ")", "\n", "_", ",", "err", ":=", "r", ".", "Read", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "b", ")", ">", "2", "&&", "b", "[", "0", "]", "==", "0x1f", "&&", "b", "[", "1", "]", "==", "0x8b", "{", "compression", "=", "\"", "\"", "\n", "}", "else", "{", "compression", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "switch", "compression", "{", "case", "\"", "\"", ":", "return", "gzip", ".", "NewReader", "(", "r", ")", "\n", "case", "\"", "\"", ":", "return", "bzip2", ".", "NewReader", "(", "r", ")", ",", "nil", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "xz", ".", "NewReader", "(", "r", ",", "0", ")", "\n", "case", "\"", "\"", ":", "return", "r", ",", "nil", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "compression", ")", "\n", "}", "\n", "}" ]
// Wrap RPM payload with uncompress reader, assumes that header has // already been read.
[ "Wrap", "RPM", "payload", "with", "uncompress", "reader", "assumes", "that", "header", "has", "already", "been", "read", "." ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/uncompress.go#L30-L77
18,199
sassoftware/go-rpmutils
vercmp.go
Less
func (vs VersionSlice) Less(i, j int) bool { return Vercmp(vs[i], vs[j]) == -1 }
go
func (vs VersionSlice) Less(i, j int) bool { return Vercmp(vs[i], vs[j]) == -1 }
[ "func", "(", "vs", "VersionSlice", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "Vercmp", "(", "vs", "[", "i", "]", ",", "vs", "[", "j", "]", ")", "==", "-", "1", "\n", "}" ]
// Less reports wheather the element with index i should sort before the // element with index j.
[ "Less", "reports", "wheather", "the", "element", "with", "index", "i", "should", "sort", "before", "the", "element", "with", "index", "j", "." ]
c37ab0fd127a1e43f40d0ba2250302e20eaee937
https://github.com/sassoftware/go-rpmutils/blob/c37ab0fd127a1e43f40d0ba2250302e20eaee937/vercmp.go#L40-L42