id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
11,500
qor/media
base.go
GetURL
func (b Base) GetURL(option *Option, scope *gorm.Scope, field *gorm.Field, templater URLTemplater) string { if path := templater.GetURLTemplate(option); path != "" { tmpl := template.New("").Funcs(getFuncMap(scope, field, b.GetFileName())) if tmpl, err := tmpl.Parse(path); err == nil { var result = bytes.NewBufferString("") if err := tmpl.Execute(result, scope.Value); err == nil { return result.String() } } } return "" }
go
func (b Base) GetURL(option *Option, scope *gorm.Scope, field *gorm.Field, templater URLTemplater) string { if path := templater.GetURLTemplate(option); path != "" { tmpl := template.New("").Funcs(getFuncMap(scope, field, b.GetFileName())) if tmpl, err := tmpl.Parse(path); err == nil { var result = bytes.NewBufferString("") if err := tmpl.Execute(result, scope.Value); err == nil { return result.String() } } } return "" }
[ "func", "(", "b", "Base", ")", "GetURL", "(", "option", "*", "Option", ",", "scope", "*", "gorm", ".", "Scope", ",", "field", "*", "gorm", ".", "Field", ",", "templater", "URLTemplater", ")", "string", "{", "if", "path", ":=", "templater", ".", "GetURLTemplate", "(", "option", ")", ";", "path", "!=", "\"", "\"", "{", "tmpl", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "getFuncMap", "(", "scope", ",", "field", ",", "b", ".", "GetFileName", "(", ")", ")", ")", "\n", "if", "tmpl", ",", "err", ":=", "tmpl", ".", "Parse", "(", "path", ")", ";", "err", "==", "nil", "{", "var", "result", "=", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "tmpl", ".", "Execute", "(", "result", ",", "scope", ".", "Value", ")", ";", "err", "==", "nil", "{", "return", "result", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// GetURL get default URL for a model based on its options
[ "GetURL", "get", "default", "URL", "for", "a", "model", "based", "on", "its", "options" ]
c3220db68c4b980ae75be2fbd4faf7cd983b9b0f
https://github.com/qor/media/blob/c3220db68c4b980ae75be2fbd4faf7cd983b9b0f/base.go#L188-L199
11,501
qor/media
base.go
Cropped
func (b *Base) Cropped(values ...bool) (result bool) { result = b.cropped for _, value := range values { b.cropped = value } return result }
go
func (b *Base) Cropped(values ...bool) (result bool) { result = b.cropped for _, value := range values { b.cropped = value } return result }
[ "func", "(", "b", "*", "Base", ")", "Cropped", "(", "values", "...", "bool", ")", "(", "result", "bool", ")", "{", "result", "=", "b", ".", "cropped", "\n", "for", "_", ",", "value", ":=", "range", "values", "{", "b", ".", "cropped", "=", "value", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Cropped mark the image to be cropped
[ "Cropped", "mark", "the", "image", "to", "be", "cropped" ]
c3220db68c4b980ae75be2fbd4faf7cd983b9b0f
https://github.com/qor/media/blob/c3220db68c4b980ae75be2fbd4faf7cd983b9b0f/base.go#L202-L208
11,502
qor/media
base.go
GetCropOption
func (b *Base) GetCropOption(name string) *image.Rectangle { if cropOption := b.CropOptions[strings.Split(name, "@")[0]]; cropOption != nil { return &image.Rectangle{ Min: image.Point{X: cropOption.X, Y: cropOption.Y}, Max: image.Point{X: cropOption.X + cropOption.Width, Y: cropOption.Y + cropOption.Height}, } } return nil }
go
func (b *Base) GetCropOption(name string) *image.Rectangle { if cropOption := b.CropOptions[strings.Split(name, "@")[0]]; cropOption != nil { return &image.Rectangle{ Min: image.Point{X: cropOption.X, Y: cropOption.Y}, Max: image.Point{X: cropOption.X + cropOption.Width, Y: cropOption.Y + cropOption.Height}, } } return nil }
[ "func", "(", "b", "*", "Base", ")", "GetCropOption", "(", "name", "string", ")", "*", "image", ".", "Rectangle", "{", "if", "cropOption", ":=", "b", ".", "CropOptions", "[", "strings", ".", "Split", "(", "name", ",", "\"", "\"", ")", "[", "0", "]", "]", ";", "cropOption", "!=", "nil", "{", "return", "&", "image", ".", "Rectangle", "{", "Min", ":", "image", ".", "Point", "{", "X", ":", "cropOption", ".", "X", ",", "Y", ":", "cropOption", ".", "Y", "}", ",", "Max", ":", "image", ".", "Point", "{", "X", ":", "cropOption", ".", "X", "+", "cropOption", ".", "Width", ",", "Y", ":", "cropOption", ".", "Y", "+", "cropOption", ".", "Height", "}", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetCropOption get crop options
[ "GetCropOption", "get", "crop", "options" ]
c3220db68c4b980ae75be2fbd4faf7cd983b9b0f
https://github.com/qor/media/blob/c3220db68c4b980ae75be2fbd4faf7cd983b9b0f/base.go#L216-L224
11,503
qor/media
oss/oss.go
GetURLTemplate
func (o OSS) GetURLTemplate(option *media.Option) (url string) { return DefaultURLTemplateHandler(o, option) }
go
func (o OSS) GetURLTemplate(option *media.Option) (url string) { return DefaultURLTemplateHandler(o, option) }
[ "func", "(", "o", "OSS", ")", "GetURLTemplate", "(", "option", "*", "media", ".", "Option", ")", "(", "url", "string", ")", "{", "return", "DefaultURLTemplateHandler", "(", "o", ",", "option", ")", "\n", "}" ]
// GetURLTemplate URL's template
[ "GetURLTemplate", "URL", "s", "template" ]
c3220db68c4b980ae75be2fbd4faf7cd983b9b0f
https://github.com/qor/media/blob/c3220db68c4b980ae75be2fbd4faf7cd983b9b0f/oss/oss.go#L48-L50
11,504
qor/media
oss/oss.go
Store
func (o OSS) Store(path string, option *media.Option, reader io.Reader) error { return DefaultStoreHandler(o, path, option, reader) }
go
func (o OSS) Store(path string, option *media.Option, reader io.Reader) error { return DefaultStoreHandler(o, path, option, reader) }
[ "func", "(", "o", "OSS", ")", "Store", "(", "path", "string", ",", "option", "*", "media", ".", "Option", ",", "reader", "io", ".", "Reader", ")", "error", "{", "return", "DefaultStoreHandler", "(", "o", ",", "path", ",", "option", ",", "reader", ")", "\n", "}" ]
// Store save reader's content with path
[ "Store", "save", "reader", "s", "content", "with", "path" ]
c3220db68c4b980ae75be2fbd4faf7cd983b9b0f
https://github.com/qor/media/blob/c3220db68c4b980ae75be2fbd4faf7cd983b9b0f/oss/oss.go#L59-L61
11,505
wallix/triplestore
source.go
NewSource
func NewSource() Source { s := &source{ triples: make(map[string]Triple), } s.latestSnap.Store(newGraph(0)) return s }
go
func NewSource() Source { s := &source{ triples: make(map[string]Triple), } s.latestSnap.Store(newGraph(0)) return s }
[ "func", "NewSource", "(", ")", "Source", "{", "s", ":=", "&", "source", "{", "triples", ":", "make", "(", "map", "[", "string", "]", "Triple", ")", ",", "}", "\n", "s", ".", "latestSnap", ".", "Store", "(", "newGraph", "(", "0", ")", ")", "\n", "return", "s", "\n", "}" ]
// A source is a persistent yet mutable source or container of triples
[ "A", "source", "is", "a", "persistent", "yet", "mutable", "source", "or", "container", "of", "triples" ]
4099dd913851642f2c0b71f9c1a0c6887748849c
https://github.com/wallix/triplestore/blob/4099dd913851642f2c0b71f9c1a0c6887748849c/source.go#L79-L85
11,506
wallix/triplestore
decode.go
NewAutoDecoder
func NewAutoDecoder(r io.Reader) Decoder { ok, newR := IsNTFormat(r) if ok { return NewLenientNTDecoder(newR) } return NewBinaryDecoder(newR) }
go
func NewAutoDecoder(r io.Reader) Decoder { ok, newR := IsNTFormat(r) if ok { return NewLenientNTDecoder(newR) } return NewBinaryDecoder(newR) }
[ "func", "NewAutoDecoder", "(", "r", "io", ".", "Reader", ")", "Decoder", "{", "ok", ",", "newR", ":=", "IsNTFormat", "(", "r", ")", "\n", "if", "ok", "{", "return", "NewLenientNTDecoder", "(", "newR", ")", "\n", "}", "\n", "return", "NewBinaryDecoder", "(", "newR", ")", "\n", "}" ]
// Use for retro compatibilty when changing file format on existing stores
[ "Use", "for", "retro", "compatibilty", "when", "changing", "file", "format", "on", "existing", "stores" ]
4099dd913851642f2c0b71f9c1a0c6887748849c
https://github.com/wallix/triplestore/blob/4099dd913851642f2c0b71f9c1a0c6887748849c/decode.go#L29-L35
11,507
wallix/triplestore
decode.go
NewDatasetDecoder
func NewDatasetDecoder(fn func(io.Reader) Decoder, readers ...io.Reader) Decoder { return &datasetDecoder{newDecoderFunc: fn, rs: readers} }
go
func NewDatasetDecoder(fn func(io.Reader) Decoder, readers ...io.Reader) Decoder { return &datasetDecoder{newDecoderFunc: fn, rs: readers} }
[ "func", "NewDatasetDecoder", "(", "fn", "func", "(", "io", ".", "Reader", ")", "Decoder", ",", "readers", "...", "io", ".", "Reader", ")", "Decoder", "{", "return", "&", "datasetDecoder", "{", "newDecoderFunc", ":", "fn", ",", "rs", ":", "readers", "}", "\n", "}" ]
// NewDatasetDecoder - a dataset is a basically a collection of RDFGraph.
[ "NewDatasetDecoder", "-", "a", "dataset", "is", "a", "basically", "a", "collection", "of", "RDFGraph", "." ]
4099dd913851642f2c0b71f9c1a0c6887748849c
https://github.com/wallix/triplestore/blob/4099dd913851642f2c0b71f9c1a0c6887748849c/decode.go#L247-L249
11,508
wallix/triplestore
tree.go
TraverseDFS
func (t *Tree) TraverseDFS(node string, each func(RDFGraph, string, int) error, depths ...int) error { var depth int if len(depths) > 0 { depth = depths[0] } if err := each(t.g, node, depth); err != nil { return err } triples := t.g.WithSubjPred(node, t.predicate) var childs []string for _, tri := range triples { n, ok := tri.Object().Resource() if !ok { return fmt.Errorf("object is not a resource identifier") } childs = append(childs, n) } sort.Strings(childs) for _, child := range childs { t.TraverseDFS(child, each, depth+1) } return nil }
go
func (t *Tree) TraverseDFS(node string, each func(RDFGraph, string, int) error, depths ...int) error { var depth int if len(depths) > 0 { depth = depths[0] } if err := each(t.g, node, depth); err != nil { return err } triples := t.g.WithSubjPred(node, t.predicate) var childs []string for _, tri := range triples { n, ok := tri.Object().Resource() if !ok { return fmt.Errorf("object is not a resource identifier") } childs = append(childs, n) } sort.Strings(childs) for _, child := range childs { t.TraverseDFS(child, each, depth+1) } return nil }
[ "func", "(", "t", "*", "Tree", ")", "TraverseDFS", "(", "node", "string", ",", "each", "func", "(", "RDFGraph", ",", "string", ",", "int", ")", "error", ",", "depths", "...", "int", ")", "error", "{", "var", "depth", "int", "\n", "if", "len", "(", "depths", ")", ">", "0", "{", "depth", "=", "depths", "[", "0", "]", "\n", "}", "\n\n", "if", "err", ":=", "each", "(", "t", ".", "g", ",", "node", ",", "depth", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "triples", ":=", "t", ".", "g", ".", "WithSubjPred", "(", "node", ",", "t", ".", "predicate", ")", "\n\n", "var", "childs", "[", "]", "string", "\n", "for", "_", ",", "tri", ":=", "range", "triples", "{", "n", ",", "ok", ":=", "tri", ".", "Object", "(", ")", ".", "Resource", "(", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "childs", "=", "append", "(", "childs", ",", "n", ")", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "childs", ")", "\n\n", "for", "_", ",", "child", ":=", "range", "childs", "{", "t", ".", "TraverseDFS", "(", "child", ",", "each", ",", "depth", "+", "1", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Traverse the tree in pre-order depth first search
[ "Traverse", "the", "tree", "in", "pre", "-", "order", "depth", "first", "search" ]
4099dd913851642f2c0b71f9c1a0c6887748849c
https://github.com/wallix/triplestore/blob/4099dd913851642f2c0b71f9c1a0c6887748849c/tree.go#L27-L55
11,509
wallix/triplestore
tree.go
TraverseAncestors
func (t *Tree) TraverseAncestors(node string, each func(RDFGraph, string, int) error, depths ...int) error { var depth int if len(depths) > 0 { depth = depths[0] } if err := each(t.g, node, depth); err != nil { return err } triples := t.g.WithPredObj(t.predicate, Resource(node)) var parents []string for _, tri := range triples { parents = append(parents, tri.Subject()) } sort.Strings(parents) for _, parent := range parents { t.TraverseAncestors(parent, each, depth+1) } return nil }
go
func (t *Tree) TraverseAncestors(node string, each func(RDFGraph, string, int) error, depths ...int) error { var depth int if len(depths) > 0 { depth = depths[0] } if err := each(t.g, node, depth); err != nil { return err } triples := t.g.WithPredObj(t.predicate, Resource(node)) var parents []string for _, tri := range triples { parents = append(parents, tri.Subject()) } sort.Strings(parents) for _, parent := range parents { t.TraverseAncestors(parent, each, depth+1) } return nil }
[ "func", "(", "t", "*", "Tree", ")", "TraverseAncestors", "(", "node", "string", ",", "each", "func", "(", "RDFGraph", ",", "string", ",", "int", ")", "error", ",", "depths", "...", "int", ")", "error", "{", "var", "depth", "int", "\n", "if", "len", "(", "depths", ")", ">", "0", "{", "depth", "=", "depths", "[", "0", "]", "\n", "}", "\n\n", "if", "err", ":=", "each", "(", "t", ".", "g", ",", "node", ",", "depth", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "triples", ":=", "t", ".", "g", ".", "WithPredObj", "(", "t", ".", "predicate", ",", "Resource", "(", "node", ")", ")", "\n\n", "var", "parents", "[", "]", "string", "\n", "for", "_", ",", "tri", ":=", "range", "triples", "{", "parents", "=", "append", "(", "parents", ",", "tri", ".", "Subject", "(", ")", ")", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "parents", ")", "\n\n", "for", "_", ",", "parent", ":=", "range", "parents", "{", "t", ".", "TraverseAncestors", "(", "parent", ",", "each", ",", "depth", "+", "1", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Traverse all ancestors from the given node
[ "Traverse", "all", "ancestors", "from", "the", "given", "node" ]
4099dd913851642f2c0b71f9c1a0c6887748849c
https://github.com/wallix/triplestore/blob/4099dd913851642f2c0b71f9c1a0c6887748849c/tree.go#L58-L82
11,510
wallix/triplestore
tree.go
TraverseSiblings
func (t *Tree) TraverseSiblings(node string, siblingCriteriaFunc func(RDFGraph, string) (string, error), each func(RDFGraph, string, int) error) error { triples := t.g.WithPredObj(t.predicate, Resource(node)) if len(triples) == 0 { return each(t.g, node, 0) } if len(triples) != 1 { return fmt.Errorf("tree[%s]: node %s with more than 1 parent: %v", t.predicate, node, triples) } otherChildTriples := t.g.WithSubjPred(triples[0].Subject(), t.predicate) var childs []string for _, c := range otherChildTriples { child, ok := c.Object().Resource() if !ok { return fmt.Errorf("object is not a resource identifier") } childs = append(childs, child) } sort.Strings(childs) nodeCriteria, err := siblingCriteriaFunc(t.g, node) if err != nil { return err } for _, child := range childs { childCriteria, err := siblingCriteriaFunc(t.g, child) if err != nil { return err } if nodeCriteria == childCriteria { if err := each(t.g, child, 0); err != nil { return err } } } return nil }
go
func (t *Tree) TraverseSiblings(node string, siblingCriteriaFunc func(RDFGraph, string) (string, error), each func(RDFGraph, string, int) error) error { triples := t.g.WithPredObj(t.predicate, Resource(node)) if len(triples) == 0 { return each(t.g, node, 0) } if len(triples) != 1 { return fmt.Errorf("tree[%s]: node %s with more than 1 parent: %v", t.predicate, node, triples) } otherChildTriples := t.g.WithSubjPred(triples[0].Subject(), t.predicate) var childs []string for _, c := range otherChildTriples { child, ok := c.Object().Resource() if !ok { return fmt.Errorf("object is not a resource identifier") } childs = append(childs, child) } sort.Strings(childs) nodeCriteria, err := siblingCriteriaFunc(t.g, node) if err != nil { return err } for _, child := range childs { childCriteria, err := siblingCriteriaFunc(t.g, child) if err != nil { return err } if nodeCriteria == childCriteria { if err := each(t.g, child, 0); err != nil { return err } } } return nil }
[ "func", "(", "t", "*", "Tree", ")", "TraverseSiblings", "(", "node", "string", ",", "siblingCriteriaFunc", "func", "(", "RDFGraph", ",", "string", ")", "(", "string", ",", "error", ")", ",", "each", "func", "(", "RDFGraph", ",", "string", ",", "int", ")", "error", ")", "error", "{", "triples", ":=", "t", ".", "g", ".", "WithPredObj", "(", "t", ".", "predicate", ",", "Resource", "(", "node", ")", ")", "\n\n", "if", "len", "(", "triples", ")", "==", "0", "{", "return", "each", "(", "t", ".", "g", ",", "node", ",", "0", ")", "\n", "}", "\n\n", "if", "len", "(", "triples", ")", "!=", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ".", "predicate", ",", "node", ",", "triples", ")", "\n", "}", "\n\n", "otherChildTriples", ":=", "t", ".", "g", ".", "WithSubjPred", "(", "triples", "[", "0", "]", ".", "Subject", "(", ")", ",", "t", ".", "predicate", ")", "\n\n", "var", "childs", "[", "]", "string", "\n", "for", "_", ",", "c", ":=", "range", "otherChildTriples", "{", "child", ",", "ok", ":=", "c", ".", "Object", "(", ")", ".", "Resource", "(", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "childs", "=", "append", "(", "childs", ",", "child", ")", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "childs", ")", "\n\n", "nodeCriteria", ",", "err", ":=", "siblingCriteriaFunc", "(", "t", ".", "g", ",", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "child", ":=", "range", "childs", "{", "childCriteria", ",", "err", ":=", "siblingCriteriaFunc", "(", "t", ".", "g", ",", "child", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "nodeCriteria", "==", "childCriteria", "{", "if", "err", ":=", "each", "(", "t", ".", "g", ",", "child", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Traverse siblings of given node. Passed function allow to output the sibling criteria
[ "Traverse", "siblings", "of", "given", "node", ".", "Passed", "function", "allow", "to", "output", "the", "sibling", "criteria" ]
4099dd913851642f2c0b71f9c1a0c6887748849c
https://github.com/wallix/triplestore/blob/4099dd913851642f2c0b71f9c1a0c6887748849c/tree.go#L85-L127
11,511
akhenakh/statgo
process_stats.go
ProcessStats
func (s *Stat) ProcessStats() *ProcessStats { s.Lock() defer s.Unlock() // Throw away the first reading as thats averaged over the machines uptime pstat := C.sg_get_process_count_of(C.sg_entire_process_count) p := &ProcessStats{ Total: int(pstat.total), Running: int(pstat.running), Sleeping: int(pstat.sleeping), Stopped: int(pstat.stopped), Zombie: int(pstat.zombie), } return p }
go
func (s *Stat) ProcessStats() *ProcessStats { s.Lock() defer s.Unlock() // Throw away the first reading as thats averaged over the machines uptime pstat := C.sg_get_process_count_of(C.sg_entire_process_count) p := &ProcessStats{ Total: int(pstat.total), Running: int(pstat.running), Sleeping: int(pstat.sleeping), Stopped: int(pstat.stopped), Zombie: int(pstat.zombie), } return p }
[ "func", "(", "s", "*", "Stat", ")", "ProcessStats", "(", ")", "*", "ProcessStats", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "// Throw away the first reading as thats averaged over the machines uptime", "pstat", ":=", "C", ".", "sg_get_process_count_of", "(", "C", ".", "sg_entire_process_count", ")", "\n\n", "p", ":=", "&", "ProcessStats", "{", "Total", ":", "int", "(", "pstat", ".", "total", ")", ",", "Running", ":", "int", "(", "pstat", ".", "running", ")", ",", "Sleeping", ":", "int", "(", "pstat", ".", "sleeping", ")", ",", "Stopped", ":", "int", "(", "pstat", ".", "stopped", ")", ",", "Zombie", ":", "int", "(", "pstat", ".", "zombie", ")", ",", "}", "\n", "return", "p", "\n", "}" ]
// ProcessStats get prceosses related stats // note that 1st call to 100ms may return NaN as values // Go equivalent to sg_cpu_percents
[ "ProcessStats", "get", "prceosses", "related", "stats", "note", "that", "1st", "call", "to", "100ms", "may", "return", "NaN", "as", "values", "Go", "equivalent", "to", "sg_cpu_percents" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/process_stats.go#L29-L44
11,512
akhenakh/statgo
cpu_stats.go
CPUStats
func (s *Stat) CPUStats() *CPUStats { s.Lock() defer s.Unlock() var cpu *CPUStats do(func() { cpup := C.sg_get_cpu_percents_of(C.sg_new_diff_cpu_percent, nil) loadStat := C.sg_get_load_stats(nil) cpu = &CPUStats{ User: float64(cpup.user), Kernel: float64(cpup.kernel), Idle: float64(cpup.idle), IOWait: float64(cpup.iowait), Swap: float64(cpup.swap), Nice: float64(cpup.nice), LoadMin1: float64(loadStat.min1), LoadMin5: float64(loadStat.min5), LoadMin15: float64(loadStat.min15), Period: time.Duration(int(cpup.time_taken)) * time.Second, TimeTaken: time.Now(), } }) return cpu }
go
func (s *Stat) CPUStats() *CPUStats { s.Lock() defer s.Unlock() var cpu *CPUStats do(func() { cpup := C.sg_get_cpu_percents_of(C.sg_new_diff_cpu_percent, nil) loadStat := C.sg_get_load_stats(nil) cpu = &CPUStats{ User: float64(cpup.user), Kernel: float64(cpup.kernel), Idle: float64(cpup.idle), IOWait: float64(cpup.iowait), Swap: float64(cpup.swap), Nice: float64(cpup.nice), LoadMin1: float64(loadStat.min1), LoadMin5: float64(loadStat.min5), LoadMin15: float64(loadStat.min15), Period: time.Duration(int(cpup.time_taken)) * time.Second, TimeTaken: time.Now(), } }) return cpu }
[ "func", "(", "s", "*", "Stat", ")", "CPUStats", "(", ")", "*", "CPUStats", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "var", "cpu", "*", "CPUStats", "\n", "do", "(", "func", "(", ")", "{", "cpup", ":=", "C", ".", "sg_get_cpu_percents_of", "(", "C", ".", "sg_new_diff_cpu_percent", ",", "nil", ")", "\n\n", "loadStat", ":=", "C", ".", "sg_get_load_stats", "(", "nil", ")", "\n\n", "cpu", "=", "&", "CPUStats", "{", "User", ":", "float64", "(", "cpup", ".", "user", ")", ",", "Kernel", ":", "float64", "(", "cpup", ".", "kernel", ")", ",", "Idle", ":", "float64", "(", "cpup", ".", "idle", ")", ",", "IOWait", ":", "float64", "(", "cpup", ".", "iowait", ")", ",", "Swap", ":", "float64", "(", "cpup", ".", "swap", ")", ",", "Nice", ":", "float64", "(", "cpup", ".", "nice", ")", ",", "LoadMin1", ":", "float64", "(", "loadStat", ".", "min1", ")", ",", "LoadMin5", ":", "float64", "(", "loadStat", ".", "min5", ")", ",", "LoadMin15", ":", "float64", "(", "loadStat", ".", "min15", ")", ",", "Period", ":", "time", ".", "Duration", "(", "int", "(", "cpup", ".", "time_taken", ")", ")", "*", "time", ".", "Second", ",", "TimeTaken", ":", "time", ".", "Now", "(", ")", ",", "}", "\n", "}", ")", "\n", "return", "cpu", "\n", "}" ]
// CPUStats get cpu related stats // note that 1st call to 100ms may return NaN as values // Go equivalent to sg_cpu_percents
[ "CPUStats", "get", "cpu", "related", "stats", "note", "that", "1st", "call", "to", "100ms", "may", "return", "NaN", "as", "values", "Go", "equivalent", "to", "sg_cpu_percents" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/cpu_stats.go#L35-L61
11,513
akhenakh/statgo
fs_infos.go
FSInfos
func (s *Stat) FSInfos() []*FSInfos { s.Lock() defer s.Unlock() var fsSize C.size_t var cArray *C.sg_fs_stats = C.sg_get_fs_stats(&fsSize) length := int(fsSize) slice := (*[1 << 16]C.sg_fs_stats)(unsafe.Pointer(cArray))[:length:length] var res []*FSInfos for _, v := range slice { f := &FSInfos{ DeviceName: C.GoString(v.device_name), FSType: C.GoString(v.fs_type), MountPoint: C.GoString(v.mnt_point), Size: int(v.size), Used: int(v.used), Free: int(v.free), Available: int(v.avail), TotalInodes: int(v.total_inodes), UsedInodes: int(v.used_inodes), FreeInodes: int(v.free_inodes), AvailableInodes: int(v.avail_inodes), } res = append(res, f) } return res }
go
func (s *Stat) FSInfos() []*FSInfos { s.Lock() defer s.Unlock() var fsSize C.size_t var cArray *C.sg_fs_stats = C.sg_get_fs_stats(&fsSize) length := int(fsSize) slice := (*[1 << 16]C.sg_fs_stats)(unsafe.Pointer(cArray))[:length:length] var res []*FSInfos for _, v := range slice { f := &FSInfos{ DeviceName: C.GoString(v.device_name), FSType: C.GoString(v.fs_type), MountPoint: C.GoString(v.mnt_point), Size: int(v.size), Used: int(v.used), Free: int(v.free), Available: int(v.avail), TotalInodes: int(v.total_inodes), UsedInodes: int(v.used_inodes), FreeInodes: int(v.free_inodes), AvailableInodes: int(v.avail_inodes), } res = append(res, f) } return res }
[ "func", "(", "s", "*", "Stat", ")", "FSInfos", "(", ")", "[", "]", "*", "FSInfos", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "var", "fsSize", "C", ".", "size_t", "\n", "var", "cArray", "*", "C", ".", "sg_fs_stats", "=", "C", ".", "sg_get_fs_stats", "(", "&", "fsSize", ")", "\n", "length", ":=", "int", "(", "fsSize", ")", "\n", "slice", ":=", "(", "*", "[", "1", "<<", "16", "]", "C", ".", "sg_fs_stats", ")", "(", "unsafe", ".", "Pointer", "(", "cArray", ")", ")", "[", ":", "length", ":", "length", "]", "\n\n", "var", "res", "[", "]", "*", "FSInfos", "\n\n", "for", "_", ",", "v", ":=", "range", "slice", "{", "f", ":=", "&", "FSInfos", "{", "DeviceName", ":", "C", ".", "GoString", "(", "v", ".", "device_name", ")", ",", "FSType", ":", "C", ".", "GoString", "(", "v", ".", "fs_type", ")", ",", "MountPoint", ":", "C", ".", "GoString", "(", "v", ".", "mnt_point", ")", ",", "Size", ":", "int", "(", "v", ".", "size", ")", ",", "Used", ":", "int", "(", "v", ".", "used", ")", ",", "Free", ":", "int", "(", "v", ".", "free", ")", ",", "Available", ":", "int", "(", "v", ".", "avail", ")", ",", "TotalInodes", ":", "int", "(", "v", ".", "total_inodes", ")", ",", "UsedInodes", ":", "int", "(", "v", ".", "used_inodes", ")", ",", "FreeInodes", ":", "int", "(", "v", ".", "free_inodes", ")", ",", "AvailableInodes", ":", "int", "(", "v", ".", "avail_inodes", ")", ",", "}", "\n", "res", "=", "append", "(", "res", ",", "f", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// FSInfos return an FSInfo struct per mounted filesystem // Go equivalent to sg_get_fs_stats
[ "FSInfos", "return", "an", "FSInfo", "struct", "per", "mounted", "filesystem", "Go", "equivalent", "to", "sg_get_fs_stats" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/fs_infos.go#L32-L59
11,514
akhenakh/statgo
statgo.go
NewStat
func NewStat() *Stat { s := &Stat{} runtime.SetFinalizer(s, (*Stat).free) initDone := make(chan bool) s.exitMessage = make(chan bool) C.sg_init(1) go func() { // We need some function calls to be performed on the same thread // Those for which statgrab is using a thread local runtime.LockOSThread() defer runtime.UnlockOSThread() // Throw away the first reading as thats averaged over the machines uptime C.sg_get_cpu_stats_diff(nil) C.sg_get_network_io_stats_diff(nil) C.sg_get_page_stats_diff(nil) C.sg_get_disk_io_stats_diff(nil) initDone <- true for { select { case <-s.exitMessage: return case f := <-mainfunc: f() } } }() <-initDone return s }
go
func NewStat() *Stat { s := &Stat{} runtime.SetFinalizer(s, (*Stat).free) initDone := make(chan bool) s.exitMessage = make(chan bool) C.sg_init(1) go func() { // We need some function calls to be performed on the same thread // Those for which statgrab is using a thread local runtime.LockOSThread() defer runtime.UnlockOSThread() // Throw away the first reading as thats averaged over the machines uptime C.sg_get_cpu_stats_diff(nil) C.sg_get_network_io_stats_diff(nil) C.sg_get_page_stats_diff(nil) C.sg_get_disk_io_stats_diff(nil) initDone <- true for { select { case <-s.exitMessage: return case f := <-mainfunc: f() } } }() <-initDone return s }
[ "func", "NewStat", "(", ")", "*", "Stat", "{", "s", ":=", "&", "Stat", "{", "}", "\n", "runtime", ".", "SetFinalizer", "(", "s", ",", "(", "*", "Stat", ")", ".", "free", ")", "\n\n", "initDone", ":=", "make", "(", "chan", "bool", ")", "\n", "s", ".", "exitMessage", "=", "make", "(", "chan", "bool", ")", "\n\n", "C", ".", "sg_init", "(", "1", ")", "\n\n", "go", "func", "(", ")", "{", "// We need some function calls to be performed on the same thread", "// Those for which statgrab is using a thread local", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n\n", "// Throw away the first reading as thats averaged over the machines uptime", "C", ".", "sg_get_cpu_stats_diff", "(", "nil", ")", "\n", "C", ".", "sg_get_network_io_stats_diff", "(", "nil", ")", "\n", "C", ".", "sg_get_page_stats_diff", "(", "nil", ")", "\n", "C", ".", "sg_get_disk_io_stats_diff", "(", "nil", ")", "\n\n", "initDone", "<-", "true", "\n\n", "for", "{", "select", "{", "case", "<-", "s", ".", "exitMessage", ":", "return", "\n", "case", "f", ":=", "<-", "mainfunc", ":", "f", "(", ")", "\n", "}", "\n", "}", "\n\n", "}", "(", ")", "\n\n", "<-", "initDone", "\n\n", "return", "s", "\n", "}" ]
// NewStat return a new Stat handle
[ "NewStat", "return", "a", "new", "Stat", "handle" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/statgo.go#L18-L55
11,515
akhenakh/statgo
statgo.go
do
func do(f func()) { done := make(chan bool, 1) mainfunc <- func() { f() done <- true } <-done }
go
func do(f func()) { done := make(chan bool, 1) mainfunc <- func() { f() done <- true } <-done }
[ "func", "do", "(", "f", "func", "(", ")", ")", "{", "done", ":=", "make", "(", "chan", "bool", ",", "1", ")", "\n", "mainfunc", "<-", "func", "(", ")", "{", "f", "(", ")", "\n", "done", "<-", "true", "\n", "}", "\n", "<-", "done", "\n", "}" ]
// do runs f on the main thread.
[ "do", "runs", "f", "on", "the", "main", "thread", "." ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/statgo.go#L68-L75
11,516
akhenakh/statgo
net_io_stats.go
NetIOStats
func (s *Stat) NetIOStats() []*NetIOStats { s.Lock() defer s.Unlock() var res []*NetIOStats do(func() { var nSize C.size_t var cArray *C.sg_network_io_stats = C.sg_get_network_io_stats_diff(&nSize) length := int(nSize) slice := (*[1 << 16]C.sg_network_io_stats)(unsafe.Pointer(cArray))[:length:length] for _, v := range slice { n := &NetIOStats{ IntName: C.GoString(v.interface_name), TX: int(v.tx), RX: int(v.rx), IPackets: int(v.ipackets), OPackets: int(v.opackets), IErrors: int(v.ierrors), OErrors: int(v.oerrors), Collisions: int(v.collisions), Period: time.Duration(int(v.systime)) * time.Second, TimeTaken: time.Now(), } res = append(res, n) } }) return res }
go
func (s *Stat) NetIOStats() []*NetIOStats { s.Lock() defer s.Unlock() var res []*NetIOStats do(func() { var nSize C.size_t var cArray *C.sg_network_io_stats = C.sg_get_network_io_stats_diff(&nSize) length := int(nSize) slice := (*[1 << 16]C.sg_network_io_stats)(unsafe.Pointer(cArray))[:length:length] for _, v := range slice { n := &NetIOStats{ IntName: C.GoString(v.interface_name), TX: int(v.tx), RX: int(v.rx), IPackets: int(v.ipackets), OPackets: int(v.opackets), IErrors: int(v.ierrors), OErrors: int(v.oerrors), Collisions: int(v.collisions), Period: time.Duration(int(v.systime)) * time.Second, TimeTaken: time.Now(), } res = append(res, n) } }) return res }
[ "func", "(", "s", "*", "Stat", ")", "NetIOStats", "(", ")", "[", "]", "*", "NetIOStats", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "var", "res", "[", "]", "*", "NetIOStats", "\n\n", "do", "(", "func", "(", ")", "{", "var", "nSize", "C", ".", "size_t", "\n", "var", "cArray", "*", "C", ".", "sg_network_io_stats", "=", "C", ".", "sg_get_network_io_stats_diff", "(", "&", "nSize", ")", "\n", "length", ":=", "int", "(", "nSize", ")", "\n", "slice", ":=", "(", "*", "[", "1", "<<", "16", "]", "C", ".", "sg_network_io_stats", ")", "(", "unsafe", ".", "Pointer", "(", "cArray", ")", ")", "[", ":", "length", ":", "length", "]", "\n\n", "for", "_", ",", "v", ":=", "range", "slice", "{", "n", ":=", "&", "NetIOStats", "{", "IntName", ":", "C", ".", "GoString", "(", "v", ".", "interface_name", ")", ",", "TX", ":", "int", "(", "v", ".", "tx", ")", ",", "RX", ":", "int", "(", "v", ".", "rx", ")", ",", "IPackets", ":", "int", "(", "v", ".", "ipackets", ")", ",", "OPackets", ":", "int", "(", "v", ".", "opackets", ")", ",", "IErrors", ":", "int", "(", "v", ".", "ierrors", ")", ",", "OErrors", ":", "int", "(", "v", ".", "oerrors", ")", ",", "Collisions", ":", "int", "(", "v", ".", "collisions", ")", ",", "Period", ":", "time", ".", "Duration", "(", "int", "(", "v", ".", "systime", ")", ")", "*", "time", ".", "Second", ",", "TimeTaken", ":", "time", ".", "Now", "(", ")", ",", "}", "\n\n", "res", "=", "append", "(", "res", ",", "n", ")", "\n", "}", "\n", "}", ")", "\n", "return", "res", "\n", "}" ]
// NetIOStats get interface ios related stats // Go equivalent to sg_get_network_io_stats
[ "NetIOStats", "get", "interface", "ios", "related", "stats", "Go", "equivalent", "to", "sg_get_network_io_stats" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/net_io_stats.go#L45-L75
11,517
akhenakh/statgo
pages_stats.go
PageStats
func (s *Stat) PageStats() *PageStats { s.Lock() defer s.Unlock() var p *PageStats do(func() { pstats := C.sg_get_page_stats_diff(nil) p = &PageStats{ PageIn: int(pstats.pages_pagein), PageOut: int(pstats.pages_pageout), Period: time.Duration(int(pstats.systime)), TimeTaken: time.Now(), } }) return p }
go
func (s *Stat) PageStats() *PageStats { s.Lock() defer s.Unlock() var p *PageStats do(func() { pstats := C.sg_get_page_stats_diff(nil) p = &PageStats{ PageIn: int(pstats.pages_pagein), PageOut: int(pstats.pages_pageout), Period: time.Duration(int(pstats.systime)), TimeTaken: time.Now(), } }) return p }
[ "func", "(", "s", "*", "Stat", ")", "PageStats", "(", ")", "*", "PageStats", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "var", "p", "*", "PageStats", "\n\n", "do", "(", "func", "(", ")", "{", "pstats", ":=", "C", ".", "sg_get_page_stats_diff", "(", "nil", ")", "\n\n", "p", "=", "&", "PageStats", "{", "PageIn", ":", "int", "(", "pstats", ".", "pages_pagein", ")", ",", "PageOut", ":", "int", "(", "pstats", ".", "pages_pageout", ")", ",", "Period", ":", "time", ".", "Duration", "(", "int", "(", "pstats", ".", "systime", ")", ")", ",", "TimeTaken", ":", "time", ".", "Now", "(", ")", ",", "}", "\n", "}", ")", "\n", "return", "p", "\n", "}" ]
// PageStats get pages related stats // Go equivalent to sg_get_page_stats_diff
[ "PageStats", "get", "pages", "related", "stats", "Go", "equivalent", "to", "sg_get_page_stats_diff" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/pages_stats.go#L27-L44
11,518
akhenakh/statgo
mem_stats.go
MemStats
func (s *Stat) MemStats() *MemStats { s.Lock() defer s.Unlock() memStats := C.sg_get_mem_stats(nil) swapStats := C.sg_get_swap_stats(nil) m := &MemStats{ Total: int(memStats.total), Free: int(memStats.free), Used: int(memStats.used), Cache: int(memStats.cache), SwapTotal: int(swapStats.total), SwapUsed: int(swapStats.used), SwapFree: int(swapStats.free), } return m }
go
func (s *Stat) MemStats() *MemStats { s.Lock() defer s.Unlock() memStats := C.sg_get_mem_stats(nil) swapStats := C.sg_get_swap_stats(nil) m := &MemStats{ Total: int(memStats.total), Free: int(memStats.free), Used: int(memStats.used), Cache: int(memStats.cache), SwapTotal: int(swapStats.total), SwapUsed: int(swapStats.used), SwapFree: int(swapStats.free), } return m }
[ "func", "(", "s", "*", "Stat", ")", "MemStats", "(", ")", "*", "MemStats", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "memStats", ":=", "C", ".", "sg_get_mem_stats", "(", "nil", ")", "\n", "swapStats", ":=", "C", ".", "sg_get_swap_stats", "(", "nil", ")", "\n\n", "m", ":=", "&", "MemStats", "{", "Total", ":", "int", "(", "memStats", ".", "total", ")", ",", "Free", ":", "int", "(", "memStats", ".", "free", ")", ",", "Used", ":", "int", "(", "memStats", ".", "used", ")", ",", "Cache", ":", "int", "(", "memStats", ".", "cache", ")", ",", "SwapTotal", ":", "int", "(", "swapStats", ".", "total", ")", ",", "SwapUsed", ":", "int", "(", "swapStats", ".", "used", ")", ",", "SwapFree", ":", "int", "(", "swapStats", ".", "free", ")", ",", "}", "\n", "return", "m", "\n", "}" ]
// MemStats get memory & swap related stats // Go equivalent to sg_get_mem_stats & sg_get_swap_stats
[ "MemStats", "get", "memory", "&", "swap", "related", "stats", "Go", "equivalent", "to", "sg_get_mem_stats", "&", "sg_get_swap_stats" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/mem_stats.go#L35-L52
11,519
akhenakh/statgo
host_info.go
HostInfos
func (s *Stat) HostInfos() *HostInfos { s.Lock() stats := C.sg_get_host_info(nil) s.Unlock() hi := &HostInfos{ OSName: C.GoString(stats.os_name), OSRelease: C.GoString(stats.os_release), OSVersion: C.GoString(stats.os_version), Platform: C.GoString(stats.platform), HostName: C.GoString(stats.hostname), NCPUs: int(stats.ncpus), MaxCPUs: int(stats.maxcpus), BitWidth: int(stats.bitwidth), //TODO: uptime } return hi }
go
func (s *Stat) HostInfos() *HostInfos { s.Lock() stats := C.sg_get_host_info(nil) s.Unlock() hi := &HostInfos{ OSName: C.GoString(stats.os_name), OSRelease: C.GoString(stats.os_release), OSVersion: C.GoString(stats.os_version), Platform: C.GoString(stats.platform), HostName: C.GoString(stats.hostname), NCPUs: int(stats.ncpus), MaxCPUs: int(stats.maxcpus), BitWidth: int(stats.bitwidth), //TODO: uptime } return hi }
[ "func", "(", "s", "*", "Stat", ")", "HostInfos", "(", ")", "*", "HostInfos", "{", "s", ".", "Lock", "(", ")", "\n", "stats", ":=", "C", ".", "sg_get_host_info", "(", "nil", ")", "\n", "s", ".", "Unlock", "(", ")", "\n\n", "hi", ":=", "&", "HostInfos", "{", "OSName", ":", "C", ".", "GoString", "(", "stats", ".", "os_name", ")", ",", "OSRelease", ":", "C", ".", "GoString", "(", "stats", ".", "os_release", ")", ",", "OSVersion", ":", "C", ".", "GoString", "(", "stats", ".", "os_version", ")", ",", "Platform", ":", "C", ".", "GoString", "(", "stats", ".", "platform", ")", ",", "HostName", ":", "C", ".", "GoString", "(", "stats", ".", "hostname", ")", ",", "NCPUs", ":", "int", "(", "stats", ".", "ncpus", ")", ",", "MaxCPUs", ":", "int", "(", "stats", ".", "maxcpus", ")", ",", "BitWidth", ":", "int", "(", "stats", ".", "bitwidth", ")", ",", "//TODO: uptime", "}", "\n\n", "return", "hi", "\n", "}" ]
// HostInfos get the host informations // Go equivalent to sg_host_info
[ "HostInfos", "get", "the", "host", "informations", "Go", "equivalent", "to", "sg_host_info" ]
3ae2cda264c55e1eaffaaa11f626b6c833eeff29
https://github.com/akhenakh/statgo/blob/3ae2cda264c55e1eaffaaa11f626b6c833eeff29/host_info.go#L27-L45
11,520
pquerna/cachecontrol
cacheobject/object.go
UsingRequestResponse
func UsingRequestResponse(req *http.Request, statusCode int, respHeaders http.Header, privateCache bool) ([]Reason, time.Time, error) { reasons, time, _, _, err := UsingRequestResponseWithObject(req, statusCode, respHeaders, privateCache) return reasons, time, err }
go
func UsingRequestResponse(req *http.Request, statusCode int, respHeaders http.Header, privateCache bool) ([]Reason, time.Time, error) { reasons, time, _, _, err := UsingRequestResponseWithObject(req, statusCode, respHeaders, privateCache) return reasons, time, err }
[ "func", "UsingRequestResponse", "(", "req", "*", "http", ".", "Request", ",", "statusCode", "int", ",", "respHeaders", "http", ".", "Header", ",", "privateCache", "bool", ")", "(", "[", "]", "Reason", ",", "time", ".", "Time", ",", "error", ")", "{", "reasons", ",", "time", ",", "_", ",", "_", ",", "err", ":=", "UsingRequestResponseWithObject", "(", "req", ",", "statusCode", ",", "respHeaders", ",", "privateCache", ")", "\n", "return", "reasons", ",", "time", ",", "err", "\n", "}" ]
// Evaluate cachability based on an HTTP request, and parts of the response.
[ "Evaluate", "cachability", "based", "on", "an", "HTTP", "request", "and", "parts", "of", "the", "response", "." ]
1555304b9b35fdd2b425bccf1a5613677705e7d0
https://github.com/pquerna/cachecontrol/blob/1555304b9b35fdd2b425bccf1a5613677705e7d0/cacheobject/object.go#L242-L248
11,521
pquerna/cachecontrol
cacheobject/object.go
UsingRequestResponseWithObject
func UsingRequestResponseWithObject(req *http.Request, statusCode int, respHeaders http.Header, privateCache bool) ([]Reason, time.Time, []Warning, *Object, error) { var reqHeaders http.Header var reqMethod string var reqDir *RequestCacheDirectives = nil respDir, err := ParseResponseCacheControl(respHeaders.Get("Cache-Control")) if err != nil { return nil, time.Time{}, nil, nil, err } if req != nil { reqDir, err = ParseRequestCacheControl(req.Header.Get("Cache-Control")) if err != nil { return nil, time.Time{}, nil, nil, err } reqHeaders = req.Header reqMethod = req.Method } var expiresHeader time.Time var dateHeader time.Time var lastModifiedHeader time.Time if respHeaders.Get("Expires") != "" { expiresHeader, err = http.ParseTime(respHeaders.Get("Expires")) if err != nil { // sometimes servers will return `Expires: 0` or `Expires: -1` to // indicate expired content expiresHeader = time.Time{} } expiresHeader = expiresHeader.UTC() } if respHeaders.Get("Date") != "" { dateHeader, err = http.ParseTime(respHeaders.Get("Date")) if err != nil { return nil, time.Time{}, nil, nil, err } dateHeader = dateHeader.UTC() } if respHeaders.Get("Last-Modified") != "" { lastModifiedHeader, err = http.ParseTime(respHeaders.Get("Last-Modified")) if err != nil { return nil, time.Time{}, nil, nil, err } lastModifiedHeader = lastModifiedHeader.UTC() } obj := Object{ CacheIsPrivate: privateCache, RespDirectives: respDir, RespHeaders: respHeaders, RespStatusCode: statusCode, RespExpiresHeader: expiresHeader, RespDateHeader: dateHeader, RespLastModifiedHeader: lastModifiedHeader, ReqDirectives: reqDir, ReqHeaders: reqHeaders, ReqMethod: reqMethod, NowUTC: time.Now().UTC(), } rv := ObjectResults{} CachableObject(&obj, &rv) if rv.OutErr != nil { return nil, time.Time{}, nil, nil, rv.OutErr } ExpirationObject(&obj, &rv) if rv.OutErr != nil { return nil, time.Time{}, nil, nil, rv.OutErr } return rv.OutReasons, rv.OutExpirationTime, rv.OutWarnings, &obj, nil }
go
func UsingRequestResponseWithObject(req *http.Request, statusCode int, respHeaders http.Header, privateCache bool) ([]Reason, time.Time, []Warning, *Object, error) { var reqHeaders http.Header var reqMethod string var reqDir *RequestCacheDirectives = nil respDir, err := ParseResponseCacheControl(respHeaders.Get("Cache-Control")) if err != nil { return nil, time.Time{}, nil, nil, err } if req != nil { reqDir, err = ParseRequestCacheControl(req.Header.Get("Cache-Control")) if err != nil { return nil, time.Time{}, nil, nil, err } reqHeaders = req.Header reqMethod = req.Method } var expiresHeader time.Time var dateHeader time.Time var lastModifiedHeader time.Time if respHeaders.Get("Expires") != "" { expiresHeader, err = http.ParseTime(respHeaders.Get("Expires")) if err != nil { // sometimes servers will return `Expires: 0` or `Expires: -1` to // indicate expired content expiresHeader = time.Time{} } expiresHeader = expiresHeader.UTC() } if respHeaders.Get("Date") != "" { dateHeader, err = http.ParseTime(respHeaders.Get("Date")) if err != nil { return nil, time.Time{}, nil, nil, err } dateHeader = dateHeader.UTC() } if respHeaders.Get("Last-Modified") != "" { lastModifiedHeader, err = http.ParseTime(respHeaders.Get("Last-Modified")) if err != nil { return nil, time.Time{}, nil, nil, err } lastModifiedHeader = lastModifiedHeader.UTC() } obj := Object{ CacheIsPrivate: privateCache, RespDirectives: respDir, RespHeaders: respHeaders, RespStatusCode: statusCode, RespExpiresHeader: expiresHeader, RespDateHeader: dateHeader, RespLastModifiedHeader: lastModifiedHeader, ReqDirectives: reqDir, ReqHeaders: reqHeaders, ReqMethod: reqMethod, NowUTC: time.Now().UTC(), } rv := ObjectResults{} CachableObject(&obj, &rv) if rv.OutErr != nil { return nil, time.Time{}, nil, nil, rv.OutErr } ExpirationObject(&obj, &rv) if rv.OutErr != nil { return nil, time.Time{}, nil, nil, rv.OutErr } return rv.OutReasons, rv.OutExpirationTime, rv.OutWarnings, &obj, nil }
[ "func", "UsingRequestResponseWithObject", "(", "req", "*", "http", ".", "Request", ",", "statusCode", "int", ",", "respHeaders", "http", ".", "Header", ",", "privateCache", "bool", ")", "(", "[", "]", "Reason", ",", "time", ".", "Time", ",", "[", "]", "Warning", ",", "*", "Object", ",", "error", ")", "{", "var", "reqHeaders", "http", ".", "Header", "\n", "var", "reqMethod", "string", "\n\n", "var", "reqDir", "*", "RequestCacheDirectives", "=", "nil", "\n", "respDir", ",", "err", ":=", "ParseResponseCacheControl", "(", "respHeaders", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "time", ".", "Time", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "if", "req", "!=", "nil", "{", "reqDir", ",", "err", "=", "ParseRequestCacheControl", "(", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "time", ".", "Time", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "reqHeaders", "=", "req", ".", "Header", "\n", "reqMethod", "=", "req", ".", "Method", "\n", "}", "\n\n", "var", "expiresHeader", "time", ".", "Time", "\n", "var", "dateHeader", "time", ".", "Time", "\n", "var", "lastModifiedHeader", "time", ".", "Time", "\n\n", "if", "respHeaders", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "expiresHeader", ",", "err", "=", "http", ".", "ParseTime", "(", "respHeaders", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "// sometimes servers will return `Expires: 0` or `Expires: -1` to", "// indicate expired content", "expiresHeader", "=", "time", ".", "Time", "{", "}", "\n", "}", "\n", "expiresHeader", "=", "expiresHeader", ".", "UTC", "(", ")", "\n", "}", "\n\n", "if", "respHeaders", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "dateHeader", ",", "err", "=", "http", ".", "ParseTime", "(", "respHeaders", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "time", ".", "Time", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "dateHeader", "=", "dateHeader", ".", "UTC", "(", ")", "\n", "}", "\n\n", "if", "respHeaders", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "lastModifiedHeader", ",", "err", "=", "http", ".", "ParseTime", "(", "respHeaders", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "time", ".", "Time", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "lastModifiedHeader", "=", "lastModifiedHeader", ".", "UTC", "(", ")", "\n", "}", "\n\n", "obj", ":=", "Object", "{", "CacheIsPrivate", ":", "privateCache", ",", "RespDirectives", ":", "respDir", ",", "RespHeaders", ":", "respHeaders", ",", "RespStatusCode", ":", "statusCode", ",", "RespExpiresHeader", ":", "expiresHeader", ",", "RespDateHeader", ":", "dateHeader", ",", "RespLastModifiedHeader", ":", "lastModifiedHeader", ",", "ReqDirectives", ":", "reqDir", ",", "ReqHeaders", ":", "reqHeaders", ",", "ReqMethod", ":", "reqMethod", ",", "NowUTC", ":", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ",", "}", "\n", "rv", ":=", "ObjectResults", "{", "}", "\n\n", "CachableObject", "(", "&", "obj", ",", "&", "rv", ")", "\n", "if", "rv", ".", "OutErr", "!=", "nil", "{", "return", "nil", ",", "time", ".", "Time", "{", "}", ",", "nil", ",", "nil", ",", "rv", ".", "OutErr", "\n", "}", "\n\n", "ExpirationObject", "(", "&", "obj", ",", "&", "rv", ")", "\n", "if", "rv", ".", "OutErr", "!=", "nil", "{", "return", "nil", ",", "time", ".", "Time", "{", "}", ",", "nil", ",", "nil", ",", "rv", ".", "OutErr", "\n", "}", "\n\n", "return", "rv", ".", "OutReasons", ",", "rv", ".", "OutExpirationTime", ",", "rv", ".", "OutWarnings", ",", "&", "obj", ",", "nil", "\n", "}" ]
// Evaluate cachability based on an HTTP request, and parts of the response. // Returns the parsed Object as well.
[ "Evaluate", "cachability", "based", "on", "an", "HTTP", "request", "and", "parts", "of", "the", "response", ".", "Returns", "the", "parsed", "Object", "as", "well", "." ]
1555304b9b35fdd2b425bccf1a5613677705e7d0
https://github.com/pquerna/cachecontrol/blob/1555304b9b35fdd2b425bccf1a5613677705e7d0/cacheobject/object.go#L252-L333
11,522
pquerna/cachecontrol
api.go
CachableResponseWriter
func CachableResponseWriter(req *http.Request, statusCode int, resp http.ResponseWriter, opts Options) ([]cacheobject.Reason, time.Time, error) { return cacheobject.UsingRequestResponse(req, statusCode, resp.Header(), opts.PrivateCache) }
go
func CachableResponseWriter(req *http.Request, statusCode int, resp http.ResponseWriter, opts Options) ([]cacheobject.Reason, time.Time, error) { return cacheobject.UsingRequestResponse(req, statusCode, resp.Header(), opts.PrivateCache) }
[ "func", "CachableResponseWriter", "(", "req", "*", "http", ".", "Request", ",", "statusCode", "int", ",", "resp", "http", ".", "ResponseWriter", ",", "opts", "Options", ")", "(", "[", "]", "cacheobject", ".", "Reason", ",", "time", ".", "Time", ",", "error", ")", "{", "return", "cacheobject", ".", "UsingRequestResponse", "(", "req", ",", "statusCode", ",", "resp", ".", "Header", "(", ")", ",", "opts", ".", "PrivateCache", ")", "\n", "}" ]
// Given an HTTP Request, the future Status Code, and an ResponseWriter, // determine the possible reasons a response SHOULD NOT be cached.
[ "Given", "an", "HTTP", "Request", "the", "future", "Status", "Code", "and", "an", "ResponseWriter", "determine", "the", "possible", "reasons", "a", "response", "SHOULD", "NOT", "be", "cached", "." ]
1555304b9b35fdd2b425bccf1a5613677705e7d0
https://github.com/pquerna/cachecontrol/blob/1555304b9b35fdd2b425bccf1a5613677705e7d0/api.go#L35-L40
11,523
pquerna/cachecontrol
api.go
CachableResponse
func CachableResponse(req *http.Request, resp *http.Response, opts Options) ([]cacheobject.Reason, time.Time, error) { return cacheobject.UsingRequestResponse(req, resp.StatusCode, resp.Header, opts.PrivateCache) }
go
func CachableResponse(req *http.Request, resp *http.Response, opts Options) ([]cacheobject.Reason, time.Time, error) { return cacheobject.UsingRequestResponse(req, resp.StatusCode, resp.Header, opts.PrivateCache) }
[ "func", "CachableResponse", "(", "req", "*", "http", ".", "Request", ",", "resp", "*", "http", ".", "Response", ",", "opts", "Options", ")", "(", "[", "]", "cacheobject", ".", "Reason", ",", "time", ".", "Time", ",", "error", ")", "{", "return", "cacheobject", ".", "UsingRequestResponse", "(", "req", ",", "resp", ".", "StatusCode", ",", "resp", ".", "Header", ",", "opts", ".", "PrivateCache", ")", "\n", "}" ]
// Given an HTTP Request and Response, determine the possible reasons a response SHOULD NOT // be cached.
[ "Given", "an", "HTTP", "Request", "and", "Response", "determine", "the", "possible", "reasons", "a", "response", "SHOULD", "NOT", "be", "cached", "." ]
1555304b9b35fdd2b425bccf1a5613677705e7d0
https://github.com/pquerna/cachecontrol/blob/1555304b9b35fdd2b425bccf1a5613677705e7d0/api.go#L44-L48
11,524
pquerna/cachecontrol
cacheobject/lex.go
httpUnquote
func httpUnquote(raw string) (eaten int, result string) { buf := make([]byte, len(raw)) if raw[0] != '"' { return -1, "" } eaten = 1 j := 0 // # of bytes written in buf for i := 1; i < len(raw); i++ { switch b := raw[i]; b { case '"': eaten++ buf = buf[0:j] return i + 1, string(buf) case '\\': if len(raw) < i+2 { return -1, "" } buf[j] = httpUnquotePair(raw[i+1]) eaten += 2 j++ i++ default: if isQdText(b) { buf[j] = b } else { buf[j] = '?' } eaten++ j++ } } return -1, "" }
go
func httpUnquote(raw string) (eaten int, result string) { buf := make([]byte, len(raw)) if raw[0] != '"' { return -1, "" } eaten = 1 j := 0 // # of bytes written in buf for i := 1; i < len(raw); i++ { switch b := raw[i]; b { case '"': eaten++ buf = buf[0:j] return i + 1, string(buf) case '\\': if len(raw) < i+2 { return -1, "" } buf[j] = httpUnquotePair(raw[i+1]) eaten += 2 j++ i++ default: if isQdText(b) { buf[j] = b } else { buf[j] = '?' } eaten++ j++ } } return -1, "" }
[ "func", "httpUnquote", "(", "raw", "string", ")", "(", "eaten", "int", ",", "result", "string", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "raw", ")", ")", "\n", "if", "raw", "[", "0", "]", "!=", "'\"'", "{", "return", "-", "1", ",", "\"", "\"", "\n", "}", "\n", "eaten", "=", "1", "\n", "j", ":=", "0", "// # of bytes written in buf", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "raw", ")", ";", "i", "++", "{", "switch", "b", ":=", "raw", "[", "i", "]", ";", "b", "{", "case", "'\"'", ":", "eaten", "++", "\n", "buf", "=", "buf", "[", "0", ":", "j", "]", "\n", "return", "i", "+", "1", ",", "string", "(", "buf", ")", "\n", "case", "'\\\\'", ":", "if", "len", "(", "raw", ")", "<", "i", "+", "2", "{", "return", "-", "1", ",", "\"", "\"", "\n", "}", "\n", "buf", "[", "j", "]", "=", "httpUnquotePair", "(", "raw", "[", "i", "+", "1", "]", ")", "\n", "eaten", "+=", "2", "\n", "j", "++", "\n", "i", "++", "\n", "default", ":", "if", "isQdText", "(", "b", ")", "{", "buf", "[", "j", "]", "=", "b", "\n", "}", "else", "{", "buf", "[", "j", "]", "=", "'?'", "\n", "}", "\n", "eaten", "++", "\n", "j", "++", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "\"", "\"", "\n", "}" ]
// raw must begin with a valid quoted string. Only the first quoted string is // parsed and is unquoted in result. eaten is the number of bytes parsed, or -1 // upon failure.
[ "raw", "must", "begin", "with", "a", "valid", "quoted", "string", ".", "Only", "the", "first", "quoted", "string", "is", "parsed", "and", "is", "unquoted", "in", "result", ".", "eaten", "is", "the", "number", "of", "bytes", "parsed", "or", "-", "1", "upon", "failure", "." ]
1555304b9b35fdd2b425bccf1a5613677705e7d0
https://github.com/pquerna/cachecontrol/blob/1555304b9b35fdd2b425bccf1a5613677705e7d0/cacheobject/lex.go#L61-L93
11,525
xeipuuv/gojsonpointer
pointer.go
NewJsonPointer
func NewJsonPointer(jsonPointerString string) (p JsonPointer, err error) { // Pointer to the root of the document if len(jsonPointerString) == 0 { // Keep referenceTokens nil return } if jsonPointerString[0] != '/' { return p, errors.New(const_invalid_start) } p.referenceTokens = strings.Split(jsonPointerString[1:], const_pointer_separator) return }
go
func NewJsonPointer(jsonPointerString string) (p JsonPointer, err error) { // Pointer to the root of the document if len(jsonPointerString) == 0 { // Keep referenceTokens nil return } if jsonPointerString[0] != '/' { return p, errors.New(const_invalid_start) } p.referenceTokens = strings.Split(jsonPointerString[1:], const_pointer_separator) return }
[ "func", "NewJsonPointer", "(", "jsonPointerString", "string", ")", "(", "p", "JsonPointer", ",", "err", "error", ")", "{", "// Pointer to the root of the document", "if", "len", "(", "jsonPointerString", ")", "==", "0", "{", "// Keep referenceTokens nil", "return", "\n", "}", "\n", "if", "jsonPointerString", "[", "0", "]", "!=", "'/'", "{", "return", "p", ",", "errors", ".", "New", "(", "const_invalid_start", ")", "\n", "}", "\n\n", "p", ".", "referenceTokens", "=", "strings", ".", "Split", "(", "jsonPointerString", "[", "1", ":", "]", ",", "const_pointer_separator", ")", "\n", "return", "\n", "}" ]
// NewJsonPointer parses the given string JSON pointer and returns an object
[ "NewJsonPointer", "parses", "the", "given", "string", "JSON", "pointer", "and", "returns", "an", "object" ]
4e3ac2762d5f479393488629ee9370b50873b3a6
https://github.com/xeipuuv/gojsonpointer/blob/4e3ac2762d5f479393488629ee9370b50873b3a6/pointer.go#L60-L73
11,526
xeipuuv/gojsonpointer
pointer.go
Get
func (p *JsonPointer) Get(document interface{}) (interface{}, reflect.Kind, error) { is := &implStruct{mode: "GET", inDocument: document} p.implementation(is) return is.getOutNode, is.getOutKind, is.outError }
go
func (p *JsonPointer) Get(document interface{}) (interface{}, reflect.Kind, error) { is := &implStruct{mode: "GET", inDocument: document} p.implementation(is) return is.getOutNode, is.getOutKind, is.outError }
[ "func", "(", "p", "*", "JsonPointer", ")", "Get", "(", "document", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "reflect", ".", "Kind", ",", "error", ")", "{", "is", ":=", "&", "implStruct", "{", "mode", ":", "\"", "\"", ",", "inDocument", ":", "document", "}", "\n", "p", ".", "implementation", "(", "is", ")", "\n", "return", "is", ".", "getOutNode", ",", "is", ".", "getOutKind", ",", "is", ".", "outError", "\n\n", "}" ]
// Uses the pointer to retrieve a value from a JSON document
[ "Uses", "the", "pointer", "to", "retrieve", "a", "value", "from", "a", "JSON", "document" ]
4e3ac2762d5f479393488629ee9370b50873b3a6
https://github.com/xeipuuv/gojsonpointer/blob/4e3ac2762d5f479393488629ee9370b50873b3a6/pointer.go#L76-L82
11,527
xeipuuv/gojsonpointer
pointer.go
Set
func (p *JsonPointer) Set(document interface{}, value interface{}) (interface{}, error) { is := &implStruct{mode: "SET", inDocument: document, setInValue: value} p.implementation(is) return document, is.outError }
go
func (p *JsonPointer) Set(document interface{}, value interface{}) (interface{}, error) { is := &implStruct{mode: "SET", inDocument: document, setInValue: value} p.implementation(is) return document, is.outError }
[ "func", "(", "p", "*", "JsonPointer", ")", "Set", "(", "document", "interface", "{", "}", ",", "value", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "is", ":=", "&", "implStruct", "{", "mode", ":", "\"", "\"", ",", "inDocument", ":", "document", ",", "setInValue", ":", "value", "}", "\n", "p", ".", "implementation", "(", "is", ")", "\n", "return", "document", ",", "is", ".", "outError", "\n\n", "}" ]
// Uses the pointer to update a value from a JSON document
[ "Uses", "the", "pointer", "to", "update", "a", "value", "from", "a", "JSON", "document" ]
4e3ac2762d5f479393488629ee9370b50873b3a6
https://github.com/xeipuuv/gojsonpointer/blob/4e3ac2762d5f479393488629ee9370b50873b3a6/pointer.go#L85-L91
11,528
xeipuuv/gojsonpointer
pointer.go
Delete
func (p *JsonPointer) Delete(document interface{}) (interface{}, error) { is := &implStruct{mode: "DEL", inDocument: document} p.implementation(is) return document, is.outError }
go
func (p *JsonPointer) Delete(document interface{}) (interface{}, error) { is := &implStruct{mode: "DEL", inDocument: document} p.implementation(is) return document, is.outError }
[ "func", "(", "p", "*", "JsonPointer", ")", "Delete", "(", "document", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "is", ":=", "&", "implStruct", "{", "mode", ":", "\"", "\"", ",", "inDocument", ":", "document", "}", "\n", "p", ".", "implementation", "(", "is", ")", "\n", "return", "document", ",", "is", ".", "outError", "\n", "}" ]
// Uses the pointer to delete a value from a JSON document
[ "Uses", "the", "pointer", "to", "delete", "a", "value", "from", "a", "JSON", "document" ]
4e3ac2762d5f479393488629ee9370b50873b3a6
https://github.com/xeipuuv/gojsonpointer/blob/4e3ac2762d5f479393488629ee9370b50873b3a6/pointer.go#L94-L98
11,529
mr-tron/base58
alphabet.go
NewAlphabet
func NewAlphabet(s string) *Alphabet { if len(s) != 58 { panic("base58 alphabets must be 58 bytes long") } ret := new(Alphabet) copy(ret.encode[:], s) for i := range ret.decode { ret.decode[i] = -1 } for i, b := range ret.encode { ret.decode[b] = int8(i) } return ret }
go
func NewAlphabet(s string) *Alphabet { if len(s) != 58 { panic("base58 alphabets must be 58 bytes long") } ret := new(Alphabet) copy(ret.encode[:], s) for i := range ret.decode { ret.decode[i] = -1 } for i, b := range ret.encode { ret.decode[b] = int8(i) } return ret }
[ "func", "NewAlphabet", "(", "s", "string", ")", "*", "Alphabet", "{", "if", "len", "(", "s", ")", "!=", "58", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "ret", ":=", "new", "(", "Alphabet", ")", "\n", "copy", "(", "ret", ".", "encode", "[", ":", "]", ",", "s", ")", "\n", "for", "i", ":=", "range", "ret", ".", "decode", "{", "ret", ".", "decode", "[", "i", "]", "=", "-", "1", "\n", "}", "\n", "for", "i", ",", "b", ":=", "range", "ret", ".", "encode", "{", "ret", ".", "decode", "[", "b", "]", "=", "int8", "(", "i", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// NewAlphabet creates a new alphabet from the passed string. // // It panics if the passed string is not 58 bytes long or isn't valid ASCII.
[ "NewAlphabet", "creates", "a", "new", "alphabet", "from", "the", "passed", "string", ".", "It", "panics", "if", "the", "passed", "string", "is", "not", "58", "bytes", "long", "or", "isn", "t", "valid", "ASCII", "." ]
d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43
https://github.com/mr-tron/base58/blob/d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43/alphabet.go#L12-L25
11,530
mr-tron/base58
base58.go
FastBase58EncodingAlphabet
func FastBase58EncodingAlphabet(bin []byte, alphabet *Alphabet) string { zero := alphabet.encode[0] binsz := len(bin) var i, j, zcount, high int var carry uint32 for zcount < binsz && bin[zcount] == 0 { zcount++ } size := ((binsz-zcount)*138/100 + 1) // allocate one big buffer up front buf := make([]byte, size*2+zcount) // use the second half for the temporary buffer tmp := buf[size+zcount:] high = size - 1 for i = zcount; i < binsz; i++ { j = size - 1 for carry = uint32(bin[i]); j > high || carry != 0; j-- { carry = carry + 256*uint32(tmp[j]) tmp[j] = byte(carry % 58) carry /= 58 } high = j } for j = 0; j < size && tmp[j] == 0; j++ { } // Use the first half for the result b58 := buf[:size-j+zcount] if zcount != 0 { for i = 0; i < zcount; i++ { b58[i] = zero } } for i = zcount; j < size; i++ { b58[i] = alphabet.encode[tmp[j]] j++ } return string(b58) }
go
func FastBase58EncodingAlphabet(bin []byte, alphabet *Alphabet) string { zero := alphabet.encode[0] binsz := len(bin) var i, j, zcount, high int var carry uint32 for zcount < binsz && bin[zcount] == 0 { zcount++ } size := ((binsz-zcount)*138/100 + 1) // allocate one big buffer up front buf := make([]byte, size*2+zcount) // use the second half for the temporary buffer tmp := buf[size+zcount:] high = size - 1 for i = zcount; i < binsz; i++ { j = size - 1 for carry = uint32(bin[i]); j > high || carry != 0; j-- { carry = carry + 256*uint32(tmp[j]) tmp[j] = byte(carry % 58) carry /= 58 } high = j } for j = 0; j < size && tmp[j] == 0; j++ { } // Use the first half for the result b58 := buf[:size-j+zcount] if zcount != 0 { for i = 0; i < zcount; i++ { b58[i] = zero } } for i = zcount; j < size; i++ { b58[i] = alphabet.encode[tmp[j]] j++ } return string(b58) }
[ "func", "FastBase58EncodingAlphabet", "(", "bin", "[", "]", "byte", ",", "alphabet", "*", "Alphabet", ")", "string", "{", "zero", ":=", "alphabet", ".", "encode", "[", "0", "]", "\n\n", "binsz", ":=", "len", "(", "bin", ")", "\n", "var", "i", ",", "j", ",", "zcount", ",", "high", "int", "\n", "var", "carry", "uint32", "\n\n", "for", "zcount", "<", "binsz", "&&", "bin", "[", "zcount", "]", "==", "0", "{", "zcount", "++", "\n", "}", "\n\n", "size", ":=", "(", "(", "binsz", "-", "zcount", ")", "*", "138", "/", "100", "+", "1", ")", "\n\n", "// allocate one big buffer up front", "buf", ":=", "make", "(", "[", "]", "byte", ",", "size", "*", "2", "+", "zcount", ")", "\n\n", "// use the second half for the temporary buffer", "tmp", ":=", "buf", "[", "size", "+", "zcount", ":", "]", "\n\n", "high", "=", "size", "-", "1", "\n", "for", "i", "=", "zcount", ";", "i", "<", "binsz", ";", "i", "++", "{", "j", "=", "size", "-", "1", "\n", "for", "carry", "=", "uint32", "(", "bin", "[", "i", "]", ")", ";", "j", ">", "high", "||", "carry", "!=", "0", ";", "j", "--", "{", "carry", "=", "carry", "+", "256", "*", "uint32", "(", "tmp", "[", "j", "]", ")", "\n", "tmp", "[", "j", "]", "=", "byte", "(", "carry", "%", "58", ")", "\n", "carry", "/=", "58", "\n", "}", "\n", "high", "=", "j", "\n", "}", "\n\n", "for", "j", "=", "0", ";", "j", "<", "size", "&&", "tmp", "[", "j", "]", "==", "0", ";", "j", "++", "{", "}", "\n\n", "// Use the first half for the result", "b58", ":=", "buf", "[", ":", "size", "-", "j", "+", "zcount", "]", "\n\n", "if", "zcount", "!=", "0", "{", "for", "i", "=", "0", ";", "i", "<", "zcount", ";", "i", "++", "{", "b58", "[", "i", "]", "=", "zero", "\n", "}", "\n", "}", "\n\n", "for", "i", "=", "zcount", ";", "j", "<", "size", ";", "i", "++", "{", "b58", "[", "i", "]", "=", "alphabet", ".", "encode", "[", "tmp", "[", "j", "]", "]", "\n", "j", "++", "\n", "}", "\n\n", "return", "string", "(", "b58", ")", "\n", "}" ]
// FastBase58EncodingAlphabet encodes the passed bytes into a base58 encoded // string with the passed alphabet.
[ "FastBase58EncodingAlphabet", "encodes", "the", "passed", "bytes", "into", "a", "base58", "encoded", "string", "with", "the", "passed", "alphabet", "." ]
d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43
https://github.com/mr-tron/base58/blob/d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43/base58.go#L25-L73
11,531
mr-tron/base58
base58.go
DecodeAlphabet
func DecodeAlphabet(str string, alphabet *Alphabet) ([]byte, error) { return FastBase58DecodingAlphabet(str, alphabet) }
go
func DecodeAlphabet(str string, alphabet *Alphabet) ([]byte, error) { return FastBase58DecodingAlphabet(str, alphabet) }
[ "func", "DecodeAlphabet", "(", "str", "string", ",", "alphabet", "*", "Alphabet", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "FastBase58DecodingAlphabet", "(", "str", ",", "alphabet", ")", "\n", "}" ]
// DecodeAlphabet decodes the base58 encoded bytes using the given b58 alphabet.
[ "DecodeAlphabet", "decodes", "the", "base58", "encoded", "bytes", "using", "the", "given", "b58", "alphabet", "." ]
d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43
https://github.com/mr-tron/base58/blob/d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43/base58.go#L81-L83
11,532
mr-tron/base58
base58/base58.go
FastBase58DecodingAlphabet
func FastBase58DecodingAlphabet(str string, alphabet *Alphabet) ([]byte, error) { if len(str) == 0 { return nil, fmt.Errorf("zero length string") } var ( t uint64 zmask, c uint32 zcount int b58u = []rune(str) b58sz = len(b58u) outisz = (b58sz + 3) / 4 // check to see if we need to change this buffer size to optimize binu = make([]byte, (b58sz+3)*3) bytesleft = b58sz % 4 zero = rune(alphabet.encode[0]) ) if bytesleft > 0 { zmask = (0xffffffff << uint32(bytesleft*8)) } else { bytesleft = 4 } var outi = make([]uint32, outisz) for i := 0; i < b58sz && b58u[i] == zero; i++ { zcount++ } for _, r := range b58u { if r > 127 { return nil, fmt.Errorf("High-bit set on invalid digit") } if alphabet.decode[r] == -1 { return nil, fmt.Errorf("Invalid base58 digit (%q)", r) } c = uint32(alphabet.decode[r]) for j := (outisz - 1); j >= 0; j-- { t = uint64(outi[j])*58 + uint64(c) c = uint32(t>>32) & 0x3f outi[j] = uint32(t & 0xffffffff) } if c > 0 { return nil, fmt.Errorf("Output number too big (carry to the next int32)") } if outi[0]&zmask != 0 { return nil, fmt.Errorf("Output number too big (last int32 filled too far)") } } // the nested for-loop below is the same as the original code: // switch (bytesleft) { // case 3: // *(binu++) = (outi[0] & 0xff0000) >> 16; // //-fallthrough // case 2: // *(binu++) = (outi[0] & 0xff00) >> 8; // //-fallthrough // case 1: // *(binu++) = (outi[0] & 0xff); // ++j; // //-fallthrough // default: // break; // } // // for (; j < outisz; ++j) // { // *(binu++) = (outi[j] >> 0x18) & 0xff; // *(binu++) = (outi[j] >> 0x10) & 0xff; // *(binu++) = (outi[j] >> 8) & 0xff; // *(binu++) = (outi[j] >> 0) & 0xff; // } var j, cnt int for j, cnt = 0, 0; j < outisz; j++ { for mask := byte(bytesleft-1) * 8; mask <= 0x18; mask, cnt = mask-8, cnt+1 { binu[cnt] = byte(outi[j] >> mask) } if j == 0 { bytesleft = 4 // because it could be less than 4 the first time through } } for n, v := range binu { if v > 0 { start := n - zcount if start < 0 { start = 0 } return binu[start:cnt], nil } } return binu[:cnt], nil }
go
func FastBase58DecodingAlphabet(str string, alphabet *Alphabet) ([]byte, error) { if len(str) == 0 { return nil, fmt.Errorf("zero length string") } var ( t uint64 zmask, c uint32 zcount int b58u = []rune(str) b58sz = len(b58u) outisz = (b58sz + 3) / 4 // check to see if we need to change this buffer size to optimize binu = make([]byte, (b58sz+3)*3) bytesleft = b58sz % 4 zero = rune(alphabet.encode[0]) ) if bytesleft > 0 { zmask = (0xffffffff << uint32(bytesleft*8)) } else { bytesleft = 4 } var outi = make([]uint32, outisz) for i := 0; i < b58sz && b58u[i] == zero; i++ { zcount++ } for _, r := range b58u { if r > 127 { return nil, fmt.Errorf("High-bit set on invalid digit") } if alphabet.decode[r] == -1 { return nil, fmt.Errorf("Invalid base58 digit (%q)", r) } c = uint32(alphabet.decode[r]) for j := (outisz - 1); j >= 0; j-- { t = uint64(outi[j])*58 + uint64(c) c = uint32(t>>32) & 0x3f outi[j] = uint32(t & 0xffffffff) } if c > 0 { return nil, fmt.Errorf("Output number too big (carry to the next int32)") } if outi[0]&zmask != 0 { return nil, fmt.Errorf("Output number too big (last int32 filled too far)") } } // the nested for-loop below is the same as the original code: // switch (bytesleft) { // case 3: // *(binu++) = (outi[0] & 0xff0000) >> 16; // //-fallthrough // case 2: // *(binu++) = (outi[0] & 0xff00) >> 8; // //-fallthrough // case 1: // *(binu++) = (outi[0] & 0xff); // ++j; // //-fallthrough // default: // break; // } // // for (; j < outisz; ++j) // { // *(binu++) = (outi[j] >> 0x18) & 0xff; // *(binu++) = (outi[j] >> 0x10) & 0xff; // *(binu++) = (outi[j] >> 8) & 0xff; // *(binu++) = (outi[j] >> 0) & 0xff; // } var j, cnt int for j, cnt = 0, 0; j < outisz; j++ { for mask := byte(bytesleft-1) * 8; mask <= 0x18; mask, cnt = mask-8, cnt+1 { binu[cnt] = byte(outi[j] >> mask) } if j == 0 { bytesleft = 4 // because it could be less than 4 the first time through } } for n, v := range binu { if v > 0 { start := n - zcount if start < 0 { start = 0 } return binu[start:cnt], nil } } return binu[:cnt], nil }
[ "func", "FastBase58DecodingAlphabet", "(", "str", "string", ",", "alphabet", "*", "Alphabet", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "str", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "(", "t", "uint64", "\n", "zmask", ",", "c", "uint32", "\n", "zcount", "int", "\n\n", "b58u", "=", "[", "]", "rune", "(", "str", ")", "\n", "b58sz", "=", "len", "(", "b58u", ")", "\n\n", "outisz", "=", "(", "b58sz", "+", "3", ")", "/", "4", "// check to see if we need to change this buffer size to optimize", "\n", "binu", "=", "make", "(", "[", "]", "byte", ",", "(", "b58sz", "+", "3", ")", "*", "3", ")", "\n", "bytesleft", "=", "b58sz", "%", "4", "\n\n", "zero", "=", "rune", "(", "alphabet", ".", "encode", "[", "0", "]", ")", "\n", ")", "\n\n", "if", "bytesleft", ">", "0", "{", "zmask", "=", "(", "0xffffffff", "<<", "uint32", "(", "bytesleft", "*", "8", ")", ")", "\n", "}", "else", "{", "bytesleft", "=", "4", "\n", "}", "\n\n", "var", "outi", "=", "make", "(", "[", "]", "uint32", ",", "outisz", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "b58sz", "&&", "b58u", "[", "i", "]", "==", "zero", ";", "i", "++", "{", "zcount", "++", "\n", "}", "\n\n", "for", "_", ",", "r", ":=", "range", "b58u", "{", "if", "r", ">", "127", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "alphabet", ".", "decode", "[", "r", "]", "==", "-", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n\n", "c", "=", "uint32", "(", "alphabet", ".", "decode", "[", "r", "]", ")", "\n\n", "for", "j", ":=", "(", "outisz", "-", "1", ")", ";", "j", ">=", "0", ";", "j", "--", "{", "t", "=", "uint64", "(", "outi", "[", "j", "]", ")", "*", "58", "+", "uint64", "(", "c", ")", "\n", "c", "=", "uint32", "(", "t", ">>", "32", ")", "&", "0x3f", "\n", "outi", "[", "j", "]", "=", "uint32", "(", "t", "&", "0xffffffff", ")", "\n", "}", "\n\n", "if", "c", ">", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "outi", "[", "0", "]", "&", "zmask", "!=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// the nested for-loop below is the same as the original code:", "// switch (bytesleft) {", "// \tcase 3:", "// \t\t*(binu++) = (outi[0] & 0xff0000) >> 16;", "// \t\t//-fallthrough", "// \tcase 2:", "// \t\t*(binu++) = (outi[0] & 0xff00) >> 8;", "// \t\t//-fallthrough", "// \tcase 1:", "// \t\t*(binu++) = (outi[0] & 0xff);", "// \t\t++j;", "// \t\t//-fallthrough", "// \tdefault:", "// \t\tbreak;", "// }", "//", "// for (; j < outisz; ++j)", "// {", "// \t*(binu++) = (outi[j] >> 0x18) & 0xff;", "// \t*(binu++) = (outi[j] >> 0x10) & 0xff;", "// \t*(binu++) = (outi[j] >> 8) & 0xff;", "// \t*(binu++) = (outi[j] >> 0) & 0xff;", "// }", "var", "j", ",", "cnt", "int", "\n", "for", "j", ",", "cnt", "=", "0", ",", "0", ";", "j", "<", "outisz", ";", "j", "++", "{", "for", "mask", ":=", "byte", "(", "bytesleft", "-", "1", ")", "*", "8", ";", "mask", "<=", "0x18", ";", "mask", ",", "cnt", "=", "mask", "-", "8", ",", "cnt", "+", "1", "{", "binu", "[", "cnt", "]", "=", "byte", "(", "outi", "[", "j", "]", ">>", "mask", ")", "\n", "}", "\n", "if", "j", "==", "0", "{", "bytesleft", "=", "4", "// because it could be less than 4 the first time through", "\n", "}", "\n", "}", "\n\n", "for", "n", ",", "v", ":=", "range", "binu", "{", "if", "v", ">", "0", "{", "start", ":=", "n", "-", "zcount", "\n", "if", "start", "<", "0", "{", "start", "=", "0", "\n", "}", "\n", "return", "binu", "[", "start", ":", "cnt", "]", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "binu", "[", ":", "cnt", "]", ",", "nil", "\n", "}" ]
// FastBase58DecodingAlphabet decodes the base58 encoded bytes using the given // b58 alphabet.
[ "FastBase58DecodingAlphabet", "decodes", "the", "base58", "encoded", "bytes", "using", "the", "given", "b58", "alphabet", "." ]
d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43
https://github.com/mr-tron/base58/blob/d504ab2e22d97cb9f10b1d146a1e6a063f4a5f43/base58/base58.go#L127-L227
11,533
davecgh/go-xdr
xdr/decode.go
decodeMap
func (d *Decoder) decodeMap(v reflect.Value) (err error) { dataLen, err := d.DecodeUint() if err != nil { return } // Allocate storage for the underlying map if needed. vt := v.Type() if v.IsNil() { v.Set(reflect.MakeMap(vt)) } // Decode each key and value according to their type. keyType := vt.Key() elemType := vt.Elem() for i := uint32(0); i < dataLen; i++ { key := reflect.New(keyType).Elem() err = d.decode(key) if err != nil { return } val := reflect.New(elemType).Elem() err = d.decode(val) if err != nil { return } v.SetMapIndex(key, val) } return }
go
func (d *Decoder) decodeMap(v reflect.Value) (err error) { dataLen, err := d.DecodeUint() if err != nil { return } // Allocate storage for the underlying map if needed. vt := v.Type() if v.IsNil() { v.Set(reflect.MakeMap(vt)) } // Decode each key and value according to their type. keyType := vt.Key() elemType := vt.Elem() for i := uint32(0); i < dataLen; i++ { key := reflect.New(keyType).Elem() err = d.decode(key) if err != nil { return } val := reflect.New(elemType).Elem() err = d.decode(val) if err != nil { return } v.SetMapIndex(key, val) } return }
[ "func", "(", "d", "*", "Decoder", ")", "decodeMap", "(", "v", "reflect", ".", "Value", ")", "(", "err", "error", ")", "{", "dataLen", ",", "err", ":=", "d", ".", "DecodeUint", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Allocate storage for the underlying map if needed.", "vt", ":=", "v", ".", "Type", "(", ")", "\n", "if", "v", ".", "IsNil", "(", ")", "{", "v", ".", "Set", "(", "reflect", ".", "MakeMap", "(", "vt", ")", ")", "\n", "}", "\n\n", "// Decode each key and value according to their type.", "keyType", ":=", "vt", ".", "Key", "(", ")", "\n", "elemType", ":=", "vt", ".", "Elem", "(", ")", "\n", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "dataLen", ";", "i", "++", "{", "key", ":=", "reflect", ".", "New", "(", "keyType", ")", ".", "Elem", "(", ")", "\n", "err", "=", "d", ".", "decode", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "val", ":=", "reflect", ".", "New", "(", "elemType", ")", ".", "Elem", "(", ")", "\n", "err", "=", "d", ".", "decode", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "v", ".", "SetMapIndex", "(", "key", ",", "val", ")", "\n", "}", "\n", "return", "\n", "}" ]
// RFC Section 4.15 - Discriminated Union // RFC Section 4.16 - Void // RFC Section 4.17 - Constant // RFC Section 4.18 - Typedef // RFC Section 4.19 - Optional data // RFC Sections 4.15 though 4.19 only apply to the data specification language // which is not implemented by this package. In the case of discriminated // unions, struct tags are used to perform a similar function. // decodeMap treats the next bytes as an XDR encoded variable array of 2-element // structures whose fields are of the same type as the map keys and elements // represented by the passed reflection value. Pointers are automatically // indirected and allocated as necessary. // // An UnmarshalError is returned if any issues are encountered while decoding // the elements.
[ "RFC", "Section", "4", ".", "15", "-", "Discriminated", "Union", "RFC", "Section", "4", ".", "16", "-", "Void", "RFC", "Section", "4", ".", "17", "-", "Constant", "RFC", "Section", "4", ".", "18", "-", "Typedef", "RFC", "Section", "4", ".", "19", "-", "Optional", "data", "RFC", "Sections", "4", ".", "15", "though", "4", ".", "19", "only", "apply", "to", "the", "data", "specification", "language", "which", "is", "not", "implemented", "by", "this", "package", ".", "In", "the", "case", "of", "discriminated", "unions", "struct", "tags", "are", "used", "to", "perform", "a", "similar", "function", ".", "decodeMap", "treats", "the", "next", "bytes", "as", "an", "XDR", "encoded", "variable", "array", "of", "2", "-", "element", "structures", "whose", "fields", "are", "of", "the", "same", "type", "as", "the", "map", "keys", "and", "elements", "represented", "by", "the", "passed", "reflection", "value", ".", "Pointers", "are", "automatically", "indirected", "and", "allocated", "as", "necessary", ".", "An", "UnmarshalError", "is", "returned", "if", "any", "issues", "are", "encountered", "while", "decoding", "the", "elements", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr/decode.go#L552-L582
11,534
davecgh/go-xdr
xdr/encode.go
encodeMap
func (enc *Encoder) encodeMap(v reflect.Value) (err error) { dataLen := v.Len() if uint(dataLen) > math.MaxUint32 { err = marshalError("encodeMap", ErrOverflow, errMaxXdr, dataLen) return } err = enc.EncodeUint(uint32(dataLen)) if err != nil { return } // Encode each key and value according to their type. for _, key := range v.MapKeys() { err = enc.encode(key) if err != nil { return } err = enc.encode(v.MapIndex(key)) if err != nil { return } } return }
go
func (enc *Encoder) encodeMap(v reflect.Value) (err error) { dataLen := v.Len() if uint(dataLen) > math.MaxUint32 { err = marshalError("encodeMap", ErrOverflow, errMaxXdr, dataLen) return } err = enc.EncodeUint(uint32(dataLen)) if err != nil { return } // Encode each key and value according to their type. for _, key := range v.MapKeys() { err = enc.encode(key) if err != nil { return } err = enc.encode(v.MapIndex(key)) if err != nil { return } } return }
[ "func", "(", "enc", "*", "Encoder", ")", "encodeMap", "(", "v", "reflect", ".", "Value", ")", "(", "err", "error", ")", "{", "dataLen", ":=", "v", ".", "Len", "(", ")", "\n", "if", "uint", "(", "dataLen", ")", ">", "math", ".", "MaxUint32", "{", "err", "=", "marshalError", "(", "\"", "\"", ",", "ErrOverflow", ",", "errMaxXdr", ",", "dataLen", ")", "\n", "return", "\n", "}", "\n", "err", "=", "enc", ".", "EncodeUint", "(", "uint32", "(", "dataLen", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Encode each key and value according to their type.", "for", "_", ",", "key", ":=", "range", "v", ".", "MapKeys", "(", ")", "{", "err", "=", "enc", ".", "encode", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "enc", ".", "encode", "(", "v", ".", "MapIndex", "(", "key", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// RFC Section 4.15 - Discriminated Union // RFC Section 4.16 - Void // RFC Section 4.17 - Constant // RFC Section 4.18 - Typedef // RFC Section 4.19 - Optional data // RFC Sections 4.15 though 4.19 only apply to the data specification language // which is not implemented by this package. In the case of discriminated // unions, struct tags are used to perform a similar function. // encodeMap treats the map represented by the passed reflection value as a // variable-length array of 2-element structures whose fields are of the same // type as the map keys and elements and appends its XDR encoded representation // to the Encoder's data. // // A MarshalError is returned if any issues are encountered while encoding // the elements.
[ "RFC", "Section", "4", ".", "15", "-", "Discriminated", "Union", "RFC", "Section", "4", ".", "16", "-", "Void", "RFC", "Section", "4", ".", "17", "-", "Constant", "RFC", "Section", "4", ".", "18", "-", "Typedef", "RFC", "Section", "4", ".", "19", "-", "Optional", "data", "RFC", "Sections", "4", ".", "15", "though", "4", ".", "19", "only", "apply", "to", "the", "data", "specification", "language", "which", "is", "not", "implemented", "by", "this", "package", ".", "In", "the", "case", "of", "discriminated", "unions", "struct", "tags", "are", "used", "to", "perform", "a", "similar", "function", ".", "encodeMap", "treats", "the", "map", "represented", "by", "the", "passed", "reflection", "value", "as", "a", "variable", "-", "length", "array", "of", "2", "-", "element", "structures", "whose", "fields", "are", "of", "the", "same", "type", "as", "the", "map", "keys", "and", "elements", "and", "appends", "its", "XDR", "encoded", "representation", "to", "the", "Encoder", "s", "data", ".", "A", "MarshalError", "is", "returned", "if", "any", "issues", "are", "encountered", "while", "encoding", "the", "elements", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr/encode.go#L490-L514
11,535
davecgh/go-xdr
xdr/encode.go
encodeInterface
func (enc *Encoder) encodeInterface(v reflect.Value) (err error) { if v.IsNil() || !v.CanInterface() { msg := fmt.Sprintf("can't encode nil interface") err = marshalError("encodeInterface", ErrNilInterface, msg, nil) return err } // Extract underlying value from the interface and indirect through pointers. ve := reflect.ValueOf(v.Interface()) ve = enc.indirect(ve) return enc.encode(ve) }
go
func (enc *Encoder) encodeInterface(v reflect.Value) (err error) { if v.IsNil() || !v.CanInterface() { msg := fmt.Sprintf("can't encode nil interface") err = marshalError("encodeInterface", ErrNilInterface, msg, nil) return err } // Extract underlying value from the interface and indirect through pointers. ve := reflect.ValueOf(v.Interface()) ve = enc.indirect(ve) return enc.encode(ve) }
[ "func", "(", "enc", "*", "Encoder", ")", "encodeInterface", "(", "v", "reflect", ".", "Value", ")", "(", "err", "error", ")", "{", "if", "v", ".", "IsNil", "(", ")", "||", "!", "v", ".", "CanInterface", "(", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", "\n", "err", "=", "marshalError", "(", "\"", "\"", ",", "ErrNilInterface", ",", "msg", ",", "nil", ")", "\n", "return", "err", "\n", "}", "\n\n", "// Extract underlying value from the interface and indirect through pointers.", "ve", ":=", "reflect", ".", "ValueOf", "(", "v", ".", "Interface", "(", ")", ")", "\n", "ve", "=", "enc", ".", "indirect", "(", "ve", ")", "\n", "return", "enc", ".", "encode", "(", "ve", ")", "\n", "}" ]
// encodeInterface examines the interface represented by the passed reflection // value to detect whether it is an interface that can be encoded if it is, // extracts the underlying value to pass back into the encode function for // encoding according to its type. // // A MarshalError is returned if any issues are encountered while encoding // the interface.
[ "encodeInterface", "examines", "the", "interface", "represented", "by", "the", "passed", "reflection", "value", "to", "detect", "whether", "it", "is", "an", "interface", "that", "can", "be", "encoded", "if", "it", "is", "extracts", "the", "underlying", "value", "to", "pass", "back", "into", "the", "encode", "function", "for", "encoding", "according", "to", "its", "type", ".", "A", "MarshalError", "is", "returned", "if", "any", "issues", "are", "encountered", "while", "encoding", "the", "interface", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr/encode.go#L523-L534
11,536
davecgh/go-xdr
xdr2/decode.go
UnmarshalLimited
func UnmarshalLimited(r io.Reader, v interface{}, maxSize uint) (int, error) { d := Decoder{r: r, maxReadSize: maxSize} return d.Decode(v) }
go
func UnmarshalLimited(r io.Reader, v interface{}, maxSize uint) (int, error) { d := Decoder{r: r, maxReadSize: maxSize} return d.Decode(v) }
[ "func", "UnmarshalLimited", "(", "r", "io", ".", "Reader", ",", "v", "interface", "{", "}", ",", "maxSize", "uint", ")", "(", "int", ",", "error", ")", "{", "d", ":=", "Decoder", "{", "r", ":", "r", ",", "maxReadSize", ":", "maxSize", "}", "\n", "return", "d", ".", "Decode", "(", "v", ")", "\n", "}" ]
// UnmarshalLimited is identical to Unmarshal but it sets maxReadSize in order // to cap reads.
[ "UnmarshalLimited", "is", "identical", "to", "Unmarshal", "but", "it", "sets", "maxReadSize", "in", "order", "to", "cap", "reads", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/decode.go#L84-L87
11,537
davecgh/go-xdr
xdr2/decode.go
decodeInterface
func (d *Decoder) decodeInterface(v reflect.Value) (int, error) { if v.IsNil() || !v.CanInterface() { msg := fmt.Sprintf("can't decode to nil interface") err := unmarshalError("decodeInterface", ErrNilInterface, msg, nil, nil) return 0, err } // Extract underlying value from the interface and indirect through // pointers allocating them as needed. ve := reflect.ValueOf(v.Interface()) ve, err := d.indirect(ve) if err != nil { return 0, err } if !ve.CanSet() { msg := fmt.Sprintf("can't decode to unsettable '%v'", ve.Type().String()) err := unmarshalError("decodeInterface", ErrNotSettable, msg, nil, nil) return 0, err } return d.decode(ve) }
go
func (d *Decoder) decodeInterface(v reflect.Value) (int, error) { if v.IsNil() || !v.CanInterface() { msg := fmt.Sprintf("can't decode to nil interface") err := unmarshalError("decodeInterface", ErrNilInterface, msg, nil, nil) return 0, err } // Extract underlying value from the interface and indirect through // pointers allocating them as needed. ve := reflect.ValueOf(v.Interface()) ve, err := d.indirect(ve) if err != nil { return 0, err } if !ve.CanSet() { msg := fmt.Sprintf("can't decode to unsettable '%v'", ve.Type().String()) err := unmarshalError("decodeInterface", ErrNotSettable, msg, nil, nil) return 0, err } return d.decode(ve) }
[ "func", "(", "d", "*", "Decoder", ")", "decodeInterface", "(", "v", "reflect", ".", "Value", ")", "(", "int", ",", "error", ")", "{", "if", "v", ".", "IsNil", "(", ")", "||", "!", "v", ".", "CanInterface", "(", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", "\n", "err", ":=", "unmarshalError", "(", "\"", "\"", ",", "ErrNilInterface", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "// Extract underlying value from the interface and indirect through", "// pointers allocating them as needed.", "ve", ":=", "reflect", ".", "ValueOf", "(", "v", ".", "Interface", "(", ")", ")", "\n", "ve", ",", "err", ":=", "d", ".", "indirect", "(", "ve", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "!", "ve", ".", "CanSet", "(", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ve", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "err", ":=", "unmarshalError", "(", "\"", "\"", ",", "ErrNotSettable", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n", "return", "d", ".", "decode", "(", "ve", ")", "\n", "}" ]
// decodeInterface examines the interface represented by the passed reflection // value to detect whether it is an interface that can be decoded into and // if it is, extracts the underlying value to pass back into the decode function // for decoding according to its type. It returns the the number of bytes // actually read. // // An UnmarshalError is returned if any issues are encountered while decoding // the interface.
[ "decodeInterface", "examines", "the", "interface", "represented", "by", "the", "passed", "reflection", "value", "to", "detect", "whether", "it", "is", "an", "interface", "that", "can", "be", "decoded", "into", "and", "if", "it", "is", "extracts", "the", "underlying", "value", "to", "pass", "back", "into", "the", "decode", "function", "for", "decoding", "according", "to", "its", "type", ".", "It", "returns", "the", "the", "number", "of", "bytes", "actually", "read", ".", "An", "UnmarshalError", "is", "returned", "if", "any", "issues", "are", "encountered", "while", "decoding", "the", "interface", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/decode.go#L626-L649
11,538
davecgh/go-xdr
xdr2/decode.go
indirect
func (d *Decoder) indirect(v reflect.Value) (reflect.Value, error) { rv := v for rv.Kind() == reflect.Ptr { // Allocate pointer if needed. isNil := rv.IsNil() if isNil && !rv.CanSet() { msg := fmt.Sprintf("unable to allocate pointer for '%v'", rv.Type().String()) err := unmarshalError("indirect", ErrNotSettable, msg, nil, nil) return rv, err } if isNil { rv.Set(reflect.New(rv.Type().Elem())) } rv = rv.Elem() } return rv, nil }
go
func (d *Decoder) indirect(v reflect.Value) (reflect.Value, error) { rv := v for rv.Kind() == reflect.Ptr { // Allocate pointer if needed. isNil := rv.IsNil() if isNil && !rv.CanSet() { msg := fmt.Sprintf("unable to allocate pointer for '%v'", rv.Type().String()) err := unmarshalError("indirect", ErrNotSettable, msg, nil, nil) return rv, err } if isNil { rv.Set(reflect.New(rv.Type().Elem())) } rv = rv.Elem() } return rv, nil }
[ "func", "(", "d", "*", "Decoder", ")", "indirect", "(", "v", "reflect", ".", "Value", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "rv", ":=", "v", "\n", "for", "rv", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "// Allocate pointer if needed.", "isNil", ":=", "rv", ".", "IsNil", "(", ")", "\n", "if", "isNil", "&&", "!", "rv", ".", "CanSet", "(", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rv", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "err", ":=", "unmarshalError", "(", "\"", "\"", ",", "ErrNotSettable", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "rv", ",", "err", "\n", "}", "\n", "if", "isNil", "{", "rv", ".", "Set", "(", "reflect", ".", "New", "(", "rv", ".", "Type", "(", ")", ".", "Elem", "(", ")", ")", ")", "\n", "}", "\n", "rv", "=", "rv", ".", "Elem", "(", ")", "\n", "}", "\n", "return", "rv", ",", "nil", "\n", "}" ]
// indirect dereferences pointers allocating them as needed until it reaches // a non-pointer. This allows transparent decoding through arbitrary levels // of indirection.
[ "indirect", "dereferences", "pointers", "allocating", "them", "as", "needed", "until", "it", "reaches", "a", "non", "-", "pointer", ".", "This", "allows", "transparent", "decoding", "through", "arbitrary", "levels", "of", "indirection", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/decode.go#L814-L832
11,539
davecgh/go-xdr
xdr2/decode.go
Decode
func (d *Decoder) Decode(v interface{}) (int, error) { if v == nil { msg := "can't unmarshal to nil interface" return 0, unmarshalError("Unmarshal", ErrNilInterface, msg, nil, nil) } vv := reflect.ValueOf(v) if vv.Kind() != reflect.Ptr { msg := fmt.Sprintf("can't unmarshal to non-pointer '%v' - use "+ "& operator", vv.Type().String()) err := unmarshalError("Unmarshal", ErrBadArguments, msg, nil, nil) return 0, err } if vv.IsNil() && !vv.CanSet() { msg := fmt.Sprintf("can't unmarshal to unsettable '%v' - use "+ "& operator", vv.Type().String()) err := unmarshalError("Unmarshal", ErrNotSettable, msg, nil, nil) return 0, err } return d.decode(vv) }
go
func (d *Decoder) Decode(v interface{}) (int, error) { if v == nil { msg := "can't unmarshal to nil interface" return 0, unmarshalError("Unmarshal", ErrNilInterface, msg, nil, nil) } vv := reflect.ValueOf(v) if vv.Kind() != reflect.Ptr { msg := fmt.Sprintf("can't unmarshal to non-pointer '%v' - use "+ "& operator", vv.Type().String()) err := unmarshalError("Unmarshal", ErrBadArguments, msg, nil, nil) return 0, err } if vv.IsNil() && !vv.CanSet() { msg := fmt.Sprintf("can't unmarshal to unsettable '%v' - use "+ "& operator", vv.Type().String()) err := unmarshalError("Unmarshal", ErrNotSettable, msg, nil, nil) return 0, err } return d.decode(vv) }
[ "func", "(", "d", "*", "Decoder", ")", "Decode", "(", "v", "interface", "{", "}", ")", "(", "int", ",", "error", ")", "{", "if", "v", "==", "nil", "{", "msg", ":=", "\"", "\"", "\n", "return", "0", ",", "unmarshalError", "(", "\"", "\"", ",", "ErrNilInterface", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "}", "\n\n", "vv", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "vv", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "vv", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "err", ":=", "unmarshalError", "(", "\"", "\"", ",", "ErrBadArguments", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n", "if", "vv", ".", "IsNil", "(", ")", "&&", "!", "vv", ".", "CanSet", "(", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ",", "vv", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "err", ":=", "unmarshalError", "(", "\"", "\"", ",", "ErrNotSettable", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "d", ".", "decode", "(", "vv", ")", "\n", "}" ]
// Decode operates identically to the Unmarshal function with the exception of // using the reader associated with the Decoder as the source of XDR-encoded // data instead of a user-supplied reader. See the Unmarhsal documentation for // specifics.
[ "Decode", "operates", "identically", "to", "the", "Unmarshal", "function", "with", "the", "exception", "of", "using", "the", "reader", "associated", "with", "the", "Decoder", "as", "the", "source", "of", "XDR", "-", "encoded", "data", "instead", "of", "a", "user", "-", "supplied", "reader", ".", "See", "the", "Unmarhsal", "documentation", "for", "specifics", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/decode.go#L838-L860
11,540
davecgh/go-xdr
xdr2/decode.go
NewDecoderLimited
func NewDecoderLimited(r io.Reader, maxSize uint) *Decoder { return &Decoder{r: r, maxReadSize: maxSize} }
go
func NewDecoderLimited(r io.Reader, maxSize uint) *Decoder { return &Decoder{r: r, maxReadSize: maxSize} }
[ "func", "NewDecoderLimited", "(", "r", "io", ".", "Reader", ",", "maxSize", "uint", ")", "*", "Decoder", "{", "return", "&", "Decoder", "{", "r", ":", "r", ",", "maxReadSize", ":", "maxSize", "}", "\n", "}" ]
// NewDecoderLimited is identical to NewDecoder but it sets maxReadSize in // order to cap reads.
[ "NewDecoderLimited", "is", "identical", "to", "NewDecoder", "but", "it", "sets", "maxReadSize", "in", "order", "to", "cap", "reads", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/decode.go#L871-L873
11,541
davecgh/go-xdr
xdr/error.go
marshalError
func marshalError(f string, c ErrorCode, desc string, v interface{}) *MarshalError { e := &MarshalError{ErrorCode: c, Func: f, Description: desc} switch t := v.(type) { case []byte: slice := make([]byte, len(t)) copy(slice, t) e.Value = slice default: e.Value = v } return e }
go
func marshalError(f string, c ErrorCode, desc string, v interface{}) *MarshalError { e := &MarshalError{ErrorCode: c, Func: f, Description: desc} switch t := v.(type) { case []byte: slice := make([]byte, len(t)) copy(slice, t) e.Value = slice default: e.Value = v } return e }
[ "func", "marshalError", "(", "f", "string", ",", "c", "ErrorCode", ",", "desc", "string", ",", "v", "interface", "{", "}", ")", "*", "MarshalError", "{", "e", ":=", "&", "MarshalError", "{", "ErrorCode", ":", "c", ",", "Func", ":", "f", ",", "Description", ":", "desc", "}", "\n", "switch", "t", ":=", "v", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "slice", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "t", ")", ")", "\n", "copy", "(", "slice", ",", "t", ")", "\n", "e", ".", "Value", "=", "slice", "\n", "default", ":", "e", ".", "Value", "=", "v", "\n", "}", "\n\n", "return", "e", "\n", "}" ]
// marshalError creates an error given a set of arguments and will copy byte // slices into the Value field since they might otherwise be changed from from // the original value.
[ "marshalError", "creates", "an", "error", "given", "a", "set", "of", "arguments", "and", "will", "copy", "byte", "slices", "into", "the", "Value", "field", "since", "they", "might", "otherwise", "be", "changed", "from", "from", "the", "original", "value", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr/error.go#L140-L152
11,542
davecgh/go-xdr
xdr2/error.go
IsIO
func IsIO(err error) bool { switch e := err.(type) { case *UnmarshalError: return e.ErrorCode == ErrIO case *MarshalError: return e.ErrorCode == ErrIO } return false }
go
func IsIO(err error) bool { switch e := err.(type) { case *UnmarshalError: return e.ErrorCode == ErrIO case *MarshalError: return e.ErrorCode == ErrIO } return false }
[ "func", "IsIO", "(", "err", "error", ")", "bool", "{", "switch", "e", ":=", "err", ".", "(", "type", ")", "{", "case", "*", "UnmarshalError", ":", "return", "e", ".", "ErrorCode", "==", "ErrIO", "\n", "case", "*", "MarshalError", ":", "return", "e", ".", "ErrorCode", "==", "ErrIO", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsIO returns a boolean indicating whether the error is known to report that // the underlying reader or writer encountered an ErrIO.
[ "IsIO", "returns", "a", "boolean", "indicating", "whether", "the", "error", "is", "known", "to", "report", "that", "the", "underlying", "reader", "or", "writer", "encountered", "an", "ErrIO", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/error.go#L127-L135
11,543
davecgh/go-xdr
xdr2/encode.go
encodeMap
func (enc *Encoder) encodeMap(v reflect.Value) (int, error) { // Number of elements. n, err := enc.EncodeUint(uint32(v.Len())) if err != nil { return n, err } // Encode each key and value according to their type. for _, key := range v.MapKeys() { n2, err := enc.encode(key) n += n2 if err != nil { return n, err } n2, err = enc.encode(v.MapIndex(key)) n += n2 if err != nil { return n, err } } return n, nil }
go
func (enc *Encoder) encodeMap(v reflect.Value) (int, error) { // Number of elements. n, err := enc.EncodeUint(uint32(v.Len())) if err != nil { return n, err } // Encode each key and value according to their type. for _, key := range v.MapKeys() { n2, err := enc.encode(key) n += n2 if err != nil { return n, err } n2, err = enc.encode(v.MapIndex(key)) n += n2 if err != nil { return n, err } } return n, nil }
[ "func", "(", "enc", "*", "Encoder", ")", "encodeMap", "(", "v", "reflect", ".", "Value", ")", "(", "int", ",", "error", ")", "{", "// Number of elements.", "n", ",", "err", ":=", "enc", ".", "EncodeUint", "(", "uint32", "(", "v", ".", "Len", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "err", "\n", "}", "\n\n", "// Encode each key and value according to their type.", "for", "_", ",", "key", ":=", "range", "v", ".", "MapKeys", "(", ")", "{", "n2", ",", "err", ":=", "enc", ".", "encode", "(", "key", ")", "\n", "n", "+=", "n2", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "err", "\n", "}", "\n\n", "n2", ",", "err", "=", "enc", ".", "encode", "(", "v", ".", "MapIndex", "(", "key", ")", ")", "\n", "n", "+=", "n2", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "n", ",", "nil", "\n", "}" ]
// RFC Section 4.15 - Discriminated Union // RFC Section 4.16 - Void // RFC Section 4.17 - Constant // RFC Section 4.18 - Typedef // RFC Section 4.19 - Optional data // RFC Sections 4.15 though 4.19 only apply to the data specification language // which is not implemented by this package. In the case of discriminated // unions, struct tags are used to perform a similar function. // encodeMap treats the map represented by the passed reflection value as a // variable-length array of 2-element structures whose fields are of the same // type as the map keys and elements and writes its XDR encoded representation // to the encapsulated writer. It returns the number of bytes written. // // A MarshalError is returned if any issues are encountered while encoding // the elements.
[ "RFC", "Section", "4", ".", "15", "-", "Discriminated", "Union", "RFC", "Section", "4", ".", "16", "-", "Void", "RFC", "Section", "4", ".", "17", "-", "Constant", "RFC", "Section", "4", ".", "18", "-", "Typedef", "RFC", "Section", "4", ".", "19", "-", "Optional", "data", "RFC", "Sections", "4", ".", "15", "though", "4", ".", "19", "only", "apply", "to", "the", "data", "specification", "language", "which", "is", "not", "implemented", "by", "this", "package", ".", "In", "the", "case", "of", "discriminated", "unions", "struct", "tags", "are", "used", "to", "perform", "a", "similar", "function", ".", "encodeMap", "treats", "the", "map", "represented", "by", "the", "passed", "reflection", "value", "as", "a", "variable", "-", "length", "array", "of", "2", "-", "element", "structures", "whose", "fields", "are", "of", "the", "same", "type", "as", "the", "map", "keys", "and", "elements", "and", "writes", "its", "XDR", "encoded", "representation", "to", "the", "encapsulated", "writer", ".", "It", "returns", "the", "number", "of", "bytes", "written", ".", "A", "MarshalError", "is", "returned", "if", "any", "issues", "are", "encountered", "while", "encoding", "the", "elements", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/encode.go#L502-L525
11,544
davecgh/go-xdr
xdr2/encode.go
encode
func (enc *Encoder) encode(v reflect.Value) (int, error) { if !v.IsValid() { msg := fmt.Sprintf("type '%s' is not valid", v.Kind().String()) err := marshalError("encode", ErrUnsupportedType, msg, nil, nil) return 0, err } // Indirect through pointers to get at the concrete value. ve := enc.indirect(v) // Handle time.Time values by encoding them as an RFC3339 formatted // string with nanosecond precision. Check the type string before // doing a full blown conversion to interface and type assertion since // checking a string is much quicker. if ve.Type().String() == "time.Time" && ve.CanInterface() { viface := ve.Interface() if tv, ok := viface.(time.Time); ok { return enc.EncodeString(tv.Format(time.RFC3339Nano)) } } // Handle native Go types. switch ve.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int: return enc.EncodeInt(int32(ve.Int())) case reflect.Int64: return enc.EncodeHyper(ve.Int()) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint: return enc.EncodeUint(uint32(ve.Uint())) case reflect.Uint64: return enc.EncodeUhyper(ve.Uint()) case reflect.Bool: return enc.EncodeBool(ve.Bool()) case reflect.Float32: return enc.EncodeFloat(float32(ve.Float())) case reflect.Float64: return enc.EncodeDouble(ve.Float()) case reflect.String: return enc.EncodeString(ve.String()) case reflect.Array: return enc.encodeFixedArray(ve, false) case reflect.Slice: return enc.encodeArray(ve, false) case reflect.Struct: return enc.encodeStruct(ve) case reflect.Map: return enc.encodeMap(ve) case reflect.Interface: return enc.encodeInterface(ve) } // The only unhandled types left are unsupported. At the time of this // writing the only remaining unsupported types that exist are // reflect.Uintptr and reflect.UnsafePointer. msg := fmt.Sprintf("unsupported Go type '%s'", ve.Kind().String()) err := marshalError("encode", ErrUnsupportedType, msg, nil, nil) return 0, err }
go
func (enc *Encoder) encode(v reflect.Value) (int, error) { if !v.IsValid() { msg := fmt.Sprintf("type '%s' is not valid", v.Kind().String()) err := marshalError("encode", ErrUnsupportedType, msg, nil, nil) return 0, err } // Indirect through pointers to get at the concrete value. ve := enc.indirect(v) // Handle time.Time values by encoding them as an RFC3339 formatted // string with nanosecond precision. Check the type string before // doing a full blown conversion to interface and type assertion since // checking a string is much quicker. if ve.Type().String() == "time.Time" && ve.CanInterface() { viface := ve.Interface() if tv, ok := viface.(time.Time); ok { return enc.EncodeString(tv.Format(time.RFC3339Nano)) } } // Handle native Go types. switch ve.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int: return enc.EncodeInt(int32(ve.Int())) case reflect.Int64: return enc.EncodeHyper(ve.Int()) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint: return enc.EncodeUint(uint32(ve.Uint())) case reflect.Uint64: return enc.EncodeUhyper(ve.Uint()) case reflect.Bool: return enc.EncodeBool(ve.Bool()) case reflect.Float32: return enc.EncodeFloat(float32(ve.Float())) case reflect.Float64: return enc.EncodeDouble(ve.Float()) case reflect.String: return enc.EncodeString(ve.String()) case reflect.Array: return enc.encodeFixedArray(ve, false) case reflect.Slice: return enc.encodeArray(ve, false) case reflect.Struct: return enc.encodeStruct(ve) case reflect.Map: return enc.encodeMap(ve) case reflect.Interface: return enc.encodeInterface(ve) } // The only unhandled types left are unsupported. At the time of this // writing the only remaining unsupported types that exist are // reflect.Uintptr and reflect.UnsafePointer. msg := fmt.Sprintf("unsupported Go type '%s'", ve.Kind().String()) err := marshalError("encode", ErrUnsupportedType, msg, nil, nil) return 0, err }
[ "func", "(", "enc", "*", "Encoder", ")", "encode", "(", "v", "reflect", ".", "Value", ")", "(", "int", ",", "error", ")", "{", "if", "!", "v", ".", "IsValid", "(", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ".", "Kind", "(", ")", ".", "String", "(", ")", ")", "\n", "err", ":=", "marshalError", "(", "\"", "\"", ",", "ErrUnsupportedType", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "// Indirect through pointers to get at the concrete value.", "ve", ":=", "enc", ".", "indirect", "(", "v", ")", "\n\n", "// Handle time.Time values by encoding them as an RFC3339 formatted", "// string with nanosecond precision. Check the type string before", "// doing a full blown conversion to interface and type assertion since", "// checking a string is much quicker.", "if", "ve", ".", "Type", "(", ")", ".", "String", "(", ")", "==", "\"", "\"", "&&", "ve", ".", "CanInterface", "(", ")", "{", "viface", ":=", "ve", ".", "Interface", "(", ")", "\n", "if", "tv", ",", "ok", ":=", "viface", ".", "(", "time", ".", "Time", ")", ";", "ok", "{", "return", "enc", ".", "EncodeString", "(", "tv", ".", "Format", "(", "time", ".", "RFC3339Nano", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Handle native Go types.", "switch", "ve", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int", ":", "return", "enc", ".", "EncodeInt", "(", "int32", "(", "ve", ".", "Int", "(", ")", ")", ")", "\n\n", "case", "reflect", ".", "Int64", ":", "return", "enc", ".", "EncodeHyper", "(", "ve", ".", "Int", "(", ")", ")", "\n\n", "case", "reflect", ".", "Uint8", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint", ":", "return", "enc", ".", "EncodeUint", "(", "uint32", "(", "ve", ".", "Uint", "(", ")", ")", ")", "\n\n", "case", "reflect", ".", "Uint64", ":", "return", "enc", ".", "EncodeUhyper", "(", "ve", ".", "Uint", "(", ")", ")", "\n\n", "case", "reflect", ".", "Bool", ":", "return", "enc", ".", "EncodeBool", "(", "ve", ".", "Bool", "(", ")", ")", "\n\n", "case", "reflect", ".", "Float32", ":", "return", "enc", ".", "EncodeFloat", "(", "float32", "(", "ve", ".", "Float", "(", ")", ")", ")", "\n\n", "case", "reflect", ".", "Float64", ":", "return", "enc", ".", "EncodeDouble", "(", "ve", ".", "Float", "(", ")", ")", "\n\n", "case", "reflect", ".", "String", ":", "return", "enc", ".", "EncodeString", "(", "ve", ".", "String", "(", ")", ")", "\n\n", "case", "reflect", ".", "Array", ":", "return", "enc", ".", "encodeFixedArray", "(", "ve", ",", "false", ")", "\n\n", "case", "reflect", ".", "Slice", ":", "return", "enc", ".", "encodeArray", "(", "ve", ",", "false", ")", "\n\n", "case", "reflect", ".", "Struct", ":", "return", "enc", ".", "encodeStruct", "(", "ve", ")", "\n\n", "case", "reflect", ".", "Map", ":", "return", "enc", ".", "encodeMap", "(", "ve", ")", "\n\n", "case", "reflect", ".", "Interface", ":", "return", "enc", ".", "encodeInterface", "(", "ve", ")", "\n", "}", "\n\n", "// The only unhandled types left are unsupported. At the time of this", "// writing the only remaining unsupported types that exist are", "// reflect.Uintptr and reflect.UnsafePointer.", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ve", ".", "Kind", "(", ")", ".", "String", "(", ")", ")", "\n", "err", ":=", "marshalError", "(", "\"", "\"", ",", "ErrUnsupportedType", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}" ]
// encode is the main workhorse for marshalling via reflection. It uses // the passed reflection value to choose the XDR primitives to encode into // the encapsulated writer and returns the number of bytes written. It is a // recursive function, so cyclic data structures are not supported and will // result in an infinite loop.
[ "encode", "is", "the", "main", "workhorse", "for", "marshalling", "via", "reflection", ".", "It", "uses", "the", "passed", "reflection", "value", "to", "choose", "the", "XDR", "primitives", "to", "encode", "into", "the", "encapsulated", "writer", "and", "returns", "the", "number", "of", "bytes", "written", ".", "It", "is", "a", "recursive", "function", "so", "cyclic", "data", "structures", "are", "not", "supported", "and", "will", "result", "in", "an", "infinite", "loop", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/encode.go#L553-L622
11,545
davecgh/go-xdr
xdr2/encode.go
indirect
func (enc *Encoder) indirect(v reflect.Value) reflect.Value { rv := v for rv.Kind() == reflect.Ptr { rv = rv.Elem() } return rv }
go
func (enc *Encoder) indirect(v reflect.Value) reflect.Value { rv := v for rv.Kind() == reflect.Ptr { rv = rv.Elem() } return rv }
[ "func", "(", "enc", "*", "Encoder", ")", "indirect", "(", "v", "reflect", ".", "Value", ")", "reflect", ".", "Value", "{", "rv", ":=", "v", "\n", "for", "rv", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "rv", "=", "rv", ".", "Elem", "(", ")", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// indirect dereferences pointers until it reaches a non-pointer. This allows // transparent encoding through arbitrary levels of indirection.
[ "indirect", "dereferences", "pointers", "until", "it", "reaches", "a", "non", "-", "pointer", ".", "This", "allows", "transparent", "encoding", "through", "arbitrary", "levels", "of", "indirection", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/encode.go#L626-L632
11,546
davecgh/go-xdr
xdr2/encode.go
Encode
func (enc *Encoder) Encode(v interface{}) (int, error) { if v == nil { msg := "can't marshal nil interface" err := marshalError("Marshal", ErrNilInterface, msg, nil, nil) return 0, err } vv := reflect.ValueOf(v) vve := vv for vve.Kind() == reflect.Ptr { if vve.IsNil() { msg := fmt.Sprintf("can't marshal nil pointer '%v'", vv.Type().String()) err := marshalError("Marshal", ErrBadArguments, msg, nil, nil) return 0, err } vve = vve.Elem() } return enc.encode(vve) }
go
func (enc *Encoder) Encode(v interface{}) (int, error) { if v == nil { msg := "can't marshal nil interface" err := marshalError("Marshal", ErrNilInterface, msg, nil, nil) return 0, err } vv := reflect.ValueOf(v) vve := vv for vve.Kind() == reflect.Ptr { if vve.IsNil() { msg := fmt.Sprintf("can't marshal nil pointer '%v'", vv.Type().String()) err := marshalError("Marshal", ErrBadArguments, msg, nil, nil) return 0, err } vve = vve.Elem() } return enc.encode(vve) }
[ "func", "(", "enc", "*", "Encoder", ")", "Encode", "(", "v", "interface", "{", "}", ")", "(", "int", ",", "error", ")", "{", "if", "v", "==", "nil", "{", "msg", ":=", "\"", "\"", "\n", "err", ":=", "marshalError", "(", "\"", "\"", ",", "ErrNilInterface", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "vv", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "vve", ":=", "vv", "\n", "for", "vve", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "if", "vve", ".", "IsNil", "(", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vv", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "err", ":=", "marshalError", "(", "\"", "\"", ",", "ErrBadArguments", ",", "msg", ",", "nil", ",", "nil", ")", "\n", "return", "0", ",", "err", "\n", "}", "\n", "vve", "=", "vve", ".", "Elem", "(", ")", "\n", "}", "\n\n", "return", "enc", ".", "encode", "(", "vve", ")", "\n", "}" ]
// Encode operates identically to the Marshal function with the exception of // using the writer associated with the Encoder for the destination of the // XDR-encoded data instead of a user-supplied writer. See the Marshal // documentation for specifics.
[ "Encode", "operates", "identically", "to", "the", "Marshal", "function", "with", "the", "exception", "of", "using", "the", "writer", "associated", "with", "the", "Encoder", "for", "the", "destination", "of", "the", "XDR", "-", "encoded", "data", "instead", "of", "a", "user", "-", "supplied", "writer", ".", "See", "the", "Marshal", "documentation", "for", "specifics", "." ]
e6a2ba005892b6a5b27cb5352f64c2e96942dd28
https://github.com/davecgh/go-xdr/blob/e6a2ba005892b6a5b27cb5352f64c2e96942dd28/xdr2/encode.go#L638-L659
11,547
coreos/discovery.etcd.io
e2e/discovery.go
NewDiscoveryProcess
func (cfg *discoveryProcessConfig) NewDiscoveryProcess() *discoveryProcess { port := int(atomic.LoadInt32(&discoveryBasePort)) atomic.AddInt32(&discoveryBasePort, 2) copied := *cfg copied.webPort = port copied.discoveryHost = fmt.Sprintf("http://localhost:%d", copied.webPort) return &discoveryProcess{cfg: &copied} }
go
func (cfg *discoveryProcessConfig) NewDiscoveryProcess() *discoveryProcess { port := int(atomic.LoadInt32(&discoveryBasePort)) atomic.AddInt32(&discoveryBasePort, 2) copied := *cfg copied.webPort = port copied.discoveryHost = fmt.Sprintf("http://localhost:%d", copied.webPort) return &discoveryProcess{cfg: &copied} }
[ "func", "(", "cfg", "*", "discoveryProcessConfig", ")", "NewDiscoveryProcess", "(", ")", "*", "discoveryProcess", "{", "port", ":=", "int", "(", "atomic", ".", "LoadInt32", "(", "&", "discoveryBasePort", ")", ")", "\n", "atomic", ".", "AddInt32", "(", "&", "discoveryBasePort", ",", "2", ")", "\n\n", "copied", ":=", "*", "cfg", "\n", "copied", ".", "webPort", "=", "port", "\n", "copied", ".", "discoveryHost", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "copied", ".", "webPort", ")", "\n\n", "return", "&", "discoveryProcess", "{", "cfg", ":", "&", "copied", "}", "\n", "}" ]
// NewDiscoveryProcess creates a new 'discoveryProcess'.
[ "NewDiscoveryProcess", "creates", "a", "new", "discoveryProcess", "." ]
78178dbc766863d76476f36755517bf7e7e29770
https://github.com/coreos/discovery.etcd.io/blob/78178dbc766863d76476f36755517bf7e7e29770/e2e/discovery.go#L29-L38
11,548
coreos/discovery.etcd.io
e2e/etcd.go
NewEtcdProcessCluster
func (cfg *etcdProcessClusterConfig) NewEtcdProcessCluster() (*etcdProcessCluster, error) { cport := int(atomic.LoadInt32(&etcdBasePort)) atomic.AddInt32(&etcdBasePort, int32(3*cfg.clusterSize)) epc := &etcdProcessCluster{ cfg: cfg, procs: make([]*etcdProcess, cfg.clusterSize), } ics := make([]string, cfg.clusterSize) for i := 0; i < cfg.clusterSize; i++ { name := fmt.Sprintf("test%d%d.etcd", cport, i) curl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", cport+2*i)} purl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", cport+2*i+1)} dataDirPath, err := ioutil.TempDir(os.TempDir(), name) if err != nil { return nil, err } ics[i] = fmt.Sprintf("%s=%s", name, purl.String()) epc.procs[i] = &etcdProcess{ cfg: &etcdProcessConfig{ execPath: cfg.execPath, args: []string{ "--name", name, "--listen-client-urls", curl.String(), "--advertise-client-urls", curl.String(), "--listen-peer-urls", purl.String(), "--initial-advertise-peer-urls", purl.String(), "--initial-cluster-token", cfg.initialToken, "--data-dir", dataDirPath, }, dataDirPath: dataDirPath, keepDataDir: cfg.keepDataDir, name: name, curl: curl, purl: purl, initialToken: cfg.initialToken, initialCluster: "", discoveryToken: cfg.discoveryToken, }, } } for i := 0; i < cfg.clusterSize; i++ { if epc.procs[i].cfg.discoveryToken == "" { cs := strings.Join(ics, ",") epc.procs[i].cfg.initialCluster = cs epc.procs[i].cfg.args = append(epc.procs[i].cfg.args, "--initial-cluster", cs) } else { epc.procs[i].cfg.args = append(epc.procs[i].cfg.args, "--discovery", epc.procs[i].cfg.discoveryToken) } } return epc, nil }
go
func (cfg *etcdProcessClusterConfig) NewEtcdProcessCluster() (*etcdProcessCluster, error) { cport := int(atomic.LoadInt32(&etcdBasePort)) atomic.AddInt32(&etcdBasePort, int32(3*cfg.clusterSize)) epc := &etcdProcessCluster{ cfg: cfg, procs: make([]*etcdProcess, cfg.clusterSize), } ics := make([]string, cfg.clusterSize) for i := 0; i < cfg.clusterSize; i++ { name := fmt.Sprintf("test%d%d.etcd", cport, i) curl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", cport+2*i)} purl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", cport+2*i+1)} dataDirPath, err := ioutil.TempDir(os.TempDir(), name) if err != nil { return nil, err } ics[i] = fmt.Sprintf("%s=%s", name, purl.String()) epc.procs[i] = &etcdProcess{ cfg: &etcdProcessConfig{ execPath: cfg.execPath, args: []string{ "--name", name, "--listen-client-urls", curl.String(), "--advertise-client-urls", curl.String(), "--listen-peer-urls", purl.String(), "--initial-advertise-peer-urls", purl.String(), "--initial-cluster-token", cfg.initialToken, "--data-dir", dataDirPath, }, dataDirPath: dataDirPath, keepDataDir: cfg.keepDataDir, name: name, curl: curl, purl: purl, initialToken: cfg.initialToken, initialCluster: "", discoveryToken: cfg.discoveryToken, }, } } for i := 0; i < cfg.clusterSize; i++ { if epc.procs[i].cfg.discoveryToken == "" { cs := strings.Join(ics, ",") epc.procs[i].cfg.initialCluster = cs epc.procs[i].cfg.args = append(epc.procs[i].cfg.args, "--initial-cluster", cs) } else { epc.procs[i].cfg.args = append(epc.procs[i].cfg.args, "--discovery", epc.procs[i].cfg.discoveryToken) } } return epc, nil }
[ "func", "(", "cfg", "*", "etcdProcessClusterConfig", ")", "NewEtcdProcessCluster", "(", ")", "(", "*", "etcdProcessCluster", ",", "error", ")", "{", "cport", ":=", "int", "(", "atomic", ".", "LoadInt32", "(", "&", "etcdBasePort", ")", ")", "\n", "atomic", ".", "AddInt32", "(", "&", "etcdBasePort", ",", "int32", "(", "3", "*", "cfg", ".", "clusterSize", ")", ")", "\n\n", "epc", ":=", "&", "etcdProcessCluster", "{", "cfg", ":", "cfg", ",", "procs", ":", "make", "(", "[", "]", "*", "etcdProcess", ",", "cfg", ".", "clusterSize", ")", ",", "}", "\n\n", "ics", ":=", "make", "(", "[", "]", "string", ",", "cfg", ".", "clusterSize", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "cfg", ".", "clusterSize", ";", "i", "++", "{", "name", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cport", ",", "i", ")", "\n", "curl", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cport", "+", "2", "*", "i", ")", "}", "\n", "purl", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cport", "+", "2", "*", "i", "+", "1", ")", "}", "\n", "dataDirPath", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "os", ".", "TempDir", "(", ")", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ics", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ",", "purl", ".", "String", "(", ")", ")", "\n\n", "epc", ".", "procs", "[", "i", "]", "=", "&", "etcdProcess", "{", "cfg", ":", "&", "etcdProcessConfig", "{", "execPath", ":", "cfg", ".", "execPath", ",", "args", ":", "[", "]", "string", "{", "\"", "\"", ",", "name", ",", "\"", "\"", ",", "curl", ".", "String", "(", ")", ",", "\"", "\"", ",", "curl", ".", "String", "(", ")", ",", "\"", "\"", ",", "purl", ".", "String", "(", ")", ",", "\"", "\"", ",", "purl", ".", "String", "(", ")", ",", "\"", "\"", ",", "cfg", ".", "initialToken", ",", "\"", "\"", ",", "dataDirPath", ",", "}", ",", "dataDirPath", ":", "dataDirPath", ",", "keepDataDir", ":", "cfg", ".", "keepDataDir", ",", "name", ":", "name", ",", "curl", ":", "curl", ",", "purl", ":", "purl", ",", "initialToken", ":", "cfg", ".", "initialToken", ",", "initialCluster", ":", "\"", "\"", ",", "discoveryToken", ":", "cfg", ".", "discoveryToken", ",", "}", ",", "}", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "cfg", ".", "clusterSize", ";", "i", "++", "{", "if", "epc", ".", "procs", "[", "i", "]", ".", "cfg", ".", "discoveryToken", "==", "\"", "\"", "{", "cs", ":=", "strings", ".", "Join", "(", "ics", ",", "\"", "\"", ")", "\n", "epc", ".", "procs", "[", "i", "]", ".", "cfg", ".", "initialCluster", "=", "cs", "\n", "epc", ".", "procs", "[", "i", "]", ".", "cfg", ".", "args", "=", "append", "(", "epc", ".", "procs", "[", "i", "]", ".", "cfg", ".", "args", ",", "\"", "\"", ",", "cs", ")", "\n", "}", "else", "{", "epc", ".", "procs", "[", "i", "]", ".", "cfg", ".", "args", "=", "append", "(", "epc", ".", "procs", "[", "i", "]", ".", "cfg", ".", "args", ",", "\"", "\"", ",", "epc", ".", "procs", "[", "i", "]", ".", "cfg", ".", "discoveryToken", ")", "\n", "}", "\n", "}", "\n", "return", "epc", ",", "nil", "\n", "}" ]
// NewEtcdProcessCluster generates a new 'etcdProcessCluster'.
[ "NewEtcdProcessCluster", "generates", "a", "new", "etcdProcessCluster", "." ]
78178dbc766863d76476f36755517bf7e7e29770
https://github.com/coreos/discovery.etcd.io/blob/78178dbc766863d76476f36755517bf7e7e29770/e2e/etcd.go#L53-L110
11,549
coreos/discovery.etcd.io
integration/server.go
NewService
func NewService(t *testing.T, etcdClientPort, etcdPeerPort, httpPort int) *Service { dataDir, err := ioutil.TempDir(os.TempDir(), "test-data") if err != nil { t.Fatal(err) } cfg := embed.NewConfig() cfg.ClusterState = embed.ClusterStateFlagNew cfg.Name = "test-etcd" cfg.Dir = dataDir curl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", etcdClientPort)} cfg.ACUrls, cfg.LCUrls = []url.URL{curl}, []url.URL{curl} purl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", etcdPeerPort)} cfg.APUrls, cfg.LPUrls = []url.URL{purl}, []url.URL{purl} cfg.InitialCluster = fmt.Sprintf("%s=%s", cfg.Name, cfg.APUrls[0].String()) cfg.SnapCount = 1000 // single-node, keep minimum snapshot // TODO: enable this with etcd v3.3+ // cfg.AutoCompactionMode = compactor.ModePeriodic // cfg.AutoCompactionRetention = 1 ctx, cancel := context.WithCancel(context.Background()) return &Service{ rootCtx: ctx, rootCancel: cancel, cfg: cfg, dataDir: dataDir, etcdCURL: curl, httpEp: fmt.Sprintf("http://localhost:%d", httpPort), httpServer: &http.Server{ Addr: fmt.Sprintf("localhost:%d", httpPort), Handler: discoveryhttp.RegisterHandlers(ctx, cfg.LCUrls[0].String(), testDiscoveryHost), }, httpErrc: make(chan error), } }
go
func NewService(t *testing.T, etcdClientPort, etcdPeerPort, httpPort int) *Service { dataDir, err := ioutil.TempDir(os.TempDir(), "test-data") if err != nil { t.Fatal(err) } cfg := embed.NewConfig() cfg.ClusterState = embed.ClusterStateFlagNew cfg.Name = "test-etcd" cfg.Dir = dataDir curl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", etcdClientPort)} cfg.ACUrls, cfg.LCUrls = []url.URL{curl}, []url.URL{curl} purl := url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", etcdPeerPort)} cfg.APUrls, cfg.LPUrls = []url.URL{purl}, []url.URL{purl} cfg.InitialCluster = fmt.Sprintf("%s=%s", cfg.Name, cfg.APUrls[0].String()) cfg.SnapCount = 1000 // single-node, keep minimum snapshot // TODO: enable this with etcd v3.3+ // cfg.AutoCompactionMode = compactor.ModePeriodic // cfg.AutoCompactionRetention = 1 ctx, cancel := context.WithCancel(context.Background()) return &Service{ rootCtx: ctx, rootCancel: cancel, cfg: cfg, dataDir: dataDir, etcdCURL: curl, httpEp: fmt.Sprintf("http://localhost:%d", httpPort), httpServer: &http.Server{ Addr: fmt.Sprintf("localhost:%d", httpPort), Handler: discoveryhttp.RegisterHandlers(ctx, cfg.LCUrls[0].String(), testDiscoveryHost), }, httpErrc: make(chan error), } }
[ "func", "NewService", "(", "t", "*", "testing", ".", "T", ",", "etcdClientPort", ",", "etcdPeerPort", ",", "httpPort", "int", ")", "*", "Service", "{", "dataDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "os", ".", "TempDir", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "cfg", ":=", "embed", ".", "NewConfig", "(", ")", "\n", "cfg", ".", "ClusterState", "=", "embed", ".", "ClusterStateFlagNew", "\n", "cfg", ".", "Name", "=", "\"", "\"", "\n", "cfg", ".", "Dir", "=", "dataDir", "\n", "curl", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "etcdClientPort", ")", "}", "\n", "cfg", ".", "ACUrls", ",", "cfg", ".", "LCUrls", "=", "[", "]", "url", ".", "URL", "{", "curl", "}", ",", "[", "]", "url", ".", "URL", "{", "curl", "}", "\n", "purl", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "etcdPeerPort", ")", "}", "\n", "cfg", ".", "APUrls", ",", "cfg", ".", "LPUrls", "=", "[", "]", "url", ".", "URL", "{", "purl", "}", ",", "[", "]", "url", ".", "URL", "{", "purl", "}", "\n", "cfg", ".", "InitialCluster", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "Name", ",", "cfg", ".", "APUrls", "[", "0", "]", ".", "String", "(", ")", ")", "\n", "cfg", ".", "SnapCount", "=", "1000", "// single-node, keep minimum snapshot", "\n\n", "// TODO: enable this with etcd v3.3+", "// cfg.AutoCompactionMode = compactor.ModePeriodic", "// cfg.AutoCompactionRetention = 1", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "return", "&", "Service", "{", "rootCtx", ":", "ctx", ",", "rootCancel", ":", "cancel", ",", "cfg", ":", "cfg", ",", "dataDir", ":", "dataDir", ",", "etcdCURL", ":", "curl", ",", "httpEp", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "httpPort", ")", ",", "httpServer", ":", "&", "http", ".", "Server", "{", "Addr", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "httpPort", ")", ",", "Handler", ":", "discoveryhttp", ".", "RegisterHandlers", "(", "ctx", ",", "cfg", ".", "LCUrls", "[", "0", "]", ".", "String", "(", ")", ",", "testDiscoveryHost", ")", ",", "}", ",", "httpErrc", ":", "make", "(", "chan", "error", ")", ",", "}", "\n", "}" ]
// NewService creates a new service.
[ "NewService", "creates", "a", "new", "service", "." ]
78178dbc766863d76476f36755517bf7e7e29770
https://github.com/coreos/discovery.etcd.io/blob/78178dbc766863d76476f36755517bf7e7e29770/integration/server.go#L37-L74
11,550
coreos/discovery.etcd.io
integration/server.go
Start
func (sv *Service) Start(t *testing.T) <-chan error { srv, err := embed.StartEtcd(sv.cfg) if err != nil { t.Fatal(err) } select { case <-srv.Server.ReadyNotify(): err = nil case err = <-srv.Err(): case <-srv.Server.StopNotify(): err = fmt.Errorf("received from etcdserver.Server.StopNotify") } if err != nil { t.Fatal(err) } sv.etcd = srv // issue linearized read to ensure leader election cli := v3client.New(srv.Server) _, err = cli.Get(context.Background(), "foo") go func() { defer close(sv.httpErrc) if err := sv.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { sv.httpErrc <- err return } sv.httpErrc <- nil }() return sv.httpErrc }
go
func (sv *Service) Start(t *testing.T) <-chan error { srv, err := embed.StartEtcd(sv.cfg) if err != nil { t.Fatal(err) } select { case <-srv.Server.ReadyNotify(): err = nil case err = <-srv.Err(): case <-srv.Server.StopNotify(): err = fmt.Errorf("received from etcdserver.Server.StopNotify") } if err != nil { t.Fatal(err) } sv.etcd = srv // issue linearized read to ensure leader election cli := v3client.New(srv.Server) _, err = cli.Get(context.Background(), "foo") go func() { defer close(sv.httpErrc) if err := sv.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { sv.httpErrc <- err return } sv.httpErrc <- nil }() return sv.httpErrc }
[ "func", "(", "sv", "*", "Service", ")", "Start", "(", "t", "*", "testing", ".", "T", ")", "<-", "chan", "error", "{", "srv", ",", "err", ":=", "embed", ".", "StartEtcd", "(", "sv", ".", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "select", "{", "case", "<-", "srv", ".", "Server", ".", "ReadyNotify", "(", ")", ":", "err", "=", "nil", "\n", "case", "err", "=", "<-", "srv", ".", "Err", "(", ")", ":", "case", "<-", "srv", ".", "Server", ".", "StopNotify", "(", ")", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "sv", ".", "etcd", "=", "srv", "\n\n", "// issue linearized read to ensure leader election", "cli", ":=", "v3client", ".", "New", "(", "srv", ".", "Server", ")", "\n", "_", ",", "err", "=", "cli", ".", "Get", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "sv", ".", "httpErrc", ")", "\n", "if", "err", ":=", "sv", ".", "httpServer", ".", "ListenAndServe", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "http", ".", "ErrServerClosed", "{", "sv", ".", "httpErrc", "<-", "err", "\n", "return", "\n", "}", "\n", "sv", ".", "httpErrc", "<-", "nil", "\n", "}", "(", ")", "\n", "return", "sv", ".", "httpErrc", "\n", "}" ]
// Start starts etcd server and http listener.
[ "Start", "starts", "etcd", "server", "and", "http", "listener", "." ]
78178dbc766863d76476f36755517bf7e7e29770
https://github.com/coreos/discovery.etcd.io/blob/78178dbc766863d76476f36755517bf7e7e29770/integration/server.go#L77-L107
11,551
coreos/discovery.etcd.io
integration/server.go
Stop
func (sv *Service) Stop(t *testing.T) { defer os.RemoveAll(sv.dataDir) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) err := sv.httpServer.Shutdown(ctx) cancel() if err != nil && err != context.DeadlineExceeded { t.Fatal(err) } err = <-sv.httpErrc if err != nil { t.Fatal(err) } sv.rootCancel() sv.etcd.Close() }
go
func (sv *Service) Stop(t *testing.T) { defer os.RemoveAll(sv.dataDir) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) err := sv.httpServer.Shutdown(ctx) cancel() if err != nil && err != context.DeadlineExceeded { t.Fatal(err) } err = <-sv.httpErrc if err != nil { t.Fatal(err) } sv.rootCancel() sv.etcd.Close() }
[ "func", "(", "sv", "*", "Service", ")", "Stop", "(", "t", "*", "testing", ".", "T", ")", "{", "defer", "os", ".", "RemoveAll", "(", "sv", ".", "dataDir", ")", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "5", "*", "time", ".", "Second", ")", "\n", "err", ":=", "sv", ".", "httpServer", ".", "Shutdown", "(", "ctx", ")", "\n", "cancel", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "context", ".", "DeadlineExceeded", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "err", "=", "<-", "sv", ".", "httpErrc", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "sv", ".", "rootCancel", "(", ")", "\n", "sv", ".", "etcd", ".", "Close", "(", ")", "\n", "}" ]
// Stop stops etcd server, removing the data directory, and http server.
[ "Stop", "stops", "etcd", "server", "removing", "the", "data", "directory", "and", "http", "server", "." ]
78178dbc766863d76476f36755517bf7e7e29770
https://github.com/coreos/discovery.etcd.io/blob/78178dbc766863d76476f36755517bf7e7e29770/integration/server.go#L110-L126
11,552
alioygur/godash
is.go
IsInRange
func IsInRange(value, left, right float64) bool { if left > right { left, right = right, left } return value >= left && value <= right }
go
func IsInRange(value, left, right float64) bool { if left > right { left, right = right, left } return value >= left && value <= right }
[ "func", "IsInRange", "(", "value", ",", "left", ",", "right", "float64", ")", "bool", "{", "if", "left", ">", "right", "{", "left", ",", "right", "=", "right", ",", "left", "\n", "}", "\n", "return", "value", ">=", "left", "&&", "value", "<=", "right", "\n", "}" ]
// IsInRange returns true if value lies between left and right border
[ "IsInRange", "returns", "true", "if", "value", "lies", "between", "left", "and", "right", "border" ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/is.go#L17-L22
11,553
alioygur/godash
is.go
IsEmail
func IsEmail(s string) bool { if !strings.Contains(s, "@") || string(s[0]) == "@" || string(s[len(s)-1]) == "@" { return false } return true }
go
func IsEmail(s string) bool { if !strings.Contains(s, "@") || string(s[0]) == "@" || string(s[len(s)-1]) == "@" { return false } return true }
[ "func", "IsEmail", "(", "s", "string", ")", "bool", "{", "if", "!", "strings", ".", "Contains", "(", "s", ",", "\"", "\"", ")", "||", "string", "(", "s", "[", "0", "]", ")", "==", "\"", "\"", "||", "string", "(", "s", "[", "len", "(", "s", ")", "-", "1", "]", ")", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsEmail is a constraint to do a simple validation for email addresses, it only check if the string contains "@" // and that it is not in the first or last character of the string // https://en.wikipedia.org/wiki/Email_address#Valid_email_addresses
[ "IsEmail", "is", "a", "constraint", "to", "do", "a", "simple", "validation", "for", "email", "addresses", "it", "only", "check", "if", "the", "string", "contains" ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/is.go#L27-L32
11,554
alioygur/godash
is.go
IsBase64
func IsBase64(s string) bool { if IsNull(s) { return false } _, err := base64.StdEncoding.DecodeString(s) return err == nil }
go
func IsBase64(s string) bool { if IsNull(s) { return false } _, err := base64.StdEncoding.DecodeString(s) return err == nil }
[ "func", "IsBase64", "(", "s", "string", ")", "bool", "{", "if", "IsNull", "(", "s", ")", "{", "return", "false", "\n", "}", "\n", "_", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "s", ")", "\n\n", "return", "err", "==", "nil", "\n", "}" ]
// IsBase64 check if a string is base64 encoded.
[ "IsBase64", "check", "if", "a", "string", "is", "base64", "encoded", "." ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/is.go#L409-L416
11,555
alioygur/godash
is.go
IsDNSName
func IsDNSName(str string) bool { if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 { // constraints already violated return false } return rxDNSName.MatchString(str) }
go
func IsDNSName(str string) bool { if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 { // constraints already violated return false } return rxDNSName.MatchString(str) }
[ "func", "IsDNSName", "(", "str", "string", ")", "bool", "{", "if", "str", "==", "\"", "\"", "||", "len", "(", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", ")", ">", "255", "{", "// constraints already violated", "return", "false", "\n", "}", "\n", "return", "rxDNSName", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsDNSName will validate the given string as a DNS name
[ "IsDNSName", "will", "validate", "the", "given", "string", "as", "a", "DNS", "name" ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/is.go#L463-L469
11,556
alioygur/godash
is.go
IsStringMatches
func IsStringMatches(s string, params ...string) bool { if len(params) == 1 { pattern := params[0] return IsMatches(s, pattern) } return false }
go
func IsStringMatches(s string, params ...string) bool { if len(params) == 1 { pattern := params[0] return IsMatches(s, pattern) } return false }
[ "func", "IsStringMatches", "(", "s", "string", ",", "params", "...", "string", ")", "bool", "{", "if", "len", "(", "params", ")", "==", "1", "{", "pattern", ":=", "params", "[", "0", "]", "\n", "return", "IsMatches", "(", "s", ",", "pattern", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsStringMatches checks if a string matches a given pattern.
[ "IsStringMatches", "checks", "if", "a", "string", "matches", "a", "given", "pattern", "." ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/is.go#L555-L561
11,557
alioygur/godash
to.go
ToInt
func ToInt(str string) (int64, error) { res, err := strconv.ParseInt(str, 0, 64) if err != nil { res = 0 } return res, err }
go
func ToInt(str string) (int64, error) { res, err := strconv.ParseInt(str, 0, 64) if err != nil { res = 0 } return res, err }
[ "func", "ToInt", "(", "str", "string", ")", "(", "int64", ",", "error", ")", "{", "res", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "str", ",", "0", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "0", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// ToInt convert the input string to an integer, or 0 if the input is not an integer.
[ "ToInt", "convert", "the", "input", "string", "to", "an", "integer", "or", "0", "if", "the", "input", "is", "not", "an", "integer", "." ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/to.go#L36-L42
11,558
alioygur/godash
to.go
ToBoolean
func ToBoolean(str string) (bool, error) { res, err := strconv.ParseBool(str) if err != nil { res = false } return res, err }
go
func ToBoolean(str string) (bool, error) { res, err := strconv.ParseBool(str) if err != nil { res = false } return res, err }
[ "func", "ToBoolean", "(", "str", "string", ")", "(", "bool", ",", "error", ")", "{", "res", ",", "err", ":=", "strconv", ".", "ParseBool", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "false", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// ToBoolean convert the input string to a boolean.
[ "ToBoolean", "convert", "the", "input", "string", "to", "a", "boolean", "." ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/to.go#L45-L51
11,559
alioygur/godash
to.go
ToCamelCase
func ToCamelCase(s string) string { byteSrc := []byte(s) chunks := rxCameling.FindAll(byteSrc, -1) for idx, val := range chunks { chunks[idx] = bytes.Title(val) } return string(bytes.Join(chunks, nil)) }
go
func ToCamelCase(s string) string { byteSrc := []byte(s) chunks := rxCameling.FindAll(byteSrc, -1) for idx, val := range chunks { chunks[idx] = bytes.Title(val) } return string(bytes.Join(chunks, nil)) }
[ "func", "ToCamelCase", "(", "s", "string", ")", "string", "{", "byteSrc", ":=", "[", "]", "byte", "(", "s", ")", "\n", "chunks", ":=", "rxCameling", ".", "FindAll", "(", "byteSrc", ",", "-", "1", ")", "\n", "for", "idx", ",", "val", ":=", "range", "chunks", "{", "chunks", "[", "idx", "]", "=", "bytes", ".", "Title", "(", "val", ")", "\n", "}", "\n", "return", "string", "(", "bytes", ".", "Join", "(", "chunks", ",", "nil", ")", ")", "\n", "}" ]
// ToCamelCase converts from underscore separated form to camel case form.
[ "ToCamelCase", "converts", "from", "underscore", "separated", "form", "to", "camel", "case", "form", "." ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/to.go#L54-L61
11,560
alioygur/godash
to.go
ToSnakeCase
func ToSnakeCase(s string) string { s = ToCamelCase(s) runes := []rune(s) length := len(runes) var out []rune for i := 0; i < length; i++ { out = append(out, unicode.ToLower(runes[i])) if i+1 < length && (unicode.IsUpper(runes[i+1]) && unicode.IsLower(runes[i])) { out = append(out, '_') } } return string(out) }
go
func ToSnakeCase(s string) string { s = ToCamelCase(s) runes := []rune(s) length := len(runes) var out []rune for i := 0; i < length; i++ { out = append(out, unicode.ToLower(runes[i])) if i+1 < length && (unicode.IsUpper(runes[i+1]) && unicode.IsLower(runes[i])) { out = append(out, '_') } } return string(out) }
[ "func", "ToSnakeCase", "(", "s", "string", ")", "string", "{", "s", "=", "ToCamelCase", "(", "s", ")", "\n", "runes", ":=", "[", "]", "rune", "(", "s", ")", "\n", "length", ":=", "len", "(", "runes", ")", "\n", "var", "out", "[", "]", "rune", "\n", "for", "i", ":=", "0", ";", "i", "<", "length", ";", "i", "++", "{", "out", "=", "append", "(", "out", ",", "unicode", ".", "ToLower", "(", "runes", "[", "i", "]", ")", ")", "\n", "if", "i", "+", "1", "<", "length", "&&", "(", "unicode", ".", "IsUpper", "(", "runes", "[", "i", "+", "1", "]", ")", "&&", "unicode", ".", "IsLower", "(", "runes", "[", "i", "]", ")", ")", "{", "out", "=", "append", "(", "out", ",", "'_'", ")", "\n", "}", "\n", "}", "\n\n", "return", "string", "(", "out", ")", "\n", "}" ]
// ToSnakeCase converts from camel case form to underscore separated form.
[ "ToSnakeCase", "converts", "from", "camel", "case", "form", "to", "underscore", "separated", "form", "." ]
af6b3da41c5a0f8c712c555d93930b971929248c
https://github.com/alioygur/godash/blob/af6b3da41c5a0f8c712c555d93930b971929248c/to.go#L64-L77
11,561
gemnasium/logrus-graylog-hook
error.go
MarshalJSON
func (m *marshalableError) MarshalJSON() ([]byte, error) { return json.Marshal(m.err.Error()) }
go
func (m *marshalableError) MarshalJSON() ([]byte, error) { return json.Marshal(m.err.Error()) }
[ "func", "(", "m", "*", "marshalableError", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "m", ".", "err", ".", "Error", "(", ")", ")", "\n", "}" ]
// MarshalJSON implements json.Marshaler for marshalableError
[ "MarshalJSON", "implements", "json", ".", "Marshaler", "for", "marshalableError" ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/error.go#L19-L21
11,562
gemnasium/logrus-graylog-hook
gelf_writer.go
numChunks
func numChunks(b []byte) int { lenB := len(b) if lenB <= ChunkSize { return 1 } return len(b)/chunkedDataLen + 1 }
go
func numChunks(b []byte) int { lenB := len(b) if lenB <= ChunkSize { return 1 } return len(b)/chunkedDataLen + 1 }
[ "func", "numChunks", "(", "b", "[", "]", "byte", ")", "int", "{", "lenB", ":=", "len", "(", "b", ")", "\n", "if", "lenB", "<=", "ChunkSize", "{", "return", "1", "\n", "}", "\n", "return", "len", "(", "b", ")", "/", "chunkedDataLen", "+", "1", "\n", "}" ]
// numChunks returns the number of GELF chunks necessary to transmit // the given compressed buffer.
[ "numChunks", "returns", "the", "number", "of", "GELF", "chunks", "necessary", "to", "transmit", "the", "given", "compressed", "buffer", "." ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/gelf_writer.go#L84-L90
11,563
gemnasium/logrus-graylog-hook
graylog_hook.go
NewGraylogHook
func NewGraylogHook(addr string, extra map[string]interface{}) *GraylogHook { g, err := NewWriter(addr) if err != nil { logrus.WithError(err).Error("Can't create Gelf logger") } host, err := os.Hostname() if err != nil { host = "localhost" } hook := &GraylogHook{ Host: host, Extra: extra, Level: logrus.DebugLevel, gelfLogger: g, synchronous: true, } return hook }
go
func NewGraylogHook(addr string, extra map[string]interface{}) *GraylogHook { g, err := NewWriter(addr) if err != nil { logrus.WithError(err).Error("Can't create Gelf logger") } host, err := os.Hostname() if err != nil { host = "localhost" } hook := &GraylogHook{ Host: host, Extra: extra, Level: logrus.DebugLevel, gelfLogger: g, synchronous: true, } return hook }
[ "func", "NewGraylogHook", "(", "addr", "string", ",", "extra", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "GraylogHook", "{", "g", ",", "err", ":=", "NewWriter", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n\n", "host", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "host", "=", "\"", "\"", "\n", "}", "\n\n", "hook", ":=", "&", "GraylogHook", "{", "Host", ":", "host", ",", "Extra", ":", "extra", ",", "Level", ":", "logrus", ".", "DebugLevel", ",", "gelfLogger", ":", "g", ",", "synchronous", ":", "true", ",", "}", "\n", "return", "hook", "\n", "}" ]
// NewGraylogHook creates a hook to be added to an instance of logger.
[ "NewGraylogHook", "creates", "a", "hook", "to", "be", "added", "to", "an", "instance", "of", "logger", "." ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L43-L62
11,564
gemnasium/logrus-graylog-hook
graylog_hook.go
NewAsyncGraylogHook
func NewAsyncGraylogHook(addr string, extra map[string]interface{}) *GraylogHook { g, err := NewWriter(addr) if err != nil { logrus.WithError(err).Error("Can't create Gelf logger") } host, err := os.Hostname() if err != nil { host = "localhost" } hook := &GraylogHook{ Host: host, Extra: extra, Level: logrus.DebugLevel, gelfLogger: g, buf: make(chan graylogEntry, BufSize), } go hook.fire() // Log in background return hook }
go
func NewAsyncGraylogHook(addr string, extra map[string]interface{}) *GraylogHook { g, err := NewWriter(addr) if err != nil { logrus.WithError(err).Error("Can't create Gelf logger") } host, err := os.Hostname() if err != nil { host = "localhost" } hook := &GraylogHook{ Host: host, Extra: extra, Level: logrus.DebugLevel, gelfLogger: g, buf: make(chan graylogEntry, BufSize), } go hook.fire() // Log in background return hook }
[ "func", "NewAsyncGraylogHook", "(", "addr", "string", ",", "extra", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "GraylogHook", "{", "g", ",", "err", ":=", "NewWriter", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n\n", "host", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "host", "=", "\"", "\"", "\n", "}", "\n\n", "hook", ":=", "&", "GraylogHook", "{", "Host", ":", "host", ",", "Extra", ":", "extra", ",", "Level", ":", "logrus", ".", "DebugLevel", ",", "gelfLogger", ":", "g", ",", "buf", ":", "make", "(", "chan", "graylogEntry", ",", "BufSize", ")", ",", "}", "\n", "go", "hook", ".", "fire", "(", ")", "// Log in background", "\n", "return", "hook", "\n", "}" ]
// NewAsyncGraylogHook creates a hook to be added to an instance of logger. // The hook created will be asynchronous, and it's the responsibility of the user to call the Flush method // before exiting to empty the log queue.
[ "NewAsyncGraylogHook", "creates", "a", "hook", "to", "be", "added", "to", "an", "instance", "of", "logger", ".", "The", "hook", "created", "will", "be", "asynchronous", "and", "it", "s", "the", "responsibility", "of", "the", "user", "to", "call", "the", "Flush", "method", "before", "exiting", "to", "empty", "the", "log", "queue", "." ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L67-L87
11,565
gemnasium/logrus-graylog-hook
graylog_hook.go
Fire
func (hook *GraylogHook) Fire(entry *logrus.Entry) error { hook.mu.RLock() // Claim the mutex as a RLock - allowing multiple go routines to log simultaneously defer hook.mu.RUnlock() var file string var line int if entry.Caller != nil { file = entry.Caller.File line = entry.Caller.Line } newData := make(map[string]interface{}) for k, v := range entry.Data { newData[k] = v } newEntry := &logrus.Entry{ Logger: entry.Logger, Data: newData, Time: entry.Time, Level: entry.Level, Caller: entry.Caller, Message: entry.Message, } gEntry := graylogEntry{newEntry, file, line} if hook.synchronous { hook.sendEntry(gEntry) } else { hook.wg.Add(1) hook.buf <- gEntry } return nil }
go
func (hook *GraylogHook) Fire(entry *logrus.Entry) error { hook.mu.RLock() // Claim the mutex as a RLock - allowing multiple go routines to log simultaneously defer hook.mu.RUnlock() var file string var line int if entry.Caller != nil { file = entry.Caller.File line = entry.Caller.Line } newData := make(map[string]interface{}) for k, v := range entry.Data { newData[k] = v } newEntry := &logrus.Entry{ Logger: entry.Logger, Data: newData, Time: entry.Time, Level: entry.Level, Caller: entry.Caller, Message: entry.Message, } gEntry := graylogEntry{newEntry, file, line} if hook.synchronous { hook.sendEntry(gEntry) } else { hook.wg.Add(1) hook.buf <- gEntry } return nil }
[ "func", "(", "hook", "*", "GraylogHook", ")", "Fire", "(", "entry", "*", "logrus", ".", "Entry", ")", "error", "{", "hook", ".", "mu", ".", "RLock", "(", ")", "// Claim the mutex as a RLock - allowing multiple go routines to log simultaneously", "\n", "defer", "hook", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "var", "file", "string", "\n", "var", "line", "int", "\n\n", "if", "entry", ".", "Caller", "!=", "nil", "{", "file", "=", "entry", ".", "Caller", ".", "File", "\n", "line", "=", "entry", ".", "Caller", ".", "Line", "\n", "}", "\n\n", "newData", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "k", ",", "v", ":=", "range", "entry", ".", "Data", "{", "newData", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "newEntry", ":=", "&", "logrus", ".", "Entry", "{", "Logger", ":", "entry", ".", "Logger", ",", "Data", ":", "newData", ",", "Time", ":", "entry", ".", "Time", ",", "Level", ":", "entry", ".", "Level", ",", "Caller", ":", "entry", ".", "Caller", ",", "Message", ":", "entry", ".", "Message", ",", "}", "\n", "gEntry", ":=", "graylogEntry", "{", "newEntry", ",", "file", ",", "line", "}", "\n\n", "if", "hook", ".", "synchronous", "{", "hook", ".", "sendEntry", "(", "gEntry", ")", "\n", "}", "else", "{", "hook", ".", "wg", ".", "Add", "(", "1", ")", "\n", "hook", ".", "buf", "<-", "gEntry", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Fire is called when a log event is fired. // We assume the entry will be altered by another hook, // otherwise we might logging something wrong to Graylog
[ "Fire", "is", "called", "when", "a", "log", "event", "is", "fired", ".", "We", "assume", "the", "entry", "will", "be", "altered", "by", "another", "hook", "otherwise", "we", "might", "logging", "something", "wrong", "to", "Graylog" ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L92-L127
11,566
gemnasium/logrus-graylog-hook
graylog_hook.go
Flush
func (hook *GraylogHook) Flush() { hook.mu.Lock() // claim the mutex as a Lock - we want exclusive access to it defer hook.mu.Unlock() hook.wg.Wait() }
go
func (hook *GraylogHook) Flush() { hook.mu.Lock() // claim the mutex as a Lock - we want exclusive access to it defer hook.mu.Unlock() hook.wg.Wait() }
[ "func", "(", "hook", "*", "GraylogHook", ")", "Flush", "(", ")", "{", "hook", ".", "mu", ".", "Lock", "(", ")", "// claim the mutex as a Lock - we want exclusive access to it", "\n", "defer", "hook", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "hook", ".", "wg", ".", "Wait", "(", ")", "\n", "}" ]
// Flush waits for the log queue to be empty. // This func is meant to be used when the hook was created with NewAsyncGraylogHook.
[ "Flush", "waits", "for", "the", "log", "queue", "to", "be", "empty", ".", "This", "func", "is", "meant", "to", "be", "used", "when", "the", "hook", "was", "created", "with", "NewAsyncGraylogHook", "." ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L131-L136
11,567
gemnasium/logrus-graylog-hook
graylog_hook.go
fire
func (hook *GraylogHook) fire() { for { entry := <-hook.buf // receive new entry on channel hook.sendEntry(entry) hook.wg.Done() } }
go
func (hook *GraylogHook) fire() { for { entry := <-hook.buf // receive new entry on channel hook.sendEntry(entry) hook.wg.Done() } }
[ "func", "(", "hook", "*", "GraylogHook", ")", "fire", "(", ")", "{", "for", "{", "entry", ":=", "<-", "hook", ".", "buf", "// receive new entry on channel", "\n", "hook", ".", "sendEntry", "(", "entry", ")", "\n", "hook", ".", "wg", ".", "Done", "(", ")", "\n", "}", "\n", "}" ]
// fire will loop on the 'buf' channel, and write entries to graylog
[ "fire", "will", "loop", "on", "the", "buf", "channel", "and", "write", "entries", "to", "graylog" ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L139-L145
11,568
gemnasium/logrus-graylog-hook
graylog_hook.go
sendEntry
func (hook *GraylogHook) sendEntry(entry graylogEntry) { if hook.gelfLogger == nil { fmt.Println("Can't connect to Graylog") return } w := hook.gelfLogger // remove trailing and leading whitespace p := bytes.TrimSpace([]byte(entry.Message)) // If there are newlines in the message, use the first line // for the short message and set the full message to the // original input. If the input has no newlines, stick the // whole thing in Short. short := p full := []byte("") if i := bytes.IndexRune(p, '\n'); i > 0 { short = p[:i] full = p } level := logrusLevelToSylog(entry.Level) // Don't modify entry.Data directly, as the entry will used after this hook was fired extra := map[string]interface{}{} // Merge extra fields for k, v := range hook.Extra { k = fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field." extra[k] = v } if entry.Caller != nil { extra["_file"] = entry.Caller.File extra["_line"] = entry.Caller.Line extra["_function"] = entry.Caller.Function } for k, v := range entry.Data { if !hook.blacklist[k] { extraK := fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field." if k == logrus.ErrorKey { asError, isError := v.(error) _, isMarshaler := v.(json.Marshaler) if isError && !isMarshaler { extra[extraK] = newMarshalableError(asError) } else { extra[extraK] = v } if stackTrace := extractStackTrace(asError); stackTrace != nil { extra[StackTraceKey] = fmt.Sprintf("%+v", stackTrace) } } else { extra[extraK] = v } } } m := Message{ Version: "1.1", Host: hook.Host, Short: string(short), Full: string(full), TimeUnix: float64(time.Now().UnixNano()/1000000) / 1000., Level: level, File: entry.file, Line: entry.line, Extra: extra, } if err := w.WriteMessage(&m); err != nil { fmt.Println(err) } }
go
func (hook *GraylogHook) sendEntry(entry graylogEntry) { if hook.gelfLogger == nil { fmt.Println("Can't connect to Graylog") return } w := hook.gelfLogger // remove trailing and leading whitespace p := bytes.TrimSpace([]byte(entry.Message)) // If there are newlines in the message, use the first line // for the short message and set the full message to the // original input. If the input has no newlines, stick the // whole thing in Short. short := p full := []byte("") if i := bytes.IndexRune(p, '\n'); i > 0 { short = p[:i] full = p } level := logrusLevelToSylog(entry.Level) // Don't modify entry.Data directly, as the entry will used after this hook was fired extra := map[string]interface{}{} // Merge extra fields for k, v := range hook.Extra { k = fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field." extra[k] = v } if entry.Caller != nil { extra["_file"] = entry.Caller.File extra["_line"] = entry.Caller.Line extra["_function"] = entry.Caller.Function } for k, v := range entry.Data { if !hook.blacklist[k] { extraK := fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field." if k == logrus.ErrorKey { asError, isError := v.(error) _, isMarshaler := v.(json.Marshaler) if isError && !isMarshaler { extra[extraK] = newMarshalableError(asError) } else { extra[extraK] = v } if stackTrace := extractStackTrace(asError); stackTrace != nil { extra[StackTraceKey] = fmt.Sprintf("%+v", stackTrace) } } else { extra[extraK] = v } } } m := Message{ Version: "1.1", Host: hook.Host, Short: string(short), Full: string(full), TimeUnix: float64(time.Now().UnixNano()/1000000) / 1000., Level: level, File: entry.file, Line: entry.line, Extra: extra, } if err := w.WriteMessage(&m); err != nil { fmt.Println(err) } }
[ "func", "(", "hook", "*", "GraylogHook", ")", "sendEntry", "(", "entry", "graylogEntry", ")", "{", "if", "hook", ".", "gelfLogger", "==", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "w", ":=", "hook", ".", "gelfLogger", "\n\n", "// remove trailing and leading whitespace", "p", ":=", "bytes", ".", "TrimSpace", "(", "[", "]", "byte", "(", "entry", ".", "Message", ")", ")", "\n\n", "// If there are newlines in the message, use the first line", "// for the short message and set the full message to the", "// original input. If the input has no newlines, stick the", "// whole thing in Short.", "short", ":=", "p", "\n", "full", ":=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "if", "i", ":=", "bytes", ".", "IndexRune", "(", "p", ",", "'\\n'", ")", ";", "i", ">", "0", "{", "short", "=", "p", "[", ":", "i", "]", "\n", "full", "=", "p", "\n", "}", "\n\n", "level", ":=", "logrusLevelToSylog", "(", "entry", ".", "Level", ")", "\n\n", "// Don't modify entry.Data directly, as the entry will used after this hook was fired", "extra", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "// Merge extra fields", "for", "k", ",", "v", ":=", "range", "hook", ".", "Extra", "{", "k", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ")", "// \"[...] every field you send and prefix with a _ (underscore) will be treated as an additional field.\"", "\n", "extra", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "if", "entry", ".", "Caller", "!=", "nil", "{", "extra", "[", "\"", "\"", "]", "=", "entry", ".", "Caller", ".", "File", "\n", "extra", "[", "\"", "\"", "]", "=", "entry", ".", "Caller", ".", "Line", "\n", "extra", "[", "\"", "\"", "]", "=", "entry", ".", "Caller", ".", "Function", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "entry", ".", "Data", "{", "if", "!", "hook", ".", "blacklist", "[", "k", "]", "{", "extraK", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ")", "// \"[...] every field you send and prefix with a _ (underscore) will be treated as an additional field.\"", "\n", "if", "k", "==", "logrus", ".", "ErrorKey", "{", "asError", ",", "isError", ":=", "v", ".", "(", "error", ")", "\n", "_", ",", "isMarshaler", ":=", "v", ".", "(", "json", ".", "Marshaler", ")", "\n", "if", "isError", "&&", "!", "isMarshaler", "{", "extra", "[", "extraK", "]", "=", "newMarshalableError", "(", "asError", ")", "\n", "}", "else", "{", "extra", "[", "extraK", "]", "=", "v", "\n", "}", "\n", "if", "stackTrace", ":=", "extractStackTrace", "(", "asError", ")", ";", "stackTrace", "!=", "nil", "{", "extra", "[", "StackTraceKey", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "stackTrace", ")", "\n", "}", "\n", "}", "else", "{", "extra", "[", "extraK", "]", "=", "v", "\n", "}", "\n", "}", "\n", "}", "\n\n", "m", ":=", "Message", "{", "Version", ":", "\"", "\"", ",", "Host", ":", "hook", ".", "Host", ",", "Short", ":", "string", "(", "short", ")", ",", "Full", ":", "string", "(", "full", ")", ",", "TimeUnix", ":", "float64", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "/", "1000000", ")", "/", "1000.", ",", "Level", ":", "level", ",", "File", ":", "entry", ".", "file", ",", "Line", ":", "entry", ".", "line", ",", "Extra", ":", "extra", ",", "}", "\n\n", "if", "err", ":=", "w", ".", "WriteMessage", "(", "&", "m", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "err", ")", "\n", "}", "\n", "}" ]
// sendEntry sends an entry to graylog synchronously
[ "sendEntry", "sends", "an", "entry", "to", "graylog", "synchronously" ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L178-L250
11,569
gemnasium/logrus-graylog-hook
graylog_hook.go
Blacklist
func (hook *GraylogHook) Blacklist(b []string) { hook.blacklist = make(map[string]bool) for _, elem := range b { hook.blacklist[elem] = true } }
go
func (hook *GraylogHook) Blacklist(b []string) { hook.blacklist = make(map[string]bool) for _, elem := range b { hook.blacklist[elem] = true } }
[ "func", "(", "hook", "*", "GraylogHook", ")", "Blacklist", "(", "b", "[", "]", "string", ")", "{", "hook", ".", "blacklist", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "elem", ":=", "range", "b", "{", "hook", ".", "blacklist", "[", "elem", "]", "=", "true", "\n", "}", "\n", "}" ]
// Blacklist create a blacklist map to filter some message keys. // This useful when you want your application to log extra fields locally // but don't want graylog to store them.
[ "Blacklist", "create", "a", "blacklist", "map", "to", "filter", "some", "message", "keys", ".", "This", "useful", "when", "you", "want", "your", "application", "to", "log", "extra", "fields", "locally", "but", "don", "t", "want", "graylog", "to", "store", "them", "." ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L266-L271
11,570
gemnasium/logrus-graylog-hook
graylog_hook.go
SetWriter
func (hook *GraylogHook) SetWriter(w *Writer) error { if w == nil { return errors.New("writer can't be nil") } hook.gelfLogger = w return nil }
go
func (hook *GraylogHook) SetWriter(w *Writer) error { if w == nil { return errors.New("writer can't be nil") } hook.gelfLogger = w return nil }
[ "func", "(", "hook", "*", "GraylogHook", ")", "SetWriter", "(", "w", "*", "Writer", ")", "error", "{", "if", "w", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "hook", ".", "gelfLogger", "=", "w", "\n", "return", "nil", "\n", "}" ]
// SetWriter sets the hook Gelf Writer
[ "SetWriter", "sets", "the", "hook", "Gelf", "Writer" ]
b3082031ff2ac00241f0499cafca1dfabec6b387
https://github.com/gemnasium/logrus-graylog-hook/blob/b3082031ff2ac00241f0499cafca1dfabec6b387/graylog_hook.go#L274-L280
11,571
k-sone/snmpgo
client.go
Open
func (s *SNMP) Open() (err error) { if s.conn != nil { return } err = retry(int(s.args.Retries), func() error { conn, e := net.DialTimeout(s.args.Network, s.args.Address, s.args.Timeout) if e == nil { s.conn = conn } return e }) if err != nil { return } s.engine = newSNMPEngine(s.args) if err = s.engine.Discover(s); err != nil { s.Close() } return }
go
func (s *SNMP) Open() (err error) { if s.conn != nil { return } err = retry(int(s.args.Retries), func() error { conn, e := net.DialTimeout(s.args.Network, s.args.Address, s.args.Timeout) if e == nil { s.conn = conn } return e }) if err != nil { return } s.engine = newSNMPEngine(s.args) if err = s.engine.Discover(s); err != nil { s.Close() } return }
[ "func", "(", "s", "*", "SNMP", ")", "Open", "(", ")", "(", "err", "error", ")", "{", "if", "s", ".", "conn", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "retry", "(", "int", "(", "s", ".", "args", ".", "Retries", ")", ",", "func", "(", ")", "error", "{", "conn", ",", "e", ":=", "net", ".", "DialTimeout", "(", "s", ".", "args", ".", "Network", ",", "s", ".", "args", ".", "Address", ",", "s", ".", "args", ".", "Timeout", ")", "\n", "if", "e", "==", "nil", "{", "s", ".", "conn", "=", "conn", "\n", "}", "\n", "return", "e", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "s", ".", "engine", "=", "newSNMPEngine", "(", "s", ".", "args", ")", "\n", "if", "err", "=", "s", ".", "engine", ".", "Discover", "(", "s", ")", ";", "err", "!=", "nil", "{", "s", ".", "Close", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Open a connection
[ "Open", "a", "connection" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/client.go#L128-L149
11,572
k-sone/snmpgo
client.go
GetBulkWalk
func (s *SNMP) GetBulkWalk(oids Oids, nonRepeaters, maxRepetitions int) (result Pdu, err error) { var nonRepBinds, resBinds VarBinds oids = append(oids[:nonRepeaters], oids[nonRepeaters:].Sort().UniqBase()...) reqOids := make(Oids, len(oids)) copy(reqOids, oids) for len(reqOids) > 0 { pdu, err := s.GetBulkRequest(reqOids, nonRepeaters, maxRepetitions) if err != nil { return nil, err } if s := pdu.ErrorStatus(); s != NoError && (s != NoSuchName || pdu.ErrorIndex() <= nonRepeaters) { return pdu, nil } varBinds := pdu.VarBinds() if nonRepeaters > 0 { nonRepBinds = append(nonRepBinds, varBinds[:nonRepeaters]...) varBinds = varBinds[nonRepeaters:] oids = oids[nonRepeaters:] reqOids = reqOids[nonRepeaters:] nonRepeaters = 0 } filled := len(varBinds) == len(reqOids)*maxRepetitions varBinds = varBinds.Sort().Uniq() for i, _ := range reqOids { matched := varBinds.MatchBaseOids(oids[i]) mLength := len(matched) if mLength == 0 || resBinds.MatchOid(matched[mLength-1].Oid) != nil { reqOids[i] = nil continue } hasError := false for _, val := range matched { switch val.Variable.(type) { case *NoSucheObject, *NoSucheInstance, *EndOfMibView: hasError = true default: resBinds = append(resBinds, val) reqOids[i] = val.Oid } } if hasError || (filled && mLength < maxRepetitions) { reqOids[i] = nil } } // sweep completed oids for i := len(reqOids) - 1; i >= 0; i-- { if reqOids[i] == nil { reqOids = append(reqOids[:i], reqOids[i+1:]...) oids = append(oids[:i], oids[i+1:]...) } } } resBinds = append(nonRepBinds, resBinds.Sort().Uniq()...) return NewPduWithVarBinds(s.args.Version, GetResponse, resBinds), nil }
go
func (s *SNMP) GetBulkWalk(oids Oids, nonRepeaters, maxRepetitions int) (result Pdu, err error) { var nonRepBinds, resBinds VarBinds oids = append(oids[:nonRepeaters], oids[nonRepeaters:].Sort().UniqBase()...) reqOids := make(Oids, len(oids)) copy(reqOids, oids) for len(reqOids) > 0 { pdu, err := s.GetBulkRequest(reqOids, nonRepeaters, maxRepetitions) if err != nil { return nil, err } if s := pdu.ErrorStatus(); s != NoError && (s != NoSuchName || pdu.ErrorIndex() <= nonRepeaters) { return pdu, nil } varBinds := pdu.VarBinds() if nonRepeaters > 0 { nonRepBinds = append(nonRepBinds, varBinds[:nonRepeaters]...) varBinds = varBinds[nonRepeaters:] oids = oids[nonRepeaters:] reqOids = reqOids[nonRepeaters:] nonRepeaters = 0 } filled := len(varBinds) == len(reqOids)*maxRepetitions varBinds = varBinds.Sort().Uniq() for i, _ := range reqOids { matched := varBinds.MatchBaseOids(oids[i]) mLength := len(matched) if mLength == 0 || resBinds.MatchOid(matched[mLength-1].Oid) != nil { reqOids[i] = nil continue } hasError := false for _, val := range matched { switch val.Variable.(type) { case *NoSucheObject, *NoSucheInstance, *EndOfMibView: hasError = true default: resBinds = append(resBinds, val) reqOids[i] = val.Oid } } if hasError || (filled && mLength < maxRepetitions) { reqOids[i] = nil } } // sweep completed oids for i := len(reqOids) - 1; i >= 0; i-- { if reqOids[i] == nil { reqOids = append(reqOids[:i], reqOids[i+1:]...) oids = append(oids[:i], oids[i+1:]...) } } } resBinds = append(nonRepBinds, resBinds.Sort().Uniq()...) return NewPduWithVarBinds(s.args.Version, GetResponse, resBinds), nil }
[ "func", "(", "s", "*", "SNMP", ")", "GetBulkWalk", "(", "oids", "Oids", ",", "nonRepeaters", ",", "maxRepetitions", "int", ")", "(", "result", "Pdu", ",", "err", "error", ")", "{", "var", "nonRepBinds", ",", "resBinds", "VarBinds", "\n\n", "oids", "=", "append", "(", "oids", "[", ":", "nonRepeaters", "]", ",", "oids", "[", "nonRepeaters", ":", "]", ".", "Sort", "(", ")", ".", "UniqBase", "(", ")", "...", ")", "\n", "reqOids", ":=", "make", "(", "Oids", ",", "len", "(", "oids", ")", ")", "\n", "copy", "(", "reqOids", ",", "oids", ")", "\n\n", "for", "len", "(", "reqOids", ")", ">", "0", "{", "pdu", ",", "err", ":=", "s", ".", "GetBulkRequest", "(", "reqOids", ",", "nonRepeaters", ",", "maxRepetitions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "s", ":=", "pdu", ".", "ErrorStatus", "(", ")", ";", "s", "!=", "NoError", "&&", "(", "s", "!=", "NoSuchName", "||", "pdu", ".", "ErrorIndex", "(", ")", "<=", "nonRepeaters", ")", "{", "return", "pdu", ",", "nil", "\n", "}", "\n\n", "varBinds", ":=", "pdu", ".", "VarBinds", "(", ")", "\n\n", "if", "nonRepeaters", ">", "0", "{", "nonRepBinds", "=", "append", "(", "nonRepBinds", ",", "varBinds", "[", ":", "nonRepeaters", "]", "...", ")", "\n", "varBinds", "=", "varBinds", "[", "nonRepeaters", ":", "]", "\n", "oids", "=", "oids", "[", "nonRepeaters", ":", "]", "\n", "reqOids", "=", "reqOids", "[", "nonRepeaters", ":", "]", "\n", "nonRepeaters", "=", "0", "\n", "}", "\n\n", "filled", ":=", "len", "(", "varBinds", ")", "==", "len", "(", "reqOids", ")", "*", "maxRepetitions", "\n", "varBinds", "=", "varBinds", ".", "Sort", "(", ")", ".", "Uniq", "(", ")", "\n\n", "for", "i", ",", "_", ":=", "range", "reqOids", "{", "matched", ":=", "varBinds", ".", "MatchBaseOids", "(", "oids", "[", "i", "]", ")", "\n", "mLength", ":=", "len", "(", "matched", ")", "\n\n", "if", "mLength", "==", "0", "||", "resBinds", ".", "MatchOid", "(", "matched", "[", "mLength", "-", "1", "]", ".", "Oid", ")", "!=", "nil", "{", "reqOids", "[", "i", "]", "=", "nil", "\n", "continue", "\n", "}", "\n\n", "hasError", ":=", "false", "\n", "for", "_", ",", "val", ":=", "range", "matched", "{", "switch", "val", ".", "Variable", ".", "(", "type", ")", "{", "case", "*", "NoSucheObject", ",", "*", "NoSucheInstance", ",", "*", "EndOfMibView", ":", "hasError", "=", "true", "\n", "default", ":", "resBinds", "=", "append", "(", "resBinds", ",", "val", ")", "\n", "reqOids", "[", "i", "]", "=", "val", ".", "Oid", "\n", "}", "\n", "}", "\n\n", "if", "hasError", "||", "(", "filled", "&&", "mLength", "<", "maxRepetitions", ")", "{", "reqOids", "[", "i", "]", "=", "nil", "\n", "}", "\n", "}", "\n\n", "// sweep completed oids", "for", "i", ":=", "len", "(", "reqOids", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "reqOids", "[", "i", "]", "==", "nil", "{", "reqOids", "=", "append", "(", "reqOids", "[", ":", "i", "]", ",", "reqOids", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "oids", "=", "append", "(", "oids", "[", ":", "i", "]", ",", "oids", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "resBinds", "=", "append", "(", "nonRepBinds", ",", "resBinds", ".", "Sort", "(", ")", ".", "Uniq", "(", ")", "...", ")", "\n", "return", "NewPduWithVarBinds", "(", "s", ".", "args", ".", "Version", ",", "GetResponse", ",", "resBinds", ")", ",", "nil", "\n", "}" ]
// This method inquire about OID subtrees by repeatedly using GetBulkRequest. // Returned PDU contains the varbind list of all subtrees. // however, if the ErrorStatus of PDU is not the NoError, return only the last query result.
[ "This", "method", "inquire", "about", "OID", "subtrees", "by", "repeatedly", "using", "GetBulkRequest", ".", "Returned", "PDU", "contains", "the", "varbind", "list", "of", "all", "subtrees", ".", "however", "if", "the", "ErrorStatus", "of", "PDU", "is", "not", "the", "NoError", "return", "only", "the", "last", "query", "result", "." ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/client.go#L201-L267
11,573
k-sone/snmpgo
client.go
V2TrapWithBootsTime
func (s *SNMP) V2TrapWithBootsTime(varBinds VarBinds, eBoots, eTime int) error { if eBoots < 0 || eBoots > math.MaxInt32 { return &ArgumentError{ Value: eBoots, Message: fmt.Sprintf("EngineBoots is range %d..%d", 0, math.MaxInt32), } } if eTime < 0 || eTime > math.MaxInt32 { return &ArgumentError{ Value: eTime, Message: fmt.Sprintf("EngineTime is range %d..%d", 0, math.MaxInt32), } } defer func() { s.args.authEngineBoots = 0 s.args.authEngineTime = 0 }() s.args.authEngineBoots = eBoots s.args.authEngineTime = eTime return s.v2trap(SNMPTrapV2, varBinds) }
go
func (s *SNMP) V2TrapWithBootsTime(varBinds VarBinds, eBoots, eTime int) error { if eBoots < 0 || eBoots > math.MaxInt32 { return &ArgumentError{ Value: eBoots, Message: fmt.Sprintf("EngineBoots is range %d..%d", 0, math.MaxInt32), } } if eTime < 0 || eTime > math.MaxInt32 { return &ArgumentError{ Value: eTime, Message: fmt.Sprintf("EngineTime is range %d..%d", 0, math.MaxInt32), } } defer func() { s.args.authEngineBoots = 0 s.args.authEngineTime = 0 }() s.args.authEngineBoots = eBoots s.args.authEngineTime = eTime return s.v2trap(SNMPTrapV2, varBinds) }
[ "func", "(", "s", "*", "SNMP", ")", "V2TrapWithBootsTime", "(", "varBinds", "VarBinds", ",", "eBoots", ",", "eTime", "int", ")", "error", "{", "if", "eBoots", "<", "0", "||", "eBoots", ">", "math", ".", "MaxInt32", "{", "return", "&", "ArgumentError", "{", "Value", ":", "eBoots", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "0", ",", "math", ".", "MaxInt32", ")", ",", "}", "\n", "}", "\n", "if", "eTime", "<", "0", "||", "eTime", ">", "math", ".", "MaxInt32", "{", "return", "&", "ArgumentError", "{", "Value", ":", "eTime", ",", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "0", ",", "math", ".", "MaxInt32", ")", ",", "}", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "s", ".", "args", ".", "authEngineBoots", "=", "0", "\n", "s", ".", "args", ".", "authEngineTime", "=", "0", "\n", "}", "(", ")", "\n", "s", ".", "args", ".", "authEngineBoots", "=", "eBoots", "\n", "s", ".", "args", ".", "authEngineTime", "=", "eTime", "\n", "return", "s", ".", "v2trap", "(", "SNMPTrapV2", ",", "varBinds", ")", "\n", "}" ]
// Send trap with the authoritative engine boots and time when used with SNMP V3.
[ "Send", "trap", "with", "the", "authoritative", "engine", "boots", "and", "time", "when", "used", "with", "SNMP", "V3", "." ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/client.go#L274-L295
11,574
k-sone/snmpgo
client.go
NewSNMP
func NewSNMP(args SNMPArguments) (*SNMP, error) { if err := args.validate(); err != nil { return nil, err } args.setDefault() return &SNMP{args: &args}, nil }
go
func NewSNMP(args SNMPArguments) (*SNMP, error) { if err := args.validate(); err != nil { return nil, err } args.setDefault() return &SNMP{args: &args}, nil }
[ "func", "NewSNMP", "(", "args", "SNMPArguments", ")", "(", "*", "SNMP", ",", "error", ")", "{", "if", "err", ":=", "args", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "args", ".", "setDefault", "(", ")", "\n", "return", "&", "SNMP", "{", "args", ":", "&", "args", "}", ",", "nil", "\n", "}" ]
// Create a SNMP Object
[ "Create", "a", "SNMP", "Object" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/client.go#L336-L342
11,575
k-sone/snmpgo
server.go
Serve
func (s *TrapServer) Serve(listener TrapListener) error { if listener == nil { return &ArgumentError{Message: "listener is nil"} } s.servingMu.Lock() s.serving = true s.servingMu.Unlock() size := s.args.MessageMaxSize if size < recvBufferSize { size = recvBufferSize } for { conn, err := s.transport.Listen() s.servingMu.RLock() serving := s.serving s.servingMu.RUnlock() if !serving { return nil } if err != nil { if e, ok := err.(net.Error); ok && e.Temporary() { continue } return err } go func(conn interface{}) { defer s.transport.Close(conn) buf := make([]byte, size) for { _, src, msg, err := s.transport.Read(conn, buf) if _, ok := err.(net.Error); ok { s.servingMu.RLock() serving := s.serving s.servingMu.RUnlock() if serving { s.logf("trap: failed to read packet: %v", err) } return } go s.handle(listener, conn, msg, src, err) } }(conn) } }
go
func (s *TrapServer) Serve(listener TrapListener) error { if listener == nil { return &ArgumentError{Message: "listener is nil"} } s.servingMu.Lock() s.serving = true s.servingMu.Unlock() size := s.args.MessageMaxSize if size < recvBufferSize { size = recvBufferSize } for { conn, err := s.transport.Listen() s.servingMu.RLock() serving := s.serving s.servingMu.RUnlock() if !serving { return nil } if err != nil { if e, ok := err.(net.Error); ok && e.Temporary() { continue } return err } go func(conn interface{}) { defer s.transport.Close(conn) buf := make([]byte, size) for { _, src, msg, err := s.transport.Read(conn, buf) if _, ok := err.(net.Error); ok { s.servingMu.RLock() serving := s.serving s.servingMu.RUnlock() if serving { s.logf("trap: failed to read packet: %v", err) } return } go s.handle(listener, conn, msg, src, err) } }(conn) } }
[ "func", "(", "s", "*", "TrapServer", ")", "Serve", "(", "listener", "TrapListener", ")", "error", "{", "if", "listener", "==", "nil", "{", "return", "&", "ArgumentError", "{", "Message", ":", "\"", "\"", "}", "\n", "}", "\n", "s", ".", "servingMu", ".", "Lock", "(", ")", "\n", "s", ".", "serving", "=", "true", "\n", "s", ".", "servingMu", ".", "Unlock", "(", ")", "\n", "size", ":=", "s", ".", "args", ".", "MessageMaxSize", "\n", "if", "size", "<", "recvBufferSize", "{", "size", "=", "recvBufferSize", "\n", "}", "\n\n", "for", "{", "conn", ",", "err", ":=", "s", ".", "transport", ".", "Listen", "(", ")", "\n", "s", ".", "servingMu", ".", "RLock", "(", ")", "\n", "serving", ":=", "s", ".", "serving", "\n", "s", ".", "servingMu", ".", "RUnlock", "(", ")", "\n", "if", "!", "serving", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "if", "e", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "&&", "e", ".", "Temporary", "(", ")", "{", "continue", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "go", "func", "(", "conn", "interface", "{", "}", ")", "{", "defer", "s", ".", "transport", ".", "Close", "(", "conn", ")", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "for", "{", "_", ",", "src", ",", "msg", ",", "err", ":=", "s", ".", "transport", ".", "Read", "(", "conn", ",", "buf", ")", "\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "{", "s", ".", "servingMu", ".", "RLock", "(", ")", "\n", "serving", ":=", "s", ".", "serving", "\n", "s", ".", "servingMu", ".", "RUnlock", "(", ")", "\n", "if", "serving", "{", "s", ".", "logf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "go", "s", ".", "handle", "(", "listener", ",", "conn", ",", "msg", ",", "src", ",", "err", ")", "\n", "}", "\n", "}", "(", "conn", ")", "\n", "}", "\n", "}" ]
// Serve starts the SNMP trap receiver. // Serve blocks, the caller should call Close when finished, to shut it down.
[ "Serve", "starts", "the", "SNMP", "trap", "receiver", ".", "Serve", "blocks", "the", "caller", "should", "call", "Close", "when", "finished", "to", "shut", "it", "down", "." ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/server.go#L188-L234
11,576
k-sone/snmpgo
server.go
handle
func (s *TrapServer) handle(listener TrapListener, conn interface{}, msg message, src net.Addr, err error) { defer func() { if err := recover(); err != nil { const size = 64 << 10 logBuf := make([]byte, size) logBuf = logBuf[:runtime.Stack(logBuf, false)] s.logf("trap: panic while receiving %v: %v\n%s", src, err, logBuf) } }() var pdu Pdu var mp messageProcessing var sec security if msg != nil { var ok bool v := msg.Version() if mp, ok = s.mps[v]; ok { if sec = s.secs[v].Lookup(msg); sec != nil { pdu, err = mp.PrepareDataElements(sec, msg, nil) } else { err = &MessageError{ Message: "Authentication failure", Detail: fmt.Sprintf("Message - [%s]", msg), } } } else { err = &MessageError{ Message: fmt.Sprintf("Unsupported SNMP version: %s", v), Detail: fmt.Sprintf("Message - [%s]", msg), } } } if pdu != nil { switch t := pdu.PduType(); t { case SNMPTrapV2, InformRequest: default: err = &MessageError{ Message: fmt.Sprintf("Invalid PduType: %s ", t), Detail: fmt.Sprintf("Message - [%s]", msg), } pdu = nil } } listener.OnTRAP(&TrapRequest{Pdu: pdu, Source: src, Error: err}) if pdu != nil && pdu.PduType() == InformRequest { if err = s.informResponse(conn, src, mp, sec, msg); err != nil && s.serving { s.logf("trap: failed to send response %v: %v", src, err) } } }
go
func (s *TrapServer) handle(listener TrapListener, conn interface{}, msg message, src net.Addr, err error) { defer func() { if err := recover(); err != nil { const size = 64 << 10 logBuf := make([]byte, size) logBuf = logBuf[:runtime.Stack(logBuf, false)] s.logf("trap: panic while receiving %v: %v\n%s", src, err, logBuf) } }() var pdu Pdu var mp messageProcessing var sec security if msg != nil { var ok bool v := msg.Version() if mp, ok = s.mps[v]; ok { if sec = s.secs[v].Lookup(msg); sec != nil { pdu, err = mp.PrepareDataElements(sec, msg, nil) } else { err = &MessageError{ Message: "Authentication failure", Detail: fmt.Sprintf("Message - [%s]", msg), } } } else { err = &MessageError{ Message: fmt.Sprintf("Unsupported SNMP version: %s", v), Detail: fmt.Sprintf("Message - [%s]", msg), } } } if pdu != nil { switch t := pdu.PduType(); t { case SNMPTrapV2, InformRequest: default: err = &MessageError{ Message: fmt.Sprintf("Invalid PduType: %s ", t), Detail: fmt.Sprintf("Message - [%s]", msg), } pdu = nil } } listener.OnTRAP(&TrapRequest{Pdu: pdu, Source: src, Error: err}) if pdu != nil && pdu.PduType() == InformRequest { if err = s.informResponse(conn, src, mp, sec, msg); err != nil && s.serving { s.logf("trap: failed to send response %v: %v", src, err) } } }
[ "func", "(", "s", "*", "TrapServer", ")", "handle", "(", "listener", "TrapListener", ",", "conn", "interface", "{", "}", ",", "msg", "message", ",", "src", "net", ".", "Addr", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "err", ":=", "recover", "(", ")", ";", "err", "!=", "nil", "{", "const", "size", "=", "64", "<<", "10", "\n", "logBuf", ":=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "logBuf", "=", "logBuf", "[", ":", "runtime", ".", "Stack", "(", "logBuf", ",", "false", ")", "]", "\n", "s", ".", "logf", "(", "\"", "\\n", "\"", ",", "src", ",", "err", ",", "logBuf", ")", "\n\n", "}", "\n", "}", "(", ")", "\n\n", "var", "pdu", "Pdu", "\n", "var", "mp", "messageProcessing", "\n", "var", "sec", "security", "\n", "if", "msg", "!=", "nil", "{", "var", "ok", "bool", "\n", "v", ":=", "msg", ".", "Version", "(", ")", "\n", "if", "mp", ",", "ok", "=", "s", ".", "mps", "[", "v", "]", ";", "ok", "{", "if", "sec", "=", "s", ".", "secs", "[", "v", "]", ".", "Lookup", "(", "msg", ")", ";", "sec", "!=", "nil", "{", "pdu", ",", "err", "=", "mp", ".", "PrepareDataElements", "(", "sec", ",", "msg", ",", "nil", ")", "\n", "}", "else", "{", "err", "=", "&", "MessageError", "{", "Message", ":", "\"", "\"", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ")", ",", "}", "\n", "}", "\n", "}", "else", "{", "err", "=", "&", "MessageError", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ")", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ")", ",", "}", "\n", "}", "\n", "}", "\n\n", "if", "pdu", "!=", "nil", "{", "switch", "t", ":=", "pdu", ".", "PduType", "(", ")", ";", "t", "{", "case", "SNMPTrapV2", ",", "InformRequest", ":", "default", ":", "err", "=", "&", "MessageError", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ")", ",", "Detail", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ")", ",", "}", "\n", "pdu", "=", "nil", "\n", "}", "\n", "}", "\n\n", "listener", ".", "OnTRAP", "(", "&", "TrapRequest", "{", "Pdu", ":", "pdu", ",", "Source", ":", "src", ",", "Error", ":", "err", "}", ")", "\n\n", "if", "pdu", "!=", "nil", "&&", "pdu", ".", "PduType", "(", ")", "==", "InformRequest", "{", "if", "err", "=", "s", ".", "informResponse", "(", "conn", ",", "src", ",", "mp", ",", "sec", ",", "msg", ")", ";", "err", "!=", "nil", "&&", "s", ".", "serving", "{", "s", ".", "logf", "(", "\"", "\"", ",", "src", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// handle a newly received trap
[ "handle", "a", "newly", "received", "trap" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/server.go#L245-L298
11,577
k-sone/snmpgo
server.go
NewTrapServer
func NewTrapServer(args ServerArguments) (*TrapServer, error) { if err := args.validate(); err != nil { return nil, err } args.setDefault() return &TrapServer{ args: &args, mps: map[SNMPVersion]messageProcessing{ V2c: newMessageProcessing(V2c), V3: newMessageProcessing(V3), }, secs: map[SNMPVersion]*securityMap{ V2c: newSecurityMap(), V3: newSecurityMap(), }, transport: newTransport(&args), }, nil }
go
func NewTrapServer(args ServerArguments) (*TrapServer, error) { if err := args.validate(); err != nil { return nil, err } args.setDefault() return &TrapServer{ args: &args, mps: map[SNMPVersion]messageProcessing{ V2c: newMessageProcessing(V2c), V3: newMessageProcessing(V3), }, secs: map[SNMPVersion]*securityMap{ V2c: newSecurityMap(), V3: newSecurityMap(), }, transport: newTransport(&args), }, nil }
[ "func", "NewTrapServer", "(", "args", "ServerArguments", ")", "(", "*", "TrapServer", ",", "error", ")", "{", "if", "err", ":=", "args", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "args", ".", "setDefault", "(", ")", "\n\n", "return", "&", "TrapServer", "{", "args", ":", "&", "args", ",", "mps", ":", "map", "[", "SNMPVersion", "]", "messageProcessing", "{", "V2c", ":", "newMessageProcessing", "(", "V2c", ")", ",", "V3", ":", "newMessageProcessing", "(", "V3", ")", ",", "}", ",", "secs", ":", "map", "[", "SNMPVersion", "]", "*", "securityMap", "{", "V2c", ":", "newSecurityMap", "(", ")", ",", "V3", ":", "newSecurityMap", "(", ")", ",", "}", ",", "transport", ":", "newTransport", "(", "&", "args", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewTrapServer returns a new Server and is using server arguments for configuration.
[ "NewTrapServer", "returns", "a", "new", "Server", "and", "is", "using", "server", "arguments", "for", "configuration", "." ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/server.go#L324-L342
11,578
k-sone/snmpgo
pdu.go
MatchOid
func (v VarBinds) MatchOid(oid *Oid) *VarBind { for _, o := range v { if o.Oid != nil && o.Oid.Equal(oid) { return o } } return nil }
go
func (v VarBinds) MatchOid(oid *Oid) *VarBind { for _, o := range v { if o.Oid != nil && o.Oid.Equal(oid) { return o } } return nil }
[ "func", "(", "v", "VarBinds", ")", "MatchOid", "(", "oid", "*", "Oid", ")", "*", "VarBind", "{", "for", "_", ",", "o", ":=", "range", "v", "{", "if", "o", ".", "Oid", "!=", "nil", "&&", "o", ".", "Oid", ".", "Equal", "(", "oid", ")", "{", "return", "o", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Gets a VarBind that matches
[ "Gets", "a", "VarBind", "that", "matches" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/pdu.go#L91-L98
11,579
k-sone/snmpgo
pdu.go
MatchBaseOids
func (v VarBinds) MatchBaseOids(prefix *Oid) VarBinds { result := make(VarBinds, 0) for _, o := range v { if o.Oid != nil && o.Oid.Contains(prefix) { result = append(result, o) } } return result }
go
func (v VarBinds) MatchBaseOids(prefix *Oid) VarBinds { result := make(VarBinds, 0) for _, o := range v { if o.Oid != nil && o.Oid.Contains(prefix) { result = append(result, o) } } return result }
[ "func", "(", "v", "VarBinds", ")", "MatchBaseOids", "(", "prefix", "*", "Oid", ")", "VarBinds", "{", "result", ":=", "make", "(", "VarBinds", ",", "0", ")", "\n", "for", "_", ",", "o", ":=", "range", "v", "{", "if", "o", ".", "Oid", "!=", "nil", "&&", "o", ".", "Oid", ".", "Contains", "(", "prefix", ")", "{", "result", "=", "append", "(", "result", ",", "o", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Gets a VarBind list that matches the prefix
[ "Gets", "a", "VarBind", "list", "that", "matches", "the", "prefix" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/pdu.go#L101-L109
11,580
k-sone/snmpgo
pdu.go
Sort
func (v VarBinds) Sort() VarBinds { c := make(VarBinds, len(v)) copy(c, v) sort.Sort(sortableVarBinds{c}) return c }
go
func (v VarBinds) Sort() VarBinds { c := make(VarBinds, len(v)) copy(c, v) sort.Sort(sortableVarBinds{c}) return c }
[ "func", "(", "v", "VarBinds", ")", "Sort", "(", ")", "VarBinds", "{", "c", ":=", "make", "(", "VarBinds", ",", "len", "(", "v", ")", ")", "\n", "copy", "(", "c", ",", "v", ")", "\n", "sort", ".", "Sort", "(", "sortableVarBinds", "{", "c", "}", ")", "\n", "return", "c", "\n", "}" ]
// Sort a VarBind list by OID
[ "Sort", "a", "VarBind", "list", "by", "OID" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/pdu.go#L112-L117
11,581
k-sone/snmpgo
pdu.go
Uniq
func (v VarBinds) Uniq() VarBinds { return v.uniq(func(a, b *VarBind) bool { if b == nil { return a == nil } else if b.Oid == nil { return a != nil && a.Oid == nil } else { return a != nil && b.Oid.Equal(a.Oid) } }) }
go
func (v VarBinds) Uniq() VarBinds { return v.uniq(func(a, b *VarBind) bool { if b == nil { return a == nil } else if b.Oid == nil { return a != nil && a.Oid == nil } else { return a != nil && b.Oid.Equal(a.Oid) } }) }
[ "func", "(", "v", "VarBinds", ")", "Uniq", "(", ")", "VarBinds", "{", "return", "v", ".", "uniq", "(", "func", "(", "a", ",", "b", "*", "VarBind", ")", "bool", "{", "if", "b", "==", "nil", "{", "return", "a", "==", "nil", "\n", "}", "else", "if", "b", ".", "Oid", "==", "nil", "{", "return", "a", "!=", "nil", "&&", "a", ".", "Oid", "==", "nil", "\n", "}", "else", "{", "return", "a", "!=", "nil", "&&", "b", ".", "Oid", ".", "Equal", "(", "a", ".", "Oid", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Filter out adjacent VarBind list
[ "Filter", "out", "adjacent", "VarBind", "list" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/pdu.go#L132-L142
11,582
k-sone/snmpgo
variables.go
Contains
func (v *Oid) Contains(o *Oid) bool { if o == nil || len(v.Value) < len(o.Value) { return false } for i := 0; i < len(o.Value); i++ { if v.Value[i] != o.Value[i] { return false } } return true }
go
func (v *Oid) Contains(o *Oid) bool { if o == nil || len(v.Value) < len(o.Value) { return false } for i := 0; i < len(o.Value); i++ { if v.Value[i] != o.Value[i] { return false } } return true }
[ "func", "(", "v", "*", "Oid", ")", "Contains", "(", "o", "*", "Oid", ")", "bool", "{", "if", "o", "==", "nil", "||", "len", "(", "v", ".", "Value", ")", "<", "len", "(", "o", ".", "Value", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "o", ".", "Value", ")", ";", "i", "++", "{", "if", "v", ".", "Value", "[", "i", "]", "!=", "o", ".", "Value", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Returns true if this OID contains the specified OID
[ "Returns", "true", "if", "this", "OID", "contains", "the", "specified", "OID" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L149-L159
11,583
k-sone/snmpgo
variables.go
Compare
func (v *Oid) Compare(o *Oid) int { if o != nil { vl := len(v.Value) ol := len(o.Value) for i := 0; i < vl; i++ { if ol <= i || v.Value[i] > o.Value[i] { return 1 } else if v.Value[i] < o.Value[i] { return -1 } } if ol == vl { return 0 } } return -1 }
go
func (v *Oid) Compare(o *Oid) int { if o != nil { vl := len(v.Value) ol := len(o.Value) for i := 0; i < vl; i++ { if ol <= i || v.Value[i] > o.Value[i] { return 1 } else if v.Value[i] < o.Value[i] { return -1 } } if ol == vl { return 0 } } return -1 }
[ "func", "(", "v", "*", "Oid", ")", "Compare", "(", "o", "*", "Oid", ")", "int", "{", "if", "o", "!=", "nil", "{", "vl", ":=", "len", "(", "v", ".", "Value", ")", "\n", "ol", ":=", "len", "(", "o", ".", "Value", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "vl", ";", "i", "++", "{", "if", "ol", "<=", "i", "||", "v", ".", "Value", "[", "i", "]", ">", "o", ".", "Value", "[", "i", "]", "{", "return", "1", "\n", "}", "else", "if", "v", ".", "Value", "[", "i", "]", "<", "o", ".", "Value", "[", "i", "]", "{", "return", "-", "1", "\n", "}", "\n", "}", "\n", "if", "ol", "==", "vl", "{", "return", "0", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// Returns 0 this OID is equal to the specified OID, // -1 this OID is lexicographically less than the specified OID, // 1 this OID is lexicographically greater than the specified OID
[ "Returns", "0", "this", "OID", "is", "equal", "to", "the", "specified", "OID", "-", "1", "this", "OID", "is", "lexicographically", "less", "than", "the", "specified", "OID", "1", "this", "OID", "is", "lexicographically", "greater", "than", "the", "specified", "OID" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L164-L180
11,584
k-sone/snmpgo
variables.go
Equal
func (v *Oid) Equal(o *Oid) bool { if o == nil { return false } return v.Value.Equal(o.Value) }
go
func (v *Oid) Equal(o *Oid) bool { if o == nil { return false } return v.Value.Equal(o.Value) }
[ "func", "(", "v", "*", "Oid", ")", "Equal", "(", "o", "*", "Oid", ")", "bool", "{", "if", "o", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "v", ".", "Value", ".", "Equal", "(", "o", ".", "Value", ")", "\n", "}" ]
// Returns true if this OID is same the specified OID
[ "Returns", "true", "if", "this", "OID", "is", "same", "the", "specified", "OID" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L183-L188
11,585
k-sone/snmpgo
variables.go
AppendSubIds
func (v *Oid) AppendSubIds(subs []int) (*Oid, error) { buf := bytes.NewBufferString(v.String()) for _, i := range subs { buf.WriteString(".") buf.WriteString(strconv.Itoa(i)) } return NewOid(buf.String()) }
go
func (v *Oid) AppendSubIds(subs []int) (*Oid, error) { buf := bytes.NewBufferString(v.String()) for _, i := range subs { buf.WriteString(".") buf.WriteString(strconv.Itoa(i)) } return NewOid(buf.String()) }
[ "func", "(", "v", "*", "Oid", ")", "AppendSubIds", "(", "subs", "[", "]", "int", ")", "(", "*", "Oid", ",", "error", ")", "{", "buf", ":=", "bytes", ".", "NewBufferString", "(", "v", ".", "String", "(", ")", ")", "\n", "for", "_", ",", "i", ":=", "range", "subs", "{", "buf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "buf", ".", "WriteString", "(", "strconv", ".", "Itoa", "(", "i", ")", ")", "\n", "}", "\n", "return", "NewOid", "(", "buf", ".", "String", "(", ")", ")", "\n", "}" ]
// Returns Oid with additional sub-ids
[ "Returns", "Oid", "with", "additional", "sub", "-", "ids" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L191-L198
11,586
k-sone/snmpgo
variables.go
MustNewOid
func MustNewOid(s string) *Oid { if oid, err := NewOid(s); err != nil { panic(`snmpgo.MustNewOid: ` + err.Error()) } else { return oid } }
go
func MustNewOid(s string) *Oid { if oid, err := NewOid(s); err != nil { panic(`snmpgo.MustNewOid: ` + err.Error()) } else { return oid } }
[ "func", "MustNewOid", "(", "s", "string", ")", "*", "Oid", "{", "if", "oid", ",", "err", ":=", "NewOid", "(", "s", ")", ";", "err", "!=", "nil", "{", "panic", "(", "`snmpgo.MustNewOid: `", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "return", "oid", "\n", "}", "\n", "}" ]
// MustNewOid is like NewOid but panics if argument cannot be parsed
[ "MustNewOid", "is", "like", "NewOid", "but", "panics", "if", "argument", "cannot", "be", "parsed" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L253-L259
11,587
k-sone/snmpgo
variables.go
Sort
func (o Oids) Sort() Oids { c := make(Oids, len(o)) copy(c, o) sort.Sort(sortableOids{c}) return c }
go
func (o Oids) Sort() Oids { c := make(Oids, len(o)) copy(c, o) sort.Sort(sortableOids{c}) return c }
[ "func", "(", "o", "Oids", ")", "Sort", "(", ")", "Oids", "{", "c", ":=", "make", "(", "Oids", ",", "len", "(", "o", ")", ")", "\n", "copy", "(", "c", ",", "o", ")", "\n", "sort", ".", "Sort", "(", "sortableOids", "{", "c", "}", ")", "\n", "return", "c", "\n", "}" ]
// Sort a Oid list
[ "Sort", "a", "Oid", "list" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L264-L269
11,588
k-sone/snmpgo
variables.go
Uniq
func (o Oids) Uniq() Oids { return o.uniq(func(a, b *Oid) bool { if b == nil { return a == nil } else { return b.Equal(a) } }) }
go
func (o Oids) Uniq() Oids { return o.uniq(func(a, b *Oid) bool { if b == nil { return a == nil } else { return b.Equal(a) } }) }
[ "func", "(", "o", "Oids", ")", "Uniq", "(", ")", "Oids", "{", "return", "o", ".", "uniq", "(", "func", "(", "a", ",", "b", "*", "Oid", ")", "bool", "{", "if", "b", "==", "nil", "{", "return", "a", "==", "nil", "\n", "}", "else", "{", "return", "b", ".", "Equal", "(", "a", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Filter out adjacent OID list
[ "Filter", "out", "adjacent", "OID", "list" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L284-L292
11,589
k-sone/snmpgo
variables.go
UniqBase
func (o Oids) UniqBase() Oids { return o.uniq(func(a, b *Oid) bool { if b == nil { return a == nil } else { return b.Contains(a) } }) }
go
func (o Oids) UniqBase() Oids { return o.uniq(func(a, b *Oid) bool { if b == nil { return a == nil } else { return b.Contains(a) } }) }
[ "func", "(", "o", "Oids", ")", "UniqBase", "(", ")", "Oids", "{", "return", "o", ".", "uniq", "(", "func", "(", "a", ",", "b", "*", "Oid", ")", "bool", "{", "if", "b", "==", "nil", "{", "return", "a", "==", "nil", "\n", "}", "else", "{", "return", "b", ".", "Contains", "(", "a", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Filter out adjacent OID list with the same prefix
[ "Filter", "out", "adjacent", "OID", "list", "with", "the", "same", "prefix" ]
de09377ff34857b08afdc16ea8c7c2929eb1fc6e
https://github.com/k-sone/snmpgo/blob/de09377ff34857b08afdc16ea8c7c2929eb1fc6e/variables.go#L295-L303
11,590
quipo/statsd
client.go
NewStatsdClient
func NewStatsdClient(addr string, prefix string) *StatsdClient { // allow %HOST% in the prefix string prefix = strings.Replace(prefix, "%HOST%", Hostname, 1) return &StatsdClient{ addr: addr, prefix: prefix, Logger: log.New(os.Stdout, "[StatsdClient] ", log.Ldate|log.Ltime), } }
go
func NewStatsdClient(addr string, prefix string) *StatsdClient { // allow %HOST% in the prefix string prefix = strings.Replace(prefix, "%HOST%", Hostname, 1) return &StatsdClient{ addr: addr, prefix: prefix, Logger: log.New(os.Stdout, "[StatsdClient] ", log.Ldate|log.Ltime), } }
[ "func", "NewStatsdClient", "(", "addr", "string", ",", "prefix", "string", ")", "*", "StatsdClient", "{", "// allow %HOST% in the prefix string", "prefix", "=", "strings", ".", "Replace", "(", "prefix", ",", "\"", "\"", ",", "Hostname", ",", "1", ")", "\n", "return", "&", "StatsdClient", "{", "addr", ":", "addr", ",", "prefix", ":", "prefix", ",", "Logger", ":", "log", ".", "New", "(", "os", ".", "Stdout", ",", "\"", "\"", ",", "log", ".", "Ldate", "|", "log", ".", "Ltime", ")", ",", "}", "\n", "}" ]
// NewStatsdClient - Factory
[ "NewStatsdClient", "-", "Factory" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L65-L73
11,591
quipo/statsd
client.go
CreateSocket
func (c *StatsdClient) CreateSocket() error { conn, err := net.DialTimeout(string(udpSocket), c.addr, 5*time.Second) if err != nil { return err } c.conn = conn c.sockType = udpSocket return nil }
go
func (c *StatsdClient) CreateSocket() error { conn, err := net.DialTimeout(string(udpSocket), c.addr, 5*time.Second) if err != nil { return err } c.conn = conn c.sockType = udpSocket return nil }
[ "func", "(", "c", "*", "StatsdClient", ")", "CreateSocket", "(", ")", "error", "{", "conn", ",", "err", ":=", "net", ".", "DialTimeout", "(", "string", "(", "udpSocket", ")", ",", "c", ".", "addr", ",", "5", "*", "time", ".", "Second", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "conn", "=", "conn", "\n", "c", ".", "sockType", "=", "udpSocket", "\n", "return", "nil", "\n", "}" ]
// CreateSocket creates a UDP connection to a StatsD server
[ "CreateSocket", "creates", "a", "UDP", "connection", "to", "a", "StatsD", "server" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L81-L89
11,592
quipo/statsd
client.go
CreateTCPSocket
func (c *StatsdClient) CreateTCPSocket() error { conn, err := net.DialTimeout(string(tcpSocket), c.addr, 5*time.Second) if err != nil { return err } c.conn = conn c.sockType = tcpSocket return nil }
go
func (c *StatsdClient) CreateTCPSocket() error { conn, err := net.DialTimeout(string(tcpSocket), c.addr, 5*time.Second) if err != nil { return err } c.conn = conn c.sockType = tcpSocket return nil }
[ "func", "(", "c", "*", "StatsdClient", ")", "CreateTCPSocket", "(", ")", "error", "{", "conn", ",", "err", ":=", "net", ".", "DialTimeout", "(", "string", "(", "tcpSocket", ")", ",", "c", ".", "addr", ",", "5", "*", "time", ".", "Second", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "conn", "=", "conn", "\n", "c", ".", "sockType", "=", "tcpSocket", "\n", "return", "nil", "\n", "}" ]
// CreateTCPSocket creates a TCP connection to a StatsD server
[ "CreateTCPSocket", "creates", "a", "TCP", "connection", "to", "a", "StatsD", "server" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L92-L100
11,593
quipo/statsd
client.go
Close
func (c *StatsdClient) Close() error { if nil == c.conn { return nil } return c.conn.Close() }
go
func (c *StatsdClient) Close() error { if nil == c.conn { return nil } return c.conn.Close() }
[ "func", "(", "c", "*", "StatsdClient", ")", "Close", "(", ")", "error", "{", "if", "nil", "==", "c", ".", "conn", "{", "return", "nil", "\n", "}", "\n", "return", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}" ]
// Close the UDP connection
[ "Close", "the", "UDP", "connection" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L103-L108
11,594
quipo/statsd
client.go
IncrWithSampling
func (c *StatsdClient) IncrWithSampling(stat string, count int64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil // ignore this call } if err := checkCount(count); err != nil { return err } return c.send(stat, "%d|c", count, sampleRate) }
go
func (c *StatsdClient) IncrWithSampling(stat string, count int64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil // ignore this call } if err := checkCount(count); err != nil { return err } return c.send(stat, "%d|c", count, sampleRate) }
[ "func", "(", "c", "*", "StatsdClient", ")", "IncrWithSampling", "(", "stat", "string", ",", "count", "int64", ",", "sampleRate", "float32", ")", "error", "{", "if", "err", ":=", "checkSampleRate", "(", "sampleRate", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "shouldFire", "(", "sampleRate", ")", "{", "return", "nil", "// ignore this call", "\n", "}", "\n\n", "if", "err", ":=", "checkCount", "(", "count", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "c", ".", "send", "(", "stat", ",", "\"", "\"", ",", "count", ",", "sampleRate", ")", "\n", "}" ]
// IncrWithSampling - Increment a counter metric with sampling between 0 and 1
[ "IncrWithSampling", "-", "Increment", "a", "counter", "metric", "with", "sampling", "between", "0", "and", "1" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L119-L133
11,595
quipo/statsd
client.go
Decr
func (c *StatsdClient) Decr(stat string, count int64) error { return c.DecrWithSampling(stat, count, 1) }
go
func (c *StatsdClient) Decr(stat string, count int64) error { return c.DecrWithSampling(stat, count, 1) }
[ "func", "(", "c", "*", "StatsdClient", ")", "Decr", "(", "stat", "string", ",", "count", "int64", ")", "error", "{", "return", "c", ".", "DecrWithSampling", "(", "stat", ",", "count", ",", "1", ")", "\n", "}" ]
// Decr - Decrement a counter metric. Often used to note a particular event
[ "Decr", "-", "Decrement", "a", "counter", "metric", ".", "Often", "used", "to", "note", "a", "particular", "event" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L136-L138
11,596
quipo/statsd
client.go
TimingWithSampling
func (c *StatsdClient) TimingWithSampling(stat string, delta int64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil // ignore this call } return c.send(stat, "%d|ms", delta, sampleRate) }
go
func (c *StatsdClient) TimingWithSampling(stat string, delta int64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil // ignore this call } return c.send(stat, "%d|ms", delta, sampleRate) }
[ "func", "(", "c", "*", "StatsdClient", ")", "TimingWithSampling", "(", "stat", "string", ",", "delta", "int64", ",", "sampleRate", "float32", ")", "error", "{", "if", "err", ":=", "checkSampleRate", "(", "sampleRate", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "shouldFire", "(", "sampleRate", ")", "{", "return", "nil", "// ignore this call", "\n", "}", "\n\n", "return", "c", ".", "send", "(", "stat", ",", "\"", "\"", ",", "delta", ",", "sampleRate", ")", "\n", "}" ]
// TimingWithSampling - Track a duration event
[ "TimingWithSampling", "-", "Track", "a", "duration", "event" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L164-L174
11,597
quipo/statsd
client.go
GaugeWithSampling
func (c *StatsdClient) GaugeWithSampling(stat string, value int64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil // ignore this call } if value < 0 { err := c.send(stat, "%d|g", 0, 1) if nil != err { return err } } return c.send(stat, "%d|g", value, sampleRate) }
go
func (c *StatsdClient) GaugeWithSampling(stat string, value int64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil // ignore this call } if value < 0 { err := c.send(stat, "%d|g", 0, 1) if nil != err { return err } } return c.send(stat, "%d|g", value, sampleRate) }
[ "func", "(", "c", "*", "StatsdClient", ")", "GaugeWithSampling", "(", "stat", "string", ",", "value", "int64", ",", "sampleRate", "float32", ")", "error", "{", "if", "err", ":=", "checkSampleRate", "(", "sampleRate", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "shouldFire", "(", "sampleRate", ")", "{", "return", "nil", "// ignore this call", "\n", "}", "\n\n", "if", "value", "<", "0", "{", "err", ":=", "c", ".", "send", "(", "stat", ",", "\"", "\"", ",", "0", ",", "1", ")", "\n", "if", "nil", "!=", "err", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "c", ".", "send", "(", "stat", ",", "\"", "\"", ",", "value", ",", "sampleRate", ")", "\n", "}" ]
// GaugeWithSampling - Gauges are a constant data type.
[ "GaugeWithSampling", "-", "Gauges", "are", "a", "constant", "data", "type", "." ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L193-L210
11,598
quipo/statsd
client.go
FGaugeWithSampling
func (c *StatsdClient) FGaugeWithSampling(stat string, value float64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil } if value < 0 { err := c.send(stat, "%d|g", 0, 1) if nil != err { return err } } return c.send(stat, "%g|g", value, sampleRate) }
go
func (c *StatsdClient) FGaugeWithSampling(stat string, value float64, sampleRate float32) error { if err := checkSampleRate(sampleRate); err != nil { return err } if !shouldFire(sampleRate) { return nil } if value < 0 { err := c.send(stat, "%d|g", 0, 1) if nil != err { return err } } return c.send(stat, "%g|g", value, sampleRate) }
[ "func", "(", "c", "*", "StatsdClient", ")", "FGaugeWithSampling", "(", "stat", "string", ",", "value", "float64", ",", "sampleRate", "float32", ")", "error", "{", "if", "err", ":=", "checkSampleRate", "(", "sampleRate", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "!", "shouldFire", "(", "sampleRate", ")", "{", "return", "nil", "\n", "}", "\n\n", "if", "value", "<", "0", "{", "err", ":=", "c", ".", "send", "(", "stat", ",", "\"", "\"", ",", "0", ",", "1", ")", "\n", "if", "nil", "!=", "err", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "c", ".", "send", "(", "stat", ",", "\"", "\"", ",", "value", ",", "sampleRate", ")", "\n", "}" ]
// FGaugeWithSampling - Gauges are a constant data type.
[ "FGaugeWithSampling", "-", "Gauges", "are", "a", "constant", "data", "type", "." ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/client.go#L227-L244
11,599
quipo/statsd
bufferedclient.go
Timing
func (sb *StatsdBuffer) Timing(stat string, delta int64) error { sb.eventChannel <- event.NewTiming(stat, delta) return nil }
go
func (sb *StatsdBuffer) Timing(stat string, delta int64) error { sb.eventChannel <- event.NewTiming(stat, delta) return nil }
[ "func", "(", "sb", "*", "StatsdBuffer", ")", "Timing", "(", "stat", "string", ",", "delta", "int64", ")", "error", "{", "sb", ".", "eventChannel", "<-", "event", ".", "NewTiming", "(", "stat", ",", "delta", ")", "\n", "return", "nil", "\n", "}" ]
// Timing - Track a duration event
[ "Timing", "-", "Track", "a", "duration", "event" ]
3d6a5565f3141ac42f8353d97b2c016da2752006
https://github.com/quipo/statsd/blob/3d6a5565f3141ac42f8353d97b2c016da2752006/bufferedclient.go#L71-L74