repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
robertkrimen/otto
repl/repl.go
RunWithPromptAndPrelude
func RunWithPromptAndPrelude(vm *otto.Otto, prompt, prelude string) error { return RunWithOptions(vm, Options{ Prompt: prompt, Prelude: prelude, }) }
go
func RunWithPromptAndPrelude(vm *otto.Otto, prompt, prelude string) error { return RunWithOptions(vm, Options{ Prompt: prompt, Prelude: prelude, }) }
[ "func", "RunWithPromptAndPrelude", "(", "vm", "*", "otto", ".", "Otto", ",", "prompt", ",", "prelude", "string", ")", "error", "{", "return", "RunWithOptions", "(", "vm", ",", "Options", "{", "Prompt", ":", "prompt", ",", "Prelude", ":", "prelude", ",", "}", ")", "\n", "}" ]
// RunWithPromptAndPrelude runs a REPL with the given prompt and prelude.
[ "RunWithPromptAndPrelude", "runs", "a", "REPL", "with", "the", "given", "prompt", "and", "prelude", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/repl/repl.go#L47-L52
train
robertkrimen/otto
repl/repl.go
RunWithOptions
func RunWithOptions(vm *otto.Otto, options Options) error { prompt := options.Prompt if prompt == "" { prompt = "> " } c := &readline.Config{ Prompt: prompt, } if options.Autocomplete { c.AutoComplete = &autoCompleter{vm} } rl, err := readline.NewEx(c) if err != nil { return err } prelude := options.Prelude if prelude != "" { if _, err := io.Copy(rl.Stderr(), strings.NewReader(prelude+"\n")); err != nil { return err } rl.Refresh() } var d []string for { l, err := rl.Readline() if err != nil { if err == readline.ErrInterrupt { if d != nil { d = nil rl.SetPrompt(prompt) rl.Refresh() continue } break } return err } if l == "" { continue } d = append(d, l) s, err := vm.Compile("repl", strings.Join(d, "\n")) if err != nil { rl.SetPrompt(strings.Repeat(" ", len(prompt))) } else { rl.SetPrompt(prompt) d = nil v, err := vm.Eval(s) if err != nil { if oerr, ok := err.(*otto.Error); ok { io.Copy(rl.Stdout(), strings.NewReader(oerr.String())) } else { io.Copy(rl.Stdout(), strings.NewReader(err.Error())) } } else { rl.Stdout().Write([]byte(v.String() + "\n")) } } rl.Refresh() } return rl.Close() }
go
func RunWithOptions(vm *otto.Otto, options Options) error { prompt := options.Prompt if prompt == "" { prompt = "> " } c := &readline.Config{ Prompt: prompt, } if options.Autocomplete { c.AutoComplete = &autoCompleter{vm} } rl, err := readline.NewEx(c) if err != nil { return err } prelude := options.Prelude if prelude != "" { if _, err := io.Copy(rl.Stderr(), strings.NewReader(prelude+"\n")); err != nil { return err } rl.Refresh() } var d []string for { l, err := rl.Readline() if err != nil { if err == readline.ErrInterrupt { if d != nil { d = nil rl.SetPrompt(prompt) rl.Refresh() continue } break } return err } if l == "" { continue } d = append(d, l) s, err := vm.Compile("repl", strings.Join(d, "\n")) if err != nil { rl.SetPrompt(strings.Repeat(" ", len(prompt))) } else { rl.SetPrompt(prompt) d = nil v, err := vm.Eval(s) if err != nil { if oerr, ok := err.(*otto.Error); ok { io.Copy(rl.Stdout(), strings.NewReader(oerr.String())) } else { io.Copy(rl.Stdout(), strings.NewReader(err.Error())) } } else { rl.Stdout().Write([]byte(v.String() + "\n")) } } rl.Refresh() } return rl.Close() }
[ "func", "RunWithOptions", "(", "vm", "*", "otto", ".", "Otto", ",", "options", "Options", ")", "error", "{", "prompt", ":=", "options", ".", "Prompt", "\n", "if", "prompt", "==", "\"", "\"", "{", "prompt", "=", "\"", "\"", "\n", "}", "\n\n", "c", ":=", "&", "readline", ".", "Config", "{", "Prompt", ":", "prompt", ",", "}", "\n\n", "if", "options", ".", "Autocomplete", "{", "c", ".", "AutoComplete", "=", "&", "autoCompleter", "{", "vm", "}", "\n", "}", "\n\n", "rl", ",", "err", ":=", "readline", ".", "NewEx", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "prelude", ":=", "options", ".", "Prelude", "\n", "if", "prelude", "!=", "\"", "\"", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "rl", ".", "Stderr", "(", ")", ",", "strings", ".", "NewReader", "(", "prelude", "+", "\"", "\\n", "\"", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "rl", ".", "Refresh", "(", ")", "\n", "}", "\n\n", "var", "d", "[", "]", "string", "\n\n", "for", "{", "l", ",", "err", ":=", "rl", ".", "Readline", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "readline", ".", "ErrInterrupt", "{", "if", "d", "!=", "nil", "{", "d", "=", "nil", "\n\n", "rl", ".", "SetPrompt", "(", "prompt", ")", "\n", "rl", ".", "Refresh", "(", ")", "\n\n", "continue", "\n", "}", "\n\n", "break", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "if", "l", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "d", "=", "append", "(", "d", ",", "l", ")", "\n\n", "s", ",", "err", ":=", "vm", ".", "Compile", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "d", ",", "\"", "\\n", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "rl", ".", "SetPrompt", "(", "strings", ".", "Repeat", "(", "\"", "\"", ",", "len", "(", "prompt", ")", ")", ")", "\n", "}", "else", "{", "rl", ".", "SetPrompt", "(", "prompt", ")", "\n\n", "d", "=", "nil", "\n\n", "v", ",", "err", ":=", "vm", ".", "Eval", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "if", "oerr", ",", "ok", ":=", "err", ".", "(", "*", "otto", ".", "Error", ")", ";", "ok", "{", "io", ".", "Copy", "(", "rl", ".", "Stdout", "(", ")", ",", "strings", ".", "NewReader", "(", "oerr", ".", "String", "(", ")", ")", ")", "\n", "}", "else", "{", "io", ".", "Copy", "(", "rl", ".", "Stdout", "(", ")", ",", "strings", ".", "NewReader", "(", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "}", "else", "{", "rl", ".", "Stdout", "(", ")", ".", "Write", "(", "[", "]", "byte", "(", "v", ".", "String", "(", ")", "+", "\"", "\\n", "\"", ")", ")", "\n", "}", "\n", "}", "\n\n", "rl", ".", "Refresh", "(", ")", "\n", "}", "\n\n", "return", "rl", ".", "Close", "(", ")", "\n", "}" ]
// RunWithOptions runs a REPL with the given options.
[ "RunWithOptions", "runs", "a", "REPL", "with", "the", "given", "options", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/repl/repl.go#L70-L149
train
robertkrimen/otto
parser/lexer.go
isLineWhiteSpace
func isLineWhiteSpace(chr rune) bool { switch chr { case '\u0009', '\u000b', '\u000c', '\u0020', '\u00a0', '\ufeff': return true case '\u000a', '\u000d', '\u2028', '\u2029': return false case '\u0085': return false } return unicode.IsSpace(chr) }
go
func isLineWhiteSpace(chr rune) bool { switch chr { case '\u0009', '\u000b', '\u000c', '\u0020', '\u00a0', '\ufeff': return true case '\u000a', '\u000d', '\u2028', '\u2029': return false case '\u0085': return false } return unicode.IsSpace(chr) }
[ "func", "isLineWhiteSpace", "(", "chr", "rune", ")", "bool", "{", "switch", "chr", "{", "case", "'\\u0009'", ",", "'\\u000b'", ",", "'\\u000c'", ",", "'\\u0020'", ",", "'\\u00a0'", ",", "'\\ufeff'", ":", "return", "true", "\n", "case", "'\\u000a'", ",", "'\\u000d'", ",", "'\\u2028'", ",", "'\\u2029'", ":", "return", "false", "\n", "case", "'\\u0085'", ":", "return", "false", "\n", "}", "\n", "return", "unicode", ".", "IsSpace", "(", "chr", ")", "\n", "}" ]
// 7.2
[ "7", ".", "2" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/parser/lexer.go#L100-L110
train
robertkrimen/otto
parser/lexer.go
read
func (self *_RegExp_parser) read() { if self.offset < self.length { self.chrOffset = self.offset chr, width := rune(self.str[self.offset]), 1 if chr >= utf8.RuneSelf { // !ASCII chr, width = utf8.DecodeRuneInString(self.str[self.offset:]) if chr == utf8.RuneError && width == 1 { self.error(self.chrOffset, "Invalid UTF-8 character") } } self.offset += width self.chr = chr } else { self.chrOffset = self.length self.chr = -1 // EOF } }
go
func (self *_RegExp_parser) read() { if self.offset < self.length { self.chrOffset = self.offset chr, width := rune(self.str[self.offset]), 1 if chr >= utf8.RuneSelf { // !ASCII chr, width = utf8.DecodeRuneInString(self.str[self.offset:]) if chr == utf8.RuneError && width == 1 { self.error(self.chrOffset, "Invalid UTF-8 character") } } self.offset += width self.chr = chr } else { self.chrOffset = self.length self.chr = -1 // EOF } }
[ "func", "(", "self", "*", "_RegExp_parser", ")", "read", "(", ")", "{", "if", "self", ".", "offset", "<", "self", ".", "length", "{", "self", ".", "chrOffset", "=", "self", ".", "offset", "\n", "chr", ",", "width", ":=", "rune", "(", "self", ".", "str", "[", "self", ".", "offset", "]", ")", ",", "1", "\n", "if", "chr", ">=", "utf8", ".", "RuneSelf", "{", "// !ASCII", "chr", ",", "width", "=", "utf8", ".", "DecodeRuneInString", "(", "self", ".", "str", "[", "self", ".", "offset", ":", "]", ")", "\n", "if", "chr", "==", "utf8", ".", "RuneError", "&&", "width", "==", "1", "{", "self", ".", "error", "(", "self", ".", "chrOffset", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "self", ".", "offset", "+=", "width", "\n", "self", ".", "chr", "=", "chr", "\n", "}", "else", "{", "self", ".", "chrOffset", "=", "self", ".", "length", "\n", "self", ".", "chr", "=", "-", "1", "// EOF", "\n", "}", "\n", "}" ]
// This is here since the functions are so similar
[ "This", "is", "here", "since", "the", "functions", "are", "so", "similar" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/parser/lexer.go#L408-L424
train
robertkrimen/otto
object_class.go
objectGetOwnProperty
func objectGetOwnProperty(self *_object, name string) *_property { // Return a _copy_ of the property property, exists := self._read(name) if !exists { return nil } return &property }
go
func objectGetOwnProperty(self *_object, name string) *_property { // Return a _copy_ of the property property, exists := self._read(name) if !exists { return nil } return &property }
[ "func", "objectGetOwnProperty", "(", "self", "*", "_object", ",", "name", "string", ")", "*", "_property", "{", "// Return a _copy_ of the property", "property", ",", "exists", ":=", "self", ".", "_read", "(", "name", ")", "\n", "if", "!", "exists", "{", "return", "nil", "\n", "}", "\n", "return", "&", "property", "\n", "}" ]
// Allons-y // 8.12.1
[ "Allons", "-", "y", "8", ".", "12", ".", "1" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/object_class.go#L169-L176
train
robertkrimen/otto
parser/parser.go
ParseFunction
func ParseFunction(parameterList, body string) (*ast.FunctionLiteral, error) { src := "(function(" + parameterList + ") {\n" + body + "\n})" parser := _newParser("", src, 1, nil) program, err := parser.parse() if err != nil { return nil, err } return program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral), nil }
go
func ParseFunction(parameterList, body string) (*ast.FunctionLiteral, error) { src := "(function(" + parameterList + ") {\n" + body + "\n})" parser := _newParser("", src, 1, nil) program, err := parser.parse() if err != nil { return nil, err } return program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral), nil }
[ "func", "ParseFunction", "(", "parameterList", ",", "body", "string", ")", "(", "*", "ast", ".", "FunctionLiteral", ",", "error", ")", "{", "src", ":=", "\"", "\"", "+", "parameterList", "+", "\"", "\\n", "\"", "+", "body", "+", "\"", "\\n", "\"", "\n\n", "parser", ":=", "_newParser", "(", "\"", "\"", ",", "src", ",", "1", ",", "nil", ")", "\n", "program", ",", "err", ":=", "parser", ".", "parse", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "program", ".", "Body", "[", "0", "]", ".", "(", "*", "ast", ".", "ExpressionStatement", ")", ".", "Expression", ".", "(", "*", "ast", ".", "FunctionLiteral", ")", ",", "nil", "\n", "}" ]
// ParseFunction parses a given parameter list and body as a function and returns the // corresponding ast.FunctionLiteral node. // // The parameter list, if any, should be a comma-separated list of identifiers. //
[ "ParseFunction", "parses", "a", "given", "parameter", "list", "and", "body", "as", "a", "function", "and", "returns", "the", "corresponding", "ast", ".", "FunctionLiteral", "node", ".", "The", "parameter", "list", "if", "any", "should", "be", "a", "comma", "-", "separated", "list", "of", "identifiers", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/parser/parser.go#L218-L229
train
robertkrimen/otto
token/token.go
precedence
func (tkn Token) precedence(in bool) int { switch tkn { case LOGICAL_OR: return 1 case LOGICAL_AND: return 2 case OR, OR_ASSIGN: return 3 case EXCLUSIVE_OR: return 4 case AND, AND_ASSIGN, AND_NOT, AND_NOT_ASSIGN: return 5 case EQUAL, NOT_EQUAL, STRICT_EQUAL, STRICT_NOT_EQUAL: return 6 case LESS, GREATER, LESS_OR_EQUAL, GREATER_OR_EQUAL, INSTANCEOF: return 7 case IN: if in { return 7 } return 0 case SHIFT_LEFT, SHIFT_RIGHT, UNSIGNED_SHIFT_RIGHT: fallthrough case SHIFT_LEFT_ASSIGN, SHIFT_RIGHT_ASSIGN, UNSIGNED_SHIFT_RIGHT_ASSIGN: return 8 case PLUS, MINUS, ADD_ASSIGN, SUBTRACT_ASSIGN: return 9 case MULTIPLY, SLASH, REMAINDER, MULTIPLY_ASSIGN, QUOTIENT_ASSIGN, REMAINDER_ASSIGN: return 11 } return 0 }
go
func (tkn Token) precedence(in bool) int { switch tkn { case LOGICAL_OR: return 1 case LOGICAL_AND: return 2 case OR, OR_ASSIGN: return 3 case EXCLUSIVE_OR: return 4 case AND, AND_ASSIGN, AND_NOT, AND_NOT_ASSIGN: return 5 case EQUAL, NOT_EQUAL, STRICT_EQUAL, STRICT_NOT_EQUAL: return 6 case LESS, GREATER, LESS_OR_EQUAL, GREATER_OR_EQUAL, INSTANCEOF: return 7 case IN: if in { return 7 } return 0 case SHIFT_LEFT, SHIFT_RIGHT, UNSIGNED_SHIFT_RIGHT: fallthrough case SHIFT_LEFT_ASSIGN, SHIFT_RIGHT_ASSIGN, UNSIGNED_SHIFT_RIGHT_ASSIGN: return 8 case PLUS, MINUS, ADD_ASSIGN, SUBTRACT_ASSIGN: return 9 case MULTIPLY, SLASH, REMAINDER, MULTIPLY_ASSIGN, QUOTIENT_ASSIGN, REMAINDER_ASSIGN: return 11 } return 0 }
[ "func", "(", "tkn", "Token", ")", "precedence", "(", "in", "bool", ")", "int", "{", "switch", "tkn", "{", "case", "LOGICAL_OR", ":", "return", "1", "\n\n", "case", "LOGICAL_AND", ":", "return", "2", "\n\n", "case", "OR", ",", "OR_ASSIGN", ":", "return", "3", "\n\n", "case", "EXCLUSIVE_OR", ":", "return", "4", "\n\n", "case", "AND", ",", "AND_ASSIGN", ",", "AND_NOT", ",", "AND_NOT_ASSIGN", ":", "return", "5", "\n\n", "case", "EQUAL", ",", "NOT_EQUAL", ",", "STRICT_EQUAL", ",", "STRICT_NOT_EQUAL", ":", "return", "6", "\n\n", "case", "LESS", ",", "GREATER", ",", "LESS_OR_EQUAL", ",", "GREATER_OR_EQUAL", ",", "INSTANCEOF", ":", "return", "7", "\n\n", "case", "IN", ":", "if", "in", "{", "return", "7", "\n", "}", "\n", "return", "0", "\n\n", "case", "SHIFT_LEFT", ",", "SHIFT_RIGHT", ",", "UNSIGNED_SHIFT_RIGHT", ":", "fallthrough", "\n", "case", "SHIFT_LEFT_ASSIGN", ",", "SHIFT_RIGHT_ASSIGN", ",", "UNSIGNED_SHIFT_RIGHT_ASSIGN", ":", "return", "8", "\n\n", "case", "PLUS", ",", "MINUS", ",", "ADD_ASSIGN", ",", "SUBTRACT_ASSIGN", ":", "return", "9", "\n\n", "case", "MULTIPLY", ",", "SLASH", ",", "REMAINDER", ",", "MULTIPLY_ASSIGN", ",", "QUOTIENT_ASSIGN", ",", "REMAINDER_ASSIGN", ":", "return", "11", "\n", "}", "\n", "return", "0", "\n", "}" ]
// This is not used for anything
[ "This", "is", "not", "used", "for", "anything" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/token/token.go#L28-L73
train
robertkrimen/otto
ast/comments.go
NewComment
func NewComment(text string, idx file.Idx) *Comment { comment := &Comment{ Begin: idx, Text: text, Position: TBD, } return comment }
go
func NewComment(text string, idx file.Idx) *Comment { comment := &Comment{ Begin: idx, Text: text, Position: TBD, } return comment }
[ "func", "NewComment", "(", "text", "string", ",", "idx", "file", ".", "Idx", ")", "*", "Comment", "{", "comment", ":=", "&", "Comment", "{", "Begin", ":", "idx", ",", "Text", ":", "text", ",", "Position", ":", "TBD", ",", "}", "\n\n", "return", "comment", "\n", "}" ]
// NewComment creates a new comment
[ "NewComment", "creates", "a", "new", "comment" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L34-L42
train
robertkrimen/otto
ast/comments.go
String
func (cp CommentPosition) String() string { switch cp { case LEADING: return "Leading" case TRAILING: return "Trailing" case KEY: return "Key" case COLON: return "Colon" case FINAL: return "Final" case IF: return "If" case WHILE: return "While" case DO: return "Do" case FOR: return "For" case WITH: return "With" default: return "???" } }
go
func (cp CommentPosition) String() string { switch cp { case LEADING: return "Leading" case TRAILING: return "Trailing" case KEY: return "Key" case COLON: return "Colon" case FINAL: return "Final" case IF: return "If" case WHILE: return "While" case DO: return "Do" case FOR: return "For" case WITH: return "With" default: return "???" } }
[ "func", "(", "cp", "CommentPosition", ")", "String", "(", ")", "string", "{", "switch", "cp", "{", "case", "LEADING", ":", "return", "\"", "\"", "\n", "case", "TRAILING", ":", "return", "\"", "\"", "\n", "case", "KEY", ":", "return", "\"", "\"", "\n", "case", "COLON", ":", "return", "\"", "\"", "\n", "case", "FINAL", ":", "return", "\"", "\"", "\n", "case", "IF", ":", "return", "\"", "\"", "\n", "case", "WHILE", ":", "return", "\"", "\"", "\n", "case", "DO", ":", "return", "\"", "\"", "\n", "case", "FOR", ":", "return", "\"", "\"", "\n", "case", "WITH", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// String returns a stringified version of the position
[ "String", "returns", "a", "stringified", "version", "of", "the", "position" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L45-L70
train
robertkrimen/otto
ast/comments.go
FetchAll
func (c *Comments) FetchAll() []*Comment { defer func() { c.Comments = nil c.future = nil }() return append(c.Comments, c.future...) }
go
func (c *Comments) FetchAll() []*Comment { defer func() { c.Comments = nil c.future = nil }() return append(c.Comments, c.future...) }
[ "func", "(", "c", "*", "Comments", ")", "FetchAll", "(", ")", "[", "]", "*", "Comment", "{", "defer", "func", "(", ")", "{", "c", ".", "Comments", "=", "nil", "\n", "c", ".", "future", "=", "nil", "\n", "}", "(", ")", "\n\n", "return", "append", "(", "c", ".", "Comments", ",", "c", ".", "future", "...", ")", "\n", "}" ]
// FetchAll returns all the currently scanned comments, // including those from the next line
[ "FetchAll", "returns", "all", "the", "currently", "scanned", "comments", "including", "those", "from", "the", "next", "line" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L110-L117
train
robertkrimen/otto
ast/comments.go
AddComment
func (c *Comments) AddComment(comment *Comment) { if c.primary { if !c.wasLineBreak { c.Comments = append(c.Comments, comment) } else { c.future = append(c.future, comment) } } else { if !c.wasLineBreak || (c.Current == nil && !c.afterBlock) { c.Comments = append(c.Comments, comment) } else { c.future = append(c.future, comment) } } }
go
func (c *Comments) AddComment(comment *Comment) { if c.primary { if !c.wasLineBreak { c.Comments = append(c.Comments, comment) } else { c.future = append(c.future, comment) } } else { if !c.wasLineBreak || (c.Current == nil && !c.afterBlock) { c.Comments = append(c.Comments, comment) } else { c.future = append(c.future, comment) } } }
[ "func", "(", "c", "*", "Comments", ")", "AddComment", "(", "comment", "*", "Comment", ")", "{", "if", "c", ".", "primary", "{", "if", "!", "c", ".", "wasLineBreak", "{", "c", ".", "Comments", "=", "append", "(", "c", ".", "Comments", ",", "comment", ")", "\n", "}", "else", "{", "c", ".", "future", "=", "append", "(", "c", ".", "future", ",", "comment", ")", "\n", "}", "\n", "}", "else", "{", "if", "!", "c", ".", "wasLineBreak", "||", "(", "c", ".", "Current", "==", "nil", "&&", "!", "c", ".", "afterBlock", ")", "{", "c", ".", "Comments", "=", "append", "(", "c", ".", "Comments", ",", "comment", ")", "\n", "}", "else", "{", "c", ".", "future", "=", "append", "(", "c", ".", "future", ",", "comment", ")", "\n", "}", "\n", "}", "\n", "}" ]
// AddComment adds a comment to the view. // Depending on the context, comments are added normally or as post line break.
[ "AddComment", "adds", "a", "comment", "to", "the", "view", ".", "Depending", "on", "the", "context", "comments", "are", "added", "normally", "or", "as", "post", "line", "break", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L146-L160
train
robertkrimen/otto
ast/comments.go
MarkComments
func (c *Comments) MarkComments(position CommentPosition) { for _, comment := range c.Comments { if comment.Position == TBD { comment.Position = position } } for _, c := range c.future { if c.Position == TBD { c.Position = position } } }
go
func (c *Comments) MarkComments(position CommentPosition) { for _, comment := range c.Comments { if comment.Position == TBD { comment.Position = position } } for _, c := range c.future { if c.Position == TBD { c.Position = position } } }
[ "func", "(", "c", "*", "Comments", ")", "MarkComments", "(", "position", "CommentPosition", ")", "{", "for", "_", ",", "comment", ":=", "range", "c", ".", "Comments", "{", "if", "comment", ".", "Position", "==", "TBD", "{", "comment", ".", "Position", "=", "position", "\n", "}", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "c", ".", "future", "{", "if", "c", ".", "Position", "==", "TBD", "{", "c", ".", "Position", "=", "position", "\n", "}", "\n", "}", "\n", "}" ]
// MarkComments will mark the found comments as the given position.
[ "MarkComments", "will", "mark", "the", "found", "comments", "as", "the", "given", "position", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L163-L174
train
robertkrimen/otto
ast/comments.go
Unset
func (c *Comments) Unset() { if c.Current != nil { c.applyComments(c.Current, c.Current, TRAILING) c.Current = nil } c.wasLineBreak = false c.primary = false c.afterBlock = false }
go
func (c *Comments) Unset() { if c.Current != nil { c.applyComments(c.Current, c.Current, TRAILING) c.Current = nil } c.wasLineBreak = false c.primary = false c.afterBlock = false }
[ "func", "(", "c", "*", "Comments", ")", "Unset", "(", ")", "{", "if", "c", ".", "Current", "!=", "nil", "{", "c", ".", "applyComments", "(", "c", ".", "Current", ",", "c", ".", "Current", ",", "TRAILING", ")", "\n", "c", ".", "Current", "=", "nil", "\n", "}", "\n", "c", ".", "wasLineBreak", "=", "false", "\n", "c", ".", "primary", "=", "false", "\n", "c", ".", "afterBlock", "=", "false", "\n", "}" ]
// Unset the current node and apply the comments to the current expression. // Resets context variables.
[ "Unset", "the", "current", "node", "and", "apply", "the", "comments", "to", "the", "current", "expression", ".", "Resets", "context", "variables", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L178-L186
train
robertkrimen/otto
ast/comments.go
SetExpression
func (c *Comments) SetExpression(node Expression) { // Skipping same node if c.Current == node { return } if c.Current != nil && c.Current.Idx1() == node.Idx1() { c.Current = node return } previous := c.Current c.Current = node // Apply the found comments and futures to the node and the previous. c.applyComments(node, previous, TRAILING) }
go
func (c *Comments) SetExpression(node Expression) { // Skipping same node if c.Current == node { return } if c.Current != nil && c.Current.Idx1() == node.Idx1() { c.Current = node return } previous := c.Current c.Current = node // Apply the found comments and futures to the node and the previous. c.applyComments(node, previous, TRAILING) }
[ "func", "(", "c", "*", "Comments", ")", "SetExpression", "(", "node", "Expression", ")", "{", "// Skipping same node", "if", "c", ".", "Current", "==", "node", "{", "return", "\n", "}", "\n", "if", "c", ".", "Current", "!=", "nil", "&&", "c", ".", "Current", ".", "Idx1", "(", ")", "==", "node", ".", "Idx1", "(", ")", "{", "c", ".", "Current", "=", "node", "\n", "return", "\n", "}", "\n", "previous", ":=", "c", ".", "Current", "\n", "c", ".", "Current", "=", "node", "\n\n", "// Apply the found comments and futures to the node and the previous.", "c", ".", "applyComments", "(", "node", ",", "previous", ",", "TRAILING", ")", "\n", "}" ]
// SetExpression sets the current expression. // It is applied the found comments, unless the previous expression has not been unset. // It is skipped if the node is already set or if it is a part of the previous node.
[ "SetExpression", "sets", "the", "current", "expression", ".", "It", "is", "applied", "the", "found", "comments", "unless", "the", "previous", "expression", "has", "not", "been", "unset", ".", "It", "is", "skipped", "if", "the", "node", "is", "already", "set", "or", "if", "it", "is", "a", "part", "of", "the", "previous", "node", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L191-L205
train
robertkrimen/otto
ast/comments.go
PostProcessNode
func (c *Comments) PostProcessNode(node Node) { c.applyComments(node, nil, TRAILING) }
go
func (c *Comments) PostProcessNode(node Node) { c.applyComments(node, nil, TRAILING) }
[ "func", "(", "c", "*", "Comments", ")", "PostProcessNode", "(", "node", "Node", ")", "{", "c", ".", "applyComments", "(", "node", ",", "nil", ",", "TRAILING", ")", "\n", "}" ]
// PostProcessNode applies all found comments to the given node
[ "PostProcessNode", "applies", "all", "found", "comments", "to", "the", "given", "node" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L208-L210
train
robertkrimen/otto
ast/comments.go
applyComments
func (c *Comments) applyComments(node, previous Node, position CommentPosition) { if previous != nil { c.CommentMap.AddComments(previous, c.Comments, position) c.Comments = nil } else { c.CommentMap.AddComments(node, c.Comments, position) c.Comments = nil } // Only apply the future comments to the node if the previous is set. // This is for detecting end of line comments and which node comments on the following lines belongs to if previous != nil { c.CommentMap.AddComments(node, c.future, position) c.future = nil } }
go
func (c *Comments) applyComments(node, previous Node, position CommentPosition) { if previous != nil { c.CommentMap.AddComments(previous, c.Comments, position) c.Comments = nil } else { c.CommentMap.AddComments(node, c.Comments, position) c.Comments = nil } // Only apply the future comments to the node if the previous is set. // This is for detecting end of line comments and which node comments on the following lines belongs to if previous != nil { c.CommentMap.AddComments(node, c.future, position) c.future = nil } }
[ "func", "(", "c", "*", "Comments", ")", "applyComments", "(", "node", ",", "previous", "Node", ",", "position", "CommentPosition", ")", "{", "if", "previous", "!=", "nil", "{", "c", ".", "CommentMap", ".", "AddComments", "(", "previous", ",", "c", ".", "Comments", ",", "position", ")", "\n", "c", ".", "Comments", "=", "nil", "\n", "}", "else", "{", "c", ".", "CommentMap", ".", "AddComments", "(", "node", ",", "c", ".", "Comments", ",", "position", ")", "\n", "c", ".", "Comments", "=", "nil", "\n", "}", "\n", "// Only apply the future comments to the node if the previous is set.", "// This is for detecting end of line comments and which node comments on the following lines belongs to", "if", "previous", "!=", "nil", "{", "c", ".", "CommentMap", ".", "AddComments", "(", "node", ",", "c", ".", "future", ",", "position", ")", "\n", "c", ".", "future", "=", "nil", "\n", "}", "\n", "}" ]
// applyComments applies both the comments and the future comments to the given node and the previous one, // based on the context.
[ "applyComments", "applies", "both", "the", "comments", "and", "the", "future", "comments", "to", "the", "given", "node", "and", "the", "previous", "one", "based", "on", "the", "context", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L214-L228
train
robertkrimen/otto
ast/comments.go
AddComment
func (cm CommentMap) AddComment(node Node, comment *Comment) { list := cm[node] list = append(list, comment) cm[node] = list }
go
func (cm CommentMap) AddComment(node Node, comment *Comment) { list := cm[node] list = append(list, comment) cm[node] = list }
[ "func", "(", "cm", "CommentMap", ")", "AddComment", "(", "node", "Node", ",", "comment", "*", "Comment", ")", "{", "list", ":=", "cm", "[", "node", "]", "\n", "list", "=", "append", "(", "list", ",", "comment", ")", "\n\n", "cm", "[", "node", "]", "=", "list", "\n", "}" ]
// AddComment adds a single comment to the map
[ "AddComment", "adds", "a", "single", "comment", "to", "the", "map" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L239-L244
train
robertkrimen/otto
ast/comments.go
AddComments
func (cm CommentMap) AddComments(node Node, comments []*Comment, position CommentPosition) { for _, comment := range comments { if comment.Position == TBD { comment.Position = position } cm.AddComment(node, comment) } }
go
func (cm CommentMap) AddComments(node Node, comments []*Comment, position CommentPosition) { for _, comment := range comments { if comment.Position == TBD { comment.Position = position } cm.AddComment(node, comment) } }
[ "func", "(", "cm", "CommentMap", ")", "AddComments", "(", "node", "Node", ",", "comments", "[", "]", "*", "Comment", ",", "position", "CommentPosition", ")", "{", "for", "_", ",", "comment", ":=", "range", "comments", "{", "if", "comment", ".", "Position", "==", "TBD", "{", "comment", ".", "Position", "=", "position", "\n", "}", "\n", "cm", ".", "AddComment", "(", "node", ",", "comment", ")", "\n", "}", "\n", "}" ]
// AddComments adds a slice of comments, given a node and an updated position
[ "AddComments", "adds", "a", "slice", "of", "comments", "given", "a", "node", "and", "an", "updated", "position" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L247-L254
train
robertkrimen/otto
ast/comments.go
Size
func (cm CommentMap) Size() int { size := 0 for _, comments := range cm { size += len(comments) } return size }
go
func (cm CommentMap) Size() int { size := 0 for _, comments := range cm { size += len(comments) } return size }
[ "func", "(", "cm", "CommentMap", ")", "Size", "(", ")", "int", "{", "size", ":=", "0", "\n", "for", "_", ",", "comments", ":=", "range", "cm", "{", "size", "+=", "len", "(", "comments", ")", "\n", "}", "\n\n", "return", "size", "\n", "}" ]
// Size returns the size of the map
[ "Size", "returns", "the", "size", "of", "the", "map" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L257-L264
train
robertkrimen/otto
ast/comments.go
MoveComments
func (cm CommentMap) MoveComments(from, to Node, position CommentPosition) { for i, c := range cm[from] { if c.Position == position { cm.AddComment(to, c) // Remove the comment from the "from" slice cm[from][i] = cm[from][len(cm[from])-1] cm[from][len(cm[from])-1] = nil cm[from] = cm[from][:len(cm[from])-1] } } }
go
func (cm CommentMap) MoveComments(from, to Node, position CommentPosition) { for i, c := range cm[from] { if c.Position == position { cm.AddComment(to, c) // Remove the comment from the "from" slice cm[from][i] = cm[from][len(cm[from])-1] cm[from][len(cm[from])-1] = nil cm[from] = cm[from][:len(cm[from])-1] } } }
[ "func", "(", "cm", "CommentMap", ")", "MoveComments", "(", "from", ",", "to", "Node", ",", "position", "CommentPosition", ")", "{", "for", "i", ",", "c", ":=", "range", "cm", "[", "from", "]", "{", "if", "c", ".", "Position", "==", "position", "{", "cm", ".", "AddComment", "(", "to", ",", "c", ")", "\n\n", "// Remove the comment from the \"from\" slice", "cm", "[", "from", "]", "[", "i", "]", "=", "cm", "[", "from", "]", "[", "len", "(", "cm", "[", "from", "]", ")", "-", "1", "]", "\n", "cm", "[", "from", "]", "[", "len", "(", "cm", "[", "from", "]", ")", "-", "1", "]", "=", "nil", "\n", "cm", "[", "from", "]", "=", "cm", "[", "from", "]", "[", ":", "len", "(", "cm", "[", "from", "]", ")", "-", "1", "]", "\n", "}", "\n", "}", "\n", "}" ]
// MoveComments moves comments with a given position from a node to another
[ "MoveComments", "moves", "comments", "with", "a", "given", "position", "from", "a", "node", "to", "another" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/ast/comments.go#L267-L278
train
robertkrimen/otto
otto.go
New
func New() *Otto { self := &Otto{ runtime: newContext(), } self.runtime.otto = self self.runtime.traceLimit = 10 self.Set("console", self.runtime.newConsole()) registry.Apply(func(entry registry.Entry) { self.Run(entry.Source()) }) return self }
go
func New() *Otto { self := &Otto{ runtime: newContext(), } self.runtime.otto = self self.runtime.traceLimit = 10 self.Set("console", self.runtime.newConsole()) registry.Apply(func(entry registry.Entry) { self.Run(entry.Source()) }) return self }
[ "func", "New", "(", ")", "*", "Otto", "{", "self", ":=", "&", "Otto", "{", "runtime", ":", "newContext", "(", ")", ",", "}", "\n", "self", ".", "runtime", ".", "otto", "=", "self", "\n", "self", ".", "runtime", ".", "traceLimit", "=", "10", "\n", "self", ".", "Set", "(", "\"", "\"", ",", "self", ".", "runtime", ".", "newConsole", "(", ")", ")", "\n\n", "registry", ".", "Apply", "(", "func", "(", "entry", "registry", ".", "Entry", ")", "{", "self", ".", "Run", "(", "entry", ".", "Source", "(", ")", ")", "\n", "}", ")", "\n\n", "return", "self", "\n", "}" ]
// New will allocate a new JavaScript runtime
[ "New", "will", "allocate", "a", "new", "JavaScript", "runtime" ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L244-L257
train
robertkrimen/otto
otto.go
Eval
func (self Otto) Eval(src interface{}) (Value, error) { if self.runtime.scope == nil { self.runtime.enterGlobalScope() defer self.runtime.leaveScope() } value, err := self.runtime.cmpl_eval(src, nil) if !value.safe() { value = Value{} } return value, err }
go
func (self Otto) Eval(src interface{}) (Value, error) { if self.runtime.scope == nil { self.runtime.enterGlobalScope() defer self.runtime.leaveScope() } value, err := self.runtime.cmpl_eval(src, nil) if !value.safe() { value = Value{} } return value, err }
[ "func", "(", "self", "Otto", ")", "Eval", "(", "src", "interface", "{", "}", ")", "(", "Value", ",", "error", ")", "{", "if", "self", ".", "runtime", ".", "scope", "==", "nil", "{", "self", ".", "runtime", ".", "enterGlobalScope", "(", ")", "\n", "defer", "self", ".", "runtime", ".", "leaveScope", "(", ")", "\n", "}", "\n\n", "value", ",", "err", ":=", "self", ".", "runtime", ".", "cmpl_eval", "(", "src", ",", "nil", ")", "\n", "if", "!", "value", ".", "safe", "(", ")", "{", "value", "=", "Value", "{", "}", "\n", "}", "\n", "return", "value", ",", "err", "\n", "}" ]
// Eval will do the same thing as Run, except without leaving the current scope. // // By staying in the same scope, the code evaluated has access to everything // already defined in the current stack frame. This is most useful in, for // example, a debugger call.
[ "Eval", "will", "do", "the", "same", "thing", "as", "Run", "except", "without", "leaving", "the", "current", "scope", ".", "By", "staying", "in", "the", "same", "scope", "the", "code", "evaluated", "has", "access", "to", "everything", "already", "defined", "in", "the", "current", "stack", "frame", ".", "This", "is", "most", "useful", "in", "for", "example", "a", "debugger", "call", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L307-L318
train
robertkrimen/otto
otto.go
MakeCustomError
func (self Otto) MakeCustomError(name, message string) Value { return self.runtime.toValue(self.runtime.newError(name, self.runtime.toValue(message), 0)) }
go
func (self Otto) MakeCustomError(name, message string) Value { return self.runtime.toValue(self.runtime.newError(name, self.runtime.toValue(message), 0)) }
[ "func", "(", "self", "Otto", ")", "MakeCustomError", "(", "name", ",", "message", "string", ")", "Value", "{", "return", "self", ".", "runtime", ".", "toValue", "(", "self", ".", "runtime", ".", "newError", "(", "name", ",", "self", ".", "runtime", ".", "toValue", "(", "message", ")", ",", "0", ")", ")", "\n", "}" ]
// MakeCustomError creates a new Error object with the given name and message, // returning it as a Value.
[ "MakeCustomError", "creates", "a", "new", "Error", "object", "with", "the", "given", "name", "and", "message", "returning", "it", "as", "a", "Value", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L396-L398
train
robertkrimen/otto
otto.go
MakeRangeError
func (self Otto) MakeRangeError(message string) Value { return self.runtime.toValue(self.runtime.newRangeError(self.runtime.toValue(message))) }
go
func (self Otto) MakeRangeError(message string) Value { return self.runtime.toValue(self.runtime.newRangeError(self.runtime.toValue(message))) }
[ "func", "(", "self", "Otto", ")", "MakeRangeError", "(", "message", "string", ")", "Value", "{", "return", "self", ".", "runtime", ".", "toValue", "(", "self", ".", "runtime", ".", "newRangeError", "(", "self", ".", "runtime", ".", "toValue", "(", "message", ")", ")", ")", "\n", "}" ]
// MakeRangeError creates a new RangeError object with the given message, // returning it as a Value.
[ "MakeRangeError", "creates", "a", "new", "RangeError", "object", "with", "the", "given", "message", "returning", "it", "as", "a", "Value", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L402-L404
train
robertkrimen/otto
otto.go
MakeSyntaxError
func (self Otto) MakeSyntaxError(message string) Value { return self.runtime.toValue(self.runtime.newSyntaxError(self.runtime.toValue(message))) }
go
func (self Otto) MakeSyntaxError(message string) Value { return self.runtime.toValue(self.runtime.newSyntaxError(self.runtime.toValue(message))) }
[ "func", "(", "self", "Otto", ")", "MakeSyntaxError", "(", "message", "string", ")", "Value", "{", "return", "self", ".", "runtime", ".", "toValue", "(", "self", ".", "runtime", ".", "newSyntaxError", "(", "self", ".", "runtime", ".", "toValue", "(", "message", ")", ")", ")", "\n", "}" ]
// MakeSyntaxError creates a new SyntaxError object with the given message, // returning it as a Value.
[ "MakeSyntaxError", "creates", "a", "new", "SyntaxError", "object", "with", "the", "given", "message", "returning", "it", "as", "a", "Value", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L408-L410
train
robertkrimen/otto
otto.go
MakeTypeError
func (self Otto) MakeTypeError(message string) Value { return self.runtime.toValue(self.runtime.newTypeError(self.runtime.toValue(message))) }
go
func (self Otto) MakeTypeError(message string) Value { return self.runtime.toValue(self.runtime.newTypeError(self.runtime.toValue(message))) }
[ "func", "(", "self", "Otto", ")", "MakeTypeError", "(", "message", "string", ")", "Value", "{", "return", "self", ".", "runtime", ".", "toValue", "(", "self", ".", "runtime", ".", "newTypeError", "(", "self", ".", "runtime", ".", "toValue", "(", "message", ")", ")", ")", "\n", "}" ]
// MakeTypeError creates a new TypeError object with the given message, // returning it as a Value.
[ "MakeTypeError", "creates", "a", "new", "TypeError", "object", "with", "the", "given", "message", "returning", "it", "as", "a", "Value", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L414-L416
train
robertkrimen/otto
otto.go
ContextLimit
func (self Otto) ContextLimit(limit int) Context { return self.ContextSkip(limit, true) }
go
func (self Otto) ContextLimit(limit int) Context { return self.ContextSkip(limit, true) }
[ "func", "(", "self", "Otto", ")", "ContextLimit", "(", "limit", "int", ")", "Context", "{", "return", "self", ".", "ContextSkip", "(", "limit", ",", "true", ")", "\n", "}" ]
// ContextLimit returns the current execution context of the vm, with a // specific limit on the number of stack frames to traverse, skipping any // innermost native function stack frames.
[ "ContextLimit", "returns", "the", "current", "execution", "context", "of", "the", "vm", "with", "a", "specific", "limit", "on", "the", "number", "of", "stack", "frames", "to", "traverse", "skipping", "any", "innermost", "native", "function", "stack", "frames", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L439-L441
train
robertkrimen/otto
otto.go
ContextSkip
func (self Otto) ContextSkip(limit int, skipNative bool) (ctx Context) { // Ensure we are operating in a scope if self.runtime.scope == nil { self.runtime.enterGlobalScope() defer self.runtime.leaveScope() } scope := self.runtime.scope frame := scope.frame for skipNative && frame.native && scope.outer != nil { scope = scope.outer frame = scope.frame } // Get location information ctx.Filename = "<unknown>" ctx.Callee = frame.callee switch { case frame.native: ctx.Filename = frame.nativeFile ctx.Line = frame.nativeLine ctx.Column = 0 case frame.file != nil: ctx.Filename = "<anonymous>" if p := frame.file.Position(file.Idx(frame.offset)); p != nil { ctx.Line = p.Line ctx.Column = p.Column if p.Filename != "" { ctx.Filename = p.Filename } } } // Get the current scope this Value ctx.This = toValue_object(scope.this) // Build stacktrace (up to 10 levels deep) ctx.Symbols = make(map[string]Value) ctx.Stacktrace = append(ctx.Stacktrace, frame.location()) for limit != 0 { // Get variables stash := scope.lexical for { for _, name := range getStashProperties(stash) { if _, ok := ctx.Symbols[name]; !ok { ctx.Symbols[name] = stash.getBinding(name, true) } } stash = stash.outer() if stash == nil || stash.outer() == nil { break } } scope = scope.outer if scope == nil { break } if scope.frame.offset >= 0 { ctx.Stacktrace = append(ctx.Stacktrace, scope.frame.location()) } limit-- } return }
go
func (self Otto) ContextSkip(limit int, skipNative bool) (ctx Context) { // Ensure we are operating in a scope if self.runtime.scope == nil { self.runtime.enterGlobalScope() defer self.runtime.leaveScope() } scope := self.runtime.scope frame := scope.frame for skipNative && frame.native && scope.outer != nil { scope = scope.outer frame = scope.frame } // Get location information ctx.Filename = "<unknown>" ctx.Callee = frame.callee switch { case frame.native: ctx.Filename = frame.nativeFile ctx.Line = frame.nativeLine ctx.Column = 0 case frame.file != nil: ctx.Filename = "<anonymous>" if p := frame.file.Position(file.Idx(frame.offset)); p != nil { ctx.Line = p.Line ctx.Column = p.Column if p.Filename != "" { ctx.Filename = p.Filename } } } // Get the current scope this Value ctx.This = toValue_object(scope.this) // Build stacktrace (up to 10 levels deep) ctx.Symbols = make(map[string]Value) ctx.Stacktrace = append(ctx.Stacktrace, frame.location()) for limit != 0 { // Get variables stash := scope.lexical for { for _, name := range getStashProperties(stash) { if _, ok := ctx.Symbols[name]; !ok { ctx.Symbols[name] = stash.getBinding(name, true) } } stash = stash.outer() if stash == nil || stash.outer() == nil { break } } scope = scope.outer if scope == nil { break } if scope.frame.offset >= 0 { ctx.Stacktrace = append(ctx.Stacktrace, scope.frame.location()) } limit-- } return }
[ "func", "(", "self", "Otto", ")", "ContextSkip", "(", "limit", "int", ",", "skipNative", "bool", ")", "(", "ctx", "Context", ")", "{", "// Ensure we are operating in a scope", "if", "self", ".", "runtime", ".", "scope", "==", "nil", "{", "self", ".", "runtime", ".", "enterGlobalScope", "(", ")", "\n", "defer", "self", ".", "runtime", ".", "leaveScope", "(", ")", "\n", "}", "\n\n", "scope", ":=", "self", ".", "runtime", ".", "scope", "\n", "frame", ":=", "scope", ".", "frame", "\n\n", "for", "skipNative", "&&", "frame", ".", "native", "&&", "scope", ".", "outer", "!=", "nil", "{", "scope", "=", "scope", ".", "outer", "\n", "frame", "=", "scope", ".", "frame", "\n", "}", "\n\n", "// Get location information", "ctx", ".", "Filename", "=", "\"", "\"", "\n", "ctx", ".", "Callee", "=", "frame", ".", "callee", "\n\n", "switch", "{", "case", "frame", ".", "native", ":", "ctx", ".", "Filename", "=", "frame", ".", "nativeFile", "\n", "ctx", ".", "Line", "=", "frame", ".", "nativeLine", "\n", "ctx", ".", "Column", "=", "0", "\n", "case", "frame", ".", "file", "!=", "nil", ":", "ctx", ".", "Filename", "=", "\"", "\"", "\n\n", "if", "p", ":=", "frame", ".", "file", ".", "Position", "(", "file", ".", "Idx", "(", "frame", ".", "offset", ")", ")", ";", "p", "!=", "nil", "{", "ctx", ".", "Line", "=", "p", ".", "Line", "\n", "ctx", ".", "Column", "=", "p", ".", "Column", "\n\n", "if", "p", ".", "Filename", "!=", "\"", "\"", "{", "ctx", ".", "Filename", "=", "p", ".", "Filename", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Get the current scope this Value", "ctx", ".", "This", "=", "toValue_object", "(", "scope", ".", "this", ")", "\n\n", "// Build stacktrace (up to 10 levels deep)", "ctx", ".", "Symbols", "=", "make", "(", "map", "[", "string", "]", "Value", ")", "\n", "ctx", ".", "Stacktrace", "=", "append", "(", "ctx", ".", "Stacktrace", ",", "frame", ".", "location", "(", ")", ")", "\n", "for", "limit", "!=", "0", "{", "// Get variables", "stash", ":=", "scope", ".", "lexical", "\n", "for", "{", "for", "_", ",", "name", ":=", "range", "getStashProperties", "(", "stash", ")", "{", "if", "_", ",", "ok", ":=", "ctx", ".", "Symbols", "[", "name", "]", ";", "!", "ok", "{", "ctx", ".", "Symbols", "[", "name", "]", "=", "stash", ".", "getBinding", "(", "name", ",", "true", ")", "\n", "}", "\n", "}", "\n", "stash", "=", "stash", ".", "outer", "(", ")", "\n", "if", "stash", "==", "nil", "||", "stash", ".", "outer", "(", ")", "==", "nil", "{", "break", "\n", "}", "\n", "}", "\n\n", "scope", "=", "scope", ".", "outer", "\n", "if", "scope", "==", "nil", "{", "break", "\n", "}", "\n", "if", "scope", ".", "frame", ".", "offset", ">=", "0", "{", "ctx", ".", "Stacktrace", "=", "append", "(", "ctx", ".", "Stacktrace", ",", "scope", ".", "frame", ".", "location", "(", ")", ")", "\n", "}", "\n", "limit", "--", "\n", "}", "\n\n", "return", "\n", "}" ]
// ContextSkip returns the current execution context of the vm, with a // specific limit on the number of stack frames to traverse, optionally // skipping any innermost native function stack frames.
[ "ContextSkip", "returns", "the", "current", "execution", "context", "of", "the", "vm", "with", "a", "specific", "limit", "on", "the", "number", "of", "stack", "frames", "to", "traverse", "optionally", "skipping", "any", "innermost", "native", "function", "stack", "frames", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L446-L515
train
robertkrimen/otto
otto.go
Get
func (self Object) Get(name string) (Value, error) { value := Value{} err := catchPanic(func() { value = self.object.get(name) }) if !value.safe() { value = Value{} } return value, err }
go
func (self Object) Get(name string) (Value, error) { value := Value{} err := catchPanic(func() { value = self.object.get(name) }) if !value.safe() { value = Value{} } return value, err }
[ "func", "(", "self", "Object", ")", "Get", "(", "name", "string", ")", "(", "Value", ",", "error", ")", "{", "value", ":=", "Value", "{", "}", "\n", "err", ":=", "catchPanic", "(", "func", "(", ")", "{", "value", "=", "self", ".", "object", ".", "get", "(", "name", ")", "\n", "}", ")", "\n", "if", "!", "value", ".", "safe", "(", ")", "{", "value", "=", "Value", "{", "}", "\n", "}", "\n", "return", "value", ",", "err", "\n", "}" ]
// Get the value of the property with the given name.
[ "Get", "the", "value", "of", "the", "property", "with", "the", "given", "name", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L696-L705
train
robertkrimen/otto
otto.go
Keys
func (self Object) Keys() []string { var keys []string self.object.enumerate(false, func(name string) bool { keys = append(keys, name) return true }) return keys }
go
func (self Object) Keys() []string { var keys []string self.object.enumerate(false, func(name string) bool { keys = append(keys, name) return true }) return keys }
[ "func", "(", "self", "Object", ")", "Keys", "(", ")", "[", "]", "string", "{", "var", "keys", "[", "]", "string", "\n", "self", ".", "object", ".", "enumerate", "(", "false", ",", "func", "(", "name", "string", ")", "bool", "{", "keys", "=", "append", "(", "keys", ",", "name", ")", "\n", "return", "true", "\n", "}", ")", "\n", "return", "keys", "\n", "}" ]
// Keys gets the keys for the given object. // // Equivalent to calling Object.keys on the object.
[ "Keys", "gets", "the", "keys", "for", "the", "given", "object", ".", "Equivalent", "to", "calling", "Object", ".", "keys", "on", "the", "object", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto.go#L727-L734
train
grpc-ecosystem/go-grpc-middleware
recovery/options.go
WithRecoveryHandler
func WithRecoveryHandler(f RecoveryHandlerFunc) Option { return func(o *options) { o.recoveryHandlerFunc = RecoveryHandlerFuncContext(func(ctx context.Context, p interface{}) error { return f(p) }) } }
go
func WithRecoveryHandler(f RecoveryHandlerFunc) Option { return func(o *options) { o.recoveryHandlerFunc = RecoveryHandlerFuncContext(func(ctx context.Context, p interface{}) error { return f(p) }) } }
[ "func", "WithRecoveryHandler", "(", "f", "RecoveryHandlerFunc", ")", "Option", "{", "return", "func", "(", "o", "*", "options", ")", "{", "o", ".", "recoveryHandlerFunc", "=", "RecoveryHandlerFuncContext", "(", "func", "(", "ctx", "context", ".", "Context", ",", "p", "interface", "{", "}", ")", "error", "{", "return", "f", "(", "p", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// WithRecoveryHandler customizes the function for recovering from a panic.
[ "WithRecoveryHandler", "customizes", "the", "function", "for", "recovering", "from", "a", "panic", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/recovery/options.go#L30-L36
train
grpc-ecosystem/go-grpc-middleware
retry/options.go
WithMax
func WithMax(maxRetries uint) CallOption { return CallOption{applyFunc: func(o *options) { o.max = maxRetries }} }
go
func WithMax(maxRetries uint) CallOption { return CallOption{applyFunc: func(o *options) { o.max = maxRetries }} }
[ "func", "WithMax", "(", "maxRetries", "uint", ")", "CallOption", "{", "return", "CallOption", "{", "applyFunc", ":", "func", "(", "o", "*", "options", ")", "{", "o", ".", "max", "=", "maxRetries", "\n", "}", "}", "\n", "}" ]
// WithMax sets the maximum number of retries on this call, or this interceptor.
[ "WithMax", "sets", "the", "maximum", "number", "of", "retries", "on", "this", "call", "or", "this", "interceptor", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/retry/options.go#L56-L60
train
grpc-ecosystem/go-grpc-middleware
retry/options.go
WithBackoff
func WithBackoff(bf BackoffFunc) CallOption { return CallOption{applyFunc: func(o *options) { o.backoffFunc = BackoffFuncContext(func(ctx context.Context, attempt uint) time.Duration { return bf(attempt) }) }} }
go
func WithBackoff(bf BackoffFunc) CallOption { return CallOption{applyFunc: func(o *options) { o.backoffFunc = BackoffFuncContext(func(ctx context.Context, attempt uint) time.Duration { return bf(attempt) }) }} }
[ "func", "WithBackoff", "(", "bf", "BackoffFunc", ")", "CallOption", "{", "return", "CallOption", "{", "applyFunc", ":", "func", "(", "o", "*", "options", ")", "{", "o", ".", "backoffFunc", "=", "BackoffFuncContext", "(", "func", "(", "ctx", "context", ".", "Context", ",", "attempt", "uint", ")", "time", ".", "Duration", "{", "return", "bf", "(", "attempt", ")", "\n", "}", ")", "\n", "}", "}", "\n", "}" ]
// WithBackoff sets the `BackoffFunc` used to control time between retries.
[ "WithBackoff", "sets", "the", "BackoffFunc", "used", "to", "control", "time", "between", "retries", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/retry/options.go#L63-L69
train
grpc-ecosystem/go-grpc-middleware
retry/options.go
WithBackoffContext
func WithBackoffContext(bf BackoffFuncContext) CallOption { return CallOption{applyFunc: func(o *options) { o.backoffFunc = bf }} }
go
func WithBackoffContext(bf BackoffFuncContext) CallOption { return CallOption{applyFunc: func(o *options) { o.backoffFunc = bf }} }
[ "func", "WithBackoffContext", "(", "bf", "BackoffFuncContext", ")", "CallOption", "{", "return", "CallOption", "{", "applyFunc", ":", "func", "(", "o", "*", "options", ")", "{", "o", ".", "backoffFunc", "=", "bf", "\n", "}", "}", "\n", "}" ]
// WithBackoffContext sets the `BackoffFuncContext` used to control time between retries.
[ "WithBackoffContext", "sets", "the", "BackoffFuncContext", "used", "to", "control", "time", "between", "retries", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/retry/options.go#L72-L76
train
grpc-ecosystem/go-grpc-middleware
logging/logrus/server_interceptors.go
UnaryServerInterceptor
func UnaryServerInterceptor(entry *logrus.Entry, opts ...Option) grpc.UnaryServerInterceptor { o := evaluateServerOpt(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { startTime := time.Now() newCtx := newLoggerForCall(ctx, entry, info.FullMethod, startTime) resp, err := handler(newCtx, req) if !o.shouldLog(info.FullMethod, err) { return resp, err } code := o.codeFunc(err) level := o.levelFunc(code) durField, durVal := o.durationFunc(time.Since(startTime)) fields := logrus.Fields{ "grpc.code": code.String(), durField: durVal, } if err != nil { fields[logrus.ErrorKey] = err } levelLogf( ctx_logrus.Extract(newCtx).WithFields(fields), // re-extract logger from newCtx, as it may have extra fields that changed in the holder. level, "finished unary call with code "+code.String()) return resp, err } }
go
func UnaryServerInterceptor(entry *logrus.Entry, opts ...Option) grpc.UnaryServerInterceptor { o := evaluateServerOpt(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { startTime := time.Now() newCtx := newLoggerForCall(ctx, entry, info.FullMethod, startTime) resp, err := handler(newCtx, req) if !o.shouldLog(info.FullMethod, err) { return resp, err } code := o.codeFunc(err) level := o.levelFunc(code) durField, durVal := o.durationFunc(time.Since(startTime)) fields := logrus.Fields{ "grpc.code": code.String(), durField: durVal, } if err != nil { fields[logrus.ErrorKey] = err } levelLogf( ctx_logrus.Extract(newCtx).WithFields(fields), // re-extract logger from newCtx, as it may have extra fields that changed in the holder. level, "finished unary call with code "+code.String()) return resp, err } }
[ "func", "UnaryServerInterceptor", "(", "entry", "*", "logrus", ".", "Entry", ",", "opts", "...", "Option", ")", "grpc", ".", "UnaryServerInterceptor", "{", "o", ":=", "evaluateServerOpt", "(", "opts", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "newCtx", ":=", "newLoggerForCall", "(", "ctx", ",", "entry", ",", "info", ".", "FullMethod", ",", "startTime", ")", "\n\n", "resp", ",", "err", ":=", "handler", "(", "newCtx", ",", "req", ")", "\n\n", "if", "!", "o", ".", "shouldLog", "(", "info", ".", "FullMethod", ",", "err", ")", "{", "return", "resp", ",", "err", "\n", "}", "\n", "code", ":=", "o", ".", "codeFunc", "(", "err", ")", "\n", "level", ":=", "o", ".", "levelFunc", "(", "code", ")", "\n", "durField", ",", "durVal", ":=", "o", ".", "durationFunc", "(", "time", ".", "Since", "(", "startTime", ")", ")", "\n", "fields", ":=", "logrus", ".", "Fields", "{", "\"", "\"", ":", "code", ".", "String", "(", ")", ",", "durField", ":", "durVal", ",", "}", "\n", "if", "err", "!=", "nil", "{", "fields", "[", "logrus", ".", "ErrorKey", "]", "=", "err", "\n", "}", "\n\n", "levelLogf", "(", "ctx_logrus", ".", "Extract", "(", "newCtx", ")", ".", "WithFields", "(", "fields", ")", ",", "// re-extract logger from newCtx, as it may have extra fields that changed in the holder.", "level", ",", "\"", "\"", "+", "code", ".", "String", "(", ")", ")", "\n\n", "return", "resp", ",", "err", "\n", "}", "\n", "}" ]
// UnaryServerInterceptor returns a new unary server interceptors that adds logrus.Entry to the context.
[ "UnaryServerInterceptor", "returns", "a", "new", "unary", "server", "interceptors", "that", "adds", "logrus", ".", "Entry", "to", "the", "context", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/logrus/server_interceptors.go#L26-L55
train
grpc-ecosystem/go-grpc-middleware
logging/logrus/server_interceptors.go
StreamServerInterceptor
func StreamServerInterceptor(entry *logrus.Entry, opts ...Option) grpc.StreamServerInterceptor { o := evaluateServerOpt(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { startTime := time.Now() newCtx := newLoggerForCall(stream.Context(), entry, info.FullMethod, startTime) wrapped := grpc_middleware.WrapServerStream(stream) wrapped.WrappedContext = newCtx err := handler(srv, wrapped) if !o.shouldLog(info.FullMethod, err) { return err } code := o.codeFunc(err) level := o.levelFunc(code) durField, durVal := o.durationFunc(time.Since(startTime)) fields := logrus.Fields{ "grpc.code": code.String(), durField: durVal, } if err != nil { fields[logrus.ErrorKey] = err } levelLogf( ctx_logrus.Extract(newCtx).WithFields(fields), // re-extract logger from newCtx, as it may have extra fields that changed in the holder. level, "finished streaming call with code "+code.String()) return err } }
go
func StreamServerInterceptor(entry *logrus.Entry, opts ...Option) grpc.StreamServerInterceptor { o := evaluateServerOpt(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { startTime := time.Now() newCtx := newLoggerForCall(stream.Context(), entry, info.FullMethod, startTime) wrapped := grpc_middleware.WrapServerStream(stream) wrapped.WrappedContext = newCtx err := handler(srv, wrapped) if !o.shouldLog(info.FullMethod, err) { return err } code := o.codeFunc(err) level := o.levelFunc(code) durField, durVal := o.durationFunc(time.Since(startTime)) fields := logrus.Fields{ "grpc.code": code.String(), durField: durVal, } if err != nil { fields[logrus.ErrorKey] = err } levelLogf( ctx_logrus.Extract(newCtx).WithFields(fields), // re-extract logger from newCtx, as it may have extra fields that changed in the holder. level, "finished streaming call with code "+code.String()) return err } }
[ "func", "StreamServerInterceptor", "(", "entry", "*", "logrus", ".", "Entry", ",", "opts", "...", "Option", ")", "grpc", ".", "StreamServerInterceptor", "{", "o", ":=", "evaluateServerOpt", "(", "opts", ")", "\n", "return", "func", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "error", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "newCtx", ":=", "newLoggerForCall", "(", "stream", ".", "Context", "(", ")", ",", "entry", ",", "info", ".", "FullMethod", ",", "startTime", ")", "\n", "wrapped", ":=", "grpc_middleware", ".", "WrapServerStream", "(", "stream", ")", "\n", "wrapped", ".", "WrappedContext", "=", "newCtx", "\n\n", "err", ":=", "handler", "(", "srv", ",", "wrapped", ")", "\n\n", "if", "!", "o", ".", "shouldLog", "(", "info", ".", "FullMethod", ",", "err", ")", "{", "return", "err", "\n", "}", "\n", "code", ":=", "o", ".", "codeFunc", "(", "err", ")", "\n", "level", ":=", "o", ".", "levelFunc", "(", "code", ")", "\n", "durField", ",", "durVal", ":=", "o", ".", "durationFunc", "(", "time", ".", "Since", "(", "startTime", ")", ")", "\n", "fields", ":=", "logrus", ".", "Fields", "{", "\"", "\"", ":", "code", ".", "String", "(", ")", ",", "durField", ":", "durVal", ",", "}", "\n", "if", "err", "!=", "nil", "{", "fields", "[", "logrus", ".", "ErrorKey", "]", "=", "err", "\n", "}", "\n\n", "levelLogf", "(", "ctx_logrus", ".", "Extract", "(", "newCtx", ")", ".", "WithFields", "(", "fields", ")", ",", "// re-extract logger from newCtx, as it may have extra fields that changed in the holder.", "level", ",", "\"", "\"", "+", "code", ".", "String", "(", ")", ")", "\n\n", "return", "err", "\n", "}", "\n", "}" ]
// StreamServerInterceptor returns a new streaming server interceptor that adds logrus.Entry to the context.
[ "StreamServerInterceptor", "returns", "a", "new", "streaming", "server", "interceptor", "that", "adds", "logrus", ".", "Entry", "to", "the", "context", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/logrus/server_interceptors.go#L58-L89
train
grpc-ecosystem/go-grpc-middleware
logging/zap/client_interceptors.go
StreamClientInterceptor
func StreamClientInterceptor(logger *zap.Logger, opts ...Option) grpc.StreamClientInterceptor { o := evaluateClientOpt(opts) return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { fields := newClientLoggerFields(ctx, method) startTime := time.Now() clientStream, err := streamer(ctx, desc, cc, method, opts...) logFinalClientLine(o, logger.With(fields...), startTime, err, "finished client streaming call") return clientStream, err } }
go
func StreamClientInterceptor(logger *zap.Logger, opts ...Option) grpc.StreamClientInterceptor { o := evaluateClientOpt(opts) return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { fields := newClientLoggerFields(ctx, method) startTime := time.Now() clientStream, err := streamer(ctx, desc, cc, method, opts...) logFinalClientLine(o, logger.With(fields...), startTime, err, "finished client streaming call") return clientStream, err } }
[ "func", "StreamClientInterceptor", "(", "logger", "*", "zap", ".", "Logger", ",", "opts", "...", "Option", ")", "grpc", ".", "StreamClientInterceptor", "{", "o", ":=", "evaluateClientOpt", "(", "opts", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "desc", "*", "grpc", ".", "StreamDesc", ",", "cc", "*", "grpc", ".", "ClientConn", ",", "method", "string", ",", "streamer", "grpc", ".", "Streamer", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "grpc", ".", "ClientStream", ",", "error", ")", "{", "fields", ":=", "newClientLoggerFields", "(", "ctx", ",", "method", ")", "\n", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "clientStream", ",", "err", ":=", "streamer", "(", "ctx", ",", "desc", ",", "cc", ",", "method", ",", "opts", "...", ")", "\n", "logFinalClientLine", "(", "o", ",", "logger", ".", "With", "(", "fields", "...", ")", ",", "startTime", ",", "err", ",", "\"", "\"", ")", "\n", "return", "clientStream", ",", "err", "\n", "}", "\n", "}" ]
// StreamClientInterceptor returns a new streaming client interceptor that optionally logs the execution of external gRPC calls.
[ "StreamClientInterceptor", "returns", "a", "new", "streaming", "client", "interceptor", "that", "optionally", "logs", "the", "execution", "of", "external", "gRPC", "calls", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/client_interceptors.go#L34-L43
train
grpc-ecosystem/go-grpc-middleware
tags/options.go
WithFieldExtractorForInitialReq
func WithFieldExtractorForInitialReq(f RequestFieldExtractorFunc) Option { return func(o *options) { o.requestFieldsFunc = f o.requestFieldsFromInitial = true } }
go
func WithFieldExtractorForInitialReq(f RequestFieldExtractorFunc) Option { return func(o *options) { o.requestFieldsFunc = f o.requestFieldsFromInitial = true } }
[ "func", "WithFieldExtractorForInitialReq", "(", "f", "RequestFieldExtractorFunc", ")", "Option", "{", "return", "func", "(", "o", "*", "options", ")", "{", "o", ".", "requestFieldsFunc", "=", "f", "\n", "o", ".", "requestFieldsFromInitial", "=", "true", "\n", "}", "\n", "}" ]
// WithFieldExtractorForInitialReq customizes the function for extracting log fields from protobuf messages, // for all unary and streaming methods. For client-streams and bidirectional-streams, the tags will be // extracted from the first message from the client.
[ "WithFieldExtractorForInitialReq", "customizes", "the", "function", "for", "extracting", "log", "fields", "from", "protobuf", "messages", "for", "all", "unary", "and", "streaming", "methods", ".", "For", "client", "-", "streams", "and", "bidirectional", "-", "streams", "the", "tags", "will", "be", "extracted", "from", "the", "first", "message", "from", "the", "client", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tags/options.go#L39-L44
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
ExtractIncoming
func ExtractIncoming(ctx context.Context) NiceMD { md, ok := metadata.FromIncomingContext(ctx) if !ok { return NiceMD(metadata.Pairs()) } return NiceMD(md) }
go
func ExtractIncoming(ctx context.Context) NiceMD { md, ok := metadata.FromIncomingContext(ctx) if !ok { return NiceMD(metadata.Pairs()) } return NiceMD(md) }
[ "func", "ExtractIncoming", "(", "ctx", "context", ".", "Context", ")", "NiceMD", "{", "md", ",", "ok", ":=", "metadata", ".", "FromIncomingContext", "(", "ctx", ")", "\n", "if", "!", "ok", "{", "return", "NiceMD", "(", "metadata", ".", "Pairs", "(", ")", ")", "\n", "}", "\n", "return", "NiceMD", "(", "md", ")", "\n", "}" ]
// ExtractIncoming extracts an inbound metadata from the server-side context. // // This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns // a new empty NiceMD.
[ "ExtractIncoming", "extracts", "an", "inbound", "metadata", "from", "the", "server", "-", "side", "context", ".", "This", "function", "always", "returns", "a", "NiceMD", "wrapper", "of", "the", "metadata", ".", "MD", "in", "case", "the", "context", "doesn", "t", "have", "metadata", "it", "returns", "a", "new", "empty", "NiceMD", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L20-L26
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
ExtractOutgoing
func ExtractOutgoing(ctx context.Context) NiceMD { md, ok := metadata.FromOutgoingContext(ctx) if !ok { return NiceMD(metadata.Pairs()) } return NiceMD(md) }
go
func ExtractOutgoing(ctx context.Context) NiceMD { md, ok := metadata.FromOutgoingContext(ctx) if !ok { return NiceMD(metadata.Pairs()) } return NiceMD(md) }
[ "func", "ExtractOutgoing", "(", "ctx", "context", ".", "Context", ")", "NiceMD", "{", "md", ",", "ok", ":=", "metadata", ".", "FromOutgoingContext", "(", "ctx", ")", "\n", "if", "!", "ok", "{", "return", "NiceMD", "(", "metadata", ".", "Pairs", "(", ")", ")", "\n", "}", "\n", "return", "NiceMD", "(", "md", ")", "\n", "}" ]
// ExtractOutgoing extracts an outbound metadata from the client-side context. // // This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns // a new empty NiceMD.
[ "ExtractOutgoing", "extracts", "an", "outbound", "metadata", "from", "the", "client", "-", "side", "context", ".", "This", "function", "always", "returns", "a", "NiceMD", "wrapper", "of", "the", "metadata", ".", "MD", "in", "case", "the", "context", "doesn", "t", "have", "metadata", "it", "returns", "a", "new", "empty", "NiceMD", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L32-L38
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
ToOutgoing
func (m NiceMD) ToOutgoing(ctx context.Context) context.Context { return metadata.NewOutgoingContext(ctx, metadata.MD(m)) }
go
func (m NiceMD) ToOutgoing(ctx context.Context) context.Context { return metadata.NewOutgoingContext(ctx, metadata.MD(m)) }
[ "func", "(", "m", "NiceMD", ")", "ToOutgoing", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "return", "metadata", ".", "NewOutgoingContext", "(", "ctx", ",", "metadata", ".", "MD", "(", "m", ")", ")", "\n", "}" ]
// ToOutgoing sets the given NiceMD as a client-side context for dispatching.
[ "ToOutgoing", "sets", "the", "given", "NiceMD", "as", "a", "client", "-", "side", "context", "for", "dispatching", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L68-L70
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
ToIncoming
func (m NiceMD) ToIncoming(ctx context.Context) context.Context { return metadata.NewIncomingContext(ctx, metadata.MD(m)) }
go
func (m NiceMD) ToIncoming(ctx context.Context) context.Context { return metadata.NewIncomingContext(ctx, metadata.MD(m)) }
[ "func", "(", "m", "NiceMD", ")", "ToIncoming", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "return", "metadata", ".", "NewIncomingContext", "(", "ctx", ",", "metadata", ".", "MD", "(", "m", ")", ")", "\n", "}" ]
// ToIncoming sets the given NiceMD as a server-side context for dispatching. // // This is mostly useful in ServerInterceptors..
[ "ToIncoming", "sets", "the", "given", "NiceMD", "as", "a", "server", "-", "side", "context", "for", "dispatching", ".", "This", "is", "mostly", "useful", "in", "ServerInterceptors", ".." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L75-L77
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
Get
func (m NiceMD) Get(key string) string { k, _ := encodeKeyValue(key, "") vv, ok := m[k] if !ok { return "" } return vv[0] }
go
func (m NiceMD) Get(key string) string { k, _ := encodeKeyValue(key, "") vv, ok := m[k] if !ok { return "" } return vv[0] }
[ "func", "(", "m", "NiceMD", ")", "Get", "(", "key", "string", ")", "string", "{", "k", ",", "_", ":=", "encodeKeyValue", "(", "key", ",", "\"", "\"", ")", "\n", "vv", ",", "ok", ":=", "m", "[", "k", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "vv", "[", "0", "]", "\n", "}" ]
// Get retrieves a single value from the metadata. // // It works analogously to http.Header.Get, returning the first value if there are many set. If the value is not set, // an empty string is returned. // // The function is binary-key safe.
[ "Get", "retrieves", "a", "single", "value", "from", "the", "metadata", ".", "It", "works", "analogously", "to", "http", ".", "Header", ".", "Get", "returning", "the", "first", "value", "if", "there", "are", "many", "set", ".", "If", "the", "value", "is", "not", "set", "an", "empty", "string", "is", "returned", ".", "The", "function", "is", "binary", "-", "key", "safe", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L85-L92
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
Del
func (m NiceMD) Del(key string) NiceMD { k, _ := encodeKeyValue(key, "") delete(m, k) return m }
go
func (m NiceMD) Del(key string) NiceMD { k, _ := encodeKeyValue(key, "") delete(m, k) return m }
[ "func", "(", "m", "NiceMD", ")", "Del", "(", "key", "string", ")", "NiceMD", "{", "k", ",", "_", ":=", "encodeKeyValue", "(", "key", ",", "\"", "\"", ")", "\n", "delete", "(", "m", ",", "k", ")", "\n", "return", "m", "\n", "}" ]
// Del retrieves a single value from the metadata. // // It works analogously to http.Header.Del, deleting all values if they exist. // // The function is binary-key safe.
[ "Del", "retrieves", "a", "single", "value", "from", "the", "metadata", ".", "It", "works", "analogously", "to", "http", ".", "Header", ".", "Del", "deleting", "all", "values", "if", "they", "exist", ".", "The", "function", "is", "binary", "-", "key", "safe", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L100-L104
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
Set
func (m NiceMD) Set(key string, value string) NiceMD { k, v := encodeKeyValue(key, value) m[k] = []string{v} return m }
go
func (m NiceMD) Set(key string, value string) NiceMD { k, v := encodeKeyValue(key, value) m[k] = []string{v} return m }
[ "func", "(", "m", "NiceMD", ")", "Set", "(", "key", "string", ",", "value", "string", ")", "NiceMD", "{", "k", ",", "v", ":=", "encodeKeyValue", "(", "key", ",", "value", ")", "\n", "m", "[", "k", "]", "=", "[", "]", "string", "{", "v", "}", "\n", "return", "m", "\n", "}" ]
// Set sets the given value in a metadata. // // It works analogously to http.Header.Set, overwriting all previous metadata values. // // The function is binary-key safe.
[ "Set", "sets", "the", "given", "value", "in", "a", "metadata", ".", "It", "works", "analogously", "to", "http", ".", "Header", ".", "Set", "overwriting", "all", "previous", "metadata", "values", ".", "The", "function", "is", "binary", "-", "key", "safe", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L111-L115
train
grpc-ecosystem/go-grpc-middleware
util/metautils/nicemd.go
Add
func (m NiceMD) Add(key string, value string) NiceMD { k, v := encodeKeyValue(key, value) m[k] = append(m[k], v) return m }
go
func (m NiceMD) Add(key string, value string) NiceMD { k, v := encodeKeyValue(key, value) m[k] = append(m[k], v) return m }
[ "func", "(", "m", "NiceMD", ")", "Add", "(", "key", "string", ",", "value", "string", ")", "NiceMD", "{", "k", ",", "v", ":=", "encodeKeyValue", "(", "key", ",", "value", ")", "\n", "m", "[", "k", "]", "=", "append", "(", "m", "[", "k", "]", ",", "v", ")", "\n", "return", "m", "\n", "}" ]
// Add retrieves a single value from the metadata. // // It works analogously to http.Header.Add, as it appends to any existing values associated with key. // // The function is binary-key safe.
[ "Add", "retrieves", "a", "single", "value", "from", "the", "metadata", ".", "It", "works", "analogously", "to", "http", ".", "Header", ".", "Add", "as", "it", "appends", "to", "any", "existing", "values", "associated", "with", "key", ".", "The", "function", "is", "binary", "-", "key", "safe", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/util/metautils/nicemd.go#L122-L126
train
grpc-ecosystem/go-grpc-middleware
logging/logrus/ctxlogrus/context.go
AddFields
func AddFields(ctx context.Context, fields logrus.Fields) { l, ok := ctx.Value(ctxLoggerKey).(*ctxLogger) if !ok || l == nil { return } for k, v := range fields { l.fields[k] = v } }
go
func AddFields(ctx context.Context, fields logrus.Fields) { l, ok := ctx.Value(ctxLoggerKey).(*ctxLogger) if !ok || l == nil { return } for k, v := range fields { l.fields[k] = v } }
[ "func", "AddFields", "(", "ctx", "context", ".", "Context", ",", "fields", "logrus", ".", "Fields", ")", "{", "l", ",", "ok", ":=", "ctx", ".", "Value", "(", "ctxLoggerKey", ")", ".", "(", "*", "ctxLogger", ")", "\n", "if", "!", "ok", "||", "l", "==", "nil", "{", "return", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "fields", "{", "l", ".", "fields", "[", "k", "]", "=", "v", "\n", "}", "\n", "}" ]
// AddFields adds logrus fields to the logger.
[ "AddFields", "adds", "logrus", "fields", "to", "the", "logger", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/logrus/ctxlogrus/context.go#L21-L29
train
grpc-ecosystem/go-grpc-middleware
logging/logrus/ctxlogrus/context.go
Extract
func Extract(ctx context.Context) *logrus.Entry { l, ok := ctx.Value(ctxLoggerKey).(*ctxLogger) if !ok || l == nil { return logrus.NewEntry(nullLogger) } fields := logrus.Fields{} // Add grpc_ctxtags tags metadata until now. tags := grpc_ctxtags.Extract(ctx) for k, v := range tags.Values() { fields[k] = v } // Add logrus fields added until now. for k, v := range l.fields { fields[k] = v } return l.logger.WithFields(fields) }
go
func Extract(ctx context.Context) *logrus.Entry { l, ok := ctx.Value(ctxLoggerKey).(*ctxLogger) if !ok || l == nil { return logrus.NewEntry(nullLogger) } fields := logrus.Fields{} // Add grpc_ctxtags tags metadata until now. tags := grpc_ctxtags.Extract(ctx) for k, v := range tags.Values() { fields[k] = v } // Add logrus fields added until now. for k, v := range l.fields { fields[k] = v } return l.logger.WithFields(fields) }
[ "func", "Extract", "(", "ctx", "context", ".", "Context", ")", "*", "logrus", ".", "Entry", "{", "l", ",", "ok", ":=", "ctx", ".", "Value", "(", "ctxLoggerKey", ")", ".", "(", "*", "ctxLogger", ")", "\n", "if", "!", "ok", "||", "l", "==", "nil", "{", "return", "logrus", ".", "NewEntry", "(", "nullLogger", ")", "\n", "}", "\n\n", "fields", ":=", "logrus", ".", "Fields", "{", "}", "\n\n", "// Add grpc_ctxtags tags metadata until now.", "tags", ":=", "grpc_ctxtags", ".", "Extract", "(", "ctx", ")", "\n", "for", "k", ",", "v", ":=", "range", "tags", ".", "Values", "(", ")", "{", "fields", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "// Add logrus fields added until now.", "for", "k", ",", "v", ":=", "range", "l", ".", "fields", "{", "fields", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "return", "l", ".", "logger", ".", "WithFields", "(", "fields", ")", "\n", "}" ]
// Extract takes the call-scoped logrus.Entry from ctx_logrus middleware. // // If the ctx_logrus middleware wasn't used, a no-op `logrus.Entry` is returned. This makes it safe to // use regardless.
[ "Extract", "takes", "the", "call", "-", "scoped", "logrus", ".", "Entry", "from", "ctx_logrus", "middleware", ".", "If", "the", "ctx_logrus", "middleware", "wasn", "t", "used", "a", "no", "-", "op", "logrus", ".", "Entry", "is", "returned", ".", "This", "makes", "it", "safe", "to", "use", "regardless", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/logrus/ctxlogrus/context.go#L35-L55
train
grpc-ecosystem/go-grpc-middleware
logging/logrus/ctxlogrus/context.go
ToContext
func ToContext(ctx context.Context, entry *logrus.Entry) context.Context { l := &ctxLogger{ logger: entry, fields: logrus.Fields{}, } return context.WithValue(ctx, ctxLoggerKey, l) }
go
func ToContext(ctx context.Context, entry *logrus.Entry) context.Context { l := &ctxLogger{ logger: entry, fields: logrus.Fields{}, } return context.WithValue(ctx, ctxLoggerKey, l) }
[ "func", "ToContext", "(", "ctx", "context", ".", "Context", ",", "entry", "*", "logrus", ".", "Entry", ")", "context", ".", "Context", "{", "l", ":=", "&", "ctxLogger", "{", "logger", ":", "entry", ",", "fields", ":", "logrus", ".", "Fields", "{", "}", ",", "}", "\n", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxLoggerKey", ",", "l", ")", "\n", "}" ]
// ToContext adds the logrus.Entry to the context for extraction later. // Returning the new context that has been created.
[ "ToContext", "adds", "the", "logrus", ".", "Entry", "to", "the", "context", "for", "extraction", "later", ".", "Returning", "the", "new", "context", "that", "has", "been", "created", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/logrus/ctxlogrus/context.go#L59-L65
train
grpc-ecosystem/go-grpc-middleware
logging/logrus/client_interceptors.go
StreamClientInterceptor
func StreamClientInterceptor(entry *logrus.Entry, opts ...Option) grpc.StreamClientInterceptor { o := evaluateClientOpt(opts) return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { fields := newClientLoggerFields(ctx, method) startTime := time.Now() clientStream, err := streamer(ctx, desc, cc, method, opts...) logFinalClientLine(o, entry.WithFields(fields), startTime, err, "finished client streaming call") return clientStream, err } }
go
func StreamClientInterceptor(entry *logrus.Entry, opts ...Option) grpc.StreamClientInterceptor { o := evaluateClientOpt(opts) return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { fields := newClientLoggerFields(ctx, method) startTime := time.Now() clientStream, err := streamer(ctx, desc, cc, method, opts...) logFinalClientLine(o, entry.WithFields(fields), startTime, err, "finished client streaming call") return clientStream, err } }
[ "func", "StreamClientInterceptor", "(", "entry", "*", "logrus", ".", "Entry", ",", "opts", "...", "Option", ")", "grpc", ".", "StreamClientInterceptor", "{", "o", ":=", "evaluateClientOpt", "(", "opts", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "desc", "*", "grpc", ".", "StreamDesc", ",", "cc", "*", "grpc", ".", "ClientConn", ",", "method", "string", ",", "streamer", "grpc", ".", "Streamer", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "grpc", ".", "ClientStream", ",", "error", ")", "{", "fields", ":=", "newClientLoggerFields", "(", "ctx", ",", "method", ")", "\n", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "clientStream", ",", "err", ":=", "streamer", "(", "ctx", ",", "desc", ",", "cc", ",", "method", ",", "opts", "...", ")", "\n", "logFinalClientLine", "(", "o", ",", "entry", ".", "WithFields", "(", "fields", ")", ",", "startTime", ",", "err", ",", "\"", "\"", ")", "\n", "return", "clientStream", ",", "err", "\n", "}", "\n", "}" ]
// StreamServerInterceptor returns a new streaming client interceptor that optionally logs the execution of external gRPC calls.
[ "StreamServerInterceptor", "returns", "a", "new", "streaming", "client", "interceptor", "that", "optionally", "logs", "the", "execution", "of", "external", "gRPC", "calls", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/logrus/client_interceptors.go#L28-L37
train
grpc-ecosystem/go-grpc-middleware
tracing/opentracing/options.go
WithTracer
func WithTracer(tracer opentracing.Tracer) Option { return func(o *options) { o.tracer = tracer } }
go
func WithTracer(tracer opentracing.Tracer) Option { return func(o *options) { o.tracer = tracer } }
[ "func", "WithTracer", "(", "tracer", "opentracing", ".", "Tracer", ")", "Option", "{", "return", "func", "(", "o", "*", "options", ")", "{", "o", ".", "tracer", "=", "tracer", "\n", "}", "\n", "}" ]
// WithTracer sets a custom tracer to be used for this middleware, otherwise the opentracing.GlobalTracer is used.
[ "WithTracer", "sets", "a", "custom", "tracer", "to", "be", "used", "for", "this", "middleware", "otherwise", "the", "opentracing", ".", "GlobalTracer", "is", "used", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tracing/opentracing/options.go#L51-L55
train
grpc-ecosystem/go-grpc-middleware
recovery/interceptors.go
UnaryServerInterceptor
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { o := evaluateOptions(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) { defer func() { if r := recover(); r != nil { err = recoverFrom(ctx, r, o.recoveryHandlerFunc) } }() return handler(ctx, req) } }
go
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { o := evaluateOptions(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) { defer func() { if r := recover(); r != nil { err = recoverFrom(ctx, r, o.recoveryHandlerFunc) } }() return handler(ctx, req) } }
[ "func", "UnaryServerInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "UnaryServerInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "_", "interface", "{", "}", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "err", "=", "recoverFrom", "(", "ctx", ",", "r", ",", "o", ".", "recoveryHandlerFunc", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "handler", "(", "ctx", ",", "req", ")", "\n", "}", "\n", "}" ]
// UnaryServerInterceptor returns a new unary server interceptor for panic recovery.
[ "UnaryServerInterceptor", "returns", "a", "new", "unary", "server", "interceptor", "for", "panic", "recovery", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/recovery/interceptors.go#L20-L31
train
grpc-ecosystem/go-grpc-middleware
recovery/interceptors.go
StreamServerInterceptor
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { o := evaluateOptions(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { defer func() { if r := recover(); r != nil { err = recoverFrom(stream.Context(), r, o.recoveryHandlerFunc) } }() return handler(srv, stream) } }
go
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { o := evaluateOptions(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { defer func() { if r := recover(); r != nil { err = recoverFrom(stream.Context(), r, o.recoveryHandlerFunc) } }() return handler(srv, stream) } }
[ "func", "StreamServerInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "StreamServerInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "err", "=", "recoverFrom", "(", "stream", ".", "Context", "(", ")", ",", "r", ",", "o", ".", "recoveryHandlerFunc", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "handler", "(", "srv", ",", "stream", ")", "\n", "}", "\n", "}" ]
// StreamServerInterceptor returns a new streaming server interceptor for panic recovery.
[ "StreamServerInterceptor", "returns", "a", "new", "streaming", "server", "interceptor", "for", "panic", "recovery", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/recovery/interceptors.go#L34-L45
train
grpc-ecosystem/go-grpc-middleware
logging/zap/options.go
WithDecider
func WithDecider(f grpc_logging.Decider) Option { return func(o *options) { o.shouldLog = f } }
go
func WithDecider(f grpc_logging.Decider) Option { return func(o *options) { o.shouldLog = f } }
[ "func", "WithDecider", "(", "f", "grpc_logging", ".", "Decider", ")", "Option", "{", "return", "func", "(", "o", "*", "options", ")", "{", "o", ".", "shouldLog", "=", "f", "\n", "}", "\n", "}" ]
// WithDecider customizes the function for deciding if the gRPC interceptor logs should log.
[ "WithDecider", "customizes", "the", "function", "for", "deciding", "if", "the", "gRPC", "interceptor", "logs", "should", "log", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/options.go#L57-L61
train
grpc-ecosystem/go-grpc-middleware
logging/zap/options.go
WithCodes
func WithCodes(f grpc_logging.ErrorToCode) Option { return func(o *options) { o.codeFunc = f } }
go
func WithCodes(f grpc_logging.ErrorToCode) Option { return func(o *options) { o.codeFunc = f } }
[ "func", "WithCodes", "(", "f", "grpc_logging", ".", "ErrorToCode", ")", "Option", "{", "return", "func", "(", "o", "*", "options", ")", "{", "o", ".", "codeFunc", "=", "f", "\n", "}", "\n", "}" ]
// WithCodes customizes the function for mapping errors to error codes.
[ "WithCodes", "customizes", "the", "function", "for", "mapping", "errors", "to", "error", "codes", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/options.go#L71-L75
train
grpc-ecosystem/go-grpc-middleware
logging/zap/options.go
DefaultCodeToLevel
func DefaultCodeToLevel(code codes.Code) zapcore.Level { switch code { case codes.OK: return zap.InfoLevel case codes.Canceled: return zap.InfoLevel case codes.Unknown: return zap.ErrorLevel case codes.InvalidArgument: return zap.InfoLevel case codes.DeadlineExceeded: return zap.WarnLevel case codes.NotFound: return zap.InfoLevel case codes.AlreadyExists: return zap.InfoLevel case codes.PermissionDenied: return zap.WarnLevel case codes.Unauthenticated: return zap.InfoLevel // unauthenticated requests can happen case codes.ResourceExhausted: return zap.WarnLevel case codes.FailedPrecondition: return zap.WarnLevel case codes.Aborted: return zap.WarnLevel case codes.OutOfRange: return zap.WarnLevel case codes.Unimplemented: return zap.ErrorLevel case codes.Internal: return zap.ErrorLevel case codes.Unavailable: return zap.WarnLevel case codes.DataLoss: return zap.ErrorLevel default: return zap.ErrorLevel } }
go
func DefaultCodeToLevel(code codes.Code) zapcore.Level { switch code { case codes.OK: return zap.InfoLevel case codes.Canceled: return zap.InfoLevel case codes.Unknown: return zap.ErrorLevel case codes.InvalidArgument: return zap.InfoLevel case codes.DeadlineExceeded: return zap.WarnLevel case codes.NotFound: return zap.InfoLevel case codes.AlreadyExists: return zap.InfoLevel case codes.PermissionDenied: return zap.WarnLevel case codes.Unauthenticated: return zap.InfoLevel // unauthenticated requests can happen case codes.ResourceExhausted: return zap.WarnLevel case codes.FailedPrecondition: return zap.WarnLevel case codes.Aborted: return zap.WarnLevel case codes.OutOfRange: return zap.WarnLevel case codes.Unimplemented: return zap.ErrorLevel case codes.Internal: return zap.ErrorLevel case codes.Unavailable: return zap.WarnLevel case codes.DataLoss: return zap.ErrorLevel default: return zap.ErrorLevel } }
[ "func", "DefaultCodeToLevel", "(", "code", "codes", ".", "Code", ")", "zapcore", ".", "Level", "{", "switch", "code", "{", "case", "codes", ".", "OK", ":", "return", "zap", ".", "InfoLevel", "\n", "case", "codes", ".", "Canceled", ":", "return", "zap", ".", "InfoLevel", "\n", "case", "codes", ".", "Unknown", ":", "return", "zap", ".", "ErrorLevel", "\n", "case", "codes", ".", "InvalidArgument", ":", "return", "zap", ".", "InfoLevel", "\n", "case", "codes", ".", "DeadlineExceeded", ":", "return", "zap", ".", "WarnLevel", "\n", "case", "codes", ".", "NotFound", ":", "return", "zap", ".", "InfoLevel", "\n", "case", "codes", ".", "AlreadyExists", ":", "return", "zap", ".", "InfoLevel", "\n", "case", "codes", ".", "PermissionDenied", ":", "return", "zap", ".", "WarnLevel", "\n", "case", "codes", ".", "Unauthenticated", ":", "return", "zap", ".", "InfoLevel", "// unauthenticated requests can happen", "\n", "case", "codes", ".", "ResourceExhausted", ":", "return", "zap", ".", "WarnLevel", "\n", "case", "codes", ".", "FailedPrecondition", ":", "return", "zap", ".", "WarnLevel", "\n", "case", "codes", ".", "Aborted", ":", "return", "zap", ".", "WarnLevel", "\n", "case", "codes", ".", "OutOfRange", ":", "return", "zap", ".", "WarnLevel", "\n", "case", "codes", ".", "Unimplemented", ":", "return", "zap", ".", "ErrorLevel", "\n", "case", "codes", ".", "Internal", ":", "return", "zap", ".", "ErrorLevel", "\n", "case", "codes", ".", "Unavailable", ":", "return", "zap", ".", "WarnLevel", "\n", "case", "codes", ".", "DataLoss", ":", "return", "zap", ".", "ErrorLevel", "\n", "default", ":", "return", "zap", ".", "ErrorLevel", "\n", "}", "\n", "}" ]
// DefaultCodeToLevel is the default implementation of gRPC return codes and interceptor log level for server side.
[ "DefaultCodeToLevel", "is", "the", "default", "implementation", "of", "gRPC", "return", "codes", "and", "interceptor", "log", "level", "for", "server", "side", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/options.go#L85-L124
train
grpc-ecosystem/go-grpc-middleware
logging/zap/options.go
DurationToTimeMillisField
func DurationToTimeMillisField(duration time.Duration) zapcore.Field { return zap.Float32("grpc.time_ms", durationToMilliseconds(duration)) }
go
func DurationToTimeMillisField(duration time.Duration) zapcore.Field { return zap.Float32("grpc.time_ms", durationToMilliseconds(duration)) }
[ "func", "DurationToTimeMillisField", "(", "duration", "time", ".", "Duration", ")", "zapcore", ".", "Field", "{", "return", "zap", ".", "Float32", "(", "\"", "\"", ",", "durationToMilliseconds", "(", "duration", ")", ")", "\n", "}" ]
// DurationToTimeMillisField converts the duration to milliseconds and uses the key `grpc.time_ms`.
[ "DurationToTimeMillisField", "converts", "the", "duration", "to", "milliseconds", "and", "uses", "the", "key", "grpc", ".", "time_ms", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/options.go#L172-L174
train
grpc-ecosystem/go-grpc-middleware
logging/zap/server_interceptors.go
UnaryServerInterceptor
func UnaryServerInterceptor(logger *zap.Logger, opts ...Option) grpc.UnaryServerInterceptor { o := evaluateServerOpt(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { startTime := time.Now() newCtx := newLoggerForCall(ctx, logger, info.FullMethod, startTime) resp, err := handler(newCtx, req) if !o.shouldLog(info.FullMethod, err) { return resp, err } code := o.codeFunc(err) level := o.levelFunc(code) // re-extract logger from newCtx, as it may have extra fields that changed in the holder. ctx_zap.Extract(newCtx).Check(level, "finished unary call with code "+code.String()).Write( zap.Error(err), zap.String("grpc.code", code.String()), o.durationFunc(time.Since(startTime)), ) return resp, err } }
go
func UnaryServerInterceptor(logger *zap.Logger, opts ...Option) grpc.UnaryServerInterceptor { o := evaluateServerOpt(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { startTime := time.Now() newCtx := newLoggerForCall(ctx, logger, info.FullMethod, startTime) resp, err := handler(newCtx, req) if !o.shouldLog(info.FullMethod, err) { return resp, err } code := o.codeFunc(err) level := o.levelFunc(code) // re-extract logger from newCtx, as it may have extra fields that changed in the holder. ctx_zap.Extract(newCtx).Check(level, "finished unary call with code "+code.String()).Write( zap.Error(err), zap.String("grpc.code", code.String()), o.durationFunc(time.Since(startTime)), ) return resp, err } }
[ "func", "UnaryServerInterceptor", "(", "logger", "*", "zap", ".", "Logger", ",", "opts", "...", "Option", ")", "grpc", ".", "UnaryServerInterceptor", "{", "o", ":=", "evaluateServerOpt", "(", "opts", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n\n", "newCtx", ":=", "newLoggerForCall", "(", "ctx", ",", "logger", ",", "info", ".", "FullMethod", ",", "startTime", ")", "\n\n", "resp", ",", "err", ":=", "handler", "(", "newCtx", ",", "req", ")", "\n", "if", "!", "o", ".", "shouldLog", "(", "info", ".", "FullMethod", ",", "err", ")", "{", "return", "resp", ",", "err", "\n", "}", "\n", "code", ":=", "o", ".", "codeFunc", "(", "err", ")", "\n", "level", ":=", "o", ".", "levelFunc", "(", "code", ")", "\n\n", "// re-extract logger from newCtx, as it may have extra fields that changed in the holder.", "ctx_zap", ".", "Extract", "(", "newCtx", ")", ".", "Check", "(", "level", ",", "\"", "\"", "+", "code", ".", "String", "(", ")", ")", ".", "Write", "(", "zap", ".", "Error", "(", "err", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "code", ".", "String", "(", ")", ")", ",", "o", ".", "durationFunc", "(", "time", ".", "Since", "(", "startTime", ")", ")", ",", ")", "\n\n", "return", "resp", ",", "err", "\n", "}", "\n", "}" ]
// UnaryServerInterceptor returns a new unary server interceptors that adds zap.Logger to the context.
[ "UnaryServerInterceptor", "returns", "a", "new", "unary", "server", "interceptors", "that", "adds", "zap", ".", "Logger", "to", "the", "context", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/server_interceptors.go#L25-L48
train
grpc-ecosystem/go-grpc-middleware
logging/zap/server_interceptors.go
StreamServerInterceptor
func StreamServerInterceptor(logger *zap.Logger, opts ...Option) grpc.StreamServerInterceptor { o := evaluateServerOpt(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { startTime := time.Now() newCtx := newLoggerForCall(stream.Context(), logger, info.FullMethod, startTime) wrapped := grpc_middleware.WrapServerStream(stream) wrapped.WrappedContext = newCtx err := handler(srv, wrapped) if !o.shouldLog(info.FullMethod, err) { return err } code := o.codeFunc(err) level := o.levelFunc(code) // re-extract logger from newCtx, as it may have extra fields that changed in the holder. ctx_zap.Extract(newCtx).Check(level, "finished streaming call with code "+code.String()).Write( zap.Error(err), zap.String("grpc.code", code.String()), o.durationFunc(time.Since(startTime)), ) return err } }
go
func StreamServerInterceptor(logger *zap.Logger, opts ...Option) grpc.StreamServerInterceptor { o := evaluateServerOpt(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { startTime := time.Now() newCtx := newLoggerForCall(stream.Context(), logger, info.FullMethod, startTime) wrapped := grpc_middleware.WrapServerStream(stream) wrapped.WrappedContext = newCtx err := handler(srv, wrapped) if !o.shouldLog(info.FullMethod, err) { return err } code := o.codeFunc(err) level := o.levelFunc(code) // re-extract logger from newCtx, as it may have extra fields that changed in the holder. ctx_zap.Extract(newCtx).Check(level, "finished streaming call with code "+code.String()).Write( zap.Error(err), zap.String("grpc.code", code.String()), o.durationFunc(time.Since(startTime)), ) return err } }
[ "func", "StreamServerInterceptor", "(", "logger", "*", "zap", ".", "Logger", ",", "opts", "...", "Option", ")", "grpc", ".", "StreamServerInterceptor", "{", "o", ":=", "evaluateServerOpt", "(", "opts", ")", "\n", "return", "func", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "error", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "newCtx", ":=", "newLoggerForCall", "(", "stream", ".", "Context", "(", ")", ",", "logger", ",", "info", ".", "FullMethod", ",", "startTime", ")", "\n", "wrapped", ":=", "grpc_middleware", ".", "WrapServerStream", "(", "stream", ")", "\n", "wrapped", ".", "WrappedContext", "=", "newCtx", "\n\n", "err", ":=", "handler", "(", "srv", ",", "wrapped", ")", "\n", "if", "!", "o", ".", "shouldLog", "(", "info", ".", "FullMethod", ",", "err", ")", "{", "return", "err", "\n", "}", "\n", "code", ":=", "o", ".", "codeFunc", "(", "err", ")", "\n", "level", ":=", "o", ".", "levelFunc", "(", "code", ")", "\n\n", "// re-extract logger from newCtx, as it may have extra fields that changed in the holder.", "ctx_zap", ".", "Extract", "(", "newCtx", ")", ".", "Check", "(", "level", ",", "\"", "\"", "+", "code", ".", "String", "(", ")", ")", ".", "Write", "(", "zap", ".", "Error", "(", "err", ")", ",", "zap", ".", "String", "(", "\"", "\"", ",", "code", ".", "String", "(", ")", ")", ",", "o", ".", "durationFunc", "(", "time", ".", "Since", "(", "startTime", ")", ")", ",", ")", "\n\n", "return", "err", "\n", "}", "\n", "}" ]
// StreamServerInterceptor returns a new streaming server interceptor that adds zap.Logger to the context.
[ "StreamServerInterceptor", "returns", "a", "new", "streaming", "server", "interceptor", "that", "adds", "zap", ".", "Logger", "to", "the", "context", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/server_interceptors.go#L51-L75
train
grpc-ecosystem/go-grpc-middleware
chain.go
WithUnaryServerChain
func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption { return grpc.UnaryInterceptor(ChainUnaryServer(interceptors...)) }
go
func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption { return grpc.UnaryInterceptor(ChainUnaryServer(interceptors...)) }
[ "func", "WithUnaryServerChain", "(", "interceptors", "...", "grpc", ".", "UnaryServerInterceptor", ")", "grpc", ".", "ServerOption", "{", "return", "grpc", ".", "UnaryInterceptor", "(", "ChainUnaryServer", "(", "interceptors", "...", ")", ")", "\n", "}" ]
// Chain creates a single interceptor out of a chain of many interceptors. // // WithUnaryServerChain is a grpc.Server config option that accepts multiple unary interceptors. // Basically syntactic sugar.
[ "Chain", "creates", "a", "single", "interceptor", "out", "of", "a", "chain", "of", "many", "interceptors", ".", "WithUnaryServerChain", "is", "a", "grpc", ".", "Server", "config", "option", "that", "accepts", "multiple", "unary", "interceptors", ".", "Basically", "syntactic", "sugar", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/chain.go#L175-L177
train
grpc-ecosystem/go-grpc-middleware
chain.go
WithStreamServerChain
func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption { return grpc.StreamInterceptor(ChainStreamServer(interceptors...)) }
go
func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption { return grpc.StreamInterceptor(ChainStreamServer(interceptors...)) }
[ "func", "WithStreamServerChain", "(", "interceptors", "...", "grpc", ".", "StreamServerInterceptor", ")", "grpc", ".", "ServerOption", "{", "return", "grpc", ".", "StreamInterceptor", "(", "ChainStreamServer", "(", "interceptors", "...", ")", ")", "\n", "}" ]
// WithStreamServerChain is a grpc.Server config option that accepts multiple stream interceptors. // Basically syntactic sugar.
[ "WithStreamServerChain", "is", "a", "grpc", ".", "Server", "config", "option", "that", "accepts", "multiple", "stream", "interceptors", ".", "Basically", "syntactic", "sugar", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/chain.go#L181-L183
train
grpc-ecosystem/go-grpc-middleware
tracing/opentracing/client_interceptors.go
UnaryClientInterceptor
func UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor { o := evaluateOptions(opts) return func(parentCtx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if o.filterOutFunc != nil && !o.filterOutFunc(parentCtx, method) { return invoker(parentCtx, method, req, reply, cc, opts...) } newCtx, clientSpan := newClientSpanFromContext(parentCtx, o.tracer, method) err := invoker(newCtx, method, req, reply, cc, opts...) finishClientSpan(clientSpan, err) return err } }
go
func UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor { o := evaluateOptions(opts) return func(parentCtx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if o.filterOutFunc != nil && !o.filterOutFunc(parentCtx, method) { return invoker(parentCtx, method, req, reply, cc, opts...) } newCtx, clientSpan := newClientSpanFromContext(parentCtx, o.tracer, method) err := invoker(newCtx, method, req, reply, cc, opts...) finishClientSpan(clientSpan, err) return err } }
[ "func", "UnaryClientInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "UnaryClientInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "parentCtx", "context", ".", "Context", ",", "method", "string", ",", "req", ",", "reply", "interface", "{", "}", ",", "cc", "*", "grpc", ".", "ClientConn", ",", "invoker", "grpc", ".", "UnaryInvoker", ",", "opts", "...", "grpc", ".", "CallOption", ")", "error", "{", "if", "o", ".", "filterOutFunc", "!=", "nil", "&&", "!", "o", ".", "filterOutFunc", "(", "parentCtx", ",", "method", ")", "{", "return", "invoker", "(", "parentCtx", ",", "method", ",", "req", ",", "reply", ",", "cc", ",", "opts", "...", ")", "\n", "}", "\n", "newCtx", ",", "clientSpan", ":=", "newClientSpanFromContext", "(", "parentCtx", ",", "o", ".", "tracer", ",", "method", ")", "\n", "err", ":=", "invoker", "(", "newCtx", ",", "method", ",", "req", ",", "reply", ",", "cc", ",", "opts", "...", ")", "\n", "finishClientSpan", "(", "clientSpan", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "}" ]
// UnaryClientInterceptor returns a new unary client interceptor for OpenTracing.
[ "UnaryClientInterceptor", "returns", "a", "new", "unary", "client", "interceptor", "for", "OpenTracing", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tracing/opentracing/client_interceptors.go#L21-L32
train
grpc-ecosystem/go-grpc-middleware
tracing/opentracing/client_interceptors.go
StreamClientInterceptor
func StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor { o := evaluateOptions(opts) return func(parentCtx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { if o.filterOutFunc != nil && !o.filterOutFunc(parentCtx, method) { return streamer(parentCtx, desc, cc, method, opts...) } newCtx, clientSpan := newClientSpanFromContext(parentCtx, o.tracer, method) clientStream, err := streamer(newCtx, desc, cc, method, opts...) if err != nil { finishClientSpan(clientSpan, err) return nil, err } return &tracedClientStream{ClientStream: clientStream, clientSpan: clientSpan}, nil } }
go
func StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor { o := evaluateOptions(opts) return func(parentCtx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { if o.filterOutFunc != nil && !o.filterOutFunc(parentCtx, method) { return streamer(parentCtx, desc, cc, method, opts...) } newCtx, clientSpan := newClientSpanFromContext(parentCtx, o.tracer, method) clientStream, err := streamer(newCtx, desc, cc, method, opts...) if err != nil { finishClientSpan(clientSpan, err) return nil, err } return &tracedClientStream{ClientStream: clientStream, clientSpan: clientSpan}, nil } }
[ "func", "StreamClientInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "StreamClientInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "parentCtx", "context", ".", "Context", ",", "desc", "*", "grpc", ".", "StreamDesc", ",", "cc", "*", "grpc", ".", "ClientConn", ",", "method", "string", ",", "streamer", "grpc", ".", "Streamer", ",", "opts", "...", "grpc", ".", "CallOption", ")", "(", "grpc", ".", "ClientStream", ",", "error", ")", "{", "if", "o", ".", "filterOutFunc", "!=", "nil", "&&", "!", "o", ".", "filterOutFunc", "(", "parentCtx", ",", "method", ")", "{", "return", "streamer", "(", "parentCtx", ",", "desc", ",", "cc", ",", "method", ",", "opts", "...", ")", "\n", "}", "\n", "newCtx", ",", "clientSpan", ":=", "newClientSpanFromContext", "(", "parentCtx", ",", "o", ".", "tracer", ",", "method", ")", "\n", "clientStream", ",", "err", ":=", "streamer", "(", "newCtx", ",", "desc", ",", "cc", ",", "method", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "finishClientSpan", "(", "clientSpan", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "tracedClientStream", "{", "ClientStream", ":", "clientStream", ",", "clientSpan", ":", "clientSpan", "}", ",", "nil", "\n", "}", "\n", "}" ]
// StreamClientInterceptor returns a new streaming client interceptor for OpenTracing.
[ "StreamClientInterceptor", "returns", "a", "new", "streaming", "client", "interceptor", "for", "OpenTracing", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tracing/opentracing/client_interceptors.go#L35-L49
train
grpc-ecosystem/go-grpc-middleware
logging/logrus/options.go
DefaultCodeToLevel
func DefaultCodeToLevel(code codes.Code) logrus.Level { switch code { case codes.OK: return logrus.InfoLevel case codes.Canceled: return logrus.InfoLevel case codes.Unknown: return logrus.ErrorLevel case codes.InvalidArgument: return logrus.InfoLevel case codes.DeadlineExceeded: return logrus.WarnLevel case codes.NotFound: return logrus.InfoLevel case codes.AlreadyExists: return logrus.InfoLevel case codes.PermissionDenied: return logrus.WarnLevel case codes.Unauthenticated: return logrus.InfoLevel // unauthenticated requests can happen case codes.ResourceExhausted: return logrus.WarnLevel case codes.FailedPrecondition: return logrus.WarnLevel case codes.Aborted: return logrus.WarnLevel case codes.OutOfRange: return logrus.WarnLevel case codes.Unimplemented: return logrus.ErrorLevel case codes.Internal: return logrus.ErrorLevel case codes.Unavailable: return logrus.WarnLevel case codes.DataLoss: return logrus.ErrorLevel default: return logrus.ErrorLevel } }
go
func DefaultCodeToLevel(code codes.Code) logrus.Level { switch code { case codes.OK: return logrus.InfoLevel case codes.Canceled: return logrus.InfoLevel case codes.Unknown: return logrus.ErrorLevel case codes.InvalidArgument: return logrus.InfoLevel case codes.DeadlineExceeded: return logrus.WarnLevel case codes.NotFound: return logrus.InfoLevel case codes.AlreadyExists: return logrus.InfoLevel case codes.PermissionDenied: return logrus.WarnLevel case codes.Unauthenticated: return logrus.InfoLevel // unauthenticated requests can happen case codes.ResourceExhausted: return logrus.WarnLevel case codes.FailedPrecondition: return logrus.WarnLevel case codes.Aborted: return logrus.WarnLevel case codes.OutOfRange: return logrus.WarnLevel case codes.Unimplemented: return logrus.ErrorLevel case codes.Internal: return logrus.ErrorLevel case codes.Unavailable: return logrus.WarnLevel case codes.DataLoss: return logrus.ErrorLevel default: return logrus.ErrorLevel } }
[ "func", "DefaultCodeToLevel", "(", "code", "codes", ".", "Code", ")", "logrus", ".", "Level", "{", "switch", "code", "{", "case", "codes", ".", "OK", ":", "return", "logrus", ".", "InfoLevel", "\n", "case", "codes", ".", "Canceled", ":", "return", "logrus", ".", "InfoLevel", "\n", "case", "codes", ".", "Unknown", ":", "return", "logrus", ".", "ErrorLevel", "\n", "case", "codes", ".", "InvalidArgument", ":", "return", "logrus", ".", "InfoLevel", "\n", "case", "codes", ".", "DeadlineExceeded", ":", "return", "logrus", ".", "WarnLevel", "\n", "case", "codes", ".", "NotFound", ":", "return", "logrus", ".", "InfoLevel", "\n", "case", "codes", ".", "AlreadyExists", ":", "return", "logrus", ".", "InfoLevel", "\n", "case", "codes", ".", "PermissionDenied", ":", "return", "logrus", ".", "WarnLevel", "\n", "case", "codes", ".", "Unauthenticated", ":", "return", "logrus", ".", "InfoLevel", "// unauthenticated requests can happen", "\n", "case", "codes", ".", "ResourceExhausted", ":", "return", "logrus", ".", "WarnLevel", "\n", "case", "codes", ".", "FailedPrecondition", ":", "return", "logrus", ".", "WarnLevel", "\n", "case", "codes", ".", "Aborted", ":", "return", "logrus", ".", "WarnLevel", "\n", "case", "codes", ".", "OutOfRange", ":", "return", "logrus", ".", "WarnLevel", "\n", "case", "codes", ".", "Unimplemented", ":", "return", "logrus", ".", "ErrorLevel", "\n", "case", "codes", ".", "Internal", ":", "return", "logrus", ".", "ErrorLevel", "\n", "case", "codes", ".", "Unavailable", ":", "return", "logrus", ".", "WarnLevel", "\n", "case", "codes", ".", "DataLoss", ":", "return", "logrus", ".", "ErrorLevel", "\n", "default", ":", "return", "logrus", ".", "ErrorLevel", "\n", "}", "\n", "}" ]
// DefaultCodeToLevel is the default implementation of gRPC return codes to log levels for server side.
[ "DefaultCodeToLevel", "is", "the", "default", "implementation", "of", "gRPC", "return", "codes", "to", "log", "levels", "for", "server", "side", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/logrus/options.go#L87-L126
train
grpc-ecosystem/go-grpc-middleware
tracing/opentracing/metadata.go
Set
func (m metadataTextMap) Set(key, val string) { // gRPC allows for complex binary values to be written. encodedKey, encodedVal := encodeKeyValue(key, val) // The metadata object is a multimap, and previous values may exist, but for opentracing headers, we do not append // we just override. m[encodedKey] = []string{encodedVal} }
go
func (m metadataTextMap) Set(key, val string) { // gRPC allows for complex binary values to be written. encodedKey, encodedVal := encodeKeyValue(key, val) // The metadata object is a multimap, and previous values may exist, but for opentracing headers, we do not append // we just override. m[encodedKey] = []string{encodedVal} }
[ "func", "(", "m", "metadataTextMap", ")", "Set", "(", "key", ",", "val", "string", ")", "{", "// gRPC allows for complex binary values to be written.", "encodedKey", ",", "encodedVal", ":=", "encodeKeyValue", "(", "key", ",", "val", ")", "\n", "// The metadata object is a multimap, and previous values may exist, but for opentracing headers, we do not append", "// we just override.", "m", "[", "encodedKey", "]", "=", "[", "]", "string", "{", "encodedVal", "}", "\n", "}" ]
// Set is a opentracing.TextMapReader interface that extracts values.
[ "Set", "is", "a", "opentracing", ".", "TextMapReader", "interface", "that", "extracts", "values", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tracing/opentracing/metadata.go#L23-L29
train
grpc-ecosystem/go-grpc-middleware
tracing/opentracing/metadata.go
ForeachKey
func (m metadataTextMap) ForeachKey(callback func(key, val string) error) error { for k, vv := range m { for _, v := range vv { if decodedKey, decodedVal, err := metadata.DecodeKeyValue(k, v); err == nil { if err = callback(decodedKey, decodedVal); err != nil { return err } } else { return fmt.Errorf("failed decoding opentracing from gRPC metadata: %v", err) } } } return nil }
go
func (m metadataTextMap) ForeachKey(callback func(key, val string) error) error { for k, vv := range m { for _, v := range vv { if decodedKey, decodedVal, err := metadata.DecodeKeyValue(k, v); err == nil { if err = callback(decodedKey, decodedVal); err != nil { return err } } else { return fmt.Errorf("failed decoding opentracing from gRPC metadata: %v", err) } } } return nil }
[ "func", "(", "m", "metadataTextMap", ")", "ForeachKey", "(", "callback", "func", "(", "key", ",", "val", "string", ")", "error", ")", "error", "{", "for", "k", ",", "vv", ":=", "range", "m", "{", "for", "_", ",", "v", ":=", "range", "vv", "{", "if", "decodedKey", ",", "decodedVal", ",", "err", ":=", "metadata", ".", "DecodeKeyValue", "(", "k", ",", "v", ")", ";", "err", "==", "nil", "{", "if", "err", "=", "callback", "(", "decodedKey", ",", "decodedVal", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ForeachKey is a opentracing.TextMapReader interface that extracts values.
[ "ForeachKey", "is", "a", "opentracing", ".", "TextMapReader", "interface", "that", "extracts", "values", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tracing/opentracing/metadata.go#L32-L45
train
grpc-ecosystem/go-grpc-middleware
logging/zap/ctxzap/context.go
AddFields
func AddFields(ctx context.Context, fields ...zapcore.Field) { l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger) if !ok || l == nil { return } l.fields = append(l.fields, fields...) }
go
func AddFields(ctx context.Context, fields ...zapcore.Field) { l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger) if !ok || l == nil { return } l.fields = append(l.fields, fields...) }
[ "func", "AddFields", "(", "ctx", "context", ".", "Context", ",", "fields", "...", "zapcore", ".", "Field", ")", "{", "l", ",", "ok", ":=", "ctx", ".", "Value", "(", "ctxMarkerKey", ")", ".", "(", "*", "ctxLogger", ")", "\n", "if", "!", "ok", "||", "l", "==", "nil", "{", "return", "\n", "}", "\n", "l", ".", "fields", "=", "append", "(", "l", ".", "fields", ",", "fields", "...", ")", "\n\n", "}" ]
// AddFields adds zap fields to the logger.
[ "AddFields", "adds", "zap", "fields", "to", "the", "logger", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/ctxzap/context.go#L23-L30
train
grpc-ecosystem/go-grpc-middleware
logging/zap/ctxzap/context.go
Extract
func Extract(ctx context.Context) *zap.Logger { l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger) if !ok || l == nil { return nullLogger } // Add grpc_ctxtags tags metadata until now. fields := TagsToFields(ctx) // Add zap fields added until now. fields = append(fields, l.fields...) return l.logger.With(fields...) }
go
func Extract(ctx context.Context) *zap.Logger { l, ok := ctx.Value(ctxMarkerKey).(*ctxLogger) if !ok || l == nil { return nullLogger } // Add grpc_ctxtags tags metadata until now. fields := TagsToFields(ctx) // Add zap fields added until now. fields = append(fields, l.fields...) return l.logger.With(fields...) }
[ "func", "Extract", "(", "ctx", "context", ".", "Context", ")", "*", "zap", ".", "Logger", "{", "l", ",", "ok", ":=", "ctx", ".", "Value", "(", "ctxMarkerKey", ")", ".", "(", "*", "ctxLogger", ")", "\n", "if", "!", "ok", "||", "l", "==", "nil", "{", "return", "nullLogger", "\n", "}", "\n", "// Add grpc_ctxtags tags metadata until now.", "fields", ":=", "TagsToFields", "(", "ctx", ")", "\n", "// Add zap fields added until now.", "fields", "=", "append", "(", "fields", ",", "l", ".", "fields", "...", ")", "\n", "return", "l", ".", "logger", ".", "With", "(", "fields", "...", ")", "\n", "}" ]
// Extract takes the call-scoped Logger from grpc_zap middleware. // // It always returns a Logger that has all the grpc_ctxtags updated.
[ "Extract", "takes", "the", "call", "-", "scoped", "Logger", "from", "grpc_zap", "middleware", ".", "It", "always", "returns", "a", "Logger", "that", "has", "all", "the", "grpc_ctxtags", "updated", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/ctxzap/context.go#L35-L45
train
grpc-ecosystem/go-grpc-middleware
logging/zap/ctxzap/context.go
TagsToFields
func TagsToFields(ctx context.Context) []zapcore.Field { fields := []zapcore.Field{} tags := grpc_ctxtags.Extract(ctx) for k, v := range tags.Values() { fields = append(fields, zap.Any(k, v)) } return fields }
go
func TagsToFields(ctx context.Context) []zapcore.Field { fields := []zapcore.Field{} tags := grpc_ctxtags.Extract(ctx) for k, v := range tags.Values() { fields = append(fields, zap.Any(k, v)) } return fields }
[ "func", "TagsToFields", "(", "ctx", "context", ".", "Context", ")", "[", "]", "zapcore", ".", "Field", "{", "fields", ":=", "[", "]", "zapcore", ".", "Field", "{", "}", "\n", "tags", ":=", "grpc_ctxtags", ".", "Extract", "(", "ctx", ")", "\n", "for", "k", ",", "v", ":=", "range", "tags", ".", "Values", "(", ")", "{", "fields", "=", "append", "(", "fields", ",", "zap", ".", "Any", "(", "k", ",", "v", ")", ")", "\n", "}", "\n", "return", "fields", "\n", "}" ]
// TagsToFields transforms the Tags on the supplied context into zap fields.
[ "TagsToFields", "transforms", "the", "Tags", "on", "the", "supplied", "context", "into", "zap", "fields", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/ctxzap/context.go#L48-L55
train
grpc-ecosystem/go-grpc-middleware
logging/zap/ctxzap/context.go
ToContext
func ToContext(ctx context.Context, logger *zap.Logger) context.Context { l := &ctxLogger{ logger: logger, } return context.WithValue(ctx, ctxMarkerKey, l) }
go
func ToContext(ctx context.Context, logger *zap.Logger) context.Context { l := &ctxLogger{ logger: logger, } return context.WithValue(ctx, ctxMarkerKey, l) }
[ "func", "ToContext", "(", "ctx", "context", ".", "Context", ",", "logger", "*", "zap", ".", "Logger", ")", "context", ".", "Context", "{", "l", ":=", "&", "ctxLogger", "{", "logger", ":", "logger", ",", "}", "\n", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxMarkerKey", ",", "l", ")", "\n", "}" ]
// ToContext adds the zap.Logger to the context for extraction later. // Returning the new context that has been created.
[ "ToContext", "adds", "the", "zap", ".", "Logger", "to", "the", "context", "for", "extraction", "later", ".", "Returning", "the", "new", "context", "that", "has", "been", "created", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/logging/zap/ctxzap/context.go#L59-L64
train
grpc-ecosystem/go-grpc-middleware
tracing/opentracing/server_interceptors.go
UnaryServerInterceptor
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { o := evaluateOptions(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if o.filterOutFunc != nil && !o.filterOutFunc(ctx, info.FullMethod) { return handler(ctx, req) } newCtx, serverSpan := newServerSpanFromInbound(ctx, o.tracer, info.FullMethod) resp, err := handler(newCtx, req) finishServerSpan(ctx, serverSpan, err) return resp, err } }
go
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { o := evaluateOptions(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if o.filterOutFunc != nil && !o.filterOutFunc(ctx, info.FullMethod) { return handler(ctx, req) } newCtx, serverSpan := newServerSpanFromInbound(ctx, o.tracer, info.FullMethod) resp, err := handler(newCtx, req) finishServerSpan(ctx, serverSpan, err) return resp, err } }
[ "func", "UnaryServerInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "UnaryServerInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "o", ".", "filterOutFunc", "!=", "nil", "&&", "!", "o", ".", "filterOutFunc", "(", "ctx", ",", "info", ".", "FullMethod", ")", "{", "return", "handler", "(", "ctx", ",", "req", ")", "\n", "}", "\n", "newCtx", ",", "serverSpan", ":=", "newServerSpanFromInbound", "(", "ctx", ",", "o", ".", "tracer", ",", "info", ".", "FullMethod", ")", "\n", "resp", ",", "err", ":=", "handler", "(", "newCtx", ",", "req", ")", "\n", "finishServerSpan", "(", "ctx", ",", "serverSpan", ",", "err", ")", "\n", "return", "resp", ",", "err", "\n", "}", "\n", "}" ]
// UnaryServerInterceptor returns a new unary server interceptor for OpenTracing.
[ "UnaryServerInterceptor", "returns", "a", "new", "unary", "server", "interceptor", "for", "OpenTracing", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tracing/opentracing/server_interceptors.go#L23-L34
train
grpc-ecosystem/go-grpc-middleware
tracing/opentracing/server_interceptors.go
StreamServerInterceptor
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { o := evaluateOptions(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if o.filterOutFunc != nil && !o.filterOutFunc(stream.Context(), info.FullMethod) { return handler(srv, stream) } newCtx, serverSpan := newServerSpanFromInbound(stream.Context(), o.tracer, info.FullMethod) wrappedStream := grpc_middleware.WrapServerStream(stream) wrappedStream.WrappedContext = newCtx err := handler(srv, wrappedStream) finishServerSpan(newCtx, serverSpan, err) return err } }
go
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { o := evaluateOptions(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if o.filterOutFunc != nil && !o.filterOutFunc(stream.Context(), info.FullMethod) { return handler(srv, stream) } newCtx, serverSpan := newServerSpanFromInbound(stream.Context(), o.tracer, info.FullMethod) wrappedStream := grpc_middleware.WrapServerStream(stream) wrappedStream.WrappedContext = newCtx err := handler(srv, wrappedStream) finishServerSpan(newCtx, serverSpan, err) return err } }
[ "func", "StreamServerInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "StreamServerInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "error", "{", "if", "o", ".", "filterOutFunc", "!=", "nil", "&&", "!", "o", ".", "filterOutFunc", "(", "stream", ".", "Context", "(", ")", ",", "info", ".", "FullMethod", ")", "{", "return", "handler", "(", "srv", ",", "stream", ")", "\n", "}", "\n", "newCtx", ",", "serverSpan", ":=", "newServerSpanFromInbound", "(", "stream", ".", "Context", "(", ")", ",", "o", ".", "tracer", ",", "info", ".", "FullMethod", ")", "\n", "wrappedStream", ":=", "grpc_middleware", ".", "WrapServerStream", "(", "stream", ")", "\n", "wrappedStream", ".", "WrappedContext", "=", "newCtx", "\n", "err", ":=", "handler", "(", "srv", ",", "wrappedStream", ")", "\n", "finishServerSpan", "(", "newCtx", ",", "serverSpan", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "}" ]
// StreamServerInterceptor returns a new streaming server interceptor for OpenTracing.
[ "StreamServerInterceptor", "returns", "a", "new", "streaming", "server", "interceptor", "for", "OpenTracing", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tracing/opentracing/server_interceptors.go#L37-L50
train
grpc-ecosystem/go-grpc-middleware
validator/validator.go
UnaryServerInterceptor
func UnaryServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if v, ok := req.(validator); ok { if err := v.Validate(); err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } } return handler(ctx, req) } }
go
func UnaryServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if v, ok := req.(validator); ok { if err := v.Validate(); err != nil { return nil, grpc.Errorf(codes.InvalidArgument, err.Error()) } } return handler(ctx, req) } }
[ "func", "UnaryServerInterceptor", "(", ")", "grpc", ".", "UnaryServerInterceptor", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "v", ",", "ok", ":=", "req", ".", "(", "validator", ")", ";", "ok", "{", "if", "err", ":=", "v", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "grpc", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "handler", "(", "ctx", ",", "req", ")", "\n", "}", "\n", "}" ]
// UnaryServerInterceptor returns a new unary server interceptor that validates incoming messages. // // Invalid messages will be rejected with `InvalidArgument` before reaching any userspace handlers.
[ "UnaryServerInterceptor", "returns", "a", "new", "unary", "server", "interceptor", "that", "validates", "incoming", "messages", ".", "Invalid", "messages", "will", "be", "rejected", "with", "InvalidArgument", "before", "reaching", "any", "userspace", "handlers", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/validator/validator.go#L19-L28
train
grpc-ecosystem/go-grpc-middleware
tags/interceptors.go
UnaryServerInterceptor
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { o := evaluateOptions(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { newCtx := newTagsForCtx(ctx) if o.requestFieldsFunc != nil { setRequestFieldTags(newCtx, o.requestFieldsFunc, info.FullMethod, req) } return handler(newCtx, req) } }
go
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { o := evaluateOptions(opts) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { newCtx := newTagsForCtx(ctx) if o.requestFieldsFunc != nil { setRequestFieldTags(newCtx, o.requestFieldsFunc, info.FullMethod, req) } return handler(newCtx, req) } }
[ "func", "UnaryServerInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "UnaryServerInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "newCtx", ":=", "newTagsForCtx", "(", "ctx", ")", "\n", "if", "o", ".", "requestFieldsFunc", "!=", "nil", "{", "setRequestFieldTags", "(", "newCtx", ",", "o", ".", "requestFieldsFunc", ",", "info", ".", "FullMethod", ",", "req", ")", "\n", "}", "\n", "return", "handler", "(", "newCtx", ",", "req", ")", "\n", "}", "\n", "}" ]
// UnaryServerInterceptor returns a new unary server interceptors that sets the values for request tags.
[ "UnaryServerInterceptor", "returns", "a", "new", "unary", "server", "interceptors", "that", "sets", "the", "values", "for", "request", "tags", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tags/interceptors.go#L14-L23
train
grpc-ecosystem/go-grpc-middleware
tags/interceptors.go
StreamServerInterceptor
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { o := evaluateOptions(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { newCtx := newTagsForCtx(stream.Context()) if o.requestFieldsFunc == nil { // Short-circuit, don't do the expensive bit of allocating a wrappedStream. wrappedStream := grpc_middleware.WrapServerStream(stream) wrappedStream.WrappedContext = newCtx return handler(srv, wrappedStream) } wrapped := &wrappedStream{stream, info, o, newCtx, true} err := handler(srv, wrapped) return err } }
go
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { o := evaluateOptions(opts) return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { newCtx := newTagsForCtx(stream.Context()) if o.requestFieldsFunc == nil { // Short-circuit, don't do the expensive bit of allocating a wrappedStream. wrappedStream := grpc_middleware.WrapServerStream(stream) wrappedStream.WrappedContext = newCtx return handler(srv, wrappedStream) } wrapped := &wrappedStream{stream, info, o, newCtx, true} err := handler(srv, wrapped) return err } }
[ "func", "StreamServerInterceptor", "(", "opts", "...", "Option", ")", "grpc", ".", "StreamServerInterceptor", "{", "o", ":=", "evaluateOptions", "(", "opts", ")", "\n", "return", "func", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "error", "{", "newCtx", ":=", "newTagsForCtx", "(", "stream", ".", "Context", "(", ")", ")", "\n", "if", "o", ".", "requestFieldsFunc", "==", "nil", "{", "// Short-circuit, don't do the expensive bit of allocating a wrappedStream.", "wrappedStream", ":=", "grpc_middleware", ".", "WrapServerStream", "(", "stream", ")", "\n", "wrappedStream", ".", "WrappedContext", "=", "newCtx", "\n", "return", "handler", "(", "srv", ",", "wrappedStream", ")", "\n", "}", "\n", "wrapped", ":=", "&", "wrappedStream", "{", "stream", ",", "info", ",", "o", ",", "newCtx", ",", "true", "}", "\n", "err", ":=", "handler", "(", "srv", ",", "wrapped", ")", "\n", "return", "err", "\n", "}", "\n", "}" ]
// StreamServerInterceptor returns a new streaming server interceptor that sets the values for request tags.
[ "StreamServerInterceptor", "returns", "a", "new", "streaming", "server", "interceptor", "that", "sets", "the", "values", "for", "request", "tags", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tags/interceptors.go#L26-L40
train
grpc-ecosystem/go-grpc-middleware
retry/backoff.go
BackoffExponential
func BackoffExponential(scalar time.Duration) BackoffFunc { return func(attempt uint) time.Duration { return scalar * time.Duration(backoffutils.ExponentBase2(attempt)) } }
go
func BackoffExponential(scalar time.Duration) BackoffFunc { return func(attempt uint) time.Duration { return scalar * time.Duration(backoffutils.ExponentBase2(attempt)) } }
[ "func", "BackoffExponential", "(", "scalar", "time", ".", "Duration", ")", "BackoffFunc", "{", "return", "func", "(", "attempt", "uint", ")", "time", ".", "Duration", "{", "return", "scalar", "*", "time", ".", "Duration", "(", "backoffutils", ".", "ExponentBase2", "(", "attempt", ")", ")", "\n", "}", "\n", "}" ]
// BackoffExponential produces increasing intervals for each attempt. // // The scalar is multiplied times 2 raised to the current attempt. So the first // retry with a scalar of 100ms is 100ms, while the 5th attempt would be 3.2s.
[ "BackoffExponential", "produces", "increasing", "intervals", "for", "each", "attempt", ".", "The", "scalar", "is", "multiplied", "times", "2", "raised", "to", "the", "current", "attempt", ".", "So", "the", "first", "retry", "with", "a", "scalar", "of", "100ms", "is", "100ms", "while", "the", "5th", "attempt", "would", "be", "3", ".", "2s", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/retry/backoff.go#L32-L36
train
grpc-ecosystem/go-grpc-middleware
retry/backoff.go
BackoffExponentialWithJitter
func BackoffExponentialWithJitter(scalar time.Duration, jitterFraction float64) BackoffFunc { return func(attempt uint) time.Duration { return backoffutils.JitterUp(scalar*time.Duration(backoffutils.ExponentBase2(attempt)), jitterFraction) } }
go
func BackoffExponentialWithJitter(scalar time.Duration, jitterFraction float64) BackoffFunc { return func(attempt uint) time.Duration { return backoffutils.JitterUp(scalar*time.Duration(backoffutils.ExponentBase2(attempt)), jitterFraction) } }
[ "func", "BackoffExponentialWithJitter", "(", "scalar", "time", ".", "Duration", ",", "jitterFraction", "float64", ")", "BackoffFunc", "{", "return", "func", "(", "attempt", "uint", ")", "time", ".", "Duration", "{", "return", "backoffutils", ".", "JitterUp", "(", "scalar", "*", "time", ".", "Duration", "(", "backoffutils", ".", "ExponentBase2", "(", "attempt", ")", ")", ",", "jitterFraction", ")", "\n", "}", "\n", "}" ]
// BackoffExponentialWithJitter creates an exponential backoff like // BackoffExponential does, but adds jitter.
[ "BackoffExponentialWithJitter", "creates", "an", "exponential", "backoff", "like", "BackoffExponential", "does", "but", "adds", "jitter", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/retry/backoff.go#L40-L44
train
grpc-ecosystem/go-grpc-middleware
tags/fieldextractor.go
CodeGenRequestFieldExtractor
func CodeGenRequestFieldExtractor(fullMethod string, req interface{}) map[string]interface{} { if ext, ok := req.(requestFieldsExtractor); ok { retMap := make(map[string]interface{}) ext.ExtractRequestFields(retMap) if len(retMap) == 0 { return nil } return retMap } return nil }
go
func CodeGenRequestFieldExtractor(fullMethod string, req interface{}) map[string]interface{} { if ext, ok := req.(requestFieldsExtractor); ok { retMap := make(map[string]interface{}) ext.ExtractRequestFields(retMap) if len(retMap) == 0 { return nil } return retMap } return nil }
[ "func", "CodeGenRequestFieldExtractor", "(", "fullMethod", "string", ",", "req", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "if", "ext", ",", "ok", ":=", "req", ".", "(", "requestFieldsExtractor", ")", ";", "ok", "{", "retMap", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "ext", ".", "ExtractRequestFields", "(", "retMap", ")", "\n", "if", "len", "(", "retMap", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "retMap", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CodeGenRequestFieldExtractor is a function that relies on code-generated functions that export log fields from requests. // These are usually coming from a protoc-plugin that generates additional information based on custom field options.
[ "CodeGenRequestFieldExtractor", "is", "a", "function", "that", "relies", "on", "code", "-", "generated", "functions", "that", "export", "log", "fields", "from", "requests", ".", "These", "are", "usually", "coming", "from", "a", "protoc", "-", "plugin", "that", "generates", "additional", "information", "based", "on", "custom", "field", "options", "." ]
cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d
https://github.com/grpc-ecosystem/go-grpc-middleware/blob/cfaf5686ec79ff8344257723b6f5ba1ae0ffeb4d/tags/fieldextractor.go#L23-L33
train
flynn/flynn
host/containerinit/init.go
changeState
func (c *ContainerInit) changeState(state State, err string, exitStatus int) { if err != "" { logger.Debug("changing state", "fn", "changeState", "state", state, "err", err) } else if exitStatus != -1 { logger.Debug("changing state", "fn", "changeState", "state", state, "exitStatus", exitStatus) } else { logger.Debug("changing state", "fn", "changeState", "state", state) } c.state = state c.error = err c.exitStatus = exitStatus c.streamsMtx.RLock() defer c.streamsMtx.RUnlock() for ch := range c.streams { ch <- StateChange{State: state, Error: err, ExitStatus: exitStatus} } }
go
func (c *ContainerInit) changeState(state State, err string, exitStatus int) { if err != "" { logger.Debug("changing state", "fn", "changeState", "state", state, "err", err) } else if exitStatus != -1 { logger.Debug("changing state", "fn", "changeState", "state", state, "exitStatus", exitStatus) } else { logger.Debug("changing state", "fn", "changeState", "state", state) } c.state = state c.error = err c.exitStatus = exitStatus c.streamsMtx.RLock() defer c.streamsMtx.RUnlock() for ch := range c.streams { ch <- StateChange{State: state, Error: err, ExitStatus: exitStatus} } }
[ "func", "(", "c", "*", "ContainerInit", ")", "changeState", "(", "state", "State", ",", "err", "string", ",", "exitStatus", "int", ")", "{", "if", "err", "!=", "\"", "\"", "{", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "state", ",", "\"", "\"", ",", "err", ")", "\n", "}", "else", "if", "exitStatus", "!=", "-", "1", "{", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "state", ",", "\"", "\"", ",", "exitStatus", ")", "\n", "}", "else", "{", "logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "state", ")", "\n", "}", "\n\n", "c", ".", "state", "=", "state", "\n", "c", ".", "error", "=", "err", "\n", "c", ".", "exitStatus", "=", "exitStatus", "\n\n", "c", ".", "streamsMtx", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "streamsMtx", ".", "RUnlock", "(", ")", "\n", "for", "ch", ":=", "range", "c", ".", "streams", "{", "ch", "<-", "StateChange", "{", "State", ":", "state", ",", "Error", ":", "err", ",", "ExitStatus", ":", "exitStatus", "}", "\n", "}", "\n", "}" ]
// Caller must hold lock
[ "Caller", "must", "hold", "lock" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/containerinit/init.go#L314-L332
train
flynn/flynn
host/containerinit/init.go
debugStackPrinter
func debugStackPrinter(out io.Writer) { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGUSR2) for range c { pprof.Lookup("goroutine").WriteTo(out, 1) } }
go
func debugStackPrinter(out io.Writer) { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGUSR2) for range c { pprof.Lookup("goroutine").WriteTo(out, 1) } }
[ "func", "debugStackPrinter", "(", "out", "io", ".", "Writer", ")", "{", "c", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "c", ",", "syscall", ".", "SIGUSR2", ")", "\n", "for", "range", "c", "{", "pprof", ".", "Lookup", "(", "\"", "\"", ")", ".", "WriteTo", "(", "out", ",", "1", ")", "\n", "}", "\n", "}" ]
// print a full goroutine stack trace to the log fd on SIGUSR2
[ "print", "a", "full", "goroutine", "stack", "trace", "to", "the", "log", "fd", "on", "SIGUSR2" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/containerinit/init.go#L754-L760
train
flynn/flynn
host/containerinit/init.go
Main
func Main() { logR, logW, err := newSocketPair("log") if err != nil { os.Exit(70) } go debugStackPrinter(logW) config := &Config{} data, err := ioutil.ReadFile("/.containerconfig") if err != nil { os.Exit(70) } if err := json.Unmarshal(data, config); err != nil { os.Exit(70) } logger = log15.New("component", "containerinit") logger.SetHandler(log15.LvlFilterHandler(config.LogLevel, log15.StreamHandler(logW, log15.LogfmtFormat()))) // Propagate the plugin-specific container env variable config.Env["container"] = os.Getenv("container") if err := containerInitApp(config, logR); err != nil { os.Exit(70) } }
go
func Main() { logR, logW, err := newSocketPair("log") if err != nil { os.Exit(70) } go debugStackPrinter(logW) config := &Config{} data, err := ioutil.ReadFile("/.containerconfig") if err != nil { os.Exit(70) } if err := json.Unmarshal(data, config); err != nil { os.Exit(70) } logger = log15.New("component", "containerinit") logger.SetHandler(log15.LvlFilterHandler(config.LogLevel, log15.StreamHandler(logW, log15.LogfmtFormat()))) // Propagate the plugin-specific container env variable config.Env["container"] = os.Getenv("container") if err := containerInitApp(config, logR); err != nil { os.Exit(70) } }
[ "func", "Main", "(", ")", "{", "logR", ",", "logW", ",", "err", ":=", "newSocketPair", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Exit", "(", "70", ")", "\n", "}", "\n", "go", "debugStackPrinter", "(", "logW", ")", "\n\n", "config", ":=", "&", "Config", "{", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Exit", "(", "70", ")", "\n", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "config", ")", ";", "err", "!=", "nil", "{", "os", ".", "Exit", "(", "70", ")", "\n", "}", "\n\n", "logger", "=", "log15", ".", "New", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "logger", ".", "SetHandler", "(", "log15", ".", "LvlFilterHandler", "(", "config", ".", "LogLevel", ",", "log15", ".", "StreamHandler", "(", "logW", ",", "log15", ".", "LogfmtFormat", "(", ")", ")", ")", ")", "\n\n", "// Propagate the plugin-specific container env variable", "config", ".", "Env", "[", "\"", "\"", "]", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n\n", "if", "err", ":=", "containerInitApp", "(", "config", ",", "logR", ")", ";", "err", "!=", "nil", "{", "os", ".", "Exit", "(", "70", ")", "\n", "}", "\n", "}" ]
// This code is run INSIDE the container and is responsible for setting // up the environment before running the actual process
[ "This", "code", "is", "run", "INSIDE", "the", "container", "and", "is", "responsible", "for", "setting", "up", "the", "environment", "before", "running", "the", "actual", "process" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/host/containerinit/init.go#L764-L789
train
flynn/flynn
pkg/iptables/iptables.go
Exists
func Exists(args ...string) bool { if _, err := Raw(append([]string{"-C"}, args...)...); err != nil { return false } return true }
go
func Exists(args ...string) bool { if _, err := Raw(append([]string{"-C"}, args...)...); err != nil { return false } return true }
[ "func", "Exists", "(", "args", "...", "string", ")", "bool", "{", "if", "_", ",", "err", ":=", "Raw", "(", "append", "(", "[", "]", "string", "{", "\"", "\"", "}", ",", "args", "...", ")", "...", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Check if an existing rule exists
[ "Check", "if", "an", "existing", "rule", "exists" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/iptables/iptables.go#L66-L71
train
flynn/flynn
appliance/mongodb/cmd.go
NewCmd
func NewCmd(cmd *exec.Cmd) *Cmd { c := &Cmd{ Cmd: cmd, stopped: make(chan struct{}, 1), } c.stoppingValue.Store(false) c.Stdout = os.Stdout c.Stderr = os.Stderr return c }
go
func NewCmd(cmd *exec.Cmd) *Cmd { c := &Cmd{ Cmd: cmd, stopped: make(chan struct{}, 1), } c.stoppingValue.Store(false) c.Stdout = os.Stdout c.Stderr = os.Stderr return c }
[ "func", "NewCmd", "(", "cmd", "*", "exec", ".", "Cmd", ")", "*", "Cmd", "{", "c", ":=", "&", "Cmd", "{", "Cmd", ":", "cmd", ",", "stopped", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "}", "\n", "c", ".", "stoppingValue", ".", "Store", "(", "false", ")", "\n", "c", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "c", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "return", "c", "\n", "}" ]
// NewCmd returns a new instance of Cmd that wraps cmd.
[ "NewCmd", "returns", "a", "new", "instance", "of", "Cmd", "that", "wraps", "cmd", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/mongodb/cmd.go#L19-L28
train
flynn/flynn
appliance/mongodb/cmd.go
Start
func (cmd *Cmd) Start() error { if err := cmd.Cmd.Start(); err != nil { return err } go cmd.monitor() return nil }
go
func (cmd *Cmd) Start() error { if err := cmd.Cmd.Start(); err != nil { return err } go cmd.monitor() return nil }
[ "func", "(", "cmd", "*", "Cmd", ")", "Start", "(", ")", "error", "{", "if", "err", ":=", "cmd", ".", "Cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "go", "cmd", ".", "monitor", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Start executes the command.
[ "Start", "executes", "the", "command", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/mongodb/cmd.go#L31-L37
train
flynn/flynn
appliance/mongodb/cmd.go
Stop
func (cmd *Cmd) Stop() error { cmd.stoppingValue.Store(true) if err := cmd.Process.Signal(syscall.SIGKILL); err != nil { return err } return nil }
go
func (cmd *Cmd) Stop() error { cmd.stoppingValue.Store(true) if err := cmd.Process.Signal(syscall.SIGKILL); err != nil { return err } return nil }
[ "func", "(", "cmd", "*", "Cmd", ")", "Stop", "(", ")", "error", "{", "cmd", ".", "stoppingValue", ".", "Store", "(", "true", ")", "\n", "if", "err", ":=", "cmd", ".", "Process", ".", "Signal", "(", "syscall", ".", "SIGKILL", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Stop marks the command as expecting an exit and stops the underlying command.
[ "Stop", "marks", "the", "command", "as", "expecting", "an", "exit", "and", "stops", "the", "underlying", "command", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/mongodb/cmd.go#L40-L46
train
flynn/flynn
appliance/mongodb/cmd.go
monitor
func (cmd *Cmd) monitor() { err := cmd.Wait() if !cmd.stoppingValue.Load().(bool) { cmd.err = err } close(cmd.stopped) }
go
func (cmd *Cmd) monitor() { err := cmd.Wait() if !cmd.stoppingValue.Load().(bool) { cmd.err = err } close(cmd.stopped) }
[ "func", "(", "cmd", "*", "Cmd", ")", "monitor", "(", ")", "{", "err", ":=", "cmd", ".", "Wait", "(", ")", "\n", "if", "!", "cmd", ".", "stoppingValue", ".", "Load", "(", ")", ".", "(", "bool", ")", "{", "cmd", ".", "err", "=", "err", "\n", "}", "\n", "close", "(", "cmd", ".", "stopped", ")", "\n", "}" ]
// monitor checks for process exit and returns
[ "monitor", "checks", "for", "process", "exit", "and", "returns" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/appliance/mongodb/cmd.go#L56-L62
train
flynn/flynn
pkg/httpclient/json.go
Stream
func (c *Client) Stream(method, path string, in, out interface{}) (stream.Stream, error) { return c.StreamWithHeader(method, path, make(http.Header), in, out) }
go
func (c *Client) Stream(method, path string, in, out interface{}) (stream.Stream, error) { return c.StreamWithHeader(method, path, make(http.Header), in, out) }
[ "func", "(", "c", "*", "Client", ")", "Stream", "(", "method", ",", "path", "string", ",", "in", ",", "out", "interface", "{", "}", ")", "(", "stream", ".", "Stream", ",", "error", ")", "{", "return", "c", ".", "StreamWithHeader", "(", "method", ",", "path", ",", "make", "(", "http", ".", "Header", ")", ",", "in", ",", "out", ")", "\n", "}" ]
// Stream returns a stream.Stream for a specific method and path. in is an // optional json object to be sent to the server via the body, and out is a // required channel, to which the output will be streamed.
[ "Stream", "returns", "a", "stream", ".", "Stream", "for", "a", "specific", "method", "and", "path", ".", "in", "is", "an", "optional", "json", "object", "to", "be", "sent", "to", "the", "server", "via", "the", "body", "and", "out", "is", "a", "required", "channel", "to", "which", "the", "output", "will", "be", "streamed", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/httpclient/json.go#L222-L224
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
NewContextComponentName
func NewContextComponentName(ctx context.Context, componentName string) context.Context { return context.WithValue(ctx, ctxKeyComponent, componentName) }
go
func NewContextComponentName(ctx context.Context, componentName string) context.Context { return context.WithValue(ctx, ctxKeyComponent, componentName) }
[ "func", "NewContextComponentName", "(", "ctx", "context", ".", "Context", ",", "componentName", "string", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxKeyComponent", ",", "componentName", ")", "\n", "}" ]
// NewContextComponentName creates a new context that carries the provided // componentName value.
[ "NewContextComponentName", "creates", "a", "new", "context", "that", "carries", "the", "provided", "componentName", "value", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L23-L25
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
ComponentNameFromContext
func ComponentNameFromContext(ctx context.Context) (componentName string, ok bool) { componentName, ok = ctx.Value(ctxKeyComponent).(string) return }
go
func ComponentNameFromContext(ctx context.Context) (componentName string, ok bool) { componentName, ok = ctx.Value(ctxKeyComponent).(string) return }
[ "func", "ComponentNameFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "componentName", "string", ",", "ok", "bool", ")", "{", "componentName", ",", "ok", "=", "ctx", ".", "Value", "(", "ctxKeyComponent", ")", ".", "(", "string", ")", "\n", "return", "\n", "}" ]
// ComponentNameFromContext extracts a component name from a context.
[ "ComponentNameFromContext", "extracts", "a", "component", "name", "from", "a", "context", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L28-L31
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
NewContextLogger
func NewContextLogger(ctx context.Context, logger log.Logger) context.Context { return context.WithValue(ctx, ctxKeyLogger, logger) }
go
func NewContextLogger(ctx context.Context, logger log.Logger) context.Context { return context.WithValue(ctx, ctxKeyLogger, logger) }
[ "func", "NewContextLogger", "(", "ctx", "context", ".", "Context", ",", "logger", "log", ".", "Logger", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxKeyLogger", ",", "logger", ")", "\n", "}" ]
// NewContextLogger creates a new context that carries the provided logger // value.
[ "NewContextLogger", "creates", "a", "new", "context", "that", "carries", "the", "provided", "logger", "value", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L35-L37
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
LoggerFromContext
func LoggerFromContext(ctx context.Context) (logger log.Logger, ok bool) { logger, ok = ctx.Value(ctxKeyLogger).(log.Logger) return }
go
func LoggerFromContext(ctx context.Context) (logger log.Logger, ok bool) { logger, ok = ctx.Value(ctxKeyLogger).(log.Logger) return }
[ "func", "LoggerFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "logger", "log", ".", "Logger", ",", "ok", "bool", ")", "{", "logger", ",", "ok", "=", "ctx", ".", "Value", "(", "ctxKeyLogger", ")", ".", "(", "log", ".", "Logger", ")", "\n", "return", "\n", "}" ]
// LoggerFromContext extracts a logger from a context.
[ "LoggerFromContext", "extracts", "a", "logger", "from", "a", "context", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L40-L43
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
NewContextParams
func NewContextParams(ctx context.Context, params httprouter.Params) context.Context { return context.WithValue(ctx, ctxKeyParams, params) }
go
func NewContextParams(ctx context.Context, params httprouter.Params) context.Context { return context.WithValue(ctx, ctxKeyParams, params) }
[ "func", "NewContextParams", "(", "ctx", "context", ".", "Context", ",", "params", "httprouter", ".", "Params", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxKeyParams", ",", "params", ")", "\n", "}" ]
// NewContextParams creates a new context that carries the provided params // value.
[ "NewContextParams", "creates", "a", "new", "context", "that", "carries", "the", "provided", "params", "value", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L47-L49
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
ParamsFromContext
func ParamsFromContext(ctx context.Context) (params httprouter.Params, ok bool) { params, ok = ctx.Value(ctxKeyParams).(httprouter.Params) return }
go
func ParamsFromContext(ctx context.Context) (params httprouter.Params, ok bool) { params, ok = ctx.Value(ctxKeyParams).(httprouter.Params) return }
[ "func", "ParamsFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "params", "httprouter", ".", "Params", ",", "ok", "bool", ")", "{", "params", ",", "ok", "=", "ctx", ".", "Value", "(", "ctxKeyParams", ")", ".", "(", "httprouter", ".", "Params", ")", "\n", "return", "\n", "}" ]
// ParamsFromContext extracts params from a context.
[ "ParamsFromContext", "extracts", "params", "from", "a", "context", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L52-L55
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
NewContextRequestID
func NewContextRequestID(ctx context.Context, id string) context.Context { return context.WithValue(ctx, ctxKeyReqID, id) }
go
func NewContextRequestID(ctx context.Context, id string) context.Context { return context.WithValue(ctx, ctxKeyReqID, id) }
[ "func", "NewContextRequestID", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxKeyReqID", ",", "id", ")", "\n", "}" ]
// NewContextRequestID creates a new context that carries the provided request // ID value.
[ "NewContextRequestID", "creates", "a", "new", "context", "that", "carries", "the", "provided", "request", "ID", "value", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L59-L61
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
RequestIDFromContext
func RequestIDFromContext(ctx context.Context) (id string, ok bool) { id, ok = ctx.Value(ctxKeyReqID).(string) return }
go
func RequestIDFromContext(ctx context.Context) (id string, ok bool) { id, ok = ctx.Value(ctxKeyReqID).(string) return }
[ "func", "RequestIDFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "id", "string", ",", "ok", "bool", ")", "{", "id", ",", "ok", "=", "ctx", ".", "Value", "(", "ctxKeyReqID", ")", ".", "(", "string", ")", "\n", "return", "\n", "}" ]
// RequestIDFromContext extracts a request ID from a context.
[ "RequestIDFromContext", "extracts", "a", "request", "ID", "from", "a", "context", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L64-L67
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
NewContextStartTime
func NewContextStartTime(ctx context.Context, start time.Time) context.Context { return context.WithValue(ctx, ctxKeyStartTime, start) }
go
func NewContextStartTime(ctx context.Context, start time.Time) context.Context { return context.WithValue(ctx, ctxKeyStartTime, start) }
[ "func", "NewContextStartTime", "(", "ctx", "context", ".", "Context", ",", "start", "time", ".", "Time", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "ctxKeyStartTime", ",", "start", ")", "\n", "}" ]
// NewContextStartTime creates a new context that carries the provided start // time.
[ "NewContextStartTime", "creates", "a", "new", "context", "that", "carries", "the", "provided", "start", "time", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L71-L73
train
flynn/flynn
pkg/ctxhelper/ctxhelper.go
StartTimeFromContext
func StartTimeFromContext(ctx context.Context) (start time.Time, ok bool) { start, ok = ctx.Value(ctxKeyStartTime).(time.Time) return }
go
func StartTimeFromContext(ctx context.Context) (start time.Time, ok bool) { start, ok = ctx.Value(ctxKeyStartTime).(time.Time) return }
[ "func", "StartTimeFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "start", "time", ".", "Time", ",", "ok", "bool", ")", "{", "start", ",", "ok", "=", "ctx", ".", "Value", "(", "ctxKeyStartTime", ")", ".", "(", "time", ".", "Time", ")", "\n", "return", "\n", "}" ]
// StartTimeFromContext extracts a start time from a context.
[ "StartTimeFromContext", "extracts", "a", "start", "time", "from", "a", "context", "." ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/pkg/ctxhelper/ctxhelper.go#L76-L79
train
flynn/flynn
controller/sink.go
CreateSink
func (c *controllerAPI) CreateSink(ctx context.Context, w http.ResponseWriter, req *http.Request) { var sink ct.Sink if err := httphelper.DecodeJSON(req, &sink); err != nil { respondWithError(w, err) return } if err := schema.Validate(&sink); err != nil { respondWithError(w, err) return } if err := c.sinkRepo.Add(&sink); err != nil { respondWithError(w, err) return } httphelper.JSON(w, 200, &sink) }
go
func (c *controllerAPI) CreateSink(ctx context.Context, w http.ResponseWriter, req *http.Request) { var sink ct.Sink if err := httphelper.DecodeJSON(req, &sink); err != nil { respondWithError(w, err) return } if err := schema.Validate(&sink); err != nil { respondWithError(w, err) return } if err := c.sinkRepo.Add(&sink); err != nil { respondWithError(w, err) return } httphelper.JSON(w, 200, &sink) }
[ "func", "(", "c", "*", "controllerAPI", ")", "CreateSink", "(", "ctx", "context", ".", "Context", ",", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "sink", "ct", ".", "Sink", "\n", "if", "err", ":=", "httphelper", ".", "DecodeJSON", "(", "req", ",", "&", "sink", ")", ";", "err", "!=", "nil", "{", "respondWithError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", ":=", "schema", ".", "Validate", "(", "&", "sink", ")", ";", "err", "!=", "nil", "{", "respondWithError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "sinkRepo", ".", "Add", "(", "&", "sink", ")", ";", "err", "!=", "nil", "{", "respondWithError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n", "httphelper", ".", "JSON", "(", "w", ",", "200", ",", "&", "sink", ")", "\n", "}" ]
// Create a new sink
[ "Create", "a", "new", "sink" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/sink.go#L132-L149
train
flynn/flynn
controller/sink.go
GetSink
func (c *controllerAPI) GetSink(ctx context.Context, w http.ResponseWriter, req *http.Request) { params, _ := ctxhelper.ParamsFromContext(ctx) sink, err := c.sinkRepo.Get(params.ByName("sink_id")) if err != nil { respondWithError(w, err) return } httphelper.JSON(w, 200, sink) }
go
func (c *controllerAPI) GetSink(ctx context.Context, w http.ResponseWriter, req *http.Request) { params, _ := ctxhelper.ParamsFromContext(ctx) sink, err := c.sinkRepo.Get(params.ByName("sink_id")) if err != nil { respondWithError(w, err) return } httphelper.JSON(w, 200, sink) }
[ "func", "(", "c", "*", "controllerAPI", ")", "GetSink", "(", "ctx", "context", ".", "Context", ",", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "params", ",", "_", ":=", "ctxhelper", ".", "ParamsFromContext", "(", "ctx", ")", "\n\n", "sink", ",", "err", ":=", "c", ".", "sinkRepo", ".", "Get", "(", "params", ".", "ByName", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "respondWithError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "httphelper", ".", "JSON", "(", "w", ",", "200", ",", "sink", ")", "\n", "}" ]
// Get a sink
[ "Get", "a", "sink" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/sink.go#L152-L162
train
flynn/flynn
controller/sink.go
DeleteSink
func (c *controllerAPI) DeleteSink(ctx context.Context, w http.ResponseWriter, req *http.Request) { params, _ := ctxhelper.ParamsFromContext(ctx) sinkID := params.ByName("sink_id") sink, err := c.sinkRepo.Get(sinkID) if err != nil { respondWithError(w, err) return } if err = c.sinkRepo.Remove(sinkID); err != nil { respondWithError(w, err) return } httphelper.JSON(w, 200, sink) }
go
func (c *controllerAPI) DeleteSink(ctx context.Context, w http.ResponseWriter, req *http.Request) { params, _ := ctxhelper.ParamsFromContext(ctx) sinkID := params.ByName("sink_id") sink, err := c.sinkRepo.Get(sinkID) if err != nil { respondWithError(w, err) return } if err = c.sinkRepo.Remove(sinkID); err != nil { respondWithError(w, err) return } httphelper.JSON(w, 200, sink) }
[ "func", "(", "c", "*", "controllerAPI", ")", "DeleteSink", "(", "ctx", "context", ".", "Context", ",", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "params", ",", "_", ":=", "ctxhelper", ".", "ParamsFromContext", "(", "ctx", ")", "\n", "sinkID", ":=", "params", ".", "ByName", "(", "\"", "\"", ")", "\n\n", "sink", ",", "err", ":=", "c", ".", "sinkRepo", ".", "Get", "(", "sinkID", ")", "\n", "if", "err", "!=", "nil", "{", "respondWithError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", "=", "c", ".", "sinkRepo", ".", "Remove", "(", "sinkID", ")", ";", "err", "!=", "nil", "{", "respondWithError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "httphelper", ".", "JSON", "(", "w", ",", "200", ",", "sink", ")", "\n", "}" ]
// Delete a sink
[ "Delete", "a", "sink" ]
b4b05fce92da5fbc53b272362d87b994b88a3869
https://github.com/flynn/flynn/blob/b4b05fce92da5fbc53b272362d87b994b88a3869/controller/sink.go#L261-L277
train