repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
ChrisTrenkamp/goxpath
tree/xmltree/xmlele/xmlele.go
GetAttrs
func (x *XMLEle) GetAttrs() []tree.Node { ret := make([]tree.Node, len(x.Attrs)) for i := range x.Attrs { ret[i] = x.Attrs[i] } return ret }
go
func (x *XMLEle) GetAttrs() []tree.Node { ret := make([]tree.Node, len(x.Attrs)) for i := range x.Attrs { ret[i] = x.Attrs[i] } return ret }
[ "func", "(", "x", "*", "XMLEle", ")", "GetAttrs", "(", ")", "[", "]", "tree", ".", "Node", "{", "ret", ":=", "make", "(", "[", "]", "tree", ".", "Node", ",", "len", "(", "x", ".", "Attrs", ")", ")", "\n", "for", "i", ":=", "range", "x", ".", "Attrs", "{", "ret", "[", "i", "]", "=", "x", ".", "Attrs", "[", "i", "]", "\n", "}", "\n", "return", "ret", "\n", "}" ]
//GetAttrs returns all attributes of the element
[ "GetAttrs", "returns", "all", "attributes", "of", "the", "element" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlele/xmlele.go#L88-L94
test
ChrisTrenkamp/goxpath
tree/xmltree/xmlele/xmlele.go
ResValue
func (x *XMLEle) ResValue() string { ret := "" for i := range x.Children { switch x.Children[i].GetNodeType() { case tree.NtChd, tree.NtElem, tree.NtRoot: ret += x.Children[i].ResValue() } } return ret }
go
func (x *XMLEle) ResValue() string { ret := "" for i := range x.Children { switch x.Children[i].GetNodeType() { case tree.NtChd, tree.NtElem, tree.NtRoot: ret += x.Children[i].ResValue() } } return ret }
[ "func", "(", "x", "*", "XMLEle", ")", "ResValue", "(", ")", "string", "{", "ret", ":=", "\"\"", "\n", "for", "i", ":=", "range", "x", ".", "Children", "{", "switch", "x", ".", "Children", "[", "i", "]", ".", "GetNodeType", "(", ")", "{", "case", "tree", ".", "NtChd", ",", "tree", ".", "NtElem", ",", "tree", ".", "NtRoot", ":", "ret", "+=", "x", ".", "Children", "[", "i", "]", ".", "ResValue", "(", ")", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
//ResValue returns the string value of the element and children
[ "ResValue", "returns", "the", "string", "value", "of", "the", "element", "and", "children" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlele/xmlele.go#L97-L106
test
ChrisTrenkamp/goxpath
parser/parser.go
Parse
func Parse(xp string) (*Node, error) { var err error c := lexer.Lex(xp) n := &Node{} p := &parseStack{cur: n} for next := range c { if next.Typ != lexer.XItemError { parseMap[next.Typ](p, next) } else if err == nil { err = fmt.Errorf(next.Val) } } return n, err }
go
func Parse(xp string) (*Node, error) { var err error c := lexer.Lex(xp) n := &Node{} p := &parseStack{cur: n} for next := range c { if next.Typ != lexer.XItemError { parseMap[next.Typ](p, next) } else if err == nil { err = fmt.Errorf(next.Val) } } return n, err }
[ "func", "Parse", "(", "xp", "string", ")", "(", "*", "Node", ",", "error", ")", "{", "var", "err", "error", "\n", "c", ":=", "lexer", ".", "Lex", "(", "xp", ")", "\n", "n", ":=", "&", "Node", "{", "}", "\n", "p", ":=", "&", "parseStack", "{", "cur", ":", "n", "}", "\n", "for", "next", ":=", "range", "c", "{", "if", "next", ".", "Typ", "!=", "lexer", ".", "XItemError", "{", "parseMap", "[", "next", ".", "Typ", "]", "(", "p", ",", "next", ")", "\n", "}", "else", "if", "err", "==", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "next", ".", "Val", ")", "\n", "}", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
//Parse creates an AST tree for XPath expressions.
[ "Parse", "creates", "an", "AST", "tree", "for", "XPath", "expressions", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/parser/parser.go#L89-L104
test
ChrisTrenkamp/goxpath
tree/xmltree/xmlnode/xmlnode.go
GetToken
func (a XMLNode) GetToken() xml.Token { if a.NodeType == tree.NtAttr { ret := a.Token.(*xml.Attr) return *ret } return a.Token }
go
func (a XMLNode) GetToken() xml.Token { if a.NodeType == tree.NtAttr { ret := a.Token.(*xml.Attr) return *ret } return a.Token }
[ "func", "(", "a", "XMLNode", ")", "GetToken", "(", ")", "xml", ".", "Token", "{", "if", "a", ".", "NodeType", "==", "tree", ".", "NtAttr", "{", "ret", ":=", "a", ".", "Token", ".", "(", "*", "xml", ".", "Attr", ")", "\n", "return", "*", "ret", "\n", "}", "\n", "return", "a", ".", "Token", "\n", "}" ]
//GetToken returns the xml.Token representation of the node
[ "GetToken", "returns", "the", "xml", ".", "Token", "representation", "of", "the", "node" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlnode/xmlnode.go#L18-L24
test
ChrisTrenkamp/goxpath
tree/xmltree/xmlnode/xmlnode.go
ResValue
func (a XMLNode) ResValue() string { switch a.NodeType { case tree.NtAttr: return a.Token.(*xml.Attr).Value case tree.NtChd: return string(a.Token.(xml.CharData)) case tree.NtComm: return string(a.Token.(xml.Comment)) } //case tree.NtPi: return string(a.Token.(xml.ProcInst).Inst) }
go
func (a XMLNode) ResValue() string { switch a.NodeType { case tree.NtAttr: return a.Token.(*xml.Attr).Value case tree.NtChd: return string(a.Token.(xml.CharData)) case tree.NtComm: return string(a.Token.(xml.Comment)) } //case tree.NtPi: return string(a.Token.(xml.ProcInst).Inst) }
[ "func", "(", "a", "XMLNode", ")", "ResValue", "(", ")", "string", "{", "switch", "a", ".", "NodeType", "{", "case", "tree", ".", "NtAttr", ":", "return", "a", ".", "Token", ".", "(", "*", "xml", ".", "Attr", ")", ".", "Value", "\n", "case", "tree", ".", "NtChd", ":", "return", "string", "(", "a", ".", "Token", ".", "(", "xml", ".", "CharData", ")", ")", "\n", "case", "tree", ".", "NtComm", ":", "return", "string", "(", "a", ".", "Token", ".", "(", "xml", ".", "Comment", ")", ")", "\n", "}", "\n", "return", "string", "(", "a", ".", "Token", ".", "(", "xml", ".", "ProcInst", ")", ".", "Inst", ")", "\n", "}" ]
//ResValue returns the string value of the attribute
[ "ResValue", "returns", "the", "string", "value", "of", "the", "attribute" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlnode/xmlnode.go#L32-L43
test
ChrisTrenkamp/goxpath
internal/execxp/execxp.go
Exec
func Exec(n *parser.Node, t tree.Node, ns map[string]string, fns map[xml.Name]tree.Wrap, v map[string]tree.Result) (tree.Result, error) { f := xpFilt{ t: t, ns: ns, ctx: tree.NodeSet{t}, fns: fns, variables: v, } return exec(&f, n) }
go
func Exec(n *parser.Node, t tree.Node, ns map[string]string, fns map[xml.Name]tree.Wrap, v map[string]tree.Result) (tree.Result, error) { f := xpFilt{ t: t, ns: ns, ctx: tree.NodeSet{t}, fns: fns, variables: v, } return exec(&f, n) }
[ "func", "Exec", "(", "n", "*", "parser", ".", "Node", ",", "t", "tree", ".", "Node", ",", "ns", "map", "[", "string", "]", "string", ",", "fns", "map", "[", "xml", ".", "Name", "]", "tree", ".", "Wrap", ",", "v", "map", "[", "string", "]", "tree", ".", "Result", ")", "(", "tree", ".", "Result", ",", "error", ")", "{", "f", ":=", "xpFilt", "{", "t", ":", "t", ",", "ns", ":", "ns", ",", "ctx", ":", "tree", ".", "NodeSet", "{", "t", "}", ",", "fns", ":", "fns", ",", "variables", ":", "v", ",", "}", "\n", "return", "exec", "(", "&", "f", ",", "n", ")", "\n", "}" ]
//Exec executes the XPath expression, xp, against the tree, t, with the //namespace mappings, ns.
[ "Exec", "executes", "the", "XPath", "expression", "xp", "against", "the", "tree", "t", "with", "the", "namespace", "mappings", "ns", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/internal/execxp/execxp.go#L12-L22
test
ChrisTrenkamp/goxpath
tree/xtypes.go
String
func (n Num) String() string { if math.IsInf(float64(n), 0) { if math.IsInf(float64(n), 1) { return "Infinity" } return "-Infinity" } return fmt.Sprintf("%g", float64(n)) }
go
func (n Num) String() string { if math.IsInf(float64(n), 0) { if math.IsInf(float64(n), 1) { return "Infinity" } return "-Infinity" } return fmt.Sprintf("%g", float64(n)) }
[ "func", "(", "n", "Num", ")", "String", "(", ")", "string", "{", "if", "math", ".", "IsInf", "(", "float64", "(", "n", ")", ",", "0", ")", "{", "if", "math", ".", "IsInf", "(", "float64", "(", "n", ")", ",", "1", ")", "{", "return", "\"Infinity\"", "\n", "}", "\n", "return", "\"-Infinity\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%g\"", ",", "float64", "(", "n", ")", ")", "\n", "}" ]
//ResValue satisfies the Res interface for Num
[ "ResValue", "satisfies", "the", "Res", "interface", "for", "Num" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xtypes.go#L46-L54
test
ChrisTrenkamp/goxpath
tree/xtypes.go
Num
func (s String) Num() Num { num, err := strconv.ParseFloat(strings.TrimSpace(string(s)), 64) if err != nil { return Num(math.NaN()) } return Num(num) }
go
func (s String) Num() Num { num, err := strconv.ParseFloat(strings.TrimSpace(string(s)), 64) if err != nil { return Num(math.NaN()) } return Num(num) }
[ "func", "(", "s", "String", ")", "Num", "(", ")", "Num", "{", "num", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "strings", ".", "TrimSpace", "(", "string", "(", "s", ")", ")", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Num", "(", "math", ".", "NaN", "(", ")", ")", "\n", "}", "\n", "return", "Num", "(", "num", ")", "\n", "}" ]
//Num satisfies the HasNum interface for String's
[ "Num", "satisfies", "the", "HasNum", "interface", "for", "String", "s" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xtypes.go#L80-L86
test
ChrisTrenkamp/goxpath
tree/tree.go
BuildNS
func BuildNS(t Elem) (ret []NS) { vals := make(map[xml.Name]string) if nselem, ok := t.(NSElem); ok { buildNS(nselem, vals) ret = make([]NS, 0, len(vals)) i := 1 for k, v := range vals { if !(k.Local == "xmlns" && k.Space == "" && v == "") { ret = append(ret, NS{ Attr: xml.Attr{Name: k, Value: v}, Parent: t, NodeType: NtNs, }) i++ } } sort.Sort(nsValueSort(ret)) for i := range ret { ret[i].NodePos = NodePos(t.Pos() + i + 1) } } return ret }
go
func BuildNS(t Elem) (ret []NS) { vals := make(map[xml.Name]string) if nselem, ok := t.(NSElem); ok { buildNS(nselem, vals) ret = make([]NS, 0, len(vals)) i := 1 for k, v := range vals { if !(k.Local == "xmlns" && k.Space == "" && v == "") { ret = append(ret, NS{ Attr: xml.Attr{Name: k, Value: v}, Parent: t, NodeType: NtNs, }) i++ } } sort.Sort(nsValueSort(ret)) for i := range ret { ret[i].NodePos = NodePos(t.Pos() + i + 1) } } return ret }
[ "func", "BuildNS", "(", "t", "Elem", ")", "(", "ret", "[", "]", "NS", ")", "{", "vals", ":=", "make", "(", "map", "[", "xml", ".", "Name", "]", "string", ")", "\n", "if", "nselem", ",", "ok", ":=", "t", ".", "(", "NSElem", ")", ";", "ok", "{", "buildNS", "(", "nselem", ",", "vals", ")", "\n", "ret", "=", "make", "(", "[", "]", "NS", ",", "0", ",", "len", "(", "vals", ")", ")", "\n", "i", ":=", "1", "\n", "for", "k", ",", "v", ":=", "range", "vals", "{", "if", "!", "(", "k", ".", "Local", "==", "\"xmlns\"", "&&", "k", ".", "Space", "==", "\"\"", "&&", "v", "==", "\"\"", ")", "{", "ret", "=", "append", "(", "ret", ",", "NS", "{", "Attr", ":", "xml", ".", "Attr", "{", "Name", ":", "k", ",", "Value", ":", "v", "}", ",", "Parent", ":", "t", ",", "NodeType", ":", "NtNs", ",", "}", ")", "\n", "i", "++", "\n", "}", "\n", "}", "\n", "sort", ".", "Sort", "(", "nsValueSort", "(", "ret", ")", ")", "\n", "for", "i", ":=", "range", "ret", "{", "ret", "[", "i", "]", ".", "NodePos", "=", "NodePos", "(", "t", ".", "Pos", "(", ")", "+", "i", "+", "1", ")", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
//BuildNS resolves all the namespace nodes of the element and returns them
[ "BuildNS", "resolves", "all", "the", "namespace", "nodes", "of", "the", "element", "and", "returns", "them" ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L89-L116
test
ChrisTrenkamp/goxpath
tree/tree.go
GetAttribute
func GetAttribute(n Elem, local, space string) (xml.Attr, bool) { attrs := n.GetAttrs() for _, i := range attrs { attr := i.GetToken().(xml.Attr) if local == attr.Name.Local && space == attr.Name.Space { return attr, true } } return xml.Attr{}, false }
go
func GetAttribute(n Elem, local, space string) (xml.Attr, bool) { attrs := n.GetAttrs() for _, i := range attrs { attr := i.GetToken().(xml.Attr) if local == attr.Name.Local && space == attr.Name.Space { return attr, true } } return xml.Attr{}, false }
[ "func", "GetAttribute", "(", "n", "Elem", ",", "local", ",", "space", "string", ")", "(", "xml", ".", "Attr", ",", "bool", ")", "{", "attrs", ":=", "n", ".", "GetAttrs", "(", ")", "\n", "for", "_", ",", "i", ":=", "range", "attrs", "{", "attr", ":=", "i", ".", "GetToken", "(", ")", ".", "(", "xml", ".", "Attr", ")", "\n", "if", "local", "==", "attr", ".", "Name", ".", "Local", "&&", "space", "==", "attr", ".", "Name", ".", "Space", "{", "return", "attr", ",", "true", "\n", "}", "\n", "}", "\n", "return", "xml", ".", "Attr", "{", "}", ",", "false", "\n", "}" ]
//GetAttribute is a convenience function for getting the specified attribute from an element. //false is returned if the attribute is not found.
[ "GetAttribute", "is", "a", "convenience", "function", "for", "getting", "the", "specified", "attribute", "from", "an", "element", ".", "false", "is", "returned", "if", "the", "attribute", "is", "not", "found", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L157-L166
test
ChrisTrenkamp/goxpath
tree/tree.go
GetAttributeVal
func GetAttributeVal(n Elem, local, space string) (string, bool) { attr, ok := GetAttribute(n, local, space) return attr.Value, ok }
go
func GetAttributeVal(n Elem, local, space string) (string, bool) { attr, ok := GetAttribute(n, local, space) return attr.Value, ok }
[ "func", "GetAttributeVal", "(", "n", "Elem", ",", "local", ",", "space", "string", ")", "(", "string", ",", "bool", ")", "{", "attr", ",", "ok", ":=", "GetAttribute", "(", "n", ",", "local", ",", "space", ")", "\n", "return", "attr", ".", "Value", ",", "ok", "\n", "}" ]
//GetAttributeVal is like GetAttribute, except it returns the attribute's value.
[ "GetAttributeVal", "is", "like", "GetAttribute", "except", "it", "returns", "the", "attribute", "s", "value", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L169-L172
test
ChrisTrenkamp/goxpath
tree/tree.go
GetAttrValOrEmpty
func GetAttrValOrEmpty(n Elem, local, space string) string { val, ok := GetAttributeVal(n, local, space) if !ok { return "" } return val }
go
func GetAttrValOrEmpty(n Elem, local, space string) string { val, ok := GetAttributeVal(n, local, space) if !ok { return "" } return val }
[ "func", "GetAttrValOrEmpty", "(", "n", "Elem", ",", "local", ",", "space", "string", ")", "string", "{", "val", ",", "ok", ":=", "GetAttributeVal", "(", "n", ",", "local", ",", "space", ")", "\n", "if", "!", "ok", "{", "return", "\"\"", "\n", "}", "\n", "return", "val", "\n", "}" ]
//GetAttrValOrEmpty is like GetAttributeVal, except it returns an empty string if //the attribute is not found instead of false.
[ "GetAttrValOrEmpty", "is", "like", "GetAttributeVal", "except", "it", "returns", "an", "empty", "string", "if", "the", "attribute", "is", "not", "found", "instead", "of", "false", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L176-L182
test
ChrisTrenkamp/goxpath
tree/tree.go
FindNodeByPos
func FindNodeByPos(n Node, pos int) Node { if n.Pos() == pos { return n } if elem, ok := n.(Elem); ok { chldrn := elem.GetChildren() for i := 1; i < len(chldrn); i++ { if chldrn[i-1].Pos() <= pos && chldrn[i].Pos() > pos { return FindNodeByPos(chldrn[i-1], pos) } } if len(chldrn) > 0 { if chldrn[len(chldrn)-1].Pos() <= pos { return FindNodeByPos(chldrn[len(chldrn)-1], pos) } } attrs := elem.GetAttrs() for _, i := range attrs { if i.Pos() == pos { return i } } ns := BuildNS(elem) for _, i := range ns { if i.Pos() == pos { return i } } } return nil }
go
func FindNodeByPos(n Node, pos int) Node { if n.Pos() == pos { return n } if elem, ok := n.(Elem); ok { chldrn := elem.GetChildren() for i := 1; i < len(chldrn); i++ { if chldrn[i-1].Pos() <= pos && chldrn[i].Pos() > pos { return FindNodeByPos(chldrn[i-1], pos) } } if len(chldrn) > 0 { if chldrn[len(chldrn)-1].Pos() <= pos { return FindNodeByPos(chldrn[len(chldrn)-1], pos) } } attrs := elem.GetAttrs() for _, i := range attrs { if i.Pos() == pos { return i } } ns := BuildNS(elem) for _, i := range ns { if i.Pos() == pos { return i } } } return nil }
[ "func", "FindNodeByPos", "(", "n", "Node", ",", "pos", "int", ")", "Node", "{", "if", "n", ".", "Pos", "(", ")", "==", "pos", "{", "return", "n", "\n", "}", "\n", "if", "elem", ",", "ok", ":=", "n", ".", "(", "Elem", ")", ";", "ok", "{", "chldrn", ":=", "elem", ".", "GetChildren", "(", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "chldrn", ")", ";", "i", "++", "{", "if", "chldrn", "[", "i", "-", "1", "]", ".", "Pos", "(", ")", "<=", "pos", "&&", "chldrn", "[", "i", "]", ".", "Pos", "(", ")", ">", "pos", "{", "return", "FindNodeByPos", "(", "chldrn", "[", "i", "-", "1", "]", ",", "pos", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "chldrn", ")", ">", "0", "{", "if", "chldrn", "[", "len", "(", "chldrn", ")", "-", "1", "]", ".", "Pos", "(", ")", "<=", "pos", "{", "return", "FindNodeByPos", "(", "chldrn", "[", "len", "(", "chldrn", ")", "-", "1", "]", ",", "pos", ")", "\n", "}", "\n", "}", "\n", "attrs", ":=", "elem", ".", "GetAttrs", "(", ")", "\n", "for", "_", ",", "i", ":=", "range", "attrs", "{", "if", "i", ".", "Pos", "(", ")", "==", "pos", "{", "return", "i", "\n", "}", "\n", "}", "\n", "ns", ":=", "BuildNS", "(", "elem", ")", "\n", "for", "_", ",", "i", ":=", "range", "ns", "{", "if", "i", ".", "Pos", "(", ")", "==", "pos", "{", "return", "i", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
//FindNodeByPos finds a node from the given position. Returns nil if the node //is not found.
[ "FindNodeByPos", "finds", "a", "node", "from", "the", "given", "position", ".", "Returns", "nil", "if", "the", "node", "is", "not", "found", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/tree.go#L186-L221
test
ChrisTrenkamp/goxpath
marshal.go
Marshal
func Marshal(n tree.Node, w io.Writer) error { return marshal(n, w) }
go
func Marshal(n tree.Node, w io.Writer) error { return marshal(n, w) }
[ "func", "Marshal", "(", "n", "tree", ".", "Node", ",", "w", "io", ".", "Writer", ")", "error", "{", "return", "marshal", "(", "n", ",", "w", ")", "\n", "}" ]
//Marshal prints the result tree, r, in XML form to w.
[ "Marshal", "prints", "the", "result", "tree", "r", "in", "XML", "form", "to", "w", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/marshal.go#L12-L14
test
ChrisTrenkamp/goxpath
marshal.go
MarshalStr
func MarshalStr(n tree.Node) (string, error) { ret := bytes.NewBufferString("") err := marshal(n, ret) return ret.String(), err }
go
func MarshalStr(n tree.Node) (string, error) { ret := bytes.NewBufferString("") err := marshal(n, ret) return ret.String(), err }
[ "func", "MarshalStr", "(", "n", "tree", ".", "Node", ")", "(", "string", ",", "error", ")", "{", "ret", ":=", "bytes", ".", "NewBufferString", "(", "\"\"", ")", "\n", "err", ":=", "marshal", "(", "n", ",", "ret", ")", "\n", "return", "ret", ".", "String", "(", ")", ",", "err", "\n", "}" ]
//MarshalStr is like Marhal, but returns a string.
[ "MarshalStr", "is", "like", "Marhal", "but", "returns", "a", "string", "." ]
c385f95c6022e7756e91beac5f5510872f7dcb7d
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/marshal.go#L17-L22
test
anmitsu/go-shlex
shlex.go
NewLexer
func NewLexer(r io.Reader, posix, whitespacesplit bool) *Lexer { return &Lexer{ reader: bufio.NewReader(r), tokenizer: &DefaultTokenizer{}, posix: posix, whitespacesplit: whitespacesplit, } }
go
func NewLexer(r io.Reader, posix, whitespacesplit bool) *Lexer { return &Lexer{ reader: bufio.NewReader(r), tokenizer: &DefaultTokenizer{}, posix: posix, whitespacesplit: whitespacesplit, } }
[ "func", "NewLexer", "(", "r", "io", ".", "Reader", ",", "posix", ",", "whitespacesplit", "bool", ")", "*", "Lexer", "{", "return", "&", "Lexer", "{", "reader", ":", "bufio", ".", "NewReader", "(", "r", ")", ",", "tokenizer", ":", "&", "DefaultTokenizer", "{", "}", ",", "posix", ":", "posix", ",", "whitespacesplit", ":", "whitespacesplit", ",", "}", "\n", "}" ]
// NewLexer creates a new Lexer reading from io.Reader. This Lexer // has a DefaultTokenizer according to posix and whitespacesplit // rules.
[ "NewLexer", "creates", "a", "new", "Lexer", "reading", "from", "io", ".", "Reader", ".", "This", "Lexer", "has", "a", "DefaultTokenizer", "according", "to", "posix", "and", "whitespacesplit", "rules", "." ]
648efa622239a2f6ff949fed78ee37b48d499ba4
https://github.com/anmitsu/go-shlex/blob/648efa622239a2f6ff949fed78ee37b48d499ba4/shlex.go#L62-L69
test
anmitsu/go-shlex
shlex.go
NewLexerString
func NewLexerString(s string, posix, whitespacesplit bool) *Lexer { return NewLexer(strings.NewReader(s), posix, whitespacesplit) }
go
func NewLexerString(s string, posix, whitespacesplit bool) *Lexer { return NewLexer(strings.NewReader(s), posix, whitespacesplit) }
[ "func", "NewLexerString", "(", "s", "string", ",", "posix", ",", "whitespacesplit", "bool", ")", "*", "Lexer", "{", "return", "NewLexer", "(", "strings", ".", "NewReader", "(", "s", ")", ",", "posix", ",", "whitespacesplit", ")", "\n", "}" ]
// NewLexerString creates a new Lexer reading from a string. This // Lexer has a DefaultTokenizer according to posix and whitespacesplit // rules.
[ "NewLexerString", "creates", "a", "new", "Lexer", "reading", "from", "a", "string", ".", "This", "Lexer", "has", "a", "DefaultTokenizer", "according", "to", "posix", "and", "whitespacesplit", "rules", "." ]
648efa622239a2f6ff949fed78ee37b48d499ba4
https://github.com/anmitsu/go-shlex/blob/648efa622239a2f6ff949fed78ee37b48d499ba4/shlex.go#L74-L76
test
anmitsu/go-shlex
shlex.go
Split
func Split(s string, posix bool) ([]string, error) { return NewLexerString(s, posix, true).Split() }
go
func Split(s string, posix bool) ([]string, error) { return NewLexerString(s, posix, true).Split() }
[ "func", "Split", "(", "s", "string", ",", "posix", "bool", ")", "(", "[", "]", "string", ",", "error", ")", "{", "return", "NewLexerString", "(", "s", ",", "posix", ",", "true", ")", ".", "Split", "(", ")", "\n", "}" ]
// Split splits a string according to posix or non-posix rules.
[ "Split", "splits", "a", "string", "according", "to", "posix", "or", "non", "-", "posix", "rules", "." ]
648efa622239a2f6ff949fed78ee37b48d499ba4
https://github.com/anmitsu/go-shlex/blob/648efa622239a2f6ff949fed78ee37b48d499ba4/shlex.go#L79-L81
test
TheThingsNetwork/go-utils
errors/registry.go
Register
func (r *registry) Register(err *ErrDescriptor) { r.Lock() defer r.Unlock() if err.Code == NoCode { panic(fmt.Errorf("No code defined in error descriptor (message: `%s`)", err.MessageFormat)) } if r.byCode[err.Code] != nil { panic(fmt.Errorf("errors: Duplicate error code %v registered", err.Code)) } err.registered = true r.byCode[err.Code] = err }
go
func (r *registry) Register(err *ErrDescriptor) { r.Lock() defer r.Unlock() if err.Code == NoCode { panic(fmt.Errorf("No code defined in error descriptor (message: `%s`)", err.MessageFormat)) } if r.byCode[err.Code] != nil { panic(fmt.Errorf("errors: Duplicate error code %v registered", err.Code)) } err.registered = true r.byCode[err.Code] = err }
[ "func", "(", "r", "*", "registry", ")", "Register", "(", "err", "*", "ErrDescriptor", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "if", "err", ".", "Code", "==", "NoCode", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"No code defined in error descriptor (message: `%s`)\"", ",", "err", ".", "MessageFormat", ")", ")", "\n", "}", "\n", "if", "r", ".", "byCode", "[", "err", ".", "Code", "]", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"errors: Duplicate error code %v registered\"", ",", "err", ".", "Code", ")", ")", "\n", "}", "\n", "err", ".", "registered", "=", "true", "\n", "r", ".", "byCode", "[", "err", ".", "Code", "]", "=", "err", "\n", "}" ]
// Register registers a new error type
[ "Register", "registers", "a", "new", "error", "type" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L18-L32
test
TheThingsNetwork/go-utils
errors/registry.go
Get
func (r *registry) Get(code Code) *ErrDescriptor { r.RLock() defer r.RUnlock() return r.byCode[code] }
go
func (r *registry) Get(code Code) *ErrDescriptor { r.RLock() defer r.RUnlock() return r.byCode[code] }
[ "func", "(", "r", "*", "registry", ")", "Get", "(", "code", "Code", ")", "*", "ErrDescriptor", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "return", "r", ".", "byCode", "[", "code", "]", "\n", "}" ]
// Get returns the descriptor if it exists or nil otherwise
[ "Get", "returns", "the", "descriptor", "if", "it", "exists", "or", "nil", "otherwise" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L35-L39
test
TheThingsNetwork/go-utils
errors/registry.go
GetAll
func (r *registry) GetAll() []*ErrDescriptor { r.RLock() defer r.RUnlock() res := make([]*ErrDescriptor, 0, len(r.byCode)) for _, d := range r.byCode { res = append(res, d) } return res }
go
func (r *registry) GetAll() []*ErrDescriptor { r.RLock() defer r.RUnlock() res := make([]*ErrDescriptor, 0, len(r.byCode)) for _, d := range r.byCode { res = append(res, d) } return res }
[ "func", "(", "r", "*", "registry", ")", "GetAll", "(", ")", "[", "]", "*", "ErrDescriptor", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "res", ":=", "make", "(", "[", "]", "*", "ErrDescriptor", ",", "0", ",", "len", "(", "r", ".", "byCode", ")", ")", "\n", "for", "_", ",", "d", ":=", "range", "r", ".", "byCode", "{", "res", "=", "append", "(", "res", ",", "d", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// GetAll returns all registered error descriptors
[ "GetAll", "returns", "all", "registered", "error", "descriptors" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L42-L51
test
TheThingsNetwork/go-utils
errors/registry.go
From
func From(in error) Error { if err, ok := in.(Error); ok { return err } return FromGRPC(in) }
go
func From(in error) Error { if err, ok := in.(Error); ok { return err } return FromGRPC(in) }
[ "func", "From", "(", "in", "error", ")", "Error", "{", "if", "err", ",", "ok", ":=", "in", ".", "(", "Error", ")", ";", "ok", "{", "return", "err", "\n", "}", "\n", "return", "FromGRPC", "(", "in", ")", "\n", "}" ]
// From lifts an error to be and Error
[ "From", "lifts", "an", "error", "to", "be", "and", "Error" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L71-L77
test
TheThingsNetwork/go-utils
errors/registry.go
Descriptor
func Descriptor(in error) (desc *ErrDescriptor) { err := From(in) descriptor := Get(err.Code()) if descriptor != nil { return descriptor } // return a new error descriptor with sane defaults return &ErrDescriptor{ MessageFormat: err.Error(), Type: err.Type(), Code: err.Code(), } }
go
func Descriptor(in error) (desc *ErrDescriptor) { err := From(in) descriptor := Get(err.Code()) if descriptor != nil { return descriptor } // return a new error descriptor with sane defaults return &ErrDescriptor{ MessageFormat: err.Error(), Type: err.Type(), Code: err.Code(), } }
[ "func", "Descriptor", "(", "in", "error", ")", "(", "desc", "*", "ErrDescriptor", ")", "{", "err", ":=", "From", "(", "in", ")", "\n", "descriptor", ":=", "Get", "(", "err", ".", "Code", "(", ")", ")", "\n", "if", "descriptor", "!=", "nil", "{", "return", "descriptor", "\n", "}", "\n", "return", "&", "ErrDescriptor", "{", "MessageFormat", ":", "err", ".", "Error", "(", ")", ",", "Type", ":", "err", ".", "Type", "(", ")", ",", "Code", ":", "err", ".", "Code", "(", ")", ",", "}", "\n", "}" ]
// Descriptor returns the error descriptor from any error
[ "Descriptor", "returns", "the", "error", "descriptor", "from", "any", "error" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L80-L93
test
TheThingsNetwork/go-utils
errors/registry.go
GetAttributes
func GetAttributes(err error) Attributes { e, ok := err.(Error) if ok { return e.Attributes() } return Attributes{} }
go
func GetAttributes(err error) Attributes { e, ok := err.(Error) if ok { return e.Attributes() } return Attributes{} }
[ "func", "GetAttributes", "(", "err", "error", ")", "Attributes", "{", "e", ",", "ok", ":=", "err", ".", "(", "Error", ")", "\n", "if", "ok", "{", "return", "e", ".", "Attributes", "(", ")", "\n", "}", "\n", "return", "Attributes", "{", "}", "\n", "}" ]
// GetAttributes returns the error attributes or falls back // to empty attributes
[ "GetAttributes", "returns", "the", "error", "attributes", "or", "falls", "back", "to", "empty", "attributes" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L114-L121
test
TheThingsNetwork/go-utils
errors/http.go
HTTPStatusCode
func (t Type) HTTPStatusCode() int { switch t { case Canceled: return http.StatusRequestTimeout case InvalidArgument: return http.StatusBadRequest case OutOfRange: return http.StatusBadRequest case NotFound: return http.StatusNotFound case Conflict: return http.StatusConflict case AlreadyExists: return http.StatusConflict case Unauthorized: return http.StatusUnauthorized case PermissionDenied: return http.StatusForbidden case Timeout: return http.StatusRequestTimeout case NotImplemented: return http.StatusNotImplemented case TemporarilyUnavailable: return http.StatusBadGateway case PermanentlyUnavailable: return http.StatusGone case ResourceExhausted: return http.StatusForbidden case Internal: return http.StatusInternalServerError case Unknown: return http.StatusInternalServerError } return http.StatusInternalServerError }
go
func (t Type) HTTPStatusCode() int { switch t { case Canceled: return http.StatusRequestTimeout case InvalidArgument: return http.StatusBadRequest case OutOfRange: return http.StatusBadRequest case NotFound: return http.StatusNotFound case Conflict: return http.StatusConflict case AlreadyExists: return http.StatusConflict case Unauthorized: return http.StatusUnauthorized case PermissionDenied: return http.StatusForbidden case Timeout: return http.StatusRequestTimeout case NotImplemented: return http.StatusNotImplemented case TemporarilyUnavailable: return http.StatusBadGateway case PermanentlyUnavailable: return http.StatusGone case ResourceExhausted: return http.StatusForbidden case Internal: return http.StatusInternalServerError case Unknown: return http.StatusInternalServerError } return http.StatusInternalServerError }
[ "func", "(", "t", "Type", ")", "HTTPStatusCode", "(", ")", "int", "{", "switch", "t", "{", "case", "Canceled", ":", "return", "http", ".", "StatusRequestTimeout", "\n", "case", "InvalidArgument", ":", "return", "http", ".", "StatusBadRequest", "\n", "case", "OutOfRange", ":", "return", "http", ".", "StatusBadRequest", "\n", "case", "NotFound", ":", "return", "http", ".", "StatusNotFound", "\n", "case", "Conflict", ":", "return", "http", ".", "StatusConflict", "\n", "case", "AlreadyExists", ":", "return", "http", ".", "StatusConflict", "\n", "case", "Unauthorized", ":", "return", "http", ".", "StatusUnauthorized", "\n", "case", "PermissionDenied", ":", "return", "http", ".", "StatusForbidden", "\n", "case", "Timeout", ":", "return", "http", ".", "StatusRequestTimeout", "\n", "case", "NotImplemented", ":", "return", "http", ".", "StatusNotImplemented", "\n", "case", "TemporarilyUnavailable", ":", "return", "http", ".", "StatusBadGateway", "\n", "case", "PermanentlyUnavailable", ":", "return", "http", ".", "StatusGone", "\n", "case", "ResourceExhausted", ":", "return", "http", ".", "StatusForbidden", "\n", "case", "Internal", ":", "return", "http", ".", "StatusInternalServerError", "\n", "case", "Unknown", ":", "return", "http", ".", "StatusInternalServerError", "\n", "}", "\n", "return", "http", ".", "StatusInternalServerError", "\n", "}" ]
// HTTPStatusCode returns the corresponding http status code from an error type
[ "HTTPStatusCode", "returns", "the", "corresponding", "http", "status", "code", "from", "an", "error", "type" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/http.go#L15-L50
test
TheThingsNetwork/go-utils
errors/http.go
HTTPStatusCode
func HTTPStatusCode(err error) int { e, ok := err.(Error) if ok { return e.Type().HTTPStatusCode() } return http.StatusInternalServerError }
go
func HTTPStatusCode(err error) int { e, ok := err.(Error) if ok { return e.Type().HTTPStatusCode() } return http.StatusInternalServerError }
[ "func", "HTTPStatusCode", "(", "err", "error", ")", "int", "{", "e", ",", "ok", ":=", "err", ".", "(", "Error", ")", "\n", "if", "ok", "{", "return", "e", ".", "Type", "(", ")", ".", "HTTPStatusCode", "(", ")", "\n", "}", "\n", "return", "http", ".", "StatusInternalServerError", "\n", "}" ]
// HTTPStatusCode returns the HTTP status code for the given error or 500 if it doesn't know
[ "HTTPStatusCode", "returns", "the", "HTTP", "status", "code", "for", "the", "given", "error", "or", "500", "if", "it", "doesn", "t", "know" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/http.go#L53-L60
test
TheThingsNetwork/go-utils
errors/http.go
HTTPStatusToType
func HTTPStatusToType(status int) Type { switch status { case http.StatusBadRequest: return InvalidArgument case http.StatusNotFound: return NotFound case http.StatusConflict: return Conflict case http.StatusUnauthorized: return Unauthorized case http.StatusForbidden: return PermissionDenied case http.StatusRequestTimeout: return Timeout case http.StatusNotImplemented: return NotImplemented case http.StatusBadGateway: case http.StatusServiceUnavailable: return TemporarilyUnavailable case http.StatusGone: return PermanentlyUnavailable case http.StatusTooManyRequests: return ResourceExhausted case http.StatusInternalServerError: return Unknown } return Unknown }
go
func HTTPStatusToType(status int) Type { switch status { case http.StatusBadRequest: return InvalidArgument case http.StatusNotFound: return NotFound case http.StatusConflict: return Conflict case http.StatusUnauthorized: return Unauthorized case http.StatusForbidden: return PermissionDenied case http.StatusRequestTimeout: return Timeout case http.StatusNotImplemented: return NotImplemented case http.StatusBadGateway: case http.StatusServiceUnavailable: return TemporarilyUnavailable case http.StatusGone: return PermanentlyUnavailable case http.StatusTooManyRequests: return ResourceExhausted case http.StatusInternalServerError: return Unknown } return Unknown }
[ "func", "HTTPStatusToType", "(", "status", "int", ")", "Type", "{", "switch", "status", "{", "case", "http", ".", "StatusBadRequest", ":", "return", "InvalidArgument", "\n", "case", "http", ".", "StatusNotFound", ":", "return", "NotFound", "\n", "case", "http", ".", "StatusConflict", ":", "return", "Conflict", "\n", "case", "http", ".", "StatusUnauthorized", ":", "return", "Unauthorized", "\n", "case", "http", ".", "StatusForbidden", ":", "return", "PermissionDenied", "\n", "case", "http", ".", "StatusRequestTimeout", ":", "return", "Timeout", "\n", "case", "http", ".", "StatusNotImplemented", ":", "return", "NotImplemented", "\n", "case", "http", ".", "StatusBadGateway", ":", "case", "http", ".", "StatusServiceUnavailable", ":", "return", "TemporarilyUnavailable", "\n", "case", "http", ".", "StatusGone", ":", "return", "PermanentlyUnavailable", "\n", "case", "http", ".", "StatusTooManyRequests", ":", "return", "ResourceExhausted", "\n", "case", "http", ".", "StatusInternalServerError", ":", "return", "Unknown", "\n", "}", "\n", "return", "Unknown", "\n", "}" ]
// HTTPStatusToType infers the error Type from a HTTP Status code
[ "HTTPStatusToType", "infers", "the", "error", "Type", "from", "a", "HTTP", "Status", "code" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/http.go#L63-L90
test
TheThingsNetwork/go-utils
errors/http.go
ToHTTP
func ToHTTP(in error, w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") if err, ok := in.(Error); ok { w.Header().Set(CodeHeader, err.Code().String()) w.WriteHeader(err.Type().HTTPStatusCode()) return json.NewEncoder(w).Encode(toJSON(err)) } w.WriteHeader(http.StatusInternalServerError) return json.NewEncoder(w).Encode(&jsonError{ Message: in.Error(), Type: Unknown, }) }
go
func ToHTTP(in error, w http.ResponseWriter) error { w.Header().Set("Content-Type", "application/json") if err, ok := in.(Error); ok { w.Header().Set(CodeHeader, err.Code().String()) w.WriteHeader(err.Type().HTTPStatusCode()) return json.NewEncoder(w).Encode(toJSON(err)) } w.WriteHeader(http.StatusInternalServerError) return json.NewEncoder(w).Encode(&jsonError{ Message: in.Error(), Type: Unknown, }) }
[ "func", "ToHTTP", "(", "in", "error", ",", "w", "http", ".", "ResponseWriter", ")", "error", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "if", "err", ",", "ok", ":=", "in", ".", "(", "Error", ")", ";", "ok", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "CodeHeader", ",", "err", ".", "Code", "(", ")", ".", "String", "(", ")", ")", "\n", "w", ".", "WriteHeader", "(", "err", ".", "Type", "(", ")", ".", "HTTPStatusCode", "(", ")", ")", "\n", "return", "json", ".", "NewEncoder", "(", "w", ")", ".", "Encode", "(", "toJSON", "(", "err", ")", ")", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "return", "json", ".", "NewEncoder", "(", "w", ")", ".", "Encode", "(", "&", "jsonError", "{", "Message", ":", "in", ".", "Error", "(", ")", ",", "Type", ":", "Unknown", ",", "}", ")", "\n", "}" ]
// ToHTTP writes the error to the http response
[ "ToHTTP", "writes", "the", "error", "to", "the", "http", "response" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/http.go#L122-L135
test
TheThingsNetwork/go-utils
errors/impl.go
toImpl
func toImpl(err Error) *impl { if i, ok := err.(*impl); ok { return i } return &impl{ message: err.Error(), code: err.Code(), typ: err.Type(), attributes: err.Attributes(), } }
go
func toImpl(err Error) *impl { if i, ok := err.(*impl); ok { return i } return &impl{ message: err.Error(), code: err.Code(), typ: err.Type(), attributes: err.Attributes(), } }
[ "func", "toImpl", "(", "err", "Error", ")", "*", "impl", "{", "if", "i", ",", "ok", ":=", "err", ".", "(", "*", "impl", ")", ";", "ok", "{", "return", "i", "\n", "}", "\n", "return", "&", "impl", "{", "message", ":", "err", ".", "Error", "(", ")", ",", "code", ":", "err", ".", "Code", "(", ")", ",", "typ", ":", "err", ".", "Type", "(", ")", ",", "attributes", ":", "err", ".", "Attributes", "(", ")", ",", "}", "\n", "}" ]
// toImpl creates an equivalent impl for any Error
[ "toImpl", "creates", "an", "equivalent", "impl", "for", "any", "Error" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/impl.go#L35-L46
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
MetadataFromIncomingContext
func MetadataFromIncomingContext(ctx context.Context) metadata.MD { md, _ := metadata.FromIncomingContext(ctx) return md }
go
func MetadataFromIncomingContext(ctx context.Context) metadata.MD { md, _ := metadata.FromIncomingContext(ctx) return md }
[ "func", "MetadataFromIncomingContext", "(", "ctx", "context", ".", "Context", ")", "metadata", ".", "MD", "{", "md", ",", "_", ":=", "metadata", ".", "FromIncomingContext", "(", "ctx", ")", "\n", "return", "md", "\n", "}" ]
// MetadataFromIncomingContext gets the metadata from the given context
[ "MetadataFromIncomingContext", "gets", "the", "metadata", "from", "the", "given", "context" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L15-L18
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
MetadataFromOutgoingContext
func MetadataFromOutgoingContext(ctx context.Context) metadata.MD { md, _ := metadata.FromOutgoingContext(ctx) return md }
go
func MetadataFromOutgoingContext(ctx context.Context) metadata.MD { md, _ := metadata.FromOutgoingContext(ctx) return md }
[ "func", "MetadataFromOutgoingContext", "(", "ctx", "context", ".", "Context", ")", "metadata", ".", "MD", "{", "md", ",", "_", ":=", "metadata", ".", "FromOutgoingContext", "(", "ctx", ")", "\n", "return", "md", "\n", "}" ]
// MetadataFromOutgoingContext gets the metadata from the given context
[ "MetadataFromOutgoingContext", "gets", "the", "metadata", "from", "the", "given", "context" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L21-L24
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
TokenFromMetadata
func TokenFromMetadata(md metadata.MD) (string, error) { token, ok := md["token"] if !ok || len(token) == 0 { return "", ErrNoToken } return token[0], nil }
go
func TokenFromMetadata(md metadata.MD) (string, error) { token, ok := md["token"] if !ok || len(token) == 0 { return "", ErrNoToken } return token[0], nil }
[ "func", "TokenFromMetadata", "(", "md", "metadata", ".", "MD", ")", "(", "string", ",", "error", ")", "{", "token", ",", "ok", ":=", "md", "[", "\"token\"", "]", "\n", "if", "!", "ok", "||", "len", "(", "token", ")", "==", "0", "{", "return", "\"\"", ",", "ErrNoToken", "\n", "}", "\n", "return", "token", "[", "0", "]", ",", "nil", "\n", "}" ]
// TokenFromMetadata gets the token from the metadata or returns ErrNoToken
[ "TokenFromMetadata", "gets", "the", "token", "from", "the", "metadata", "or", "returns", "ErrNoToken" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L27-L33
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
TokenFromIncomingContext
func TokenFromIncomingContext(ctx context.Context) (string, error) { md := MetadataFromIncomingContext(ctx) return TokenFromMetadata(md) }
go
func TokenFromIncomingContext(ctx context.Context) (string, error) { md := MetadataFromIncomingContext(ctx) return TokenFromMetadata(md) }
[ "func", "TokenFromIncomingContext", "(", "ctx", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "md", ":=", "MetadataFromIncomingContext", "(", "ctx", ")", "\n", "return", "TokenFromMetadata", "(", "md", ")", "\n", "}" ]
// TokenFromIncomingContext gets the token from the incoming context or returns ErrNoToken
[ "TokenFromIncomingContext", "gets", "the", "token", "from", "the", "incoming", "context", "or", "returns", "ErrNoToken" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L42-L45
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
OutgoingContextWithToken
func OutgoingContextWithToken(ctx context.Context, token string) context.Context { return outgoingContextWithMergedMetadata(ctx, "token", token) }
go
func OutgoingContextWithToken(ctx context.Context, token string) context.Context { return outgoingContextWithMergedMetadata(ctx, "token", token) }
[ "func", "OutgoingContextWithToken", "(", "ctx", "context", ".", "Context", ",", "token", "string", ")", "context", ".", "Context", "{", "return", "outgoingContextWithMergedMetadata", "(", "ctx", ",", "\"token\"", ",", "token", ")", "\n", "}" ]
// OutgoingContextWithToken returns an outgoing context with the token
[ "OutgoingContextWithToken", "returns", "an", "outgoing", "context", "with", "the", "token" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L48-L50
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
KeyFromMetadata
func KeyFromMetadata(md metadata.MD) (string, error) { key, ok := md["key"] if !ok || len(key) == 0 { return "", ErrNoKey } return key[0], nil }
go
func KeyFromMetadata(md metadata.MD) (string, error) { key, ok := md["key"] if !ok || len(key) == 0 { return "", ErrNoKey } return key[0], nil }
[ "func", "KeyFromMetadata", "(", "md", "metadata", ".", "MD", ")", "(", "string", ",", "error", ")", "{", "key", ",", "ok", ":=", "md", "[", "\"key\"", "]", "\n", "if", "!", "ok", "||", "len", "(", "key", ")", "==", "0", "{", "return", "\"\"", ",", "ErrNoKey", "\n", "}", "\n", "return", "key", "[", "0", "]", ",", "nil", "\n", "}" ]
// KeyFromMetadata gets the key from the metadata or returns ErrNoKey
[ "KeyFromMetadata", "gets", "the", "key", "from", "the", "metadata", "or", "returns", "ErrNoKey" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L53-L59
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
KeyFromIncomingContext
func KeyFromIncomingContext(ctx context.Context) (string, error) { md := MetadataFromIncomingContext(ctx) return KeyFromMetadata(md) }
go
func KeyFromIncomingContext(ctx context.Context) (string, error) { md := MetadataFromIncomingContext(ctx) return KeyFromMetadata(md) }
[ "func", "KeyFromIncomingContext", "(", "ctx", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "md", ":=", "MetadataFromIncomingContext", "(", "ctx", ")", "\n", "return", "KeyFromMetadata", "(", "md", ")", "\n", "}" ]
// KeyFromIncomingContext gets the key from the incoming context or returns ErrNoKey
[ "KeyFromIncomingContext", "gets", "the", "key", "from", "the", "incoming", "context", "or", "returns", "ErrNoKey" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L62-L65
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
OutgoingContextWithKey
func OutgoingContextWithKey(ctx context.Context, key string) context.Context { return outgoingContextWithMergedMetadata(ctx, "key", key) }
go
func OutgoingContextWithKey(ctx context.Context, key string) context.Context { return outgoingContextWithMergedMetadata(ctx, "key", key) }
[ "func", "OutgoingContextWithKey", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "context", ".", "Context", "{", "return", "outgoingContextWithMergedMetadata", "(", "ctx", ",", "\"key\"", ",", "key", ")", "\n", "}" ]
// OutgoingContextWithKey returns an outgoing context with the key
[ "OutgoingContextWithKey", "returns", "an", "outgoing", "context", "with", "the", "key" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L68-L70
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
IDFromMetadata
func IDFromMetadata(md metadata.MD) (string, error) { id, ok := md["id"] if !ok || len(id) == 0 { return "", ErrNoID } return id[0], nil }
go
func IDFromMetadata(md metadata.MD) (string, error) { id, ok := md["id"] if !ok || len(id) == 0 { return "", ErrNoID } return id[0], nil }
[ "func", "IDFromMetadata", "(", "md", "metadata", ".", "MD", ")", "(", "string", ",", "error", ")", "{", "id", ",", "ok", ":=", "md", "[", "\"id\"", "]", "\n", "if", "!", "ok", "||", "len", "(", "id", ")", "==", "0", "{", "return", "\"\"", ",", "ErrNoID", "\n", "}", "\n", "return", "id", "[", "0", "]", ",", "nil", "\n", "}" ]
// IDFromMetadata gets the key from the metadata or returns ErrNoID
[ "IDFromMetadata", "gets", "the", "key", "from", "the", "metadata", "or", "returns", "ErrNoID" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L73-L79
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
IDFromIncomingContext
func IDFromIncomingContext(ctx context.Context) (string, error) { md := MetadataFromIncomingContext(ctx) return IDFromMetadata(md) }
go
func IDFromIncomingContext(ctx context.Context) (string, error) { md := MetadataFromIncomingContext(ctx) return IDFromMetadata(md) }
[ "func", "IDFromIncomingContext", "(", "ctx", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "md", ":=", "MetadataFromIncomingContext", "(", "ctx", ")", "\n", "return", "IDFromMetadata", "(", "md", ")", "\n", "}" ]
// IDFromIncomingContext gets the key from the incoming context or returns ErrNoID
[ "IDFromIncomingContext", "gets", "the", "key", "from", "the", "incoming", "context", "or", "returns", "ErrNoID" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L82-L85
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
OutgoingContextWithID
func OutgoingContextWithID(ctx context.Context, id string) context.Context { return outgoingContextWithMergedMetadata(ctx, "id", id) }
go
func OutgoingContextWithID(ctx context.Context, id string) context.Context { return outgoingContextWithMergedMetadata(ctx, "id", id) }
[ "func", "OutgoingContextWithID", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "context", ".", "Context", "{", "return", "outgoingContextWithMergedMetadata", "(", "ctx", ",", "\"id\"", ",", "id", ")", "\n", "}" ]
// OutgoingContextWithID returns an outgoing context with the id
[ "OutgoingContextWithID", "returns", "an", "outgoing", "context", "with", "the", "id" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L88-L90
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
ServiceInfoFromMetadata
func ServiceInfoFromMetadata(md metadata.MD) (serviceName, serviceVersion, netAddress string, err error) { serviceNameL, ok := md["service-name"] if ok && len(serviceNameL) > 0 { serviceName = serviceNameL[0] } serviceVersionL, ok := md["service-version"] if ok && len(serviceVersionL) > 0 { serviceVersion = serviceVersionL[0] } netAddressL, ok := md["net-address"] if ok && len(netAddressL) > 0 { netAddress = netAddressL[0] } return }
go
func ServiceInfoFromMetadata(md metadata.MD) (serviceName, serviceVersion, netAddress string, err error) { serviceNameL, ok := md["service-name"] if ok && len(serviceNameL) > 0 { serviceName = serviceNameL[0] } serviceVersionL, ok := md["service-version"] if ok && len(serviceVersionL) > 0 { serviceVersion = serviceVersionL[0] } netAddressL, ok := md["net-address"] if ok && len(netAddressL) > 0 { netAddress = netAddressL[0] } return }
[ "func", "ServiceInfoFromMetadata", "(", "md", "metadata", ".", "MD", ")", "(", "serviceName", ",", "serviceVersion", ",", "netAddress", "string", ",", "err", "error", ")", "{", "serviceNameL", ",", "ok", ":=", "md", "[", "\"service-name\"", "]", "\n", "if", "ok", "&&", "len", "(", "serviceNameL", ")", ">", "0", "{", "serviceName", "=", "serviceNameL", "[", "0", "]", "\n", "}", "\n", "serviceVersionL", ",", "ok", ":=", "md", "[", "\"service-version\"", "]", "\n", "if", "ok", "&&", "len", "(", "serviceVersionL", ")", ">", "0", "{", "serviceVersion", "=", "serviceVersionL", "[", "0", "]", "\n", "}", "\n", "netAddressL", ",", "ok", ":=", "md", "[", "\"net-address\"", "]", "\n", "if", "ok", "&&", "len", "(", "netAddressL", ")", ">", "0", "{", "netAddress", "=", "netAddressL", "[", "0", "]", "\n", "}", "\n", "return", "\n", "}" ]
// ServiceInfoFromMetadata gets the service information from the metadata or returns empty strings
[ "ServiceInfoFromMetadata", "gets", "the", "service", "information", "from", "the", "metadata", "or", "returns", "empty", "strings" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L93-L107
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
ServiceInfoFromIncomingContext
func ServiceInfoFromIncomingContext(ctx context.Context) (serviceName, serviceVersion, netAddress string, err error) { md := MetadataFromIncomingContext(ctx) return ServiceInfoFromMetadata(md) }
go
func ServiceInfoFromIncomingContext(ctx context.Context) (serviceName, serviceVersion, netAddress string, err error) { md := MetadataFromIncomingContext(ctx) return ServiceInfoFromMetadata(md) }
[ "func", "ServiceInfoFromIncomingContext", "(", "ctx", "context", ".", "Context", ")", "(", "serviceName", ",", "serviceVersion", ",", "netAddress", "string", ",", "err", "error", ")", "{", "md", ":=", "MetadataFromIncomingContext", "(", "ctx", ")", "\n", "return", "ServiceInfoFromMetadata", "(", "md", ")", "\n", "}" ]
// ServiceInfoFromIncomingContext gets the service information from the incoming context or returns empty strings
[ "ServiceInfoFromIncomingContext", "gets", "the", "service", "information", "from", "the", "incoming", "context", "or", "returns", "empty", "strings" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L110-L113
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
OutgoingContextWithServiceInfo
func OutgoingContextWithServiceInfo(ctx context.Context, serviceName, serviceVersion, netAddress string) context.Context { return outgoingContextWithMergedMetadata(ctx, "service-name", serviceName, "service-version", serviceVersion, "net-address", netAddress) }
go
func OutgoingContextWithServiceInfo(ctx context.Context, serviceName, serviceVersion, netAddress string) context.Context { return outgoingContextWithMergedMetadata(ctx, "service-name", serviceName, "service-version", serviceVersion, "net-address", netAddress) }
[ "func", "OutgoingContextWithServiceInfo", "(", "ctx", "context", ".", "Context", ",", "serviceName", ",", "serviceVersion", ",", "netAddress", "string", ")", "context", ".", "Context", "{", "return", "outgoingContextWithMergedMetadata", "(", "ctx", ",", "\"service-name\"", ",", "serviceName", ",", "\"service-version\"", ",", "serviceVersion", ",", "\"net-address\"", ",", "netAddress", ")", "\n", "}" ]
// OutgoingContextWithServiceInfo returns an outgoing context with the id
[ "OutgoingContextWithServiceInfo", "returns", "an", "outgoing", "context", "with", "the", "id" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L116-L118
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
LimitFromMetadata
func LimitFromMetadata(md metadata.MD) (uint64, error) { limit, ok := md["limit"] if !ok || len(limit) == 0 { return 0, nil } return strconv.ParseUint(limit[0], 10, 64) }
go
func LimitFromMetadata(md metadata.MD) (uint64, error) { limit, ok := md["limit"] if !ok || len(limit) == 0 { return 0, nil } return strconv.ParseUint(limit[0], 10, 64) }
[ "func", "LimitFromMetadata", "(", "md", "metadata", ".", "MD", ")", "(", "uint64", ",", "error", ")", "{", "limit", ",", "ok", ":=", "md", "[", "\"limit\"", "]", "\n", "if", "!", "ok", "||", "len", "(", "limit", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "return", "strconv", ".", "ParseUint", "(", "limit", "[", "0", "]", ",", "10", ",", "64", ")", "\n", "}" ]
// LimitFromMetadata gets the limit from the metadata
[ "LimitFromMetadata", "gets", "the", "limit", "from", "the", "metadata" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L121-L127
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
OffsetFromMetadata
func OffsetFromMetadata(md metadata.MD) (uint64, error) { offset, ok := md["offset"] if !ok || len(offset) == 0 { return 0, nil } return strconv.ParseUint(offset[0], 10, 64) }
go
func OffsetFromMetadata(md metadata.MD) (uint64, error) { offset, ok := md["offset"] if !ok || len(offset) == 0 { return 0, nil } return strconv.ParseUint(offset[0], 10, 64) }
[ "func", "OffsetFromMetadata", "(", "md", "metadata", ".", "MD", ")", "(", "uint64", ",", "error", ")", "{", "offset", ",", "ok", ":=", "md", "[", "\"offset\"", "]", "\n", "if", "!", "ok", "||", "len", "(", "offset", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "return", "strconv", ".", "ParseUint", "(", "offset", "[", "0", "]", ",", "10", ",", "64", ")", "\n", "}" ]
// OffsetFromMetadata gets the offset from the metadata
[ "OffsetFromMetadata", "gets", "the", "offset", "from", "the", "metadata" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L130-L136
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
LimitAndOffsetFromIncomingContext
func LimitAndOffsetFromIncomingContext(ctx context.Context) (limit, offset uint64, err error) { md := MetadataFromIncomingContext(ctx) limit, err = LimitFromMetadata(md) if err != nil { return 0, 0, err } offset, err = OffsetFromMetadata(md) if err != nil { return 0, 0, err } return limit, offset, nil }
go
func LimitAndOffsetFromIncomingContext(ctx context.Context) (limit, offset uint64, err error) { md := MetadataFromIncomingContext(ctx) limit, err = LimitFromMetadata(md) if err != nil { return 0, 0, err } offset, err = OffsetFromMetadata(md) if err != nil { return 0, 0, err } return limit, offset, nil }
[ "func", "LimitAndOffsetFromIncomingContext", "(", "ctx", "context", ".", "Context", ")", "(", "limit", ",", "offset", "uint64", ",", "err", "error", ")", "{", "md", ":=", "MetadataFromIncomingContext", "(", "ctx", ")", "\n", "limit", ",", "err", "=", "LimitFromMetadata", "(", "md", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "offset", ",", "err", "=", "OffsetFromMetadata", "(", "md", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "return", "limit", ",", "offset", ",", "nil", "\n", "}" ]
// LimitAndOffsetFromIncomingContext gets the limit and offset from the incoming context
[ "LimitAndOffsetFromIncomingContext", "gets", "the", "limit", "and", "offset", "from", "the", "incoming", "context" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L139-L150
test
TheThingsNetwork/go-utils
grpc/ttnctx/context.go
OutgoingContextWithLimitAndOffset
func OutgoingContextWithLimitAndOffset(ctx context.Context, limit, offset uint64) context.Context { var pairs []string if limit != 0 { pairs = append(pairs, "limit", strconv.FormatUint(limit, 10)) } if offset != 0 { pairs = append(pairs, "offset", strconv.FormatUint(offset, 10)) } if len(pairs) == 0 { return ctx } return outgoingContextWithMergedMetadata(ctx, pairs...) }
go
func OutgoingContextWithLimitAndOffset(ctx context.Context, limit, offset uint64) context.Context { var pairs []string if limit != 0 { pairs = append(pairs, "limit", strconv.FormatUint(limit, 10)) } if offset != 0 { pairs = append(pairs, "offset", strconv.FormatUint(offset, 10)) } if len(pairs) == 0 { return ctx } return outgoingContextWithMergedMetadata(ctx, pairs...) }
[ "func", "OutgoingContextWithLimitAndOffset", "(", "ctx", "context", ".", "Context", ",", "limit", ",", "offset", "uint64", ")", "context", ".", "Context", "{", "var", "pairs", "[", "]", "string", "\n", "if", "limit", "!=", "0", "{", "pairs", "=", "append", "(", "pairs", ",", "\"limit\"", ",", "strconv", ".", "FormatUint", "(", "limit", ",", "10", ")", ")", "\n", "}", "\n", "if", "offset", "!=", "0", "{", "pairs", "=", "append", "(", "pairs", ",", "\"offset\"", ",", "strconv", ".", "FormatUint", "(", "offset", ",", "10", ")", ")", "\n", "}", "\n", "if", "len", "(", "pairs", ")", "==", "0", "{", "return", "ctx", "\n", "}", "\n", "return", "outgoingContextWithMergedMetadata", "(", "ctx", ",", "pairs", "...", ")", "\n", "}" ]
// OutgoingContextWithLimitAndOffset returns an outgoing context with the limit and offset
[ "OutgoingContextWithLimitAndOffset", "returns", "an", "outgoing", "context", "with", "the", "limit", "and", "offset" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L153-L165
test
TheThingsNetwork/go-utils
queue/schedule.go
before
func before(i, j ScheduleItem) bool { iEnd := i.Time().UnixNano() + i.Duration().Nanoseconds() jStart := j.Time().UnixNano() if i, ok := i.(ScheduleItemWithTimestamp); ok { if j, ok := j.(ScheduleItemWithTimestamp); ok { iEnd = i.Timestamp() + i.Duration().Nanoseconds() jStart = j.Timestamp() } } return iEnd < jStart }
go
func before(i, j ScheduleItem) bool { iEnd := i.Time().UnixNano() + i.Duration().Nanoseconds() jStart := j.Time().UnixNano() if i, ok := i.(ScheduleItemWithTimestamp); ok { if j, ok := j.(ScheduleItemWithTimestamp); ok { iEnd = i.Timestamp() + i.Duration().Nanoseconds() jStart = j.Timestamp() } } return iEnd < jStart }
[ "func", "before", "(", "i", ",", "j", "ScheduleItem", ")", "bool", "{", "iEnd", ":=", "i", ".", "Time", "(", ")", ".", "UnixNano", "(", ")", "+", "i", ".", "Duration", "(", ")", ".", "Nanoseconds", "(", ")", "\n", "jStart", ":=", "j", ".", "Time", "(", ")", ".", "UnixNano", "(", ")", "\n", "if", "i", ",", "ok", ":=", "i", ".", "(", "ScheduleItemWithTimestamp", ")", ";", "ok", "{", "if", "j", ",", "ok", ":=", "j", ".", "(", "ScheduleItemWithTimestamp", ")", ";", "ok", "{", "iEnd", "=", "i", ".", "Timestamp", "(", ")", "+", "i", ".", "Duration", "(", ")", ".", "Nanoseconds", "(", ")", "\n", "jStart", "=", "j", ".", "Timestamp", "(", ")", "\n", "}", "\n", "}", "\n", "return", "iEnd", "<", "jStart", "\n", "}" ]
// returns true if i before j
[ "returns", "true", "if", "i", "before", "j" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/queue/schedule.go#L67-L77
test
TheThingsNetwork/go-utils
errors/descriptor.go
New
func (err *ErrDescriptor) New(attributes Attributes) Error { if err.Code != NoCode && !err.registered { panic(fmt.Errorf("Error descriptor with code %v was not registered", err.Code)) } return &impl{ message: Format(err.MessageFormat, attributes), code: err.Code, typ: err.Type, attributes: attributes, } }
go
func (err *ErrDescriptor) New(attributes Attributes) Error { if err.Code != NoCode && !err.registered { panic(fmt.Errorf("Error descriptor with code %v was not registered", err.Code)) } return &impl{ message: Format(err.MessageFormat, attributes), code: err.Code, typ: err.Type, attributes: attributes, } }
[ "func", "(", "err", "*", "ErrDescriptor", ")", "New", "(", "attributes", "Attributes", ")", "Error", "{", "if", "err", ".", "Code", "!=", "NoCode", "&&", "!", "err", ".", "registered", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"Error descriptor with code %v was not registered\"", ",", "err", ".", "Code", ")", ")", "\n", "}", "\n", "return", "&", "impl", "{", "message", ":", "Format", "(", "err", ".", "MessageFormat", ",", "attributes", ")", ",", "code", ":", "err", ".", "Code", ",", "typ", ":", "err", ".", "Type", ",", "attributes", ":", "attributes", ",", "}", "\n", "}" ]
// New creates a new error based on the error descriptor
[ "New", "creates", "a", "new", "error", "based", "on", "the", "error", "descriptor" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/descriptor.go#L38-L49
test
TheThingsNetwork/go-utils
log/namespaced/namespaced.go
WithNamespace
func WithNamespace(namespace string, ctx log.Interface) log.Interface { return ctx.WithField(NamespaceKey, namespace) }
go
func WithNamespace(namespace string, ctx log.Interface) log.Interface { return ctx.WithField(NamespaceKey, namespace) }
[ "func", "WithNamespace", "(", "namespace", "string", ",", "ctx", "log", ".", "Interface", ")", "log", ".", "Interface", "{", "return", "ctx", ".", "WithField", "(", "NamespaceKey", ",", "namespace", ")", "\n", "}" ]
// WithNamespace adds a namespace to the logging context
[ "WithNamespace", "adds", "a", "namespace", "to", "the", "logging", "context" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaced.go#L21-L23
test
TheThingsNetwork/go-utils
log/namespaced/namespaced.go
Wrap
func Wrap(ctx log.Interface, namespaces ...string) *Namespaced { return &Namespaced{ Interface: ctx, namespaces: &ns{ namespaces: namespaces, }, } }
go
func Wrap(ctx log.Interface, namespaces ...string) *Namespaced { return &Namespaced{ Interface: ctx, namespaces: &ns{ namespaces: namespaces, }, } }
[ "func", "Wrap", "(", "ctx", "log", ".", "Interface", ",", "namespaces", "...", "string", ")", "*", "Namespaced", "{", "return", "&", "Namespaced", "{", "Interface", ":", "ctx", ",", "namespaces", ":", "&", "ns", "{", "namespaces", ":", "namespaces", ",", "}", ",", "}", "\n", "}" ]
// Wrap wraps the logger in a Namespaced logger and enables the specified // namespaces. See SetNamespaces for information on how to set the namspaces
[ "Wrap", "wraps", "the", "logger", "in", "a", "Namespaced", "logger", "and", "enables", "the", "specified", "namespaces", ".", "See", "SetNamespaces", "for", "information", "on", "how", "to", "set", "the", "namspaces" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaced.go#L27-L34
test
TheThingsNetwork/go-utils
log/namespaced/namespaced.go
WithField
func (n *Namespaced) WithField(k string, v interface{}) log.Interface { if k == NamespaceKey { if str, ok := v.(string); ok { return &Namespaced{ Interface: n.Interface, namespaces: n.namespaces, namespace: str, } } } return &Namespaced{ Interface: n.Interface.WithField(k, v), namespaces: n.namespaces, namespace: n.namespace, } }
go
func (n *Namespaced) WithField(k string, v interface{}) log.Interface { if k == NamespaceKey { if str, ok := v.(string); ok { return &Namespaced{ Interface: n.Interface, namespaces: n.namespaces, namespace: str, } } } return &Namespaced{ Interface: n.Interface.WithField(k, v), namespaces: n.namespaces, namespace: n.namespace, } }
[ "func", "(", "n", "*", "Namespaced", ")", "WithField", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "log", ".", "Interface", "{", "if", "k", "==", "NamespaceKey", "{", "if", "str", ",", "ok", ":=", "v", ".", "(", "string", ")", ";", "ok", "{", "return", "&", "Namespaced", "{", "Interface", ":", "n", ".", "Interface", ",", "namespaces", ":", "n", ".", "namespaces", ",", "namespace", ":", "str", ",", "}", "\n", "}", "\n", "}", "\n", "return", "&", "Namespaced", "{", "Interface", ":", "n", ".", "Interface", ".", "WithField", "(", "k", ",", "v", ")", ",", "namespaces", ":", "n", ".", "namespaces", ",", "namespace", ":", "n", ".", "namespace", ",", "}", "\n", "}" ]
// WithField adds a field to the logger
[ "WithField", "adds", "a", "field", "to", "the", "logger" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaced.go#L52-L68
test
TheThingsNetwork/go-utils
log/namespaced/namespaced.go
WithFields
func (n *Namespaced) WithFields(fields log.Fields) log.Interface { return &Namespaced{ Interface: n.Interface.WithFields(fields), namespaces: n.namespaces, namespace: n.namespace, } }
go
func (n *Namespaced) WithFields(fields log.Fields) log.Interface { return &Namespaced{ Interface: n.Interface.WithFields(fields), namespaces: n.namespaces, namespace: n.namespace, } }
[ "func", "(", "n", "*", "Namespaced", ")", "WithFields", "(", "fields", "log", ".", "Fields", ")", "log", ".", "Interface", "{", "return", "&", "Namespaced", "{", "Interface", ":", "n", ".", "Interface", ".", "WithFields", "(", "fields", ")", ",", "namespaces", ":", "n", ".", "namespaces", ",", "namespace", ":", "n", ".", "namespace", ",", "}", "\n", "}" ]
// WithFields adds multiple fields to the logger
[ "WithFields", "adds", "multiple", "fields", "to", "the", "logger" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaced.go#L71-L77
test
TheThingsNetwork/go-utils
errors/format.go
Format
func Format(format string, values Attributes) string { formatter, err := messageformat.New() if err != nil { return format } fm, err := formatter.Parse(format) if err != nil { return format } fixed := make(map[string]interface{}, len(values)) for k, v := range values { fixed[k] = fix(v) } // todo format unsupported types res, err := fm.FormatMap(fixed) if err != nil { fmt.Println("err", err) return format } return res }
go
func Format(format string, values Attributes) string { formatter, err := messageformat.New() if err != nil { return format } fm, err := formatter.Parse(format) if err != nil { return format } fixed := make(map[string]interface{}, len(values)) for k, v := range values { fixed[k] = fix(v) } // todo format unsupported types res, err := fm.FormatMap(fixed) if err != nil { fmt.Println("err", err) return format } return res }
[ "func", "Format", "(", "format", "string", ",", "values", "Attributes", ")", "string", "{", "formatter", ",", "err", ":=", "messageformat", ".", "New", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "format", "\n", "}", "\n", "fm", ",", "err", ":=", "formatter", ".", "Parse", "(", "format", ")", "\n", "if", "err", "!=", "nil", "{", "return", "format", "\n", "}", "\n", "fixed", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "values", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "values", "{", "fixed", "[", "k", "]", "=", "fix", "(", "v", ")", "\n", "}", "\n", "res", ",", "err", ":=", "fm", ".", "FormatMap", "(", "fixed", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"err\"", ",", "err", ")", "\n", "return", "format", "\n", "}", "\n", "return", "res", "\n", "}" ]
// Format formats the values into the provided string
[ "Format", "formats", "the", "values", "into", "the", "provided", "string" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/format.go#L14-L38
test
TheThingsNetwork/go-utils
errors/format.go
fix
func fix(v interface{}) interface{} { if v == nil { return "<nil>" } switch reflect.TypeOf(v).Kind() { case reflect.Bool: case reflect.Int: case reflect.Int8: case reflect.Int16: case reflect.Int32: case reflect.Int64: case reflect.Uint: case reflect.Uint8: case reflect.Uint16: case reflect.Uint32: case reflect.Uint64: case reflect.Uintptr: case reflect.Float32: case reflect.Float64: return v case reflect.Ptr: // dereference and fix return fix(reflect.ValueOf(v).Elem()) } return fmt.Sprintf("%v", v) }
go
func fix(v interface{}) interface{} { if v == nil { return "<nil>" } switch reflect.TypeOf(v).Kind() { case reflect.Bool: case reflect.Int: case reflect.Int8: case reflect.Int16: case reflect.Int32: case reflect.Int64: case reflect.Uint: case reflect.Uint8: case reflect.Uint16: case reflect.Uint32: case reflect.Uint64: case reflect.Uintptr: case reflect.Float32: case reflect.Float64: return v case reflect.Ptr: // dereference and fix return fix(reflect.ValueOf(v).Elem()) } return fmt.Sprintf("%v", v) }
[ "func", "fix", "(", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "v", "==", "nil", "{", "return", "\"<nil>\"", "\n", "}", "\n", "switch", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Bool", ":", "case", "reflect", ".", "Int", ":", "case", "reflect", ".", "Int8", ":", "case", "reflect", ".", "Int16", ":", "case", "reflect", ".", "Int32", ":", "case", "reflect", ".", "Int64", ":", "case", "reflect", ".", "Uint", ":", "case", "reflect", ".", "Uint8", ":", "case", "reflect", ".", "Uint16", ":", "case", "reflect", ".", "Uint32", ":", "case", "reflect", ".", "Uint64", ":", "case", "reflect", ".", "Uintptr", ":", "case", "reflect", ".", "Float32", ":", "case", "reflect", ".", "Float64", ":", "return", "v", "\n", "case", "reflect", ".", "Ptr", ":", "return", "fix", "(", "reflect", ".", "ValueOf", "(", "v", ")", ".", "Elem", "(", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "v", ")", "\n", "}" ]
// Fix coerces types that cannot be formatted by messageformat to string
[ "Fix", "coerces", "types", "that", "cannot", "be", "formatted", "by", "messageformat", "to", "string" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/format.go#L41-L67
test
TheThingsNetwork/go-utils
errors/grpc.go
GRPCCode
func (t Type) GRPCCode() codes.Code { switch t { case InvalidArgument: return codes.InvalidArgument case OutOfRange: return codes.OutOfRange case NotFound: return codes.NotFound case Conflict: case AlreadyExists: return codes.AlreadyExists case Unauthorized: return codes.Unauthenticated case PermissionDenied: return codes.PermissionDenied case Timeout: return codes.DeadlineExceeded case NotImplemented: return codes.Unimplemented case TemporarilyUnavailable: return codes.Unavailable case PermanentlyUnavailable: return codes.FailedPrecondition case Canceled: return codes.Canceled case ResourceExhausted: return codes.ResourceExhausted case Internal: case Unknown: return codes.Unknown } return codes.Unknown }
go
func (t Type) GRPCCode() codes.Code { switch t { case InvalidArgument: return codes.InvalidArgument case OutOfRange: return codes.OutOfRange case NotFound: return codes.NotFound case Conflict: case AlreadyExists: return codes.AlreadyExists case Unauthorized: return codes.Unauthenticated case PermissionDenied: return codes.PermissionDenied case Timeout: return codes.DeadlineExceeded case NotImplemented: return codes.Unimplemented case TemporarilyUnavailable: return codes.Unavailable case PermanentlyUnavailable: return codes.FailedPrecondition case Canceled: return codes.Canceled case ResourceExhausted: return codes.ResourceExhausted case Internal: case Unknown: return codes.Unknown } return codes.Unknown }
[ "func", "(", "t", "Type", ")", "GRPCCode", "(", ")", "codes", ".", "Code", "{", "switch", "t", "{", "case", "InvalidArgument", ":", "return", "codes", ".", "InvalidArgument", "\n", "case", "OutOfRange", ":", "return", "codes", ".", "OutOfRange", "\n", "case", "NotFound", ":", "return", "codes", ".", "NotFound", "\n", "case", "Conflict", ":", "case", "AlreadyExists", ":", "return", "codes", ".", "AlreadyExists", "\n", "case", "Unauthorized", ":", "return", "codes", ".", "Unauthenticated", "\n", "case", "PermissionDenied", ":", "return", "codes", ".", "PermissionDenied", "\n", "case", "Timeout", ":", "return", "codes", ".", "DeadlineExceeded", "\n", "case", "NotImplemented", ":", "return", "codes", ".", "Unimplemented", "\n", "case", "TemporarilyUnavailable", ":", "return", "codes", ".", "Unavailable", "\n", "case", "PermanentlyUnavailable", ":", "return", "codes", ".", "FailedPrecondition", "\n", "case", "Canceled", ":", "return", "codes", ".", "Canceled", "\n", "case", "ResourceExhausted", ":", "return", "codes", ".", "ResourceExhausted", "\n", "case", "Internal", ":", "case", "Unknown", ":", "return", "codes", ".", "Unknown", "\n", "}", "\n", "return", "codes", ".", "Unknown", "\n", "}" ]
// GRPCCode returns the corresponding http status code from an error type
[ "GRPCCode", "returns", "the", "corresponding", "http", "status", "code", "from", "an", "error", "type" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L15-L48
test
TheThingsNetwork/go-utils
errors/grpc.go
GRPCCodeToType
func GRPCCodeToType(code codes.Code) Type { switch code { case codes.InvalidArgument: return InvalidArgument case codes.OutOfRange: return OutOfRange case codes.NotFound: return NotFound case codes.AlreadyExists: return AlreadyExists case codes.Unauthenticated: return Unauthorized case codes.PermissionDenied: return PermissionDenied case codes.DeadlineExceeded: return Timeout case codes.Unimplemented: return NotImplemented case codes.Unavailable: return TemporarilyUnavailable case codes.FailedPrecondition: return PermanentlyUnavailable case codes.Canceled: return Canceled case codes.ResourceExhausted: return ResourceExhausted case codes.Unknown: return Unknown } return Unknown }
go
func GRPCCodeToType(code codes.Code) Type { switch code { case codes.InvalidArgument: return InvalidArgument case codes.OutOfRange: return OutOfRange case codes.NotFound: return NotFound case codes.AlreadyExists: return AlreadyExists case codes.Unauthenticated: return Unauthorized case codes.PermissionDenied: return PermissionDenied case codes.DeadlineExceeded: return Timeout case codes.Unimplemented: return NotImplemented case codes.Unavailable: return TemporarilyUnavailable case codes.FailedPrecondition: return PermanentlyUnavailable case codes.Canceled: return Canceled case codes.ResourceExhausted: return ResourceExhausted case codes.Unknown: return Unknown } return Unknown }
[ "func", "GRPCCodeToType", "(", "code", "codes", ".", "Code", ")", "Type", "{", "switch", "code", "{", "case", "codes", ".", "InvalidArgument", ":", "return", "InvalidArgument", "\n", "case", "codes", ".", "OutOfRange", ":", "return", "OutOfRange", "\n", "case", "codes", ".", "NotFound", ":", "return", "NotFound", "\n", "case", "codes", ".", "AlreadyExists", ":", "return", "AlreadyExists", "\n", "case", "codes", ".", "Unauthenticated", ":", "return", "Unauthorized", "\n", "case", "codes", ".", "PermissionDenied", ":", "return", "PermissionDenied", "\n", "case", "codes", ".", "DeadlineExceeded", ":", "return", "Timeout", "\n", "case", "codes", ".", "Unimplemented", ":", "return", "NotImplemented", "\n", "case", "codes", ".", "Unavailable", ":", "return", "TemporarilyUnavailable", "\n", "case", "codes", ".", "FailedPrecondition", ":", "return", "PermanentlyUnavailable", "\n", "case", "codes", ".", "Canceled", ":", "return", "Canceled", "\n", "case", "codes", ".", "ResourceExhausted", ":", "return", "ResourceExhausted", "\n", "case", "codes", ".", "Unknown", ":", "return", "Unknown", "\n", "}", "\n", "return", "Unknown", "\n", "}" ]
// GRPCCodeToType converts the gRPC error code to an error type or returns the // Unknown type if not possible.
[ "GRPCCodeToType", "converts", "the", "gRPC", "error", "code", "to", "an", "error", "type", "or", "returns", "the", "Unknown", "type", "if", "not", "possible", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L52-L82
test
TheThingsNetwork/go-utils
errors/grpc.go
GRPCCode
func GRPCCode(err error) codes.Code { e, ok := err.(Error) if ok { return e.Type().GRPCCode() } return grpc.Code(err) }
go
func GRPCCode(err error) codes.Code { e, ok := err.(Error) if ok { return e.Type().GRPCCode() } return grpc.Code(err) }
[ "func", "GRPCCode", "(", "err", "error", ")", "codes", ".", "Code", "{", "e", ",", "ok", ":=", "err", ".", "(", "Error", ")", "\n", "if", "ok", "{", "return", "e", ".", "Type", "(", ")", ".", "GRPCCode", "(", ")", "\n", "}", "\n", "return", "grpc", ".", "Code", "(", "err", ")", "\n", "}" ]
// GRPCCode returns the corresponding http status code from an error
[ "GRPCCode", "returns", "the", "corresponding", "http", "status", "code", "from", "an", "error" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L85-L92
test
TheThingsNetwork/go-utils
errors/grpc.go
FromGRPC
func FromGRPC(in error) Error { out := &impl{ message: grpc.ErrorDesc(in), typ: GRPCCodeToType(grpc.Code(in)), code: NoCode, } matches := grpcMessageFormat.FindStringSubmatch(in.Error()) if len(matches) < 4 { return out } out.message = matches[1] out.code = parseCode(matches[2]) _ = json.Unmarshal([]byte(matches[3]), &out.attributes) got := Get(Code(out.code)) if got == nil { return out } return got.New(out.attributes) }
go
func FromGRPC(in error) Error { out := &impl{ message: grpc.ErrorDesc(in), typ: GRPCCodeToType(grpc.Code(in)), code: NoCode, } matches := grpcMessageFormat.FindStringSubmatch(in.Error()) if len(matches) < 4 { return out } out.message = matches[1] out.code = parseCode(matches[2]) _ = json.Unmarshal([]byte(matches[3]), &out.attributes) got := Get(Code(out.code)) if got == nil { return out } return got.New(out.attributes) }
[ "func", "FromGRPC", "(", "in", "error", ")", "Error", "{", "out", ":=", "&", "impl", "{", "message", ":", "grpc", ".", "ErrorDesc", "(", "in", ")", ",", "typ", ":", "GRPCCodeToType", "(", "grpc", ".", "Code", "(", "in", ")", ")", ",", "code", ":", "NoCode", ",", "}", "\n", "matches", ":=", "grpcMessageFormat", ".", "FindStringSubmatch", "(", "in", ".", "Error", "(", ")", ")", "\n", "if", "len", "(", "matches", ")", "<", "4", "{", "return", "out", "\n", "}", "\n", "out", ".", "message", "=", "matches", "[", "1", "]", "\n", "out", ".", "code", "=", "parseCode", "(", "matches", "[", "2", "]", ")", "\n", "_", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "matches", "[", "3", "]", ")", ",", "&", "out", ".", "attributes", ")", "\n", "got", ":=", "Get", "(", "Code", "(", "out", ".", "code", ")", ")", "\n", "if", "got", "==", "nil", "{", "return", "out", "\n", "}", "\n", "return", "got", ".", "New", "(", "out", ".", "attributes", ")", "\n", "}" ]
// FromGRPC parses a gRPC error and returns an Error
[ "FromGRPC", "parses", "a", "gRPC", "error", "and", "returns", "an", "Error" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L98-L121
test
TheThingsNetwork/go-utils
errors/grpc.go
ToGRPC
func ToGRPC(in error) error { if err, ok := in.(Error); ok { attrs, _ := json.Marshal(err.Attributes()) return grpc.Errorf(err.Type().GRPCCode(), format, err.Error(), err.Code(), attrs) } return grpc.Errorf(codes.Unknown, in.Error()) }
go
func ToGRPC(in error) error { if err, ok := in.(Error); ok { attrs, _ := json.Marshal(err.Attributes()) return grpc.Errorf(err.Type().GRPCCode(), format, err.Error(), err.Code(), attrs) } return grpc.Errorf(codes.Unknown, in.Error()) }
[ "func", "ToGRPC", "(", "in", "error", ")", "error", "{", "if", "err", ",", "ok", ":=", "in", ".", "(", "Error", ")", ";", "ok", "{", "attrs", ",", "_", ":=", "json", ".", "Marshal", "(", "err", ".", "Attributes", "(", ")", ")", "\n", "return", "grpc", ".", "Errorf", "(", "err", ".", "Type", "(", ")", ".", "GRPCCode", "(", ")", ",", "format", ",", "err", ".", "Error", "(", ")", ",", "err", ".", "Code", "(", ")", ",", "attrs", ")", "\n", "}", "\n", "return", "grpc", ".", "Errorf", "(", "codes", ".", "Unknown", ",", "in", ".", "Error", "(", ")", ")", "\n", "}" ]
// ToGRPC turns an error into a gRPC error
[ "ToGRPC", "turns", "an", "error", "into", "a", "gRPC", "error" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/grpc.go#L124-L131
test
TheThingsNetwork/go-utils
log/namespaced/namespaces.go
IsEnabled
func (n *ns) IsEnabled(namespace string) bool { n.RLock() defer n.RUnlock() if namespace == "" { return true } hasStar := false included := false for _, ns := range n.namespaces { // if the namspace is negated, it can never be enabled if ns == negate(namespace) { return false } // if the namespace is explicitly enabled, mark it as included if ns == namespace { included = true } // mark that we have a * if ns == "*" { hasStar = true } } // non-mentioned namespaces are only enabled if we got the catch-all * return hasStar || included }
go
func (n *ns) IsEnabled(namespace string) bool { n.RLock() defer n.RUnlock() if namespace == "" { return true } hasStar := false included := false for _, ns := range n.namespaces { // if the namspace is negated, it can never be enabled if ns == negate(namespace) { return false } // if the namespace is explicitly enabled, mark it as included if ns == namespace { included = true } // mark that we have a * if ns == "*" { hasStar = true } } // non-mentioned namespaces are only enabled if we got the catch-all * return hasStar || included }
[ "func", "(", "n", "*", "ns", ")", "IsEnabled", "(", "namespace", "string", ")", "bool", "{", "n", ".", "RLock", "(", ")", "\n", "defer", "n", ".", "RUnlock", "(", ")", "\n", "if", "namespace", "==", "\"\"", "{", "return", "true", "\n", "}", "\n", "hasStar", ":=", "false", "\n", "included", ":=", "false", "\n", "for", "_", ",", "ns", ":=", "range", "n", ".", "namespaces", "{", "if", "ns", "==", "negate", "(", "namespace", ")", "{", "return", "false", "\n", "}", "\n", "if", "ns", "==", "namespace", "{", "included", "=", "true", "\n", "}", "\n", "if", "ns", "==", "\"*\"", "{", "hasStar", "=", "true", "\n", "}", "\n", "}", "\n", "return", "hasStar", "||", "included", "\n", "}" ]
// isEnabled checks wether or not the namespace is enabled
[ "isEnabled", "checks", "wether", "or", "not", "the", "namespace", "is", "enabled" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaces.go#L16-L46
test
TheThingsNetwork/go-utils
log/namespaced/namespaces.go
Set
func (n *ns) Set(namespaces []string) { n.Lock() defer n.Unlock() n.namespaces = namespaces }
go
func (n *ns) Set(namespaces []string) { n.Lock() defer n.Unlock() n.namespaces = namespaces }
[ "func", "(", "n", "*", "ns", ")", "Set", "(", "namespaces", "[", "]", "string", ")", "{", "n", ".", "Lock", "(", ")", "\n", "defer", "n", ".", "Unlock", "(", ")", "\n", "n", ".", "namespaces", "=", "namespaces", "\n", "}" ]
// Set updates the namespaces
[ "Set", "updates", "the", "namespaces" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaces.go#L49-L53
test
TheThingsNetwork/go-utils
errors/cause.go
Cause
func Cause(err Error) error { attributes := err.Attributes() if attributes == nil { return nil } cause, ok := attributes[causeKey] if !ok { return nil } switch v := cause.(type) { case error: return v case string: return errors.New(v) default: return nil } }
go
func Cause(err Error) error { attributes := err.Attributes() if attributes == nil { return nil } cause, ok := attributes[causeKey] if !ok { return nil } switch v := cause.(type) { case error: return v case string: return errors.New(v) default: return nil } }
[ "func", "Cause", "(", "err", "Error", ")", "error", "{", "attributes", ":=", "err", ".", "Attributes", "(", ")", "\n", "if", "attributes", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "cause", ",", "ok", ":=", "attributes", "[", "causeKey", "]", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "switch", "v", ":=", "cause", ".", "(", "type", ")", "{", "case", "error", ":", "return", "v", "\n", "case", "string", ":", "return", "errors", ".", "New", "(", "v", ")", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// Cause returns the cause of an error
[ "Cause", "returns", "the", "cause", "of", "an", "error" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/cause.go#L16-L35
test
TheThingsNetwork/go-utils
errors/code.go
parseCode
func parseCode(str string) Code { code, err := strconv.Atoi(str) if err != nil { return Code(0) } return Code(code) }
go
func parseCode(str string) Code { code, err := strconv.Atoi(str) if err != nil { return Code(0) } return Code(code) }
[ "func", "parseCode", "(", "str", "string", ")", "Code", "{", "code", ",", "err", ":=", "strconv", ".", "Atoi", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Code", "(", "0", ")", "\n", "}", "\n", "return", "Code", "(", "code", ")", "\n", "}" ]
// pareCode parses a string into a Code or returns 0 if the parse failed
[ "pareCode", "parses", "a", "string", "into", "a", "Code", "or", "returns", "0", "if", "the", "parse", "failed" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/code.go#L23-L29
test
TheThingsNetwork/go-utils
grpc/rpcerror/grpc.go
UnaryServerInterceptor
func UnaryServerInterceptor(fn ConvertFunc) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { resp, err = handler(ctx, req) return resp, fn(err) } }
go
func UnaryServerInterceptor(fn ConvertFunc) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { resp, err = handler(ctx, req) return resp, fn(err) } }
[ "func", "UnaryServerInterceptor", "(", "fn", "ConvertFunc", ")", "grpc", ".", "UnaryServerInterceptor", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "resp", "interface", "{", "}", ",", "err", "error", ")", "{", "resp", ",", "err", "=", "handler", "(", "ctx", ",", "req", ")", "\n", "return", "resp", ",", "fn", "(", "err", ")", "\n", "}", "\n", "}" ]
// UnaryServerInterceptor applies fn to errors returned by server.
[ "UnaryServerInterceptor", "applies", "fn", "to", "errors", "returned", "by", "server", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpcerror/grpc.go#L15-L20
test
TheThingsNetwork/go-utils
grpc/rpcerror/grpc.go
StreamServerInterceptor
func StreamServerInterceptor(fn ConvertFunc) grpc.StreamServerInterceptor { return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { return fn(handler(srv, ss)) } }
go
func StreamServerInterceptor(fn ConvertFunc) grpc.StreamServerInterceptor { return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { return fn(handler(srv, ss)) } }
[ "func", "StreamServerInterceptor", "(", "fn", "ConvertFunc", ")", "grpc", ".", "StreamServerInterceptor", "{", "return", "func", "(", "srv", "interface", "{", "}", ",", "ss", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "(", "err", "error", ")", "{", "return", "fn", "(", "handler", "(", "srv", ",", "ss", ")", ")", "\n", "}", "\n", "}" ]
// StreamServerInterceptor applies fn to errors returned by server.
[ "StreamServerInterceptor", "applies", "fn", "to", "errors", "returned", "by", "server", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpcerror/grpc.go#L23-L27
test
TheThingsNetwork/go-utils
grpc/rpcerror/grpc.go
UnaryClientInterceptor
func UnaryClientInterceptor(fn ConvertFunc) grpc.UnaryClientInterceptor { return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) { return fn(invoker(ctx, method, req, reply, cc, opts...)) } }
go
func UnaryClientInterceptor(fn ConvertFunc) grpc.UnaryClientInterceptor { return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) { return fn(invoker(ctx, method, req, reply, cc, opts...)) } }
[ "func", "UnaryClientInterceptor", "(", "fn", "ConvertFunc", ")", "grpc", ".", "UnaryClientInterceptor", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "method", "string", ",", "req", ",", "reply", "interface", "{", "}", ",", "cc", "*", "grpc", ".", "ClientConn", ",", "invoker", "grpc", ".", "UnaryInvoker", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "err", "error", ")", "{", "return", "fn", "(", "invoker", "(", "ctx", ",", "method", ",", "req", ",", "reply", ",", "cc", ",", "opts", "...", ")", ")", "\n", "}", "\n", "}" ]
// UnaryClientInterceptor applies fn to errors recieved by client.
[ "UnaryClientInterceptor", "applies", "fn", "to", "errors", "recieved", "by", "client", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpcerror/grpc.go#L30-L34
test
TheThingsNetwork/go-utils
grpc/rpcerror/grpc.go
StreamClientInterceptor
func StreamClientInterceptor(fn ConvertFunc) grpc.StreamClientInterceptor { return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) { stream, err = streamer(ctx, desc, cc, method, opts...) return stream, fn(err) } }
go
func StreamClientInterceptor(fn ConvertFunc) grpc.StreamClientInterceptor { return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) { stream, err = streamer(ctx, desc, cc, method, opts...) return stream, fn(err) } }
[ "func", "StreamClientInterceptor", "(", "fn", "ConvertFunc", ")", "grpc", ".", "StreamClientInterceptor", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "desc", "*", "grpc", ".", "StreamDesc", ",", "cc", "*", "grpc", ".", "ClientConn", ",", "method", "string", ",", "streamer", "grpc", ".", "Streamer", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "stream", "grpc", ".", "ClientStream", ",", "err", "error", ")", "{", "stream", ",", "err", "=", "streamer", "(", "ctx", ",", "desc", ",", "cc", ",", "method", ",", "opts", "...", ")", "\n", "return", "stream", ",", "fn", "(", "err", ")", "\n", "}", "\n", "}" ]
// StreamClientInterceptor applies fn to errors recieved by client.
[ "StreamClientInterceptor", "applies", "fn", "to", "errors", "recieved", "by", "client", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpcerror/grpc.go#L37-L42
test
TheThingsNetwork/go-utils
grpc/restartstream/restart.go
Interceptor
func Interceptor(settings Settings) grpc.StreamClientInterceptor { return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) { s := &restartingStream{ log: log.Get().WithField("method", method), ctx: ctx, desc: desc, cc: cc, method: method, streamer: streamer, opts: opts, retryableCodes: settings.RetryableCodes, backoff: settings.Backoff, retries: -1, } err = s.start() stream = s return } }
go
func Interceptor(settings Settings) grpc.StreamClientInterceptor { return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) { s := &restartingStream{ log: log.Get().WithField("method", method), ctx: ctx, desc: desc, cc: cc, method: method, streamer: streamer, opts: opts, retryableCodes: settings.RetryableCodes, backoff: settings.Backoff, retries: -1, } err = s.start() stream = s return } }
[ "func", "Interceptor", "(", "settings", "Settings", ")", "grpc", ".", "StreamClientInterceptor", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "desc", "*", "grpc", ".", "StreamDesc", ",", "cc", "*", "grpc", ".", "ClientConn", ",", "method", "string", ",", "streamer", "grpc", ".", "Streamer", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "stream", "grpc", ".", "ClientStream", ",", "err", "error", ")", "{", "s", ":=", "&", "restartingStream", "{", "log", ":", "log", ".", "Get", "(", ")", ".", "WithField", "(", "\"method\"", ",", "method", ")", ",", "ctx", ":", "ctx", ",", "desc", ":", "desc", ",", "cc", ":", "cc", ",", "method", ":", "method", ",", "streamer", ":", "streamer", ",", "opts", ":", "opts", ",", "retryableCodes", ":", "settings", ".", "RetryableCodes", ",", "backoff", ":", "settings", ".", "Backoff", ",", "retries", ":", "-", "1", ",", "}", "\n", "err", "=", "s", ".", "start", "(", ")", "\n", "stream", "=", "s", "\n", "return", "\n", "}", "\n", "}" ]
// Interceptor automatically restarts streams on non-expected errors // To do so, the application should create a for-loop around RecvMsg, which // returns the same errors that are received from the server. // // An io.EOF indicates the end of the stream // // To stop the reconnect behaviour, you have to cancel the context
[ "Interceptor", "automatically", "restarts", "streams", "on", "non", "-", "expected", "errors", "To", "do", "so", "the", "application", "should", "create", "a", "for", "-", "loop", "around", "RecvMsg", "which", "returns", "the", "same", "errors", "that", "are", "received", "from", "the", "server", ".", "An", "io", ".", "EOF", "indicates", "the", "end", "of", "the", "stream", "To", "stop", "the", "reconnect", "behaviour", "you", "have", "to", "cancel", "the", "context" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/restartstream/restart.go#L200-L222
test
TheThingsNetwork/go-utils
log/logrus/logrus.go
Wrap
func Wrap(logger *logrus.Logger) log.Interface { return &logrusEntryWrapper{logrus.NewEntry(logger)} }
go
func Wrap(logger *logrus.Logger) log.Interface { return &logrusEntryWrapper{logrus.NewEntry(logger)} }
[ "func", "Wrap", "(", "logger", "*", "logrus", ".", "Logger", ")", "log", ".", "Interface", "{", "return", "&", "logrusEntryWrapper", "{", "logrus", ".", "NewEntry", "(", "logger", ")", "}", "\n", "}" ]
// Wrap logrus.Logger
[ "Wrap", "logrus", ".", "Logger" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/logrus/logrus.go#L14-L16
test
TheThingsNetwork/go-utils
rate/rate.go
NewCounter
func NewCounter(bucketSize, retention time.Duration) Counter { return &counter{ bucketSize: bucketSize, retention: retention, buckets: make([]uint64, 2*retention/bucketSize), } }
go
func NewCounter(bucketSize, retention time.Duration) Counter { return &counter{ bucketSize: bucketSize, retention: retention, buckets: make([]uint64, 2*retention/bucketSize), } }
[ "func", "NewCounter", "(", "bucketSize", ",", "retention", "time", ".", "Duration", ")", "Counter", "{", "return", "&", "counter", "{", "bucketSize", ":", "bucketSize", ",", "retention", ":", "retention", ",", "buckets", ":", "make", "(", "[", "]", "uint64", ",", "2", "*", "retention", "/", "bucketSize", ")", ",", "}", "\n", "}" ]
// NewCounter returns a new rate counter with the given bucket size and retention
[ "NewCounter", "returns", "a", "new", "rate", "counter", "with", "the", "given", "bucket", "size", "and", "retention" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/rate/rate.go#L27-L33
test
TheThingsNetwork/go-utils
rate/rate.go
NewRedisCounter
func NewRedisCounter(client *redis.Client, key string, bucketSize, retention time.Duration) Counter { return &redisCounter{ client: client, key: key, bucketSize: bucketSize, retention: retention, } }
go
func NewRedisCounter(client *redis.Client, key string, bucketSize, retention time.Duration) Counter { return &redisCounter{ client: client, key: key, bucketSize: bucketSize, retention: retention, } }
[ "func", "NewRedisCounter", "(", "client", "*", "redis", ".", "Client", ",", "key", "string", ",", "bucketSize", ",", "retention", "time", ".", "Duration", ")", "Counter", "{", "return", "&", "redisCounter", "{", "client", ":", "client", ",", "key", ":", "key", ",", "bucketSize", ":", "bucketSize", ",", "retention", ":", "retention", ",", "}", "\n", "}" ]
// NewRedisCounter returns a new redis-based counter
[ "NewRedisCounter", "returns", "a", "new", "redis", "-", "based", "counter" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/rate/rate.go#L97-L104
test
TheThingsNetwork/go-utils
rate/rate.go
NewLimiter
func NewLimiter(counter Counter, duration time.Duration, limit uint64) Limiter { return &limiter{ Counter: counter, duration: duration, limit: limit, } }
go
func NewLimiter(counter Counter, duration time.Duration, limit uint64) Limiter { return &limiter{ Counter: counter, duration: duration, limit: limit, } }
[ "func", "NewLimiter", "(", "counter", "Counter", ",", "duration", "time", ".", "Duration", ",", "limit", "uint64", ")", "Limiter", "{", "return", "&", "limiter", "{", "Counter", ":", "counter", ",", "duration", ":", "duration", ",", "limit", ":", "limit", ",", "}", "\n", "}" ]
// NewLimiter returns a new limiter
[ "NewLimiter", "returns", "a", "new", "limiter" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/rate/rate.go#L166-L172
test
TheThingsNetwork/go-utils
grpc/auth/auth.go
WithInsecure
func (c *TokenCredentials) WithInsecure() *TokenCredentials { return &TokenCredentials{token: c.token, tokenFunc: c.tokenFunc, allowInsecure: true} }
go
func (c *TokenCredentials) WithInsecure() *TokenCredentials { return &TokenCredentials{token: c.token, tokenFunc: c.tokenFunc, allowInsecure: true} }
[ "func", "(", "c", "*", "TokenCredentials", ")", "WithInsecure", "(", ")", "*", "TokenCredentials", "{", "return", "&", "TokenCredentials", "{", "token", ":", "c", ".", "token", ",", "tokenFunc", ":", "c", ".", "tokenFunc", ",", "allowInsecure", ":", "true", "}", "\n", "}" ]
// WithInsecure returns a copy of the TokenCredentials, allowing insecure transport
[ "WithInsecure", "returns", "a", "copy", "of", "the", "TokenCredentials", "allowing", "insecure", "transport" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/auth/auth.go#L23-L25
test
TheThingsNetwork/go-utils
grpc/auth/auth.go
WithTokenFunc
func WithTokenFunc(k string, tokenFunc func(v string) string) *TokenCredentials { return &TokenCredentials{ tokenFunc: tokenFunc, tokenFuncKey: k, } }
go
func WithTokenFunc(k string, tokenFunc func(v string) string) *TokenCredentials { return &TokenCredentials{ tokenFunc: tokenFunc, tokenFuncKey: k, } }
[ "func", "WithTokenFunc", "(", "k", "string", ",", "tokenFunc", "func", "(", "v", "string", ")", "string", ")", "*", "TokenCredentials", "{", "return", "&", "TokenCredentials", "{", "tokenFunc", ":", "tokenFunc", ",", "tokenFuncKey", ":", "k", ",", "}", "\n", "}" ]
// WithTokenFunc returns TokenCredentials that execute the tokenFunc on each request // The value of v sent to the tokenFunk is the MD value of the supplied k
[ "WithTokenFunc", "returns", "TokenCredentials", "that", "execute", "the", "tokenFunc", "on", "each", "request", "The", "value", "of", "v", "sent", "to", "the", "tokenFunk", "is", "the", "MD", "value", "of", "the", "supplied", "k" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/auth/auth.go#L36-L41
test
TheThingsNetwork/go-utils
grpc/auth/auth.go
GetRequestMetadata
func (c *TokenCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { md := ttnctx.MetadataFromOutgoingContext(ctx) token, _ := ttnctx.TokenFromMetadata(md) if token != "" { return map[string]string{tokenKey: token}, nil } if c.tokenFunc != nil { var k string if v, ok := md[c.tokenFuncKey]; ok && len(v) > 0 { k = v[0] } return map[string]string{tokenKey: c.tokenFunc(k)}, nil } if c.token != "" { return map[string]string{tokenKey: c.token}, nil } return map[string]string{tokenKey: ""}, nil }
go
func (c *TokenCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { md := ttnctx.MetadataFromOutgoingContext(ctx) token, _ := ttnctx.TokenFromMetadata(md) if token != "" { return map[string]string{tokenKey: token}, nil } if c.tokenFunc != nil { var k string if v, ok := md[c.tokenFuncKey]; ok && len(v) > 0 { k = v[0] } return map[string]string{tokenKey: c.tokenFunc(k)}, nil } if c.token != "" { return map[string]string{tokenKey: c.token}, nil } return map[string]string{tokenKey: ""}, nil }
[ "func", "(", "c", "*", "TokenCredentials", ")", "GetRequestMetadata", "(", "ctx", "context", ".", "Context", ",", "uri", "...", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "md", ":=", "ttnctx", ".", "MetadataFromOutgoingContext", "(", "ctx", ")", "\n", "token", ",", "_", ":=", "ttnctx", ".", "TokenFromMetadata", "(", "md", ")", "\n", "if", "token", "!=", "\"\"", "{", "return", "map", "[", "string", "]", "string", "{", "tokenKey", ":", "token", "}", ",", "nil", "\n", "}", "\n", "if", "c", ".", "tokenFunc", "!=", "nil", "{", "var", "k", "string", "\n", "if", "v", ",", "ok", ":=", "md", "[", "c", ".", "tokenFuncKey", "]", ";", "ok", "&&", "len", "(", "v", ")", ">", "0", "{", "k", "=", "v", "[", "0", "]", "\n", "}", "\n", "return", "map", "[", "string", "]", "string", "{", "tokenKey", ":", "c", ".", "tokenFunc", "(", "k", ")", "}", ",", "nil", "\n", "}", "\n", "if", "c", ".", "token", "!=", "\"\"", "{", "return", "map", "[", "string", "]", "string", "{", "tokenKey", ":", "c", ".", "token", "}", ",", "nil", "\n", "}", "\n", "return", "map", "[", "string", "]", "string", "{", "tokenKey", ":", "\"\"", "}", ",", "nil", "\n", "}" ]
// GetRequestMetadata implements credentials.PerRPCCredentials
[ "GetRequestMetadata", "implements", "credentials", ".", "PerRPCCredentials" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/auth/auth.go#L47-L64
test
TheThingsNetwork/go-utils
grpc/rpclog/fields.go
FieldsFromIncomingContext
func FieldsFromIncomingContext(ctx context.Context) ttnlog.Fields { fields := make(fieldMap) if peer, ok := peer.FromContext(ctx); ok { fields.addFromPeer(peer) } if md, ok := metadata.FromIncomingContext(ctx); ok { fields.addFromMD(md) } return fields.LogFields() }
go
func FieldsFromIncomingContext(ctx context.Context) ttnlog.Fields { fields := make(fieldMap) if peer, ok := peer.FromContext(ctx); ok { fields.addFromPeer(peer) } if md, ok := metadata.FromIncomingContext(ctx); ok { fields.addFromMD(md) } return fields.LogFields() }
[ "func", "FieldsFromIncomingContext", "(", "ctx", "context", ".", "Context", ")", "ttnlog", ".", "Fields", "{", "fields", ":=", "make", "(", "fieldMap", ")", "\n", "if", "peer", ",", "ok", ":=", "peer", ".", "FromContext", "(", "ctx", ")", ";", "ok", "{", "fields", ".", "addFromPeer", "(", "peer", ")", "\n", "}", "\n", "if", "md", ",", "ok", ":=", "metadata", ".", "FromIncomingContext", "(", "ctx", ")", ";", "ok", "{", "fields", ".", "addFromMD", "(", "md", ")", "\n", "}", "\n", "return", "fields", ".", "LogFields", "(", ")", "\n", "}" ]
// FieldsFromIncomingContext returns peer information and MDLogFields from the given context
[ "FieldsFromIncomingContext", "returns", "peer", "information", "and", "MDLogFields", "from", "the", "given", "context" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpclog/fields.go#L68-L77
test
TheThingsNetwork/go-utils
errors/type.go
String
func (t Type) String() string { switch t { case Unknown: return "Unknown" case Internal: return "Internal" case InvalidArgument: return "Invalid argument" case OutOfRange: return "Out of range" case NotFound: return "Not found" case Conflict: return "Conflict" case AlreadyExists: return "Already exists" case Unauthorized: return "Unauthorized" case PermissionDenied: return "Permission denied" case Timeout: return "Timeout" case NotImplemented: return "Not implemented" case TemporarilyUnavailable: return "Temporarily unavailable" case PermanentlyUnavailable: return "Permanently unavailable" case Canceled: return "Canceled" case ResourceExhausted: return "Resource exhausted" default: return "Unknown" } }
go
func (t Type) String() string { switch t { case Unknown: return "Unknown" case Internal: return "Internal" case InvalidArgument: return "Invalid argument" case OutOfRange: return "Out of range" case NotFound: return "Not found" case Conflict: return "Conflict" case AlreadyExists: return "Already exists" case Unauthorized: return "Unauthorized" case PermissionDenied: return "Permission denied" case Timeout: return "Timeout" case NotImplemented: return "Not implemented" case TemporarilyUnavailable: return "Temporarily unavailable" case PermanentlyUnavailable: return "Permanently unavailable" case Canceled: return "Canceled" case ResourceExhausted: return "Resource exhausted" default: return "Unknown" } }
[ "func", "(", "t", "Type", ")", "String", "(", ")", "string", "{", "switch", "t", "{", "case", "Unknown", ":", "return", "\"Unknown\"", "\n", "case", "Internal", ":", "return", "\"Internal\"", "\n", "case", "InvalidArgument", ":", "return", "\"Invalid argument\"", "\n", "case", "OutOfRange", ":", "return", "\"Out of range\"", "\n", "case", "NotFound", ":", "return", "\"Not found\"", "\n", "case", "Conflict", ":", "return", "\"Conflict\"", "\n", "case", "AlreadyExists", ":", "return", "\"Already exists\"", "\n", "case", "Unauthorized", ":", "return", "\"Unauthorized\"", "\n", "case", "PermissionDenied", ":", "return", "\"Permission denied\"", "\n", "case", "Timeout", ":", "return", "\"Timeout\"", "\n", "case", "NotImplemented", ":", "return", "\"Not implemented\"", "\n", "case", "TemporarilyUnavailable", ":", "return", "\"Temporarily unavailable\"", "\n", "case", "PermanentlyUnavailable", ":", "return", "\"Permanently unavailable\"", "\n", "case", "Canceled", ":", "return", "\"Canceled\"", "\n", "case", "ResourceExhausted", ":", "return", "\"Resource exhausted\"", "\n", "default", ":", "return", "\"Unknown\"", "\n", "}", "\n", "}" ]
// String implements stringer
[ "String", "implements", "stringer" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/type.go#L73-L108
test
TheThingsNetwork/go-utils
errors/type.go
UnmarshalText
func (t *Type) UnmarshalText(text []byte) error { e, err := fromString(string(text)) if err != nil { return err } *t = e return nil }
go
func (t *Type) UnmarshalText(text []byte) error { e, err := fromString(string(text)) if err != nil { return err } *t = e return nil }
[ "func", "(", "t", "*", "Type", ")", "UnmarshalText", "(", "text", "[", "]", "byte", ")", "error", "{", "e", ",", "err", ":=", "fromString", "(", "string", "(", "text", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "t", "=", "e", "\n", "return", "nil", "\n", "}" ]
// UnmarshalText implements TextUnmarsheler
[ "UnmarshalText", "implements", "TextUnmarsheler" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/type.go#L116-L125
test
TheThingsNetwork/go-utils
errors/type.go
fromString
func fromString(str string) (Type, error) { enum := strings.ToLower(str) switch enum { case "unknown": return Unknown, nil case "internal": return Internal, nil case "invalid argument": return InvalidArgument, nil case "out of range": return OutOfRange, nil case "not found": return NotFound, nil case "conflict": return Conflict, nil case "already exists": return AlreadyExists, nil case "unauthorized": return Unauthorized, nil case "permission denied": return PermissionDenied, nil case "timeout": return Timeout, nil case "not implemented": return NotImplemented, nil case "temporarily unavailable": return TemporarilyUnavailable, nil case "permanently unavailable": return PermanentlyUnavailable, nil case "canceled": return Canceled, nil case "resource exhausted": return ResourceExhausted, nil default: return Unknown, fmt.Errorf("Invalid error type") } }
go
func fromString(str string) (Type, error) { enum := strings.ToLower(str) switch enum { case "unknown": return Unknown, nil case "internal": return Internal, nil case "invalid argument": return InvalidArgument, nil case "out of range": return OutOfRange, nil case "not found": return NotFound, nil case "conflict": return Conflict, nil case "already exists": return AlreadyExists, nil case "unauthorized": return Unauthorized, nil case "permission denied": return PermissionDenied, nil case "timeout": return Timeout, nil case "not implemented": return NotImplemented, nil case "temporarily unavailable": return TemporarilyUnavailable, nil case "permanently unavailable": return PermanentlyUnavailable, nil case "canceled": return Canceled, nil case "resource exhausted": return ResourceExhausted, nil default: return Unknown, fmt.Errorf("Invalid error type") } }
[ "func", "fromString", "(", "str", "string", ")", "(", "Type", ",", "error", ")", "{", "enum", ":=", "strings", ".", "ToLower", "(", "str", ")", "\n", "switch", "enum", "{", "case", "\"unknown\"", ":", "return", "Unknown", ",", "nil", "\n", "case", "\"internal\"", ":", "return", "Internal", ",", "nil", "\n", "case", "\"invalid argument\"", ":", "return", "InvalidArgument", ",", "nil", "\n", "case", "\"out of range\"", ":", "return", "OutOfRange", ",", "nil", "\n", "case", "\"not found\"", ":", "return", "NotFound", ",", "nil", "\n", "case", "\"conflict\"", ":", "return", "Conflict", ",", "nil", "\n", "case", "\"already exists\"", ":", "return", "AlreadyExists", ",", "nil", "\n", "case", "\"unauthorized\"", ":", "return", "Unauthorized", ",", "nil", "\n", "case", "\"permission denied\"", ":", "return", "PermissionDenied", ",", "nil", "\n", "case", "\"timeout\"", ":", "return", "Timeout", ",", "nil", "\n", "case", "\"not implemented\"", ":", "return", "NotImplemented", ",", "nil", "\n", "case", "\"temporarily unavailable\"", ":", "return", "TemporarilyUnavailable", ",", "nil", "\n", "case", "\"permanently unavailable\"", ":", "return", "PermanentlyUnavailable", ",", "nil", "\n", "case", "\"canceled\"", ":", "return", "Canceled", ",", "nil", "\n", "case", "\"resource exhausted\"", ":", "return", "ResourceExhausted", ",", "nil", "\n", "default", ":", "return", "Unknown", ",", "fmt", ".", "Errorf", "(", "\"Invalid error type\"", ")", "\n", "}", "\n", "}" ]
// fromString parses a string into an error type. If the type is invalid, the // Unknown type will be returned as well as an error.
[ "fromString", "parses", "a", "string", "into", "an", "error", "type", ".", "If", "the", "type", "is", "invalid", "the", "Unknown", "type", "will", "be", "returned", "as", "well", "as", "an", "error", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/type.go#L129-L165
test
TheThingsNetwork/go-utils
stats/stats.go
Start
func Start(ctx log.Interface, interval time.Duration) { ctx.WithField("interval", interval).Debug("starting stats loop") go func() { memstats := new(runtime.MemStats) for range time.Tick(interval) { runtime.ReadMemStats(memstats) ctx.WithFields(log.Fields{ "goroutines": runtime.NumGoroutine(), "memory": float64(memstats.Alloc) / megaByte, // MegaBytes allocated and not yet freed }).Debugf("memory stats") } }() }
go
func Start(ctx log.Interface, interval time.Duration) { ctx.WithField("interval", interval).Debug("starting stats loop") go func() { memstats := new(runtime.MemStats) for range time.Tick(interval) { runtime.ReadMemStats(memstats) ctx.WithFields(log.Fields{ "goroutines": runtime.NumGoroutine(), "memory": float64(memstats.Alloc) / megaByte, // MegaBytes allocated and not yet freed }).Debugf("memory stats") } }() }
[ "func", "Start", "(", "ctx", "log", ".", "Interface", ",", "interval", "time", ".", "Duration", ")", "{", "ctx", ".", "WithField", "(", "\"interval\"", ",", "interval", ")", ".", "Debug", "(", "\"starting stats loop\"", ")", "\n", "go", "func", "(", ")", "{", "memstats", ":=", "new", "(", "runtime", ".", "MemStats", ")", "\n", "for", "range", "time", ".", "Tick", "(", "interval", ")", "{", "runtime", ".", "ReadMemStats", "(", "memstats", ")", "\n", "ctx", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"goroutines\"", ":", "runtime", ".", "NumGoroutine", "(", ")", ",", "\"memory\"", ":", "float64", "(", "memstats", ".", "Alloc", ")", "/", "megaByte", ",", "}", ")", ".", "Debugf", "(", "\"memory stats\"", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Start starts the stat process that will log relevant memory-related stats // to ctx, at an interval determined by interval.
[ "Start", "starts", "the", "stat", "process", "that", "will", "log", "relevant", "memory", "-", "related", "stats", "to", "ctx", "at", "an", "interval", "determined", "by", "interval", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/stats/stats.go#L17-L29
test
TheThingsNetwork/go-utils
queue/simple.go
NewSimple
func NewSimple() Simple { q := &simpleQueue{ queue: make([]interface{}, 0), } q.available = sync.NewCond(&q.mu) return q }
go
func NewSimple() Simple { q := &simpleQueue{ queue: make([]interface{}, 0), } q.available = sync.NewCond(&q.mu) return q }
[ "func", "NewSimple", "(", ")", "Simple", "{", "q", ":=", "&", "simpleQueue", "{", "queue", ":", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ")", ",", "}", "\n", "q", ".", "available", "=", "sync", ".", "NewCond", "(", "&", "q", ".", "mu", ")", "\n", "return", "q", "\n", "}" ]
// NewSimple returns a new Simple Queue
[ "NewSimple", "returns", "a", "new", "Simple", "Queue" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/queue/simple.go#L23-L29
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
Wrap
func Wrap(logger log.Interface, filters ...Filter) *Filtered { return &Filtered{ Interface: logger, filters: filters, } }
go
func Wrap(logger log.Interface, filters ...Filter) *Filtered { return &Filtered{ Interface: logger, filters: filters, } }
[ "func", "Wrap", "(", "logger", "log", ".", "Interface", ",", "filters", "...", "Filter", ")", "*", "Filtered", "{", "return", "&", "Filtered", "{", "Interface", ":", "logger", ",", "filters", ":", "filters", ",", "}", "\n", "}" ]
// Wrap wraps an existing logger, filtering the fields as it goes along // using the provided filters
[ "Wrap", "wraps", "an", "existing", "logger", "filtering", "the", "fields", "as", "it", "goes", "along", "using", "the", "provided", "filters" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L31-L36
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
WithFilters
func (f *Filtered) WithFilters(filters ...Filter) *Filtered { return &Filtered{ Interface: f.Interface, filters: append(f.filters, filters...), } }
go
func (f *Filtered) WithFilters(filters ...Filter) *Filtered { return &Filtered{ Interface: f.Interface, filters: append(f.filters, filters...), } }
[ "func", "(", "f", "*", "Filtered", ")", "WithFilters", "(", "filters", "...", "Filter", ")", "*", "Filtered", "{", "return", "&", "Filtered", "{", "Interface", ":", "f", ".", "Interface", ",", "filters", ":", "append", "(", "f", ".", "filters", ",", "filters", "...", ")", ",", "}", "\n", "}" ]
// WithFilter creates a new Filtered that will use the extra filters
[ "WithFilter", "creates", "a", "new", "Filtered", "that", "will", "use", "the", "extra", "filters" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L39-L44
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
WithField
func (f *Filtered) WithField(k string, v interface{}) log.Interface { val := v // apply the filters for _, filter := range f.filters { val = filter.Filter(k, val) } return &Filtered{ Interface: f.Interface.WithField(k, val), filters: f.filters, } }
go
func (f *Filtered) WithField(k string, v interface{}) log.Interface { val := v // apply the filters for _, filter := range f.filters { val = filter.Filter(k, val) } return &Filtered{ Interface: f.Interface.WithField(k, val), filters: f.filters, } }
[ "func", "(", "f", "*", "Filtered", ")", "WithField", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "log", ".", "Interface", "{", "val", ":=", "v", "\n", "for", "_", ",", "filter", ":=", "range", "f", ".", "filters", "{", "val", "=", "filter", ".", "Filter", "(", "k", ",", "val", ")", "\n", "}", "\n", "return", "&", "Filtered", "{", "Interface", ":", "f", ".", "Interface", ".", "WithField", "(", "k", ",", "val", ")", ",", "filters", ":", "f", ".", "filters", ",", "}", "\n", "}" ]
// WithField filters the field and passes it on to the wrapped loggers WithField
[ "WithField", "filters", "the", "field", "and", "passes", "it", "on", "to", "the", "wrapped", "loggers", "WithField" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L47-L59
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
WithFields
func (f *Filtered) WithFields(fields log.Fields) log.Interface { res := make(map[string]interface{}, len(fields)) for k, v := range fields { val := v // apply the filters for _, filter := range f.filters { val = filter.Filter(k, val) } res[k] = val } return &Filtered{ Interface: f.Interface.WithFields(res), filters: f.filters, } }
go
func (f *Filtered) WithFields(fields log.Fields) log.Interface { res := make(map[string]interface{}, len(fields)) for k, v := range fields { val := v // apply the filters for _, filter := range f.filters { val = filter.Filter(k, val) } res[k] = val } return &Filtered{ Interface: f.Interface.WithFields(res), filters: f.filters, } }
[ "func", "(", "f", "*", "Filtered", ")", "WithFields", "(", "fields", "log", ".", "Fields", ")", "log", ".", "Interface", "{", "res", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "fields", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "fields", "{", "val", ":=", "v", "\n", "for", "_", ",", "filter", ":=", "range", "f", ".", "filters", "{", "val", "=", "filter", ".", "Filter", "(", "k", ",", "val", ")", "\n", "}", "\n", "res", "[", "k", "]", "=", "val", "\n", "}", "\n", "return", "&", "Filtered", "{", "Interface", ":", "f", ".", "Interface", ".", "WithFields", "(", "res", ")", ",", "filters", ":", "f", ".", "filters", ",", "}", "\n", "}" ]
// WithFields filters the fields and passes them on to the wrapped loggers WithFields
[ "WithFields", "filters", "the", "fields", "and", "passes", "them", "on", "to", "the", "wrapped", "loggers", "WithFields" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L62-L80
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
FilterSensitive
func FilterSensitive(sensitive []string, elided interface{}) Filter { return FilterFunc(func(key string, v interface{}) interface{} { lower := strings.ToLower(key) for _, s := range sensitive { if lower == s { return elided } } return v }) }
go
func FilterSensitive(sensitive []string, elided interface{}) Filter { return FilterFunc(func(key string, v interface{}) interface{} { lower := strings.ToLower(key) for _, s := range sensitive { if lower == s { return elided } } return v }) }
[ "func", "FilterSensitive", "(", "sensitive", "[", "]", "string", ",", "elided", "interface", "{", "}", ")", "Filter", "{", "return", "FilterFunc", "(", "func", "(", "key", "string", ",", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "lower", ":=", "strings", ".", "ToLower", "(", "key", ")", "\n", "for", "_", ",", "s", ":=", "range", "sensitive", "{", "if", "lower", "==", "s", "{", "return", "elided", "\n", "}", "\n", "}", "\n", "return", "v", "\n", "}", ")", "\n", "}" ]
// FilterSensitive creates a Filter that filters most sensitive data like passwords, // keys, access_tokens, etc. and replaces them with the elided value
[ "FilterSensitive", "creates", "a", "Filter", "that", "filters", "most", "sensitive", "data", "like", "passwords", "keys", "access_tokens", "etc", ".", "and", "replaces", "them", "with", "the", "elided", "value" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L105-L116
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
SliceFilter
func SliceFilter(filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { r := reflect.ValueOf(v) if r.Kind() == reflect.Slice { res := make([]interface{}, 0, r.Len()) for i := 0; i < r.Len(); i++ { el := r.Index(i).Interface() res = append(res, filter.Filter(k, el)) } return res } return filter.Filter(k, v) }) }
go
func SliceFilter(filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { r := reflect.ValueOf(v) if r.Kind() == reflect.Slice { res := make([]interface{}, 0, r.Len()) for i := 0; i < r.Len(); i++ { el := r.Index(i).Interface() res = append(res, filter.Filter(k, el)) } return res } return filter.Filter(k, v) }) }
[ "func", "SliceFilter", "(", "filter", "Filter", ")", "Filter", "{", "return", "FilterFunc", "(", "func", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "r", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "r", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "{", "res", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "r", ".", "Len", "(", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "r", ".", "Len", "(", ")", ";", "i", "++", "{", "el", ":=", "r", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", "\n", "res", "=", "append", "(", "res", ",", "filter", ".", "Filter", "(", "k", ",", "el", ")", ")", "\n", "}", "\n", "return", "res", "\n", "}", "\n", "return", "filter", ".", "Filter", "(", "k", ",", "v", ")", "\n", "}", ")", "\n", "}" ]
// SliceFilter lifts the filter to also work on slices. It loses the // type information of the slice elements
[ "SliceFilter", "lifts", "the", "filter", "to", "also", "work", "on", "slices", ".", "It", "loses", "the", "type", "information", "of", "the", "slice", "elements" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L120-L135
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
MapFilter
func MapFilter(filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { r := reflect.ValueOf(v) if r.Kind() == reflect.Map { // res will be the filtered map res := make(map[string]interface{}, r.Len()) for _, key := range r.MapKeys() { str := key.String() val := r.MapIndex(key).Interface() res[str] = filter.Filter(str, val) } return res } return v }) }
go
func MapFilter(filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { r := reflect.ValueOf(v) if r.Kind() == reflect.Map { // res will be the filtered map res := make(map[string]interface{}, r.Len()) for _, key := range r.MapKeys() { str := key.String() val := r.MapIndex(key).Interface() res[str] = filter.Filter(str, val) } return res } return v }) }
[ "func", "MapFilter", "(", "filter", "Filter", ")", "Filter", "{", "return", "FilterFunc", "(", "func", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "r", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "r", ".", "Kind", "(", ")", "==", "reflect", ".", "Map", "{", "res", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "r", ".", "Len", "(", ")", ")", "\n", "for", "_", ",", "key", ":=", "range", "r", ".", "MapKeys", "(", ")", "{", "str", ":=", "key", ".", "String", "(", ")", "\n", "val", ":=", "r", ".", "MapIndex", "(", "key", ")", ".", "Interface", "(", ")", "\n", "res", "[", "str", "]", "=", "filter", ".", "Filter", "(", "str", ",", "val", ")", "\n", "}", "\n", "return", "res", "\n", "}", "\n", "return", "v", "\n", "}", ")", "\n", "}" ]
// MapFilter lifts the filter to also work on maps. It loses the type // information of the map fields
[ "MapFilter", "lifts", "the", "filter", "to", "also", "work", "on", "maps", ".", "It", "loses", "the", "type", "information", "of", "the", "map", "fields" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L139-L156
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
RestrictFilter
func RestrictFilter(fieldName string, filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { if fieldName == k { return filter.Filter(k, v) } return v }) }
go
func RestrictFilter(fieldName string, filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { if fieldName == k { return filter.Filter(k, v) } return v }) }
[ "func", "RestrictFilter", "(", "fieldName", "string", ",", "filter", "Filter", ")", "Filter", "{", "return", "FilterFunc", "(", "func", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "fieldName", "==", "k", "{", "return", "filter", ".", "Filter", "(", "k", ",", "v", ")", "\n", "}", "\n", "return", "v", "\n", "}", ")", "\n", "}" ]
// RestrictFilter restricts the filter to only work on a certain field
[ "RestrictFilter", "restricts", "the", "filter", "to", "only", "work", "on", "a", "certain", "field" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L159-L167
test
TheThingsNetwork/go-utils
log/filtered/filtered.go
LowerCaseFilter
func LowerCaseFilter(filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { return filter.Filter(strings.ToLower(k), v) }) }
go
func LowerCaseFilter(filter Filter) Filter { return FilterFunc(func(k string, v interface{}) interface{} { return filter.Filter(strings.ToLower(k), v) }) }
[ "func", "LowerCaseFilter", "(", "filter", "Filter", ")", "Filter", "{", "return", "FilterFunc", "(", "func", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "interface", "{", "}", "{", "return", "filter", ".", "Filter", "(", "strings", ".", "ToLower", "(", "k", ")", ",", "v", ")", "\n", "}", ")", "\n", "}" ]
// LowerCaseFilter creates a filter that only get passed lowercase field names
[ "LowerCaseFilter", "creates", "a", "filter", "that", "only", "get", "passed", "lowercase", "field", "names" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/filtered/filtered.go#L170-L174
test
TheThingsNetwork/go-utils
influx/writer.go
newBatchPoints
func newBatchPoints(bpConf influxdb.BatchPointsConfig) influxdb.BatchPoints { bp, err := influxdb.NewBatchPoints(bpConf) if err != nil { // Can only happen if there's an error in the code panic(fmt.Errorf("Invalid batch point configuration: %s", err)) } return bp }
go
func newBatchPoints(bpConf influxdb.BatchPointsConfig) influxdb.BatchPoints { bp, err := influxdb.NewBatchPoints(bpConf) if err != nil { // Can only happen if there's an error in the code panic(fmt.Errorf("Invalid batch point configuration: %s", err)) } return bp }
[ "func", "newBatchPoints", "(", "bpConf", "influxdb", ".", "BatchPointsConfig", ")", "influxdb", ".", "BatchPoints", "{", "bp", ",", "err", ":=", "influxdb", ".", "NewBatchPoints", "(", "bpConf", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"Invalid batch point configuration: %s\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "bp", "\n", "}" ]
// newBatchPoints creates new influxdb.BatchPoints with specified bpConf. // Panics on errors.
[ "newBatchPoints", "creates", "new", "influxdb", ".", "BatchPoints", "with", "specified", "bpConf", ".", "Panics", "on", "errors", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L24-L31
test
TheThingsNetwork/go-utils
influx/writer.go
NewSinglePointWriter
func NewSinglePointWriter(log ttnlog.Interface, w BatchPointsWriter) *SinglePointWriter { return &SinglePointWriter{ log: log, writer: w, } }
go
func NewSinglePointWriter(log ttnlog.Interface, w BatchPointsWriter) *SinglePointWriter { return &SinglePointWriter{ log: log, writer: w, } }
[ "func", "NewSinglePointWriter", "(", "log", "ttnlog", ".", "Interface", ",", "w", "BatchPointsWriter", ")", "*", "SinglePointWriter", "{", "return", "&", "SinglePointWriter", "{", "log", ":", "log", ",", "writer", ":", "w", ",", "}", "\n", "}" ]
// NewSinglePointWriter creates new SinglePointWriter
[ "NewSinglePointWriter", "creates", "new", "SinglePointWriter" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L50-L55
test
TheThingsNetwork/go-utils
influx/writer.go
Write
func (w *SinglePointWriter) Write(bpConf influxdb.BatchPointsConfig, p *influxdb.Point) error { bp := newBatchPoints(bpConf) bp.AddPoint(p) return w.writer.Write(bp) }
go
func (w *SinglePointWriter) Write(bpConf influxdb.BatchPointsConfig, p *influxdb.Point) error { bp := newBatchPoints(bpConf) bp.AddPoint(p) return w.writer.Write(bp) }
[ "func", "(", "w", "*", "SinglePointWriter", ")", "Write", "(", "bpConf", "influxdb", ".", "BatchPointsConfig", ",", "p", "*", "influxdb", ".", "Point", ")", "error", "{", "bp", ":=", "newBatchPoints", "(", "bpConf", ")", "\n", "bp", ".", "AddPoint", "(", "p", ")", "\n", "return", "w", ".", "writer", ".", "Write", "(", "bp", ")", "\n", "}" ]
// Write creates new influxdb.BatchPoints containing p and delegates that to the writer
[ "Write", "creates", "new", "influxdb", ".", "BatchPoints", "containing", "p", "and", "delegates", "that", "to", "the", "writer" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L58-L62
test
TheThingsNetwork/go-utils
influx/writer.go
WithScalingInterval
func WithScalingInterval(v time.Duration) BatchingWriterOption { return func(w *BatchingWriter) { w.scalingInterval = v } }
go
func WithScalingInterval(v time.Duration) BatchingWriterOption { return func(w *BatchingWriter) { w.scalingInterval = v } }
[ "func", "WithScalingInterval", "(", "v", "time", ".", "Duration", ")", "BatchingWriterOption", "{", "return", "func", "(", "w", "*", "BatchingWriter", ")", "{", "w", ".", "scalingInterval", "=", "v", "\n", "}", "\n", "}" ]
// WithInstanceLimit sets a limit on amount of additional instances spawned by BatchingWriter
[ "WithInstanceLimit", "sets", "a", "limit", "on", "amount", "of", "additional", "instances", "spawned", "by", "BatchingWriter" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L148-L152
test
TheThingsNetwork/go-utils
influx/writer.go
NewBatchingWriter
func NewBatchingWriter(log ttnlog.Interface, w BatchPointsWriter, opts ...BatchingWriterOption) *BatchingWriter { bw := &BatchingWriter{ log: log, writer: w, scalingInterval: DefaultScalingInterval, limit: DefaultInstanceLimit, pointChans: make(map[influxdb.BatchPointsConfig]chan *batchPoint), } for _, opt := range opts { opt(bw) } bw.log = bw.log.WithFields(ttnlog.Fields{ "limit": bw.limit, "scalingInterval": bw.scalingInterval, }) return bw }
go
func NewBatchingWriter(log ttnlog.Interface, w BatchPointsWriter, opts ...BatchingWriterOption) *BatchingWriter { bw := &BatchingWriter{ log: log, writer: w, scalingInterval: DefaultScalingInterval, limit: DefaultInstanceLimit, pointChans: make(map[influxdb.BatchPointsConfig]chan *batchPoint), } for _, opt := range opts { opt(bw) } bw.log = bw.log.WithFields(ttnlog.Fields{ "limit": bw.limit, "scalingInterval": bw.scalingInterval, }) return bw }
[ "func", "NewBatchingWriter", "(", "log", "ttnlog", ".", "Interface", ",", "w", "BatchPointsWriter", ",", "opts", "...", "BatchingWriterOption", ")", "*", "BatchingWriter", "{", "bw", ":=", "&", "BatchingWriter", "{", "log", ":", "log", ",", "writer", ":", "w", ",", "scalingInterval", ":", "DefaultScalingInterval", ",", "limit", ":", "DefaultInstanceLimit", ",", "pointChans", ":", "make", "(", "map", "[", "influxdb", ".", "BatchPointsConfig", "]", "chan", "*", "batchPoint", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "bw", ")", "\n", "}", "\n", "bw", ".", "log", "=", "bw", ".", "log", ".", "WithFields", "(", "ttnlog", ".", "Fields", "{", "\"limit\"", ":", "bw", ".", "limit", ",", "\"scalingInterval\"", ":", "bw", ".", "scalingInterval", ",", "}", ")", "\n", "return", "bw", "\n", "}" ]
// NewBatchingWriter creates new BatchingWriter. If WithScalingInterval is not specified, DefaultScalingInterval value is used. If WithInstanceLimit is not specified, DefaultInstanceLimit is used.
[ "NewBatchingWriter", "creates", "new", "BatchingWriter", ".", "If", "WithScalingInterval", "is", "not", "specified", "DefaultScalingInterval", "value", "is", "used", ".", "If", "WithInstanceLimit", "is", "not", "specified", "DefaultInstanceLimit", "is", "used", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L155-L171
test
TheThingsNetwork/go-utils
influx/writer.go
Write
func (w *BatchingWriter) Write(bpConf influxdb.BatchPointsConfig, p *influxdb.Point) error { log := w.log.WithField("config", bpConf) w.pointChanMutex.RLock() ch, ok := w.pointChans[bpConf] w.pointChanMutex.RUnlock() if !ok { w.pointChanMutex.Lock() ch, ok = w.pointChans[bpConf] if !ok { w.mutex.Lock() w.active++ w.limit++ w.mutex.Unlock() ch = make(chan *batchPoint) w.pointChans[bpConf] = ch go writeInBatches(log, w.writer, bpConf, w.scalingInterval, ch, true) } w.pointChanMutex.Unlock() } point := &batchPoint{ Point: p, errch: make(chan error, 1), } select { case ch <- point: case <-time.After(w.scalingInterval): w.mutex.Lock() if w.active < w.limit { w.active++ go writeInBatches(w.log, w.writer, bpConf, w.scalingInterval, ch, false) } w.mutex.Unlock() ch <- point } return <-point.errch }
go
func (w *BatchingWriter) Write(bpConf influxdb.BatchPointsConfig, p *influxdb.Point) error { log := w.log.WithField("config", bpConf) w.pointChanMutex.RLock() ch, ok := w.pointChans[bpConf] w.pointChanMutex.RUnlock() if !ok { w.pointChanMutex.Lock() ch, ok = w.pointChans[bpConf] if !ok { w.mutex.Lock() w.active++ w.limit++ w.mutex.Unlock() ch = make(chan *batchPoint) w.pointChans[bpConf] = ch go writeInBatches(log, w.writer, bpConf, w.scalingInterval, ch, true) } w.pointChanMutex.Unlock() } point := &batchPoint{ Point: p, errch: make(chan error, 1), } select { case ch <- point: case <-time.After(w.scalingInterval): w.mutex.Lock() if w.active < w.limit { w.active++ go writeInBatches(w.log, w.writer, bpConf, w.scalingInterval, ch, false) } w.mutex.Unlock() ch <- point } return <-point.errch }
[ "func", "(", "w", "*", "BatchingWriter", ")", "Write", "(", "bpConf", "influxdb", ".", "BatchPointsConfig", ",", "p", "*", "influxdb", ".", "Point", ")", "error", "{", "log", ":=", "w", ".", "log", ".", "WithField", "(", "\"config\"", ",", "bpConf", ")", "\n", "w", ".", "pointChanMutex", ".", "RLock", "(", ")", "\n", "ch", ",", "ok", ":=", "w", ".", "pointChans", "[", "bpConf", "]", "\n", "w", ".", "pointChanMutex", ".", "RUnlock", "(", ")", "\n", "if", "!", "ok", "{", "w", ".", "pointChanMutex", ".", "Lock", "(", ")", "\n", "ch", ",", "ok", "=", "w", ".", "pointChans", "[", "bpConf", "]", "\n", "if", "!", "ok", "{", "w", ".", "mutex", ".", "Lock", "(", ")", "\n", "w", ".", "active", "++", "\n", "w", ".", "limit", "++", "\n", "w", ".", "mutex", ".", "Unlock", "(", ")", "\n", "ch", "=", "make", "(", "chan", "*", "batchPoint", ")", "\n", "w", ".", "pointChans", "[", "bpConf", "]", "=", "ch", "\n", "go", "writeInBatches", "(", "log", ",", "w", ".", "writer", ",", "bpConf", ",", "w", ".", "scalingInterval", ",", "ch", ",", "true", ")", "\n", "}", "\n", "w", ".", "pointChanMutex", ".", "Unlock", "(", ")", "\n", "}", "\n", "point", ":=", "&", "batchPoint", "{", "Point", ":", "p", ",", "errch", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "}", "\n", "select", "{", "case", "ch", "<-", "point", ":", "case", "<-", "time", ".", "After", "(", "w", ".", "scalingInterval", ")", ":", "w", ".", "mutex", ".", "Lock", "(", ")", "\n", "if", "w", ".", "active", "<", "w", ".", "limit", "{", "w", ".", "active", "++", "\n", "go", "writeInBatches", "(", "w", ".", "log", ",", "w", ".", "writer", ",", "bpConf", ",", "w", ".", "scalingInterval", ",", "ch", ",", "false", ")", "\n", "}", "\n", "w", ".", "mutex", ".", "Unlock", "(", ")", "\n", "ch", "<-", "point", "\n", "}", "\n", "return", "<-", "point", ".", "errch", "\n", "}" ]
// Write delegates p to a running instance of BatchingWriter and spawns new instances as required.
[ "Write", "delegates", "p", "to", "a", "running", "instance", "of", "BatchingWriter", "and", "spawns", "new", "instances", "as", "required", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L174-L212
test
TheThingsNetwork/go-utils
log/apex/apex.go
MustParseLevel
func (w *apexInterfaceWrapper) MustParseLevel(s string) { level, err := ParseLevel(s) if err != nil { w.WithError(err).WithField("level", s).Fatal("Could not parse log level") } w.Level = level }
go
func (w *apexInterfaceWrapper) MustParseLevel(s string) { level, err := ParseLevel(s) if err != nil { w.WithError(err).WithField("level", s).Fatal("Could not parse log level") } w.Level = level }
[ "func", "(", "w", "*", "apexInterfaceWrapper", ")", "MustParseLevel", "(", "s", "string", ")", "{", "level", ",", "err", ":=", "ParseLevel", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "w", ".", "WithError", "(", "err", ")", ".", "WithField", "(", "\"level\"", ",", "s", ")", ".", "Fatal", "(", "\"Could not parse log level\"", ")", "\n", "}", "\n", "w", ".", "Level", "=", "level", "\n", "}" ]
// MustParseLevel is a convience function that parses the passed in string // as a log level and sets the log level of the apexInterfaceWrapper to the // parsed level. If an error occurs it will handle it with w.Fatal
[ "MustParseLevel", "is", "a", "convience", "function", "that", "parses", "the", "passed", "in", "string", "as", "a", "log", "level", "and", "sets", "the", "log", "level", "of", "the", "apexInterfaceWrapper", "to", "the", "parsed", "level", ".", "If", "an", "error", "occurs", "it", "will", "handle", "it", "with", "w", ".", "Fatal" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/apex/apex.go#L56-L62
test
TheThingsNetwork/go-utils
grpc/streambuffer/streambuffer.go
New
func New(bufferSize int, setup func() (grpc.ClientStream, error)) *Stream { return &Stream{ setupFunc: setup, sendBuffer: make(chan interface{}, bufferSize), log: ttnlog.Get(), } }
go
func New(bufferSize int, setup func() (grpc.ClientStream, error)) *Stream { return &Stream{ setupFunc: setup, sendBuffer: make(chan interface{}, bufferSize), log: ttnlog.Get(), } }
[ "func", "New", "(", "bufferSize", "int", ",", "setup", "func", "(", ")", "(", "grpc", ".", "ClientStream", ",", "error", ")", ")", "*", "Stream", "{", "return", "&", "Stream", "{", "setupFunc", ":", "setup", ",", "sendBuffer", ":", "make", "(", "chan", "interface", "{", "}", ",", "bufferSize", ")", ",", "log", ":", "ttnlog", ".", "Get", "(", ")", ",", "}", "\n", "}" ]
// New returns a new Stream with the given buffer size and setup function.
[ "New", "returns", "a", "new", "Stream", "with", "the", "given", "buffer", "size", "and", "setup", "function", "." ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/streambuffer/streambuffer.go#L19-L25
test
TheThingsNetwork/go-utils
grpc/streambuffer/streambuffer.go
SetLogger
func (s *Stream) SetLogger(log ttnlog.Interface) { s.mu.Lock() s.log = log s.mu.Unlock() }
go
func (s *Stream) SetLogger(log ttnlog.Interface) { s.mu.Lock() s.log = log s.mu.Unlock() }
[ "func", "(", "s", "*", "Stream", ")", "SetLogger", "(", "log", "ttnlog", ".", "Interface", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "log", "=", "log", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// SetLogger sets the logger for this streambuffer
[ "SetLogger", "sets", "the", "logger", "for", "this", "streambuffer" ]
aa2a11bd59104d2a8609328c2b2b55da61826470
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/streambuffer/streambuffer.go#L54-L58
test