id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
153,400 | iamduo/go-workq | client.go | parseOk | func (p *responseParser) parseOk() error {
line, err := p.readLine()
if err != nil {
return err
}
if len(line) < 3 {
return ErrMalformed
}
sign := string(line[0])
if sign == "+" && string(line[1:3]) == "OK" && len(line) == 3 {
return nil
}
if sign != "-" {
return ErrMalformed
}
err, _ = p.errorFromLine(line)
return err
} | go | func (p *responseParser) parseOk() error {
line, err := p.readLine()
if err != nil {
return err
}
if len(line) < 3 {
return ErrMalformed
}
sign := string(line[0])
if sign == "+" && string(line[1:3]) == "OK" && len(line) == 3 {
return nil
}
if sign != "-" {
return ErrMalformed
}
err, _ = p.errorFromLine(line)
return err
} | [
"func",
"(",
"p",
"*",
"responseParser",
")",
"parseOk",
"(",
")",
"error",
"{",
"line",
",",
"err",
":=",
"p",
".",
"readLine",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"line",
")",
"... | // Parse "OK\r\n" response. | [
"Parse",
"OK",
"\\",
"r",
"\\",
"n",
"response",
"."
] | b301b13f232653cacf107864e699c30cc6e9d821 | https://github.com/iamduo/go-workq/blob/b301b13f232653cacf107864e699c30cc6e9d821/client.go#L309-L330 |
153,401 | iamduo/go-workq | client.go | readLine | func (p *responseParser) readLine() ([]byte, error) {
line, err := p.rdr.ReadBytes(byte('\n'))
if err != nil {
return nil, NewNetError(err.Error())
}
if len(line) < termLen {
return nil, ErrMalformed
}
if len(line) >= termLen {
if line[len(line)-termLen] != '\r' {
return nil, ErrMalformed
}
line = line[:len(line)-termLen]
}
return line, nil
} | go | func (p *responseParser) readLine() ([]byte, error) {
line, err := p.rdr.ReadBytes(byte('\n'))
if err != nil {
return nil, NewNetError(err.Error())
}
if len(line) < termLen {
return nil, ErrMalformed
}
if len(line) >= termLen {
if line[len(line)-termLen] != '\r' {
return nil, ErrMalformed
}
line = line[:len(line)-termLen]
}
return line, nil
} | [
"func",
"(",
"p",
"*",
"responseParser",
")",
"readLine",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"line",
",",
"err",
":=",
"p",
".",
"rdr",
".",
"ReadBytes",
"(",
"byte",
"(",
"'\\n'",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",... | // Read valid line terminated by "\r\n" | [
"Read",
"valid",
"line",
"terminated",
"by",
"\\",
"r",
"\\",
"n"
] | b301b13f232653cacf107864e699c30cc6e9d821 | https://github.com/iamduo/go-workq/blob/b301b13f232653cacf107864e699c30cc6e9d821/client.go#L362-L381 |
153,402 | iamduo/go-workq | client.go | readBlock | func (p *responseParser) readBlock(size int) ([]byte, error) {
if size < 0 || size > maxDataBlock {
return nil, ErrMalformed
}
block := make([]byte, size)
n, err := io.ReadAtLeast(p.rdr, block, size)
if n != size || err != nil {
return nil, ErrMalformed
}
b := make([]byte, termLen)
n, err = p.rdr.Read(b)
if err != nil || n != termLen || string(b) != crnl {
// Size does not match end of line.
// Trailing garbage is not allowed.
return nil, ErrMalformed
}
return block, nil
} | go | func (p *responseParser) readBlock(size int) ([]byte, error) {
if size < 0 || size > maxDataBlock {
return nil, ErrMalformed
}
block := make([]byte, size)
n, err := io.ReadAtLeast(p.rdr, block, size)
if n != size || err != nil {
return nil, ErrMalformed
}
b := make([]byte, termLen)
n, err = p.rdr.Read(b)
if err != nil || n != termLen || string(b) != crnl {
// Size does not match end of line.
// Trailing garbage is not allowed.
return nil, ErrMalformed
}
return block, nil
} | [
"func",
"(",
"p",
"*",
"responseParser",
")",
"readBlock",
"(",
"size",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"size",
"<",
"0",
"||",
"size",
">",
"maxDataBlock",
"{",
"return",
"nil",
",",
"ErrMalformed",
"\n",
"}",
"\n\... | // Read data block up to size terminated by "\r\n" | [
"Read",
"data",
"block",
"up",
"to",
"size",
"terminated",
"by",
"\\",
"r",
"\\",
"n"
] | b301b13f232653cacf107864e699c30cc6e9d821 | https://github.com/iamduo/go-workq/blob/b301b13f232653cacf107864e699c30cc6e9d821/client.go#L384-L404 |
153,403 | iamduo/go-workq | client.go | errorFromLine | func (p *responseParser) errorFromLine(line []byte) (error, bool) {
split := strings.SplitN(string(line), " ", 2)
if len(split[0]) <= 1 {
return ErrMalformed, false
}
code := split[0][1:]
var text string
if len(split) == 2 {
if len(split[1]) == 0 {
return ErrMalformed, false
}
text = split[1]
}
return NewResponseError(code, text), true
} | go | func (p *responseParser) errorFromLine(line []byte) (error, bool) {
split := strings.SplitN(string(line), " ", 2)
if len(split[0]) <= 1 {
return ErrMalformed, false
}
code := split[0][1:]
var text string
if len(split) == 2 {
if len(split[1]) == 0 {
return ErrMalformed, false
}
text = split[1]
}
return NewResponseError(code, text), true
} | [
"func",
"(",
"p",
"*",
"responseParser",
")",
"errorFromLine",
"(",
"line",
"[",
"]",
"byte",
")",
"(",
"error",
",",
"bool",
")",
"{",
"split",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"line",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n"... | // Parse an error from "-CODE TEXT" | [
"Parse",
"an",
"error",
"from",
"-",
"CODE",
"TEXT"
] | b301b13f232653cacf107864e699c30cc6e9d821 | https://github.com/iamduo/go-workq/blob/b301b13f232653cacf107864e699c30cc6e9d821/client.go#L480-L497 |
153,404 | iamduo/go-workq | client.go | idFromString | func idFromString(s string) (string, error) {
_, err := uuid.FromString(s)
if err != nil {
return "", ErrMalformed
}
return s, nil
} | go | func idFromString(s string) (string, error) {
_, err := uuid.FromString(s)
if err != nil {
return "", ErrMalformed
}
return s, nil
} | [
"func",
"idFromString",
"(",
"s",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"uuid",
".",
"FromString",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"ErrMalformed",
"\n",
"}",
"\... | // Return a valid ID string
// Returns ErrMalformed if not a valid UUID. | [
"Return",
"a",
"valid",
"ID",
"string",
"Returns",
"ErrMalformed",
"if",
"not",
"a",
"valid",
"UUID",
"."
] | b301b13f232653cacf107864e699c30cc6e9d821 | https://github.com/iamduo/go-workq/blob/b301b13f232653cacf107864e699c30cc6e9d821/client.go#L501-L508 |
153,405 | alexkappa/mustache | parse.go | read | func (p *parser) read() token {
if len(p.buf) > 0 {
r := p.buf[0]
p.buf = p.buf[1:]
return r
}
return p.lexer.token()
} | go | func (p *parser) read() token {
if len(p.buf) > 0 {
r := p.buf[0]
p.buf = p.buf[1:]
return r
}
return p.lexer.token()
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"read",
"(",
")",
"token",
"{",
"if",
"len",
"(",
"p",
".",
"buf",
")",
">",
"0",
"{",
"r",
":=",
"p",
".",
"buf",
"[",
"0",
"]",
"\n",
"p",
".",
"buf",
"=",
"p",
".",
"buf",
"[",
"1",
":",
"]",
"... | // read returns the next token from the lexer and advances the cursor. This
// token will not be available by the parser after it has been read. | [
"read",
"returns",
"the",
"next",
"token",
"from",
"the",
"lexer",
"and",
"advances",
"the",
"cursor",
".",
"This",
"token",
"will",
"not",
"be",
"available",
"by",
"the",
"parser",
"after",
"it",
"has",
"been",
"read",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L18-L25 |
153,406 | alexkappa/mustache | parse.go | readn | func (p *parser) readn(n int) ([]token, error) {
tokens := make([]token, 0, n) // make a slice capable of storing up to n tokens
for i := 0; i < n; i++ {
tokens = append(tokens, p.read())
if tokens[i].typ == tokenEOF {
return tokens, io.EOF
}
}
return tokens, nil
} | go | func (p *parser) readn(n int) ([]token, error) {
tokens := make([]token, 0, n) // make a slice capable of storing up to n tokens
for i := 0; i < n; i++ {
tokens = append(tokens, p.read())
if tokens[i].typ == tokenEOF {
return tokens, io.EOF
}
}
return tokens, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"readn",
"(",
"n",
"int",
")",
"(",
"[",
"]",
"token",
",",
"error",
")",
"{",
"tokens",
":=",
"make",
"(",
"[",
"]",
"token",
",",
"0",
",",
"n",
")",
"// make a slice capable of storing up to n tokens",
"\n",
"... | // readn returns the next n tokens from the lexer and advances the cursor. If it
// coundn't read all n tokens, for example if a tokenEOF was returned by the
// lexer, an error is returned and the returned slice will have all tokens read
// until that point, including tokenEOF. | [
"readn",
"returns",
"the",
"next",
"n",
"tokens",
"from",
"the",
"lexer",
"and",
"advances",
"the",
"cursor",
".",
"If",
"it",
"coundn",
"t",
"read",
"all",
"n",
"tokens",
"for",
"example",
"if",
"a",
"tokenEOF",
"was",
"returned",
"by",
"the",
"lexer",
... | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L31-L40 |
153,407 | alexkappa/mustache | parse.go | readt | func (p *parser) readt(t tokenType) ([]token, error) {
var tokens []token
for {
token := p.read()
tokens = append(tokens, token)
switch token.typ {
case tokenEOF:
return tokens, fmt.Errorf("token %q not found", t)
case t:
return tokens, nil
}
}
} | go | func (p *parser) readt(t tokenType) ([]token, error) {
var tokens []token
for {
token := p.read()
tokens = append(tokens, token)
switch token.typ {
case tokenEOF:
return tokens, fmt.Errorf("token %q not found", t)
case t:
return tokens, nil
}
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"readt",
"(",
"t",
"tokenType",
")",
"(",
"[",
"]",
"token",
",",
"error",
")",
"{",
"var",
"tokens",
"[",
"]",
"token",
"\n",
"for",
"{",
"token",
":=",
"p",
".",
"read",
"(",
")",
"\n",
"tokens",
"=",
"... | // readt returns the tokens starting from the current position until the first
// match of t. Similar to readn it will return an error if a tokenEOF was
// returned by the lexer before a match was made. | [
"readt",
"returns",
"the",
"tokens",
"starting",
"from",
"the",
"current",
"position",
"until",
"the",
"first",
"match",
"of",
"t",
".",
"Similar",
"to",
"readn",
"it",
"will",
"return",
"an",
"error",
"if",
"a",
"tokenEOF",
"was",
"returned",
"by",
"the",... | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L45-L57 |
153,408 | alexkappa/mustache | parse.go | readv | func (p *parser) readv(t token) ([]token, error) {
var tokens []token
for {
read, err := p.readt(t.typ)
tokens = append(tokens, read...)
if err != nil {
return tokens, err
}
if len(read) > 0 && read[len(read)-1].val == t.val {
break
}
}
return tokens, nil
} | go | func (p *parser) readv(t token) ([]token, error) {
var tokens []token
for {
read, err := p.readt(t.typ)
tokens = append(tokens, read...)
if err != nil {
return tokens, err
}
if len(read) > 0 && read[len(read)-1].val == t.val {
break
}
}
return tokens, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"readv",
"(",
"t",
"token",
")",
"(",
"[",
"]",
"token",
",",
"error",
")",
"{",
"var",
"tokens",
"[",
"]",
"token",
"\n",
"for",
"{",
"read",
",",
"err",
":=",
"p",
".",
"readt",
"(",
"t",
".",
"typ",
... | // readv returns the tokens starting from the current position until the first
// match of t. A match is made only of t.typ and t.val are equal to the examined
// token. | [
"readv",
"returns",
"the",
"tokens",
"starting",
"from",
"the",
"current",
"position",
"until",
"the",
"first",
"match",
"of",
"t",
".",
"A",
"match",
"is",
"made",
"only",
"of",
"t",
".",
"typ",
"and",
"t",
".",
"val",
"are",
"equal",
"to",
"the",
"... | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L62-L75 |
153,409 | alexkappa/mustache | parse.go | peek | func (p *parser) peek() token {
if len(p.buf) > 0 {
return p.buf[0]
}
t := p.lexer.token()
p.buf = append(p.buf, t)
return t
} | go | func (p *parser) peek() token {
if len(p.buf) > 0 {
return p.buf[0]
}
t := p.lexer.token()
p.buf = append(p.buf, t)
return t
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"peek",
"(",
")",
"token",
"{",
"if",
"len",
"(",
"p",
".",
"buf",
")",
">",
"0",
"{",
"return",
"p",
".",
"buf",
"[",
"0",
"]",
"\n",
"}",
"\n",
"t",
":=",
"p",
".",
"lexer",
".",
"token",
"(",
")",
... | // peek returns the next token without advancing the cursor. Consecutive calls
// of peek would result in the same token being retuned. To advance the cursor,
// a read must be made. | [
"peek",
"returns",
"the",
"next",
"token",
"without",
"advancing",
"the",
"cursor",
".",
"Consecutive",
"calls",
"of",
"peek",
"would",
"result",
"in",
"the",
"same",
"token",
"being",
"retuned",
".",
"To",
"advance",
"the",
"cursor",
"a",
"read",
"must",
... | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L80-L87 |
153,410 | alexkappa/mustache | parse.go | peekn | func (p *parser) peekn(n int) ([]token, error) {
if len(p.buf) > n {
return p.buf[:n], nil
}
for i := len(p.buf) - 1; i < n; i++ {
t := p.lexer.token()
p.buf = append(p.buf, t)
if t.typ == tokenEOF {
return p.buf, io.EOF
}
}
return p.buf, nil
} | go | func (p *parser) peekn(n int) ([]token, error) {
if len(p.buf) > n {
return p.buf[:n], nil
}
for i := len(p.buf) - 1; i < n; i++ {
t := p.lexer.token()
p.buf = append(p.buf, t)
if t.typ == tokenEOF {
return p.buf, io.EOF
}
}
return p.buf, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"peekn",
"(",
"n",
"int",
")",
"(",
"[",
"]",
"token",
",",
"error",
")",
"{",
"if",
"len",
"(",
"p",
".",
"buf",
")",
">",
"n",
"{",
"return",
"p",
".",
"buf",
"[",
":",
"n",
"]",
",",
"nil",
"\n",
... | // peekn returns the next n tokens without advancing the cursor. | [
"peekn",
"returns",
"the",
"next",
"n",
"tokens",
"without",
"advancing",
"the",
"cursor",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L90-L102 |
153,411 | alexkappa/mustache | parse.go | peekt | func (p *parser) peekt(t tokenType) ([]token, error) {
for i := 0; i < len(p.buf); i++ {
switch p.buf[i].typ {
case t:
return p.buf[:i], nil
case tokenEOF:
return p.buf[:i], io.EOF
}
}
for {
token := p.lexer.token()
p.buf = append(p.buf, token)
switch token.typ {
case t:
return p.buf, nil
case tokenEOF:
return p.buf, io.EOF
}
}
} | go | func (p *parser) peekt(t tokenType) ([]token, error) {
for i := 0; i < len(p.buf); i++ {
switch p.buf[i].typ {
case t:
return p.buf[:i], nil
case tokenEOF:
return p.buf[:i], io.EOF
}
}
for {
token := p.lexer.token()
p.buf = append(p.buf, token)
switch token.typ {
case t:
return p.buf, nil
case tokenEOF:
return p.buf, io.EOF
}
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"peekt",
"(",
"t",
"tokenType",
")",
"(",
"[",
"]",
"token",
",",
"error",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"p",
".",
"buf",
")",
";",
"i",
"++",
"{",
"switch",
"p",
".",
"b... | // peekt returns the tokens from the current postition until the first match of
// t. it will not advance the cursor. | [
"peekt",
"returns",
"the",
"tokens",
"from",
"the",
"current",
"postition",
"until",
"the",
"first",
"match",
"of",
"t",
".",
"it",
"will",
"not",
"advance",
"the",
"cursor",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L106-L125 |
153,412 | alexkappa/mustache | parse.go | parse | func (p *parser) parse() ([]node, error) {
var nodes []node
loop:
for {
token := p.read()
switch token.typ {
case tokenEOF:
break loop
case tokenError:
return nil, p.errorf(token, "%s", token.val)
case tokenText:
nodes = append(nodes, textNode(token.val))
case tokenLeftDelim:
node, err := p.parseTag()
if err != nil {
return nodes, err
}
nodes = append(nodes, node)
case tokenRawStart:
node, err := p.parseRawTag()
if err != nil {
return nodes, err
}
nodes = append(nodes, node)
case tokenSetDelim:
nodes = append(nodes, new(delimNode))
}
}
return nodes, nil
} | go | func (p *parser) parse() ([]node, error) {
var nodes []node
loop:
for {
token := p.read()
switch token.typ {
case tokenEOF:
break loop
case tokenError:
return nil, p.errorf(token, "%s", token.val)
case tokenText:
nodes = append(nodes, textNode(token.val))
case tokenLeftDelim:
node, err := p.parseTag()
if err != nil {
return nodes, err
}
nodes = append(nodes, node)
case tokenRawStart:
node, err := p.parseRawTag()
if err != nil {
return nodes, err
}
nodes = append(nodes, node)
case tokenSetDelim:
nodes = append(nodes, new(delimNode))
}
}
return nodes, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"parse",
"(",
")",
"(",
"[",
"]",
"node",
",",
"error",
")",
"{",
"var",
"nodes",
"[",
"]",
"node",
"\n",
"loop",
":",
"for",
"{",
"token",
":=",
"p",
".",
"read",
"(",
")",
"\n",
"switch",
"token",
".",
... | // parse begins parsing based on tokens read from the lexer. | [
"parse",
"begins",
"parsing",
"based",
"on",
"tokens",
"read",
"from",
"the",
"lexer",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L132-L161 |
153,413 | alexkappa/mustache | parse.go | parseTag | func (p *parser) parseTag() (node, error) {
token := p.read()
switch token.typ {
case tokenIdentifier:
return p.parseVar(token, true)
case tokenRawStart:
return p.parseRawTag()
case tokenRawAlt:
return p.parseVar(p.read(), false)
case tokenComment:
return p.parseComment()
case tokenSectionInverse:
return p.parseSection(true)
case tokenSectionStart:
return p.parseSection(false)
case tokenPartial:
return p.parsePartial()
}
return nil, p.errorf(token, "unreachable code %s", token)
} | go | func (p *parser) parseTag() (node, error) {
token := p.read()
switch token.typ {
case tokenIdentifier:
return p.parseVar(token, true)
case tokenRawStart:
return p.parseRawTag()
case tokenRawAlt:
return p.parseVar(p.read(), false)
case tokenComment:
return p.parseComment()
case tokenSectionInverse:
return p.parseSection(true)
case tokenSectionStart:
return p.parseSection(false)
case tokenPartial:
return p.parsePartial()
}
return nil, p.errorf(token, "unreachable code %s", token)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"parseTag",
"(",
")",
"(",
"node",
",",
"error",
")",
"{",
"token",
":=",
"p",
".",
"read",
"(",
")",
"\n",
"switch",
"token",
".",
"typ",
"{",
"case",
"tokenIdentifier",
":",
"return",
"p",
".",
"parseVar",
... | // parseTag parses a beggining of a mustache tag. It is assumed that a leftDelim
// was already read by the parser. | [
"parseTag",
"parses",
"a",
"beggining",
"of",
"a",
"mustache",
"tag",
".",
"It",
"is",
"assumed",
"that",
"a",
"leftDelim",
"was",
"already",
"read",
"by",
"the",
"parser",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L165-L184 |
153,414 | alexkappa/mustache | parse.go | parseRawTag | func (p *parser) parseRawTag() (node, error) {
t := p.read()
if t.typ != tokenIdentifier {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRawEnd {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
return &varNode{name: t.val, escape: false}, nil
} | go | func (p *parser) parseRawTag() (node, error) {
t := p.read()
if t.typ != tokenIdentifier {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRawEnd {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
return &varNode{name: t.val, escape: false}, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"parseRawTag",
"(",
")",
"(",
"node",
",",
"error",
")",
"{",
"t",
":=",
"p",
".",
"read",
"(",
")",
"\n",
"if",
"t",
".",
"typ",
"!=",
"tokenIdentifier",
"{",
"return",
"nil",
",",
"p",
".",
"errorf",
"(",... | // parseRawTag parses a simple variable tag. It is assumed that the read from
// the parser should return an identifier. | [
"parseRawTag",
"parses",
"a",
"simple",
"variable",
"tag",
".",
"It",
"is",
"assumed",
"that",
"the",
"read",
"from",
"the",
"parser",
"should",
"return",
"an",
"identifier",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L188-L200 |
153,415 | alexkappa/mustache | parse.go | parseVar | func (p *parser) parseVar(ident token, escape bool) (node, error) {
if t := p.read(); t.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
return &varNode{name: ident.val, escape: escape}, nil
} | go | func (p *parser) parseVar(ident token, escape bool) (node, error) {
if t := p.read(); t.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
return &varNode{name: ident.val, escape: escape}, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"parseVar",
"(",
"ident",
"token",
",",
"escape",
"bool",
")",
"(",
"node",
",",
"error",
")",
"{",
"if",
"t",
":=",
"p",
".",
"read",
"(",
")",
";",
"t",
".",
"typ",
"!=",
"tokenRightDelim",
"{",
"return",
... | // parseVar parses a simple variable tag. It is assumed that the read from the
// parser should return an identifier. | [
"parseVar",
"parses",
"a",
"simple",
"variable",
"tag",
".",
"It",
"is",
"assumed",
"that",
"the",
"read",
"from",
"the",
"parser",
"should",
"return",
"an",
"identifier",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L204-L209 |
153,416 | alexkappa/mustache | parse.go | parseComment | func (p *parser) parseComment() (node, error) {
var comment string
for {
t := p.read()
switch t.typ {
case tokenEOF:
return nil, p.errorf(t, "unexpected token %s", t)
case tokenError:
return nil, p.errorf(t, t.val)
case tokenRightDelim:
return commentNode(comment), nil
default:
comment += t.val
}
}
} | go | func (p *parser) parseComment() (node, error) {
var comment string
for {
t := p.read()
switch t.typ {
case tokenEOF:
return nil, p.errorf(t, "unexpected token %s", t)
case tokenError:
return nil, p.errorf(t, t.val)
case tokenRightDelim:
return commentNode(comment), nil
default:
comment += t.val
}
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"parseComment",
"(",
")",
"(",
"node",
",",
"error",
")",
"{",
"var",
"comment",
"string",
"\n",
"for",
"{",
"t",
":=",
"p",
".",
"read",
"(",
")",
"\n",
"switch",
"t",
".",
"typ",
"{",
"case",
"tokenEOF",
... | // parseComment parses a comment block. It is assumed that the next read should
// return a t_comment token. | [
"parseComment",
"parses",
"a",
"comment",
"block",
".",
"It",
"is",
"assumed",
"that",
"the",
"next",
"read",
"should",
"return",
"a",
"t_comment",
"token",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L213-L228 |
153,417 | alexkappa/mustache | parse.go | parseSection | func (p *parser) parseSection(inverse bool) (node, error) {
t := p.read()
if t.typ != tokenIdentifier {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
var (
tokens []token
stack = 1
)
for {
read, err := p.readv(t)
if err != nil {
return nil, err
}
tokens = append(tokens, read...)
if len(read) > 1 {
// Check the token that preceeded the matching identifier. For
// section start and inverse tokens we increase the stack, otherwise
// decrease.
tt := read[len(read)-2]
switch {
case tt.typ == tokenSectionStart || tt.typ == tokenSectionInverse:
stack++
case tt.typ == tokenSectionEnd:
stack--
}
}
if stack == 0 {
break
}
}
nodes, err := subParser(tokens[:len(tokens)-3]).parse()
if err != nil {
return nil, err
}
section := §ionNode{
name: t.val,
inverted: inverse,
elems: nodes,
}
return section, nil
} | go | func (p *parser) parseSection(inverse bool) (node, error) {
t := p.read()
if t.typ != tokenIdentifier {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
var (
tokens []token
stack = 1
)
for {
read, err := p.readv(t)
if err != nil {
return nil, err
}
tokens = append(tokens, read...)
if len(read) > 1 {
// Check the token that preceeded the matching identifier. For
// section start and inverse tokens we increase the stack, otherwise
// decrease.
tt := read[len(read)-2]
switch {
case tt.typ == tokenSectionStart || tt.typ == tokenSectionInverse:
stack++
case tt.typ == tokenSectionEnd:
stack--
}
}
if stack == 0 {
break
}
}
nodes, err := subParser(tokens[:len(tokens)-3]).parse()
if err != nil {
return nil, err
}
section := §ionNode{
name: t.val,
inverted: inverse,
elems: nodes,
}
return section, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"parseSection",
"(",
"inverse",
"bool",
")",
"(",
"node",
",",
"error",
")",
"{",
"t",
":=",
"p",
".",
"read",
"(",
")",
"\n",
"if",
"t",
".",
"typ",
"!=",
"tokenIdentifier",
"{",
"return",
"nil",
",",
"p",
... | // parseSection parses a section block. It is assumed that the next read should
// return a t_section token. | [
"parseSection",
"parses",
"a",
"section",
"block",
".",
"It",
"is",
"assumed",
"that",
"the",
"next",
"read",
"should",
"return",
"a",
"t_section",
"token",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L232-L276 |
153,418 | alexkappa/mustache | parse.go | parsePartial | func (p *parser) parsePartial() (node, error) {
t := p.read()
if t.typ != tokenIdentifier {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
return &partialNode{t.val}, nil
} | go | func (p *parser) parsePartial() (node, error) {
t := p.read()
if t.typ != tokenIdentifier {
return nil, p.errorf(t, "unexpected token %s", t)
}
if next := p.read(); next.typ != tokenRightDelim {
return nil, p.errorf(t, "unexpected token %s", t)
}
return &partialNode{t.val}, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"parsePartial",
"(",
")",
"(",
"node",
",",
"error",
")",
"{",
"t",
":=",
"p",
".",
"read",
"(",
")",
"\n",
"if",
"t",
".",
"typ",
"!=",
"tokenIdentifier",
"{",
"return",
"nil",
",",
"p",
".",
"errorf",
"("... | // parsePartial parses a partial block. It is assumed that the next read should
// return a t_ident token. | [
"parsePartial",
"parses",
"a",
"partial",
"block",
".",
"It",
"is",
"assumed",
"that",
"the",
"next",
"read",
"should",
"return",
"a",
"t_ident",
"token",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L280-L289 |
153,419 | alexkappa/mustache | parse.go | subParser | func subParser(b []token) *parser {
return &parser{buf: append(b, token{typ: tokenEOF})}
} | go | func subParser(b []token) *parser {
return &parser{buf: append(b, token{typ: tokenEOF})}
} | [
"func",
"subParser",
"(",
"b",
"[",
"]",
"token",
")",
"*",
"parser",
"{",
"return",
"&",
"parser",
"{",
"buf",
":",
"append",
"(",
"b",
",",
"token",
"{",
"typ",
":",
"tokenEOF",
"}",
")",
"}",
"\n",
"}"
] | // subParser creates a new parser with a pre-defined token buffer. | [
"subParser",
"creates",
"a",
"new",
"parser",
"with",
"a",
"pre",
"-",
"defined",
"token",
"buffer",
"."
] | d29845f60a879542625ba65812ddfb99fd9b12b9 | https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/parse.go#L297-L299 |
153,420 | ONSdigital/go-ns | healthcheck/ticker.go | NewTicker | func NewTicker(duration, recoveryDuration time.Duration, clients ...Client) *Ticker {
return NewTickerWithAlerts(duration, recoveryDuration, nil, nil, clients...)
} | go | func NewTicker(duration, recoveryDuration time.Duration, clients ...Client) *Ticker {
return NewTickerWithAlerts(duration, recoveryDuration, nil, nil, clients...)
} | [
"func",
"NewTicker",
"(",
"duration",
",",
"recoveryDuration",
"time",
".",
"Duration",
",",
"clients",
"...",
"Client",
")",
"*",
"Ticker",
"{",
"return",
"NewTickerWithAlerts",
"(",
"duration",
",",
"recoveryDuration",
",",
"nil",
",",
"nil",
",",
"clients",... | // NewTicker returns a new ticker that checks the given clients at intervals of the given duration | [
"NewTicker",
"returns",
"a",
"new",
"ticker",
"that",
"checks",
"the",
"given",
"clients",
"at",
"intervals",
"of",
"the",
"given",
"duration"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/healthcheck/ticker.go#L19-L21 |
153,421 | ONSdigital/go-ns | healthcheck/ticker.go | Close | func (ticker *Ticker) Close() {
ticker.timeTicker.Stop()
close(ticker.closing)
<-ticker.closed
} | go | func (ticker *Ticker) Close() {
ticker.timeTicker.Stop()
close(ticker.closing)
<-ticker.closed
} | [
"func",
"(",
"ticker",
"*",
"Ticker",
")",
"Close",
"(",
")",
"{",
"ticker",
".",
"timeTicker",
".",
"Stop",
"(",
")",
"\n",
"close",
"(",
"ticker",
".",
"closing",
")",
"\n",
"<-",
"ticker",
".",
"closed",
"\n",
"}"
] | // Close the ticker to exit its internal goroutine | [
"Close",
"the",
"ticker",
"to",
"exit",
"its",
"internal",
"goroutine"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/healthcheck/ticker.go#L137-L141 |
153,422 | peter-edge/pkg-go | file/pkgfile.go | EditFile | func EditFile(filePath string, f func(io.Reader, io.Writer) error) (retErr error) {
tempFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("%s.%d", filepath.Base(filePath), os.Getpid()))
if err := os.Rename(filePath, tempFilePath); err != nil {
return err
}
var tempFile *os.File
defer func() {
if tempFile != nil {
if err := tempFile.Close(); err != nil && retErr == nil {
retErr = err
}
}
if err := os.Remove(tempFilePath); err != nil && retErr == nil {
retErr = err
}
}()
var err error
tempFile, err = os.Open(tempFilePath)
if err != nil {
return err
}
file, err := os.Create(filePath)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil && retErr == nil {
retErr = err
}
}()
return f(tempFile, file)
} | go | func EditFile(filePath string, f func(io.Reader, io.Writer) error) (retErr error) {
tempFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("%s.%d", filepath.Base(filePath), os.Getpid()))
if err := os.Rename(filePath, tempFilePath); err != nil {
return err
}
var tempFile *os.File
defer func() {
if tempFile != nil {
if err := tempFile.Close(); err != nil && retErr == nil {
retErr = err
}
}
if err := os.Remove(tempFilePath); err != nil && retErr == nil {
retErr = err
}
}()
var err error
tempFile, err = os.Open(tempFilePath)
if err != nil {
return err
}
file, err := os.Create(filePath)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil && retErr == nil {
retErr = err
}
}()
return f(tempFile, file)
} | [
"func",
"EditFile",
"(",
"filePath",
"string",
",",
"f",
"func",
"(",
"io",
".",
"Reader",
",",
"io",
".",
"Writer",
")",
"error",
")",
"(",
"retErr",
"error",
")",
"{",
"tempFilePath",
":=",
"filepath",
".",
"Join",
"(",
"os",
".",
"TempDir",
"(",
... | // EditFile edits the file using f and saves it. | [
"EditFile",
"edits",
"the",
"file",
"using",
"f",
"and",
"saves",
"it",
"."
] | 318cf31141c87eaa4348bd8a54886ba3aaf2a427 | https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/file/pkgfile.go#L13-L44 |
153,423 | ONSdigital/go-ns | render/render.go | HTML | func HTML(w io.Writer, status int, name string, binding interface{}, htmlOpt ...render.HTMLOptions) error {
hMutex.Lock()
defer hMutex.Unlock()
return Renderer.HTML(w, status, name, binding, htmlOpt...)
} | go | func HTML(w io.Writer, status int, name string, binding interface{}, htmlOpt ...render.HTMLOptions) error {
hMutex.Lock()
defer hMutex.Unlock()
return Renderer.HTML(w, status, name, binding, htmlOpt...)
} | [
"func",
"HTML",
"(",
"w",
"io",
".",
"Writer",
",",
"status",
"int",
",",
"name",
"string",
",",
"binding",
"interface",
"{",
"}",
",",
"htmlOpt",
"...",
"render",
".",
"HTMLOptions",
")",
"error",
"{",
"hMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",... | // HTML controls the rendering of an HTML template with a given name and template parameters to an io.Writer | [
"HTML",
"controls",
"the",
"rendering",
"of",
"an",
"HTML",
"template",
"with",
"a",
"given",
"name",
"and",
"template",
"parameters",
"to",
"an",
"io",
".",
"Writer"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/render/render.go#L47-L51 |
153,424 | ONSdigital/go-ns | render/render.go | JSON | func JSON(w io.Writer, status int, v interface{}) error {
jMutex.Lock()
defer jMutex.Unlock()
return Renderer.JSON(w, status, v)
} | go | func JSON(w io.Writer, status int, v interface{}) error {
jMutex.Lock()
defer jMutex.Unlock()
return Renderer.JSON(w, status, v)
} | [
"func",
"JSON",
"(",
"w",
"io",
".",
"Writer",
",",
"status",
"int",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"jMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"jMutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"Renderer",
".",
"JSON",
"... | // JSON controls the rendering of a JSON template with a given name and template parameters to an io.Writer | [
"JSON",
"controls",
"the",
"rendering",
"of",
"a",
"JSON",
"template",
"with",
"a",
"given",
"name",
"and",
"template",
"parameters",
"to",
"an",
"io",
".",
"Writer"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/render/render.go#L54-L58 |
153,425 | soheilhy/args | args.go | Get | func (a A) Get(vals ...interface{}) (val interface{}) {
val = get(a(nil).arg(), vals)
return
} | go | func (a A) Get(vals ...interface{}) (val interface{}) {
val = get(a(nil).arg(), vals)
return
} | [
"func",
"(",
"a",
"A",
")",
"Get",
"(",
"vals",
"...",
"interface",
"{",
"}",
")",
"(",
"val",
"interface",
"{",
"}",
")",
"{",
"val",
"=",
"get",
"(",
"a",
"(",
"nil",
")",
".",
"arg",
"(",
")",
",",
"vals",
")",
"\n",
"return",
"\n",
"}"
... | // Get returns the value of the argument from the values.
// nil is returned if no value and no default is set for this argument. | [
"Get",
"returns",
"the",
"value",
"of",
"the",
"argument",
"from",
"the",
"values",
".",
"nil",
"is",
"returned",
"if",
"no",
"value",
"and",
"no",
"default",
"is",
"set",
"for",
"this",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L14-L17 |
153,426 | soheilhy/args | args.go | New | func New(vals ...V) A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
panic("cannot set flag for interface{}")
}
return a.getA()
} | go | func New(vals ...V) A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
panic("cannot set flag for interface{}")
}
return a.getA()
} | [
"func",
"New",
"(",
"vals",
"...",
"V",
")",
"A",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
".",
"Get",
"... | // New creates a new argument. | [
"New",
"creates",
"a",
"new",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L25-L37 |
153,427 | soheilhy/args | args.go | NewBool | func NewBool(vals ...V) BoolA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Bool(f.name, f.defv.(bool), f.usage)
}
ab := a.getA()
return func(b bool) V {
return ab(b)
}
} | go | func NewBool(vals ...V) BoolA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Bool(f.name, f.defv.(bool), f.usage)
}
ab := a.getA()
return func(b bool) V {
return ab(b)
}
} | [
"func",
"NewBool",
"(",
"vals",
"...",
"V",
")",
"BoolA",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
".",
"G... | // NewBool creates a new integer argument. | [
"NewBool",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L60-L76 |
153,428 | soheilhy/args | args.go | NewInt | func NewInt(vals ...V) IntA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Int(f.name, f.defv.(int), f.usage)
}
ai := a.getA()
return func(i int) V {
return ai(i)
}
} | go | func NewInt(vals ...V) IntA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Int(f.name, f.defv.(int), f.usage)
}
ai := a.getA()
return func(i int) V {
return ai(i)
}
} | [
"func",
"NewInt",
"(",
"vals",
"...",
"V",
")",
"IntA",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
".",
"Get... | // NewInt creates a new integer argument. | [
"NewInt",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L99-L115 |
153,429 | soheilhy/args | args.go | NewUint | func NewUint(vals ...V) UintA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Uint(f.name, f.defv.(uint), f.usage)
}
ai := a.getA()
return func(i uint) V {
return ai(i)
}
} | go | func NewUint(vals ...V) UintA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Uint(f.name, f.defv.(uint), f.usage)
}
ai := a.getA()
return func(i uint) V {
return ai(i)
}
} | [
"func",
"NewUint",
"(",
"vals",
"...",
"V",
")",
"UintA",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
".",
"G... | // NewUint creates a new integer argument. | [
"NewUint",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L138-L154 |
153,430 | soheilhy/args | args.go | Get | func (a Int64A) Get(vals ...interface{}) (val int64) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *int64:
return *v
case int64:
return v
}
return
} | go | func (a Int64A) Get(vals ...interface{}) (val int64) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *int64:
return *v
case int64:
return v
}
return
} | [
"func",
"(",
"a",
"Int64A",
")",
"Get",
"(",
"vals",
"...",
"interface",
"{",
"}",
")",
"(",
"val",
"int64",
")",
"{",
"v",
":=",
"get",
"(",
"a",
"(",
"0",
")",
".",
"arg",
"(",
")",
",",
"vals",
")",
"\n",
"switch",
"v",
":=",
"v",
".",
... | // Get returns the value of the int64 argument among vals. | [
"Get",
"returns",
"the",
"value",
"of",
"the",
"int64",
"argument",
"among",
"vals",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L160-L169 |
153,431 | soheilhy/args | args.go | NewInt64 | func NewInt64(vals ...V) Int64A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Int64(f.name, f.defv.(int64), f.usage)
}
ai := a.getA()
return func(i int64) V {
return ai(i)
}
} | go | func NewInt64(vals ...V) Int64A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Int64(f.name, f.defv.(int64), f.usage)
}
ai := a.getA()
return func(i int64) V {
return ai(i)
}
} | [
"func",
"NewInt64",
"(",
"vals",
"...",
"V",
")",
"Int64A",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
".",
... | // NewInt64 creates a new integer argument. | [
"NewInt64",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L177-L193 |
153,432 | soheilhy/args | args.go | Get | func (a Uint64A) Get(vals ...interface{}) (val uint64) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *uint64:
return *v
case uint64:
return v
}
return
} | go | func (a Uint64A) Get(vals ...interface{}) (val uint64) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *uint64:
return *v
case uint64:
return v
}
return
} | [
"func",
"(",
"a",
"Uint64A",
")",
"Get",
"(",
"vals",
"...",
"interface",
"{",
"}",
")",
"(",
"val",
"uint64",
")",
"{",
"v",
":=",
"get",
"(",
"a",
"(",
"0",
")",
".",
"arg",
"(",
")",
",",
"vals",
")",
"\n",
"switch",
"v",
":=",
"v",
".",... | // Get returns the value of the uint64 argument among vals. | [
"Get",
"returns",
"the",
"value",
"of",
"the",
"uint64",
"argument",
"among",
"vals",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L199-L208 |
153,433 | soheilhy/args | args.go | NewUint64 | func NewUint64(vals ...V) Uint64A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Uint64(f.name, f.defv.(uint64), f.usage)
}
ai := a.getA()
return func(i uint64) V {
return ai(i)
}
} | go | func NewUint64(vals ...V) Uint64A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Uint64(f.name, f.defv.(uint64), f.usage)
}
ai := a.getA()
return func(i uint64) V {
return ai(i)
}
} | [
"func",
"NewUint64",
"(",
"vals",
"...",
"V",
")",
"Uint64A",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
".",
... | // NewUint64 creates a new integer argument. | [
"NewUint64",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L216-L232 |
153,434 | soheilhy/args | args.go | Get | func (a Float64A) Get(vals ...interface{}) (val float64) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *float64:
return *v
case float64:
return v
}
return
} | go | func (a Float64A) Get(vals ...interface{}) (val float64) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *float64:
return *v
case float64:
return v
}
return
} | [
"func",
"(",
"a",
"Float64A",
")",
"Get",
"(",
"vals",
"...",
"interface",
"{",
"}",
")",
"(",
"val",
"float64",
")",
"{",
"v",
":=",
"get",
"(",
"a",
"(",
"0",
")",
".",
"arg",
"(",
")",
",",
"vals",
")",
"\n",
"switch",
"v",
":=",
"v",
".... | // Get returns the value of the float64 argument among vals. | [
"Get",
"returns",
"the",
"value",
"of",
"the",
"float64",
"argument",
"among",
"vals",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L238-L247 |
153,435 | soheilhy/args | args.go | NewFloat64 | func NewFloat64(vals ...V) Float64A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Float64(f.name, f.defv.(float64), f.usage)
}
af := a.getA()
return func(f float64) V {
return af(f)
}
} | go | func NewFloat64(vals ...V) Float64A {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Float64(f.name, f.defv.(float64), f.usage)
}
af := a.getA()
return func(f float64) V {
return af(f)
}
} | [
"func",
"NewFloat64",
"(",
"vals",
"...",
"V",
")",
"Float64A",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
"."... | // NewFloat64 creates a new integer argument. | [
"NewFloat64",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L255-L271 |
153,436 | soheilhy/args | args.go | Get | func (a StringA) Get(vals ...interface{}) (val string) {
v := get(a("").arg(), vals)
switch v := v.(type) {
case *string:
return *v
case string:
return v
}
return
} | go | func (a StringA) Get(vals ...interface{}) (val string) {
v := get(a("").arg(), vals)
switch v := v.(type) {
case *string:
return *v
case string:
return v
}
return
} | [
"func",
"(",
"a",
"StringA",
")",
"Get",
"(",
"vals",
"...",
"interface",
"{",
"}",
")",
"(",
"val",
"string",
")",
"{",
"v",
":=",
"get",
"(",
"a",
"(",
"\"",
"\"",
")",
".",
"arg",
"(",
")",
",",
"vals",
")",
"\n",
"switch",
"v",
":=",
"v... | // Get returns the value of the string argument among vals. | [
"Get",
"returns",
"the",
"value",
"of",
"the",
"string",
"argument",
"among",
"vals",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L277-L286 |
153,437 | soheilhy/args | args.go | NewString | func NewString(vals ...V) StringA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.String(f.name, f.defv.(string), f.usage)
}
as := a.getA()
return func(s string) V {
return as(s)
}
} | go | func NewString(vals ...V) StringA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.String(f.name, f.defv.(string), f.usage)
}
as := a.getA()
return func(s string) V {
return as(s)
}
} | [
"func",
"NewString",
"(",
"vals",
"...",
"V",
")",
"StringA",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
".",
... | // NewString creates a new integer argument. | [
"NewString",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L294-L310 |
153,438 | soheilhy/args | args.go | Get | func (a DurationA) Get(vals ...interface{}) (val time.Duration) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *time.Duration:
return *v
case time.Duration:
return v
}
return
} | go | func (a DurationA) Get(vals ...interface{}) (val time.Duration) {
v := get(a(0).arg(), vals)
switch v := v.(type) {
case *time.Duration:
return *v
case time.Duration:
return v
}
return
} | [
"func",
"(",
"a",
"DurationA",
")",
"Get",
"(",
"vals",
"...",
"interface",
"{",
"}",
")",
"(",
"val",
"time",
".",
"Duration",
")",
"{",
"v",
":=",
"get",
"(",
"a",
"(",
"0",
")",
".",
"arg",
"(",
")",
",",
"vals",
")",
"\n",
"switch",
"v",
... | // Get returns the value of the time.Duration argument among vals. | [
"Get",
"returns",
"the",
"value",
"of",
"the",
"time",
".",
"Duration",
"argument",
"among",
"vals",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L316-L325 |
153,439 | soheilhy/args | args.go | NewDuration | func NewDuration(vals ...V) DurationA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Duration(f.name, f.defv.(time.Duration), f.usage)
}
ad := a.getA()
return func(d time.Duration) V {
return ad(d)
}
} | go | func NewDuration(vals ...V) DurationA {
a := &arg{}
d := Default.Get(vals)
a.defv = d
f := A(flagA).Get(vals)
if f != nil {
f := f.(flagT)
a.defv = flag.Duration(f.name, f.defv.(time.Duration), f.usage)
}
ad := a.getA()
return func(d time.Duration) V {
return ad(d)
}
} | [
"func",
"NewDuration",
"(",
"vals",
"...",
"V",
")",
"DurationA",
"{",
"a",
":=",
"&",
"arg",
"{",
"}",
"\n\n",
"d",
":=",
"Default",
".",
"Get",
"(",
"vals",
")",
"\n",
"a",
".",
"defv",
"=",
"d",
"\n\n",
"f",
":=",
"A",
"(",
"flagA",
")",
"... | // NewDuration creates a new integer argument. | [
"NewDuration",
"creates",
"a",
"new",
"integer",
"argument",
"."
] | 6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc | https://github.com/soheilhy/args/blob/6bcf4c78e87e38c051ddd7dc4deae19d3fc5b9bc/args.go#L333-L349 |
153,440 | maximilien/softlayer-go | client/fakes/http_client_fake.go | DoRawHttpRequest | func (fhc *FakeHttpClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error) {
fhc.DoRawHttpRequestPath = path
fhc.DoRawHttpRequestRequestType = requestType
fhc.DoRawHttpRequestRequestBody = requestBody
return fhc.processResponse()
} | go | func (fhc *FakeHttpClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, int, error) {
fhc.DoRawHttpRequestPath = path
fhc.DoRawHttpRequestRequestType = requestType
fhc.DoRawHttpRequestRequestBody = requestBody
return fhc.processResponse()
} | [
"func",
"(",
"fhc",
"*",
"FakeHttpClient",
")",
"DoRawHttpRequest",
"(",
"path",
"string",
",",
"requestType",
"string",
",",
"requestBody",
"*",
"bytes",
".",
"Buffer",
")",
"(",
"[",
"]",
"byte",
",",
"int",
",",
"error",
")",
"{",
"fhc",
".",
"DoRaw... | //softlayer.HttpClient interface methods | [
"softlayer",
".",
"HttpClient",
"interface",
"methods"
] | 6b3ad7fc2d3cfd98fb92bf6898093a059326ca81 | https://github.com/maximilien/softlayer-go/blob/6b3ad7fc2d3cfd98fb92bf6898093a059326ca81/client/fakes/http_client_fake.go#L71-L77 |
153,441 | ONSdigital/go-ns | clients/filter/filter.go | CreateBlueprint | func (c *Client) CreateBlueprint(ctx context.Context, datasetID, edition, version string, names []string) (string, error) {
ver, err := strconv.Atoi(version)
if err != nil {
return "", err
}
cb := CreateBlueprint{Dataset: Dataset{DatasetID: datasetID, Edition: edition, Version: ver}}
var dimensions []ModelDimension
for _, name := range names {
dimensions = append(dimensions, ModelDimension{Name: name})
}
cb.Dimensions = dimensions
b, err := json.Marshal(cb)
if err != nil {
return "", err
}
uri := c.url + "/filters"
clientlog.Do(ctx, "attemping to create filter blueprint", service, uri, log.Data{
"method": "POST",
"datasetID": datasetID,
"edition": edition,
"version": version,
})
req, err := http.NewRequest("POST", uri, bytes.NewBuffer(b))
if err != nil {
return "", err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusCreated {
return "", ErrInvalidFilterAPIResponse{http.StatusCreated, resp.StatusCode, uri}
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if err = json.Unmarshal(b, &cb); err != nil {
return "", err
}
return cb.FilterID, nil
} | go | func (c *Client) CreateBlueprint(ctx context.Context, datasetID, edition, version string, names []string) (string, error) {
ver, err := strconv.Atoi(version)
if err != nil {
return "", err
}
cb := CreateBlueprint{Dataset: Dataset{DatasetID: datasetID, Edition: edition, Version: ver}}
var dimensions []ModelDimension
for _, name := range names {
dimensions = append(dimensions, ModelDimension{Name: name})
}
cb.Dimensions = dimensions
b, err := json.Marshal(cb)
if err != nil {
return "", err
}
uri := c.url + "/filters"
clientlog.Do(ctx, "attemping to create filter blueprint", service, uri, log.Data{
"method": "POST",
"datasetID": datasetID,
"edition": edition,
"version": version,
})
req, err := http.NewRequest("POST", uri, bytes.NewBuffer(b))
if err != nil {
return "", err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusCreated {
return "", ErrInvalidFilterAPIResponse{http.StatusCreated, resp.StatusCode, uri}
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if err = json.Unmarshal(b, &cb); err != nil {
return "", err
}
return cb.FilterID, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CreateBlueprint",
"(",
"ctx",
"context",
".",
"Context",
",",
"datasetID",
",",
"edition",
",",
"version",
"string",
",",
"names",
"[",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"ver",
",",
"err... | // CreateBlueprint creates a filter blueprint and returns the associated filterID | [
"CreateBlueprint",
"creates",
"a",
"filter",
"blueprint",
"and",
"returns",
"the",
"associated",
"filterID"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/filter/filter.go#L216-L269 |
153,442 | ONSdigital/go-ns | clients/filter/filter.go | UpdateBlueprint | func (c *Client) UpdateBlueprint(ctx context.Context, m Model, doSubmit bool) (mdl Model, err error) {
b, err := json.Marshal(m)
if err != nil {
return
}
uri := fmt.Sprintf("%s/filters/%s", c.url, m.FilterID)
if doSubmit {
uri = uri + "?submitted=true"
}
clientlog.Do(ctx, "updating filter job", service, uri, log.Data{
"method": "PUT",
"body": string(b),
})
req, err := http.NewRequest("PUT", uri, bytes.NewBuffer(b))
if err != nil {
return
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
return m, ErrInvalidFilterAPIResponse{http.StatusOK, resp.StatusCode, uri}
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err = json.Unmarshal(b, &m); err != nil {
return
}
return m, nil
} | go | func (c *Client) UpdateBlueprint(ctx context.Context, m Model, doSubmit bool) (mdl Model, err error) {
b, err := json.Marshal(m)
if err != nil {
return
}
uri := fmt.Sprintf("%s/filters/%s", c.url, m.FilterID)
if doSubmit {
uri = uri + "?submitted=true"
}
clientlog.Do(ctx, "updating filter job", service, uri, log.Data{
"method": "PUT",
"body": string(b),
})
req, err := http.NewRequest("PUT", uri, bytes.NewBuffer(b))
if err != nil {
return
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
return m, ErrInvalidFilterAPIResponse{http.StatusOK, resp.StatusCode, uri}
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err = json.Unmarshal(b, &m); err != nil {
return
}
return m, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"UpdateBlueprint",
"(",
"ctx",
"context",
".",
"Context",
",",
"m",
"Model",
",",
"doSubmit",
"bool",
")",
"(",
"mdl",
"Model",
",",
"err",
"error",
")",
"{",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",... | // UpdateBlueprint will update a blueprint with a given filter model | [
"UpdateBlueprint",
"will",
"update",
"a",
"blueprint",
"with",
"a",
"given",
"filter",
"model"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/filter/filter.go#L272-L313 |
153,443 | ONSdigital/go-ns | clients/filter/filter.go | AddDimensionValue | func (c *Client) AddDimensionValue(ctx context.Context, filterID, name, value string) error {
uri := fmt.Sprintf("%s/filters/%s/dimensions/%s/options/%s", c.url, filterID, name, value)
clientlog.Do(ctx, "adding dimension option to filter job", service, uri, log.Data{
"method": "POST",
"value": value,
})
req, err := http.NewRequest("POST", uri, nil)
if err != nil {
return err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusCreated {
return &ErrInvalidFilterAPIResponse{http.StatusCreated, resp.StatusCode, uri}
}
return nil
} | go | func (c *Client) AddDimensionValue(ctx context.Context, filterID, name, value string) error {
uri := fmt.Sprintf("%s/filters/%s/dimensions/%s/options/%s", c.url, filterID, name, value)
clientlog.Do(ctx, "adding dimension option to filter job", service, uri, log.Data{
"method": "POST",
"value": value,
})
req, err := http.NewRequest("POST", uri, nil)
if err != nil {
return err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusCreated {
return &ErrInvalidFilterAPIResponse{http.StatusCreated, resp.StatusCode, uri}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AddDimensionValue",
"(",
"ctx",
"context",
".",
"Context",
",",
"filterID",
",",
"name",
",",
"value",
"string",
")",
"error",
"{",
"uri",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"url",
",... | // AddDimensionValue adds a particular value to a filter job for a given filterID
// and name | [
"AddDimensionValue",
"adds",
"a",
"particular",
"value",
"to",
"a",
"filter",
"job",
"for",
"a",
"given",
"filterID",
"and",
"name"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/filter/filter.go#L317-L339 |
153,444 | ONSdigital/go-ns | clients/filter/filter.go | AddDimension | func (c *Client) AddDimension(ctx context.Context, id, name string) error {
uri := fmt.Sprintf("%s/filters/%s/dimensions/%s", c.url, id, name)
clientlog.Do(ctx, "adding dimension to filter job", service, uri, log.Data{
"method": "POST",
"dimension": name,
})
req, err := http.NewRequest("POST", uri, bytes.NewBufferString(`{}`))
if err != nil {
return err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusCreated {
return errors.New("invalid status from filter api")
}
return nil
} | go | func (c *Client) AddDimension(ctx context.Context, id, name string) error {
uri := fmt.Sprintf("%s/filters/%s/dimensions/%s", c.url, id, name)
clientlog.Do(ctx, "adding dimension to filter job", service, uri, log.Data{
"method": "POST",
"dimension": name,
})
req, err := http.NewRequest("POST", uri, bytes.NewBufferString(`{}`))
if err != nil {
return err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusCreated {
return errors.New("invalid status from filter api")
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AddDimension",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
",",
"name",
"string",
")",
"error",
"{",
"uri",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"url",
",",
"id",
",",
"name",
... | // AddDimension adds a new dimension to a filter job | [
"AddDimension",
"adds",
"a",
"new",
"dimension",
"to",
"a",
"filter",
"job"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/filter/filter.go#L394-L416 |
153,445 | ONSdigital/go-ns | clients/filter/filter.go | AddDimensionValues | func (c *Client) AddDimensionValues(ctx context.Context, filterID, name string, options []string) error {
uri := fmt.Sprintf("%s/filters/%s/dimensions/%s", c.url, filterID, name)
clientlog.Do(ctx, "adding multiple dimension values to filter job", service, uri, log.Data{
"method": "POST",
"options": options,
})
body := struct {
Options []string `json:"options"`
}{
Options: options,
}
b, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequest("POST", uri, bytes.NewBuffer(b))
if err != nil {
return err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusCreated {
return &ErrInvalidFilterAPIResponse{http.StatusCreated, resp.StatusCode, uri}
}
return nil
} | go | func (c *Client) AddDimensionValues(ctx context.Context, filterID, name string, options []string) error {
uri := fmt.Sprintf("%s/filters/%s/dimensions/%s", c.url, filterID, name)
clientlog.Do(ctx, "adding multiple dimension values to filter job", service, uri, log.Data{
"method": "POST",
"options": options,
})
body := struct {
Options []string `json:"options"`
}{
Options: options,
}
b, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequest("POST", uri, bytes.NewBuffer(b))
if err != nil {
return err
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusCreated {
return &ErrInvalidFilterAPIResponse{http.StatusCreated, resp.StatusCode, uri}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AddDimensionValues",
"(",
"ctx",
"context",
".",
"Context",
",",
"filterID",
",",
"name",
"string",
",",
"options",
"[",
"]",
"string",
")",
"error",
"{",
"uri",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
","... | // AddDimensionValues adds many options to a filter job dimension | [
"AddDimensionValues",
"adds",
"many",
"options",
"to",
"a",
"filter",
"job",
"dimension"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/filter/filter.go#L450-L484 |
153,446 | ONSdigital/go-ns | clients/filter/filter.go | GetPreview | func (c *Client) GetPreview(ctx context.Context, filterOutputID string) (p Preview, err error) {
uri := fmt.Sprintf("%s/filter-outputs/%s/preview", c.url, filterOutputID)
clientlog.Do(ctx, "retrieving preview for filter output job", service, uri, log.Data{
"method": "GET",
"filterID": filterOutputID,
})
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
return p, &ErrInvalidFilterAPIResponse{http.StatusOK, resp.StatusCode, uri}
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
defer resp.Body.Close()
err = json.Unmarshal(b, &p)
return
} | go | func (c *Client) GetPreview(ctx context.Context, filterOutputID string) (p Preview, err error) {
uri := fmt.Sprintf("%s/filter-outputs/%s/preview", c.url, filterOutputID)
clientlog.Do(ctx, "retrieving preview for filter output job", service, uri, log.Data{
"method": "GET",
"filterID": filterOutputID,
})
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return
}
resp, err := c.cli.Do(ctx, req)
if err != nil {
return
}
if resp.StatusCode != http.StatusOK {
return p, &ErrInvalidFilterAPIResponse{http.StatusOK, resp.StatusCode, uri}
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
defer resp.Body.Close()
err = json.Unmarshal(b, &p)
return
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetPreview",
"(",
"ctx",
"context",
".",
"Context",
",",
"filterOutputID",
"string",
")",
"(",
"p",
"Preview",
",",
"err",
"error",
")",
"{",
"uri",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",... | // GetPreview attempts to retrieve a preview for a given filterOutputID | [
"GetPreview",
"attempts",
"to",
"retrieve",
"a",
"preview",
"for",
"a",
"given",
"filterOutputID"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/filter/filter.go#L487-L517 |
153,447 | keegancsmith/shell | escape.go | ReadableEscapeArg | func ReadableEscapeArg(arg string) string {
if readableRe.MatchString(arg) {
return arg
}
return EscapeArg(arg)
} | go | func ReadableEscapeArg(arg string) string {
if readableRe.MatchString(arg) {
return arg
}
return EscapeArg(arg)
} | [
"func",
"ReadableEscapeArg",
"(",
"arg",
"string",
")",
"string",
"{",
"if",
"readableRe",
".",
"MatchString",
"(",
"arg",
")",
"{",
"return",
"arg",
"\n",
"}",
"\n",
"return",
"EscapeArg",
"(",
"arg",
")",
"\n",
"}"
] | // ReadableEscapeArg will not escape strings that do not requiring
// escaping. Note that it is conservative, so may escape strings which do not
// require it. | [
"ReadableEscapeArg",
"will",
"not",
"escape",
"strings",
"that",
"do",
"not",
"requiring",
"escaping",
".",
"Note",
"that",
"it",
"is",
"conservative",
"so",
"may",
"escape",
"strings",
"which",
"do",
"not",
"require",
"it",
"."
] | ccb53e0c7c5c3deb421db041b1c4a7737d33ff44 | https://github.com/keegancsmith/shell/blob/ccb53e0c7c5c3deb421db041b1c4a7737d33ff44/escape.go#L18-L23 |
153,448 | peter-edge/pkg-go | log/pkglog.go | SetupLogging | func SetupLogging(appName string, env Env) error {
var pushers []lion.Pusher
if !env.DisableStderrLog {
pushers = append(
pushers,
lion.NewTextWritePusher(
os.Stderr,
),
)
}
if env.LogDir != "" {
pushers = append(
pushers,
lion.NewTextWritePusher(
&lumberjack.Logger{
Filename: filepath.Join(env.LogDir, fmt.Sprintf("%s.log", appName)),
MaxBackups: 3,
},
),
)
}
if env.SyslogNetwork != "" && env.SyslogAddress != "" {
writer, err := syslog.Dial(
env.SyslogNetwork,
env.SyslogAddress,
syslog.LOG_INFO,
appName,
)
if err != nil {
return err
}
pushers = append(
pushers,
sysloglion.NewPusher(
writer,
),
)
}
if len(pushers) > 0 {
lion.SetLogger(
lion.NewLogger(
lion.NewMultiPusher(
pushers...,
),
),
)
} else {
lion.SetLogger(
lion.DiscardLogger,
)
}
lion.RedirectStdLogger()
if env.LogLevel != "" {
level, err := lion.NameToLevel(strings.ToUpper(env.LogLevel))
if err != nil {
return err
}
lion.SetLevel(level)
}
return nil
} | go | func SetupLogging(appName string, env Env) error {
var pushers []lion.Pusher
if !env.DisableStderrLog {
pushers = append(
pushers,
lion.NewTextWritePusher(
os.Stderr,
),
)
}
if env.LogDir != "" {
pushers = append(
pushers,
lion.NewTextWritePusher(
&lumberjack.Logger{
Filename: filepath.Join(env.LogDir, fmt.Sprintf("%s.log", appName)),
MaxBackups: 3,
},
),
)
}
if env.SyslogNetwork != "" && env.SyslogAddress != "" {
writer, err := syslog.Dial(
env.SyslogNetwork,
env.SyslogAddress,
syslog.LOG_INFO,
appName,
)
if err != nil {
return err
}
pushers = append(
pushers,
sysloglion.NewPusher(
writer,
),
)
}
if len(pushers) > 0 {
lion.SetLogger(
lion.NewLogger(
lion.NewMultiPusher(
pushers...,
),
),
)
} else {
lion.SetLogger(
lion.DiscardLogger,
)
}
lion.RedirectStdLogger()
if env.LogLevel != "" {
level, err := lion.NameToLevel(strings.ToUpper(env.LogLevel))
if err != nil {
return err
}
lion.SetLevel(level)
}
return nil
} | [
"func",
"SetupLogging",
"(",
"appName",
"string",
",",
"env",
"Env",
")",
"error",
"{",
"var",
"pushers",
"[",
"]",
"lion",
".",
"Pusher",
"\n",
"if",
"!",
"env",
".",
"DisableStderrLog",
"{",
"pushers",
"=",
"append",
"(",
"pushers",
",",
"lion",
".",... | // SetupLogging sets up logging. | [
"SetupLogging",
"sets",
"up",
"logging",
"."
] | 318cf31141c87eaa4348bd8a54886ba3aaf2a427 | https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/log/pkglog.go#L36-L96 |
153,449 | ONSdigital/go-ns | request/request.go | DrainBody | func DrainBody(r *http.Request) {
if r.Body == nil {
return
}
_, err := io.Copy(ioutil.Discard, r.Body)
if err != nil {
log.ErrorCtx(r.Context(), errors.Wrap(err, "error draining request body"), nil)
}
err = r.Body.Close()
if err != nil {
log.ErrorCtx(r.Context(), errors.Wrap(err, "error closing request body"), nil)
}
} | go | func DrainBody(r *http.Request) {
if r.Body == nil {
return
}
_, err := io.Copy(ioutil.Discard, r.Body)
if err != nil {
log.ErrorCtx(r.Context(), errors.Wrap(err, "error draining request body"), nil)
}
err = r.Body.Close()
if err != nil {
log.ErrorCtx(r.Context(), errors.Wrap(err, "error closing request body"), nil)
}
} | [
"func",
"DrainBody",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Body",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"r",
".",
"Body",
")",
... | // DrainBody drains the body of the given of the given HTTP request. | [
"DrainBody",
"drains",
"the",
"body",
"of",
"the",
"given",
"of",
"the",
"given",
"HTTP",
"request",
"."
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/request/request.go#L12-L27 |
153,450 | ONSdigital/go-ns | validator/validate.go | New | func New(r io.Reader) (fv FormValidator, err error) {
buf := &bytes.Buffer{}
_, err = io.Copy(buf, r)
if err == nil {
err = json.Unmarshal(buf.Bytes(), &fv.flds)
}
return
} | go | func New(r io.Reader) (fv FormValidator, err error) {
buf := &bytes.Buffer{}
_, err = io.Copy(buf, r)
if err == nil {
err = json.Unmarshal(buf.Bytes(), &fv.flds)
}
return
} | [
"func",
"New",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"fv",
"FormValidator",
",",
"err",
"error",
")",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"buf",
",",
"r",
")",
"\n",
... | // New creates a new FormValidator which takes in an io.Reader containing the
// rules for all form fields which need to be validated for a particular service | [
"New",
"creates",
"a",
"new",
"FormValidator",
"which",
"takes",
"in",
"an",
"io",
".",
"Reader",
"containing",
"the",
"rules",
"for",
"all",
"form",
"fields",
"which",
"need",
"to",
"be",
"validated",
"for",
"a",
"particular",
"service"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/validator/validate.go#L40-L48 |
153,451 | ONSdigital/go-ns | validator/validate.go | Validate | func (fv FormValidator) Validate(req *http.Request, s interface{}) error {
fieldErrs := make(map[string][]error)
if err := decodeRequest(req, s); err != nil {
return err
}
v := getValue(s)
for i := 0; i < v.NumField(); i++ {
tag := string(v.Type().Field(i).Tag.Get("schema"))
fieldVal := getValue(v.Field(i).Interface())
if tag == "" {
log.Debug("field missing schema tag", log.Data{"field": v.Type().Field(i).Name})
continue
}
for _, fld := range fv.flds {
if fld.ID == tag {
for _, rule := range fld.Rules {
fn, ok := RulesList[rule.Name]
if !ok {
return fmt.Errorf("rule name: %s, missing corresponding validation function", rule.Name)
}
if err := fn(fieldVal.Interface(), rule.Value); err != nil {
if _, ok := err.(FieldValidationErr); !ok {
return err
}
fieldErrs[tag] = append(fieldErrs[tag], err)
}
}
}
}
}
if len(fieldErrs) > 0 {
return ErrFormValidationFailed{fieldErrs}
}
return nil
} | go | func (fv FormValidator) Validate(req *http.Request, s interface{}) error {
fieldErrs := make(map[string][]error)
if err := decodeRequest(req, s); err != nil {
return err
}
v := getValue(s)
for i := 0; i < v.NumField(); i++ {
tag := string(v.Type().Field(i).Tag.Get("schema"))
fieldVal := getValue(v.Field(i).Interface())
if tag == "" {
log.Debug("field missing schema tag", log.Data{"field": v.Type().Field(i).Name})
continue
}
for _, fld := range fv.flds {
if fld.ID == tag {
for _, rule := range fld.Rules {
fn, ok := RulesList[rule.Name]
if !ok {
return fmt.Errorf("rule name: %s, missing corresponding validation function", rule.Name)
}
if err := fn(fieldVal.Interface(), rule.Value); err != nil {
if _, ok := err.(FieldValidationErr); !ok {
return err
}
fieldErrs[tag] = append(fieldErrs[tag], err)
}
}
}
}
}
if len(fieldErrs) > 0 {
return ErrFormValidationFailed{fieldErrs}
}
return nil
} | [
"func",
"(",
"fv",
"FormValidator",
")",
"Validate",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"s",
"interface",
"{",
"}",
")",
"error",
"{",
"fieldErrs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"error",
")",
"\n\n",
"if",
"err"... | // Validate will validate a request form parameters against a provided struct | [
"Validate",
"will",
"validate",
"a",
"request",
"form",
"parameters",
"against",
"a",
"provided",
"struct"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/validator/validate.go#L51-L93 |
153,452 | ONSdigital/go-ns | zebedee/client/client.go | NewZebedeeClient | func NewZebedeeClient(url string) *ZebedeeClient {
timeout, err := strconv.Atoi(os.Getenv("ZEBEDEE_REQUEST_TIMEOUT_SECONDS"))
if timeout == 0 || err != nil {
timeout = 5
}
cli := rhttp.DefaultClient
cli.HTTPClient.Timeout = time.Duration(timeout) * time.Second
return &ZebedeeClient{
zebedeeURL: url,
client: cli,
}
} | go | func NewZebedeeClient(url string) *ZebedeeClient {
timeout, err := strconv.Atoi(os.Getenv("ZEBEDEE_REQUEST_TIMEOUT_SECONDS"))
if timeout == 0 || err != nil {
timeout = 5
}
cli := rhttp.DefaultClient
cli.HTTPClient.Timeout = time.Duration(timeout) * time.Second
return &ZebedeeClient{
zebedeeURL: url,
client: cli,
}
} | [
"func",
"NewZebedeeClient",
"(",
"url",
"string",
")",
"*",
"ZebedeeClient",
"{",
"timeout",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"timeout",
"==",
"0",
"||",
"err",
"!=",
"nil",
... | // NewZebedeeClient creates a new Zebedee Client, set ZEBEDEE_REQUEST_TIMEOUT_SECOND
// environment variable to modify default client timeout as zebedee can often be slow
// to respond | [
"NewZebedeeClient",
"creates",
"a",
"new",
"Zebedee",
"Client",
"set",
"ZEBEDEE_REQUEST_TIMEOUT_SECOND",
"environment",
"variable",
"to",
"modify",
"default",
"client",
"timeout",
"as",
"zebedee",
"can",
"often",
"be",
"slow",
"to",
"respond"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/zebedee/client/client.go#L46-L58 |
153,453 | ONSdigital/go-ns | zebedee/client/client.go | Get | func (c *ZebedeeClient) Get(path string) ([]byte, error) {
return c.get(path)
} | go | func (c *ZebedeeClient) Get(path string) ([]byte, error) {
return c.get(path)
} | [
"func",
"(",
"c",
"*",
"ZebedeeClient",
")",
"Get",
"(",
"path",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"c",
".",
"get",
"(",
"path",
")",
"\n",
"}"
] | // Get returns a response for the requested uri in zebedee | [
"Get",
"returns",
"a",
"response",
"for",
"the",
"requested",
"uri",
"in",
"zebedee"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/zebedee/client/client.go#L61-L63 |
153,454 | ONSdigital/go-ns | zebedee/client/client.go | GetDatasetLandingPage | func (c *ZebedeeClient) GetDatasetLandingPage(path string) (data.DatasetLandingPage, error) {
b, err := c.get(path)
if err != nil {
return data.DatasetLandingPage{}, err
}
var dlp data.DatasetLandingPage
if err = json.Unmarshal(b, &dlp); err != nil {
return dlp, err
}
related := [][]data.Related{
dlp.RelatedDatasets,
dlp.RelatedDocuments,
dlp.RelatedMethodology,
dlp.RelatedMethodologyArticle,
}
//Concurrently resolve any URIs where we need more data from another page
var wg sync.WaitGroup
sem := make(chan int, 10)
for _, element := range related {
for i, e := range element {
sem <- 1
wg.Add(1)
go func(i int, e data.Related, element []data.Related) {
defer func() {
<-sem
wg.Done()
}()
t, _ := c.GetPageTitle(e.URI)
element[i].Title = t.Title
}(i, e, element)
}
}
wg.Wait()
return dlp, nil
} | go | func (c *ZebedeeClient) GetDatasetLandingPage(path string) (data.DatasetLandingPage, error) {
b, err := c.get(path)
if err != nil {
return data.DatasetLandingPage{}, err
}
var dlp data.DatasetLandingPage
if err = json.Unmarshal(b, &dlp); err != nil {
return dlp, err
}
related := [][]data.Related{
dlp.RelatedDatasets,
dlp.RelatedDocuments,
dlp.RelatedMethodology,
dlp.RelatedMethodologyArticle,
}
//Concurrently resolve any URIs where we need more data from another page
var wg sync.WaitGroup
sem := make(chan int, 10)
for _, element := range related {
for i, e := range element {
sem <- 1
wg.Add(1)
go func(i int, e data.Related, element []data.Related) {
defer func() {
<-sem
wg.Done()
}()
t, _ := c.GetPageTitle(e.URI)
element[i].Title = t.Title
}(i, e, element)
}
}
wg.Wait()
return dlp, nil
} | [
"func",
"(",
"c",
"*",
"ZebedeeClient",
")",
"GetDatasetLandingPage",
"(",
"path",
"string",
")",
"(",
"data",
".",
"DatasetLandingPage",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"get",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil"... | // GetDatasetLandingPage returns a DatasetLandingPage populated with data from a zebedee response. If an error
// is returned there is a chance that a partly completed DatasetLandingPage is returned | [
"GetDatasetLandingPage",
"returns",
"a",
"DatasetLandingPage",
"populated",
"with",
"data",
"from",
"a",
"zebedee",
"response",
".",
"If",
"an",
"error",
"is",
"returned",
"there",
"is",
"a",
"chance",
"that",
"a",
"partly",
"completed",
"DatasetLandingPage",
"is"... | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/zebedee/client/client.go#L81-L120 |
153,455 | ONSdigital/go-ns | zebedee/client/client.go | GetBreadcrumb | func (c *ZebedeeClient) GetBreadcrumb(uri string) ([]data.Breadcrumb, error) {
b, err := c.get("/parents?uri=" + uri)
if err != nil {
return nil, err
}
var parentsJSON []data.Breadcrumb
if err = json.Unmarshal(b, &parentsJSON); err != nil {
return nil, err
}
return parentsJSON, nil
} | go | func (c *ZebedeeClient) GetBreadcrumb(uri string) ([]data.Breadcrumb, error) {
b, err := c.get("/parents?uri=" + uri)
if err != nil {
return nil, err
}
var parentsJSON []data.Breadcrumb
if err = json.Unmarshal(b, &parentsJSON); err != nil {
return nil, err
}
return parentsJSON, nil
} | [
"func",
"(",
"c",
"*",
"ZebedeeClient",
")",
"GetBreadcrumb",
"(",
"uri",
"string",
")",
"(",
"[",
"]",
"data",
".",
"Breadcrumb",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"get",
"(",
"\"",
"\"",
"+",
"uri",
")",
"\n",
"if",
"er... | // GetBreadcrumb returns a Breadcrumb | [
"GetBreadcrumb",
"returns",
"a",
"Breadcrumb"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/zebedee/client/client.go#L152-L164 |
153,456 | ONSdigital/go-ns | zebedee/client/client.go | GetDataset | func (c *ZebedeeClient) GetDataset(uri string) (data.Dataset, error) {
b, err := c.get("/data?uri=" + uri)
if err != nil {
return data.Dataset{}, err
}
var d data.Dataset
if err = json.Unmarshal(b, &d); err != nil {
return d, err
}
downloads := make([]data.Download, 0)
for _, v := range d.Downloads {
fs, err := c.GetFileSize(uri + "/" + v.File)
if err != nil {
return d, err
}
downloads = append(downloads, data.Download{
File: v.File,
Size: strconv.Itoa(fs.Size),
})
}
d.Downloads = downloads
supplementaryFiles := make([]data.SupplementaryFile, 0)
for _, v := range d.SupplementaryFiles {
fs, err := c.GetFileSize(uri + "/" + v.File)
if err != nil {
return d, err
}
supplementaryFiles = append(supplementaryFiles, data.SupplementaryFile{
File: v.File,
Title: v.Title,
Size: strconv.Itoa(fs.Size),
})
}
d.SupplementaryFiles = supplementaryFiles
return d, nil
} | go | func (c *ZebedeeClient) GetDataset(uri string) (data.Dataset, error) {
b, err := c.get("/data?uri=" + uri)
if err != nil {
return data.Dataset{}, err
}
var d data.Dataset
if err = json.Unmarshal(b, &d); err != nil {
return d, err
}
downloads := make([]data.Download, 0)
for _, v := range d.Downloads {
fs, err := c.GetFileSize(uri + "/" + v.File)
if err != nil {
return d, err
}
downloads = append(downloads, data.Download{
File: v.File,
Size: strconv.Itoa(fs.Size),
})
}
d.Downloads = downloads
supplementaryFiles := make([]data.SupplementaryFile, 0)
for _, v := range d.SupplementaryFiles {
fs, err := c.GetFileSize(uri + "/" + v.File)
if err != nil {
return d, err
}
supplementaryFiles = append(supplementaryFiles, data.SupplementaryFile{
File: v.File,
Title: v.Title,
Size: strconv.Itoa(fs.Size),
})
}
d.SupplementaryFiles = supplementaryFiles
return d, nil
} | [
"func",
"(",
"c",
"*",
"ZebedeeClient",
")",
"GetDataset",
"(",
"uri",
"string",
")",
"(",
"data",
".",
"Dataset",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"get",
"(",
"\"",
"\"",
"+",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",... | // GetDataset returns details about a dataset from zebedee | [
"GetDataset",
"returns",
"details",
"about",
"a",
"dataset",
"from",
"zebedee"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/zebedee/client/client.go#L167-L211 |
153,457 | ONSdigital/go-ns | zebedee/client/client.go | GetFileSize | func (c *ZebedeeClient) GetFileSize(uri string) (data.FileSize, error) {
b, err := c.get("/filesize?uri=" + uri)
if err != nil {
return data.FileSize{}, err
}
var fs data.FileSize
if err = json.Unmarshal(b, &fs); err != nil {
return fs, err
}
return fs, nil
} | go | func (c *ZebedeeClient) GetFileSize(uri string) (data.FileSize, error) {
b, err := c.get("/filesize?uri=" + uri)
if err != nil {
return data.FileSize{}, err
}
var fs data.FileSize
if err = json.Unmarshal(b, &fs); err != nil {
return fs, err
}
return fs, nil
} | [
"func",
"(",
"c",
"*",
"ZebedeeClient",
")",
"GetFileSize",
"(",
"uri",
"string",
")",
"(",
"data",
".",
"FileSize",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"get",
"(",
"\"",
"\"",
"+",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil... | // GetFileSize retrieves a given filesize from zebedee | [
"GetFileSize",
"retrieves",
"a",
"given",
"filesize",
"from",
"zebedee"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/zebedee/client/client.go#L214-L226 |
153,458 | ONSdigital/go-ns | zebedee/client/client.go | GetPageTitle | func (c *ZebedeeClient) GetPageTitle(uri string) (data.PageTitle, error) {
b, err := c.get("/data?uri=" + uri + "&title")
if err != nil {
return data.PageTitle{}, err
}
var pt data.PageTitle
if err = json.Unmarshal(b, &pt); err != nil {
return pt, err
}
return pt, nil
} | go | func (c *ZebedeeClient) GetPageTitle(uri string) (data.PageTitle, error) {
b, err := c.get("/data?uri=" + uri + "&title")
if err != nil {
return data.PageTitle{}, err
}
var pt data.PageTitle
if err = json.Unmarshal(b, &pt); err != nil {
return pt, err
}
return pt, nil
} | [
"func",
"(",
"c",
"*",
"ZebedeeClient",
")",
"GetPageTitle",
"(",
"uri",
"string",
")",
"(",
"data",
".",
"PageTitle",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"c",
".",
"get",
"(",
"\"",
"\"",
"+",
"uri",
"+",
"\"",
"\"",
")",
"\n",
"if"... | // GetPageTitle retrieves a page title from zebedee | [
"GetPageTitle",
"retrieves",
"a",
"page",
"title",
"from",
"zebedee"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/zebedee/client/client.go#L229-L241 |
153,459 | hjr265/postmark.go | postmark/postmark.go | SendBatch | func (c *Client) SendBatch(msg []*Message) ([]*Result, error) {
buf := bytes.Buffer{}
err := json.NewEncoder(&buf).Encode(msg)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.endpoint("email/batch").String(), &buf)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Postmark-Server-Token", c.ApiKey)
resp, err := (&http.Client{}).Do(req)
if err != nil {
return nil, err
}
res := []*Result{}
json.NewDecoder(resp.Body).Decode(res)
return res, nil
} | go | func (c *Client) SendBatch(msg []*Message) ([]*Result, error) {
buf := bytes.Buffer{}
err := json.NewEncoder(&buf).Encode(msg)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.endpoint("email/batch").String(), &buf)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Postmark-Server-Token", c.ApiKey)
resp, err := (&http.Client{}).Do(req)
if err != nil {
return nil, err
}
res := []*Result{}
json.NewDecoder(resp.Body).Decode(res)
return res, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendBatch",
"(",
"msg",
"[",
"]",
"*",
"Message",
")",
"(",
"[",
"]",
"*",
"Result",
",",
"error",
")",
"{",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"NewEncoder",
"("... | // SendBatch sends multiple messages using the batch API | [
"SendBatch",
"sends",
"multiple",
"messages",
"using",
"the",
"batch",
"API"
] | 5546b2897115a65a0b2a9f2763f8c4253fc6423a | https://github.com/hjr265/postmark.go/blob/5546b2897115a65a0b2a9f2763f8c4253fc6423a/postmark/postmark.go#L187-L210 |
153,460 | ONSdigital/go-ns | mongo/mongo.go | Close | func Close(ctx context.Context, session *mgo.Session) error {
closedChannel := make(chan bool)
defer close(closedChannel)
if deadline, ok := ctx.Deadline(); ok {
// Add some time to timeLeft so case where ctx.Done in select
// statement below gets called before time.After(timeLeft) gets called.
// This is so the context error is returned over hardcoded error.
timeLeft = deadline.Sub(time.Now()) + (10 * time.Millisecond)
}
go func() {
start.shutdown(ctx, session, closedChannel)
return
}()
select {
case <-time.After(timeLeft):
return errors.New("closing mongo timed out")
case <-closedChannel:
return nil
case <-ctx.Done():
return ctx.Err()
}
} | go | func Close(ctx context.Context, session *mgo.Session) error {
closedChannel := make(chan bool)
defer close(closedChannel)
if deadline, ok := ctx.Deadline(); ok {
// Add some time to timeLeft so case where ctx.Done in select
// statement below gets called before time.After(timeLeft) gets called.
// This is so the context error is returned over hardcoded error.
timeLeft = deadline.Sub(time.Now()) + (10 * time.Millisecond)
}
go func() {
start.shutdown(ctx, session, closedChannel)
return
}()
select {
case <-time.After(timeLeft):
return errors.New("closing mongo timed out")
case <-closedChannel:
return nil
case <-ctx.Done():
return ctx.Err()
}
} | [
"func",
"Close",
"(",
"ctx",
"context",
".",
"Context",
",",
"session",
"*",
"mgo",
".",
"Session",
")",
"error",
"{",
"closedChannel",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"defer",
"close",
"(",
"closedChannel",
")",
"\n\n",
"if",
"deadline",
... | // Close represents mongo session closing within the context deadline | [
"Close",
"represents",
"mongo",
"session",
"closing",
"within",
"the",
"context",
"deadline"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L44-L68 |
153,461 | ONSdigital/go-ns | mongo/mongo.go | WithUpdates | func WithUpdates(updateDoc bson.M) (bson.M, error) {
newUpdateDoc, err := WithLastUpdatedUpdate(updateDoc)
if err != nil {
return nil, err
}
return WithUniqueTimestampUpdate(newUpdateDoc)
} | go | func WithUpdates(updateDoc bson.M) (bson.M, error) {
newUpdateDoc, err := WithLastUpdatedUpdate(updateDoc)
if err != nil {
return nil, err
}
return WithUniqueTimestampUpdate(newUpdateDoc)
} | [
"func",
"WithUpdates",
"(",
"updateDoc",
"bson",
".",
"M",
")",
"(",
"bson",
".",
"M",
",",
"error",
")",
"{",
"newUpdateDoc",
",",
"err",
":=",
"WithLastUpdatedUpdate",
"(",
"updateDoc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
... | // WithUpdates adds all timestamps to updateDoc | [
"WithUpdates",
"adds",
"all",
"timestamps",
"to",
"updateDoc"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L88-L94 |
153,462 | ONSdigital/go-ns | mongo/mongo.go | WithNamespacedUpdates | func WithNamespacedUpdates(updateDoc bson.M, prefixes []string) (bson.M, error) {
newUpdateDoc, err := WithNamespacedLastUpdatedUpdate(updateDoc, prefixes)
if err != nil {
return nil, err
}
return WithNamespacedUniqueTimestampUpdate(newUpdateDoc, prefixes)
} | go | func WithNamespacedUpdates(updateDoc bson.M, prefixes []string) (bson.M, error) {
newUpdateDoc, err := WithNamespacedLastUpdatedUpdate(updateDoc, prefixes)
if err != nil {
return nil, err
}
return WithNamespacedUniqueTimestampUpdate(newUpdateDoc, prefixes)
} | [
"func",
"WithNamespacedUpdates",
"(",
"updateDoc",
"bson",
".",
"M",
",",
"prefixes",
"[",
"]",
"string",
")",
"(",
"bson",
".",
"M",
",",
"error",
")",
"{",
"newUpdateDoc",
",",
"err",
":=",
"WithNamespacedLastUpdatedUpdate",
"(",
"updateDoc",
",",
"prefixe... | // WithNamespacedUpdates adds all timestamps to updateDoc | [
"WithNamespacedUpdates",
"adds",
"all",
"timestamps",
"to",
"updateDoc"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L97-L103 |
153,463 | ONSdigital/go-ns | mongo/mongo.go | WithLastUpdatedUpdate | func WithLastUpdatedUpdate(updateDoc bson.M) (bson.M, error) {
return withCurrentDate(updateDoc, LastUpdatedKey, true)
} | go | func WithLastUpdatedUpdate(updateDoc bson.M) (bson.M, error) {
return withCurrentDate(updateDoc, LastUpdatedKey, true)
} | [
"func",
"WithLastUpdatedUpdate",
"(",
"updateDoc",
"bson",
".",
"M",
")",
"(",
"bson",
".",
"M",
",",
"error",
")",
"{",
"return",
"withCurrentDate",
"(",
"updateDoc",
",",
"LastUpdatedKey",
",",
"true",
")",
"\n",
"}"
] | // WithLastUpdatedUpdate adds last_updated to updateDoc | [
"WithLastUpdatedUpdate",
"adds",
"last_updated",
"to",
"updateDoc"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L106-L108 |
153,464 | ONSdigital/go-ns | mongo/mongo.go | WithNamespacedLastUpdatedUpdate | func WithNamespacedLastUpdatedUpdate(updateDoc bson.M, prefixes []string) (newUpdateDoc bson.M, err error) {
newUpdateDoc = updateDoc
for _, prefix := range prefixes {
if newUpdateDoc, err = withCurrentDate(newUpdateDoc, prefix+LastUpdatedKey, true); err != nil {
return nil, err
}
}
return newUpdateDoc, nil
} | go | func WithNamespacedLastUpdatedUpdate(updateDoc bson.M, prefixes []string) (newUpdateDoc bson.M, err error) {
newUpdateDoc = updateDoc
for _, prefix := range prefixes {
if newUpdateDoc, err = withCurrentDate(newUpdateDoc, prefix+LastUpdatedKey, true); err != nil {
return nil, err
}
}
return newUpdateDoc, nil
} | [
"func",
"WithNamespacedLastUpdatedUpdate",
"(",
"updateDoc",
"bson",
".",
"M",
",",
"prefixes",
"[",
"]",
"string",
")",
"(",
"newUpdateDoc",
"bson",
".",
"M",
",",
"err",
"error",
")",
"{",
"newUpdateDoc",
"=",
"updateDoc",
"\n",
"for",
"_",
",",
"prefix"... | // WithNamespacedLastUpdatedUpdate adds unique timestamp to updateDoc | [
"WithNamespacedLastUpdatedUpdate",
"adds",
"unique",
"timestamp",
"to",
"updateDoc"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L111-L119 |
153,465 | ONSdigital/go-ns | mongo/mongo.go | WithUniqueTimestampUpdate | func WithUniqueTimestampUpdate(updateDoc bson.M) (bson.M, error) {
return withCurrentDate(updateDoc, UniqueTimestampKey, bson.M{"$type": "timestamp"})
} | go | func WithUniqueTimestampUpdate(updateDoc bson.M) (bson.M, error) {
return withCurrentDate(updateDoc, UniqueTimestampKey, bson.M{"$type": "timestamp"})
} | [
"func",
"WithUniqueTimestampUpdate",
"(",
"updateDoc",
"bson",
".",
"M",
")",
"(",
"bson",
".",
"M",
",",
"error",
")",
"{",
"return",
"withCurrentDate",
"(",
"updateDoc",
",",
"UniqueTimestampKey",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"\"",
"\""... | // WithUniqueTimestampUpdate adds unique timestamp to updateDoc | [
"WithUniqueTimestampUpdate",
"adds",
"unique",
"timestamp",
"to",
"updateDoc"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L122-L124 |
153,466 | ONSdigital/go-ns | mongo/mongo.go | WithNamespacedUniqueTimestampUpdate | func WithNamespacedUniqueTimestampUpdate(updateDoc bson.M, prefixes []string) (newUpdateDoc bson.M, err error) {
newUpdateDoc = updateDoc
for _, prefix := range prefixes {
if newUpdateDoc, err = withCurrentDate(newUpdateDoc, prefix+UniqueTimestampKey, bson.M{"$type": "timestamp"}); err != nil {
return nil, err
}
}
return newUpdateDoc, nil
} | go | func WithNamespacedUniqueTimestampUpdate(updateDoc bson.M, prefixes []string) (newUpdateDoc bson.M, err error) {
newUpdateDoc = updateDoc
for _, prefix := range prefixes {
if newUpdateDoc, err = withCurrentDate(newUpdateDoc, prefix+UniqueTimestampKey, bson.M{"$type": "timestamp"}); err != nil {
return nil, err
}
}
return newUpdateDoc, nil
} | [
"func",
"WithNamespacedUniqueTimestampUpdate",
"(",
"updateDoc",
"bson",
".",
"M",
",",
"prefixes",
"[",
"]",
"string",
")",
"(",
"newUpdateDoc",
"bson",
".",
"M",
",",
"err",
"error",
")",
"{",
"newUpdateDoc",
"=",
"updateDoc",
"\n",
"for",
"_",
",",
"pre... | // WithNamespacedUniqueTimestampUpdate adds unique timestamp to updateDoc | [
"WithNamespacedUniqueTimestampUpdate",
"adds",
"unique",
"timestamp",
"to",
"updateDoc"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L127-L135 |
153,467 | ONSdigital/go-ns | mongo/mongo.go | WithUniqueTimestampQuery | func WithUniqueTimestampQuery(queryDoc bson.M, timestamp bson.MongoTimestamp) bson.M {
queryDoc[UniqueTimestampKey] = timestamp
return queryDoc
} | go | func WithUniqueTimestampQuery(queryDoc bson.M, timestamp bson.MongoTimestamp) bson.M {
queryDoc[UniqueTimestampKey] = timestamp
return queryDoc
} | [
"func",
"WithUniqueTimestampQuery",
"(",
"queryDoc",
"bson",
".",
"M",
",",
"timestamp",
"bson",
".",
"MongoTimestamp",
")",
"bson",
".",
"M",
"{",
"queryDoc",
"[",
"UniqueTimestampKey",
"]",
"=",
"timestamp",
"\n",
"return",
"queryDoc",
"\n",
"}"
] | // WithUniqueTimestampQuery adds unique timestamp to queryDoc | [
"WithUniqueTimestampQuery",
"adds",
"unique",
"timestamp",
"to",
"queryDoc"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L138-L141 |
153,468 | ONSdigital/go-ns | mongo/mongo.go | WithNamespacedUniqueTimestampQuery | func WithNamespacedUniqueTimestampQuery(queryDoc bson.M, timestamps []bson.MongoTimestamp, prefixes []string) bson.M {
newQueryDoc := queryDoc
for idx, prefix := range prefixes {
newQueryDoc[prefix+UniqueTimestampKey] = timestamps[idx]
}
return newQueryDoc
} | go | func WithNamespacedUniqueTimestampQuery(queryDoc bson.M, timestamps []bson.MongoTimestamp, prefixes []string) bson.M {
newQueryDoc := queryDoc
for idx, prefix := range prefixes {
newQueryDoc[prefix+UniqueTimestampKey] = timestamps[idx]
}
return newQueryDoc
} | [
"func",
"WithNamespacedUniqueTimestampQuery",
"(",
"queryDoc",
"bson",
".",
"M",
",",
"timestamps",
"[",
"]",
"bson",
".",
"MongoTimestamp",
",",
"prefixes",
"[",
"]",
"string",
")",
"bson",
".",
"M",
"{",
"newQueryDoc",
":=",
"queryDoc",
"\n",
"for",
"idx",... | // WithNamespacedUniqueTimestampQuery adds unique timestamps to queryDoc sub-docs | [
"WithNamespacedUniqueTimestampQuery",
"adds",
"unique",
"timestamps",
"to",
"queryDoc",
"sub",
"-",
"docs"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/mongo.go#L144-L150 |
153,469 | ONSdigital/go-ns | log/log.go | Handler | func Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
rc := &responseCapture{w, 0}
s := time.Now()
h.ServeHTTP(rc, req)
e := time.Now()
d := e.Sub(s)
data := Data{
"start": s,
"end": e,
"duration": d,
"status": rc.statusCode,
"method": req.Method,
"path": req.URL.Path,
}
if len(req.URL.RawQuery) > 0 {
data["query"] = req.URL.Query()
}
Event("request", GetRequestID(req), data)
})
} | go | func Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
rc := &responseCapture{w, 0}
s := time.Now()
h.ServeHTTP(rc, req)
e := time.Now()
d := e.Sub(s)
data := Data{
"start": s,
"end": e,
"duration": d,
"status": rc.statusCode,
"method": req.Method,
"path": req.URL.Path,
}
if len(req.URL.RawQuery) > 0 {
data["query"] = req.URL.Query()
}
Event("request", GetRequestID(req), data)
})
} | [
"func",
"Handler",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"rc",
":=",
"&",
"... | // Handler wraps a http.Handler and logs the status code and total response time | [
"Handler",
"wraps",
"a",
"http",
".",
"Handler",
"and",
"logs",
"the",
"status",
"code",
"and",
"total",
"response",
"time"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L45-L67 |
153,470 | ONSdigital/go-ns | log/log.go | ErrorC | func ErrorC(correlationKey string, err error, data Data) {
if data == nil {
data = Data{}
}
if err != nil {
data["message"] = err.Error()
data["error"] = err
}
Event("error", correlationKey, data)
} | go | func ErrorC(correlationKey string, err error, data Data) {
if data == nil {
data = Data{}
}
if err != nil {
data["message"] = err.Error()
data["error"] = err
}
Event("error", correlationKey, data)
} | [
"func",
"ErrorC",
"(",
"correlationKey",
"string",
",",
"err",
"error",
",",
"data",
"Data",
")",
"{",
"if",
"data",
"==",
"nil",
"{",
"data",
"=",
"Data",
"{",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"data",
"[",
"\"",
"\"",
"]",
... | // ErrorC is a structured error message with correlationKey | [
"ErrorC",
"is",
"a",
"structured",
"error",
"message",
"with",
"correlationKey"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L174-L183 |
153,471 | ONSdigital/go-ns | log/log.go | ErrorCtx | func ErrorCtx(ctx context.Context, err error, data Data) {
correlationKey := common.GetRequestId(ctx)
ErrorC(correlationKey, err, data)
} | go | func ErrorCtx(ctx context.Context, err error, data Data) {
correlationKey := common.GetRequestId(ctx)
ErrorC(correlationKey, err, data)
} | [
"func",
"ErrorCtx",
"(",
"ctx",
"context",
".",
"Context",
",",
"err",
"error",
",",
"data",
"Data",
")",
"{",
"correlationKey",
":=",
"common",
".",
"GetRequestId",
"(",
"ctx",
")",
"\n",
"ErrorC",
"(",
"correlationKey",
",",
"err",
",",
"data",
")",
... | // ErrorCtx is a structured error message and retrieves the correlationKey from go context | [
"ErrorCtx",
"is",
"a",
"structured",
"error",
"message",
"and",
"retrieves",
"the",
"correlationKey",
"from",
"go",
"context"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L186-L189 |
153,472 | ONSdigital/go-ns | log/log.go | ErrorR | func ErrorR(req *http.Request, err error, data Data) {
ErrorC(GetRequestID(req), err, data)
} | go | func ErrorR(req *http.Request, err error, data Data) {
ErrorC(GetRequestID(req), err, data)
} | [
"func",
"ErrorR",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"err",
"error",
",",
"data",
"Data",
")",
"{",
"ErrorC",
"(",
"GetRequestID",
"(",
"req",
")",
",",
"err",
",",
"data",
")",
"\n",
"}"
] | // ErrorR is a structured error message for a request | [
"ErrorR",
"is",
"a",
"structured",
"error",
"message",
"for",
"a",
"request"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L192-L194 |
153,473 | ONSdigital/go-ns | log/log.go | DebugC | func DebugC(correlationKey string, message string, data Data) {
if data == nil {
data = Data{}
}
if len(message) > 0 {
data["message"] = message
}
Event("debug", correlationKey, data)
} | go | func DebugC(correlationKey string, message string, data Data) {
if data == nil {
data = Data{}
}
if len(message) > 0 {
data["message"] = message
}
Event("debug", correlationKey, data)
} | [
"func",
"DebugC",
"(",
"correlationKey",
"string",
",",
"message",
"string",
",",
"data",
"Data",
")",
"{",
"if",
"data",
"==",
"nil",
"{",
"data",
"=",
"Data",
"{",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"message",
")",
">",
"0",
"{",
"data",
"... | // DebugC is a structured debug message with correlationKey | [
"DebugC",
"is",
"a",
"structured",
"debug",
"message",
"with",
"correlationKey"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L202-L210 |
153,474 | ONSdigital/go-ns | log/log.go | DebugCtx | func DebugCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
DebugC(correlationKey, message, data)
} | go | func DebugCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
DebugC(correlationKey, message, data)
} | [
"func",
"DebugCtx",
"(",
"ctx",
"context",
".",
"Context",
",",
"message",
"string",
",",
"data",
"Data",
")",
"{",
"correlationKey",
":=",
"common",
".",
"GetRequestId",
"(",
"ctx",
")",
"\n",
"DebugC",
"(",
"correlationKey",
",",
"message",
",",
"data",
... | // DebugCtx is a structured debug message and retrieves the correlationKey from go context | [
"DebugCtx",
"is",
"a",
"structured",
"debug",
"message",
"and",
"retrieves",
"the",
"correlationKey",
"from",
"go",
"context"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L213-L216 |
153,475 | ONSdigital/go-ns | log/log.go | DebugR | func DebugR(req *http.Request, message string, data Data) {
DebugC(GetRequestID(req), message, data)
} | go | func DebugR(req *http.Request, message string, data Data) {
DebugC(GetRequestID(req), message, data)
} | [
"func",
"DebugR",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"message",
"string",
",",
"data",
"Data",
")",
"{",
"DebugC",
"(",
"GetRequestID",
"(",
"req",
")",
",",
"message",
",",
"data",
")",
"\n",
"}"
] | // DebugR is a structured debug message for a request | [
"DebugR",
"is",
"a",
"structured",
"debug",
"message",
"for",
"a",
"request"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L219-L221 |
153,476 | ONSdigital/go-ns | log/log.go | TraceCtx | func TraceCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
TraceC(correlationKey, message, data)
} | go | func TraceCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
TraceC(correlationKey, message, data)
} | [
"func",
"TraceCtx",
"(",
"ctx",
"context",
".",
"Context",
",",
"message",
"string",
",",
"data",
"Data",
")",
"{",
"correlationKey",
":=",
"common",
".",
"GetRequestId",
"(",
"ctx",
")",
"\n",
"TraceC",
"(",
"correlationKey",
",",
"message",
",",
"data",
... | // TraceCtx is a structured trace message and retrieves the correlationKey from go context | [
"TraceCtx",
"is",
"a",
"structured",
"trace",
"message",
"and",
"retrieves",
"the",
"correlationKey",
"from",
"go",
"context"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L240-L243 |
153,477 | ONSdigital/go-ns | log/log.go | TraceR | func TraceR(req *http.Request, message string, data Data) {
TraceC(GetRequestID(req), message, data)
} | go | func TraceR(req *http.Request, message string, data Data) {
TraceC(GetRequestID(req), message, data)
} | [
"func",
"TraceR",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"message",
"string",
",",
"data",
"Data",
")",
"{",
"TraceC",
"(",
"GetRequestID",
"(",
"req",
")",
",",
"message",
",",
"data",
")",
"\n",
"}"
] | // TraceR is a structured trace message for a request | [
"TraceR",
"is",
"a",
"structured",
"trace",
"message",
"for",
"a",
"request"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L246-L248 |
153,478 | ONSdigital/go-ns | log/log.go | InfoCtx | func InfoCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
InfoC(correlationKey, message, data)
} | go | func InfoCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
InfoC(correlationKey, message, data)
} | [
"func",
"InfoCtx",
"(",
"ctx",
"context",
".",
"Context",
",",
"message",
"string",
",",
"data",
"Data",
")",
"{",
"correlationKey",
":=",
"common",
".",
"GetRequestId",
"(",
"ctx",
")",
"\n",
"InfoC",
"(",
"correlationKey",
",",
"message",
",",
"data",
... | // InfoCtx is a structured info message and retrieves the correlationKey from go context | [
"InfoCtx",
"is",
"a",
"structured",
"info",
"message",
"and",
"retrieves",
"the",
"correlationKey",
"from",
"go",
"context"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L267-L270 |
153,479 | ONSdigital/go-ns | log/log.go | InfoR | func InfoR(req *http.Request, message string, data Data) {
InfoC(GetRequestID(req), message, data)
} | go | func InfoR(req *http.Request, message string, data Data) {
InfoC(GetRequestID(req), message, data)
} | [
"func",
"InfoR",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"message",
"string",
",",
"data",
"Data",
")",
"{",
"InfoC",
"(",
"GetRequestID",
"(",
"req",
")",
",",
"message",
",",
"data",
")",
"\n",
"}"
] | // InfoR is a structured info message for a request | [
"InfoR",
"is",
"a",
"structured",
"info",
"message",
"for",
"a",
"request"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/log/log.go#L273-L275 |
153,480 | ONSdigital/go-ns | server/server.go | New | func New(bindAddr string, router http.Handler) *Server {
middleware := map[string]alice.Constructor{
RequestIDHandlerKey: requestID.Handler(16),
LogHandlerKey: log.Handler,
}
return &Server{
Alice: nil,
Middleware: middleware,
MiddlewareOrder: []string{RequestIDHandlerKey, LogHandlerKey},
Server: http.Server{
Handler: router,
Addr: bindAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
ReadHeaderTimeout: 0,
IdleTimeout: 0,
MaxHeaderBytes: 0,
},
HandleOSSignals: true,
DefaultShutdownTimeout: 10 * time.Second,
}
} | go | func New(bindAddr string, router http.Handler) *Server {
middleware := map[string]alice.Constructor{
RequestIDHandlerKey: requestID.Handler(16),
LogHandlerKey: log.Handler,
}
return &Server{
Alice: nil,
Middleware: middleware,
MiddlewareOrder: []string{RequestIDHandlerKey, LogHandlerKey},
Server: http.Server{
Handler: router,
Addr: bindAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
ReadHeaderTimeout: 0,
IdleTimeout: 0,
MaxHeaderBytes: 0,
},
HandleOSSignals: true,
DefaultShutdownTimeout: 10 * time.Second,
}
} | [
"func",
"New",
"(",
"bindAddr",
"string",
",",
"router",
"http",
".",
"Handler",
")",
"*",
"Server",
"{",
"middleware",
":=",
"map",
"[",
"string",
"]",
"alice",
".",
"Constructor",
"{",
"RequestIDHandlerKey",
":",
"requestID",
".",
"Handler",
"(",
"16",
... | // New creates a new server | [
"New",
"creates",
"a",
"new",
"server"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/server/server.go#L33-L55 |
153,481 | ONSdigital/go-ns | server/server.go | ListenAndServeTLS | func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
if len(certFile) == 0 || len(keyFile) == 0 {
panic("either CertFile/KeyFile must be blank, or both provided")
}
s.KeyFile = keyFile
s.CertFile = certFile
return s.ListenAndServe()
} | go | func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
if len(certFile) == 0 || len(keyFile) == 0 {
panic("either CertFile/KeyFile must be blank, or both provided")
}
s.KeyFile = keyFile
s.CertFile = certFile
return s.ListenAndServe()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ListenAndServeTLS",
"(",
"certFile",
",",
"keyFile",
"string",
")",
"error",
"{",
"if",
"len",
"(",
"certFile",
")",
"==",
"0",
"||",
"len",
"(",
"keyFile",
")",
"==",
"0",
"{",
"panic",
"(",
"\"",
"\"",
")",
... | // ListenAndServeTLS sets KeyFile and CertFile, then calls ListenAndServe | [
"ListenAndServeTLS",
"sets",
"KeyFile",
"and",
"CertFile",
"then",
"calls",
"ListenAndServe"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/server/server.go#L86-L93 |
153,482 | ONSdigital/go-ns | server/server.go | Shutdown | func (s *Server) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx, _ = context.WithTimeout(context.Background(), s.DefaultShutdownTimeout)
}
return s.Server.Shutdown(ctx)
} | go | func (s *Server) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx, _ = context.WithTimeout(context.Background(), s.DefaultShutdownTimeout)
}
return s.Server.Shutdown(ctx)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Shutdown",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"ctx",
"==",
"nil",
"{",
"ctx",
",",
"_",
"=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"s",
... | // Shutdown will gracefully shutdown the server, using a default shutdown
// timeout if a context is not provided. | [
"Shutdown",
"will",
"gracefully",
"shutdown",
"the",
"server",
"using",
"a",
"default",
"shutdown",
"timeout",
"if",
"a",
"context",
"is",
"not",
"provided",
"."
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/server/server.go#L97-L104 |
153,483 | ONSdigital/go-ns | server/server.go | Close | func (s *Server) Close(ctx context.Context) error {
return s.Shutdown(ctx)
} | go | func (s *Server) Close(ctx context.Context) error {
return s.Shutdown(ctx)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Close",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"s",
".",
"Shutdown",
"(",
"ctx",
")",
"\n",
"}"
] | // Close is simply a wrapper around Shutdown that enables Server to be treated as a Closable | [
"Close",
"is",
"simply",
"a",
"wrapper",
"around",
"Shutdown",
"that",
"enables",
"Server",
"to",
"be",
"treated",
"as",
"a",
"Closable"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/server/server.go#L107-L109 |
153,484 | op/go-libspotify | spotify/error.go | spError | func spError(err C.sp_error) error {
if err != C.SP_ERROR_OK {
return Error(err)
}
return nil
} | go | func spError(err C.sp_error) error {
if err != C.SP_ERROR_OK {
return Error(err)
}
return nil
} | [
"func",
"spError",
"(",
"err",
"C",
".",
"sp_error",
")",
"error",
"{",
"if",
"err",
"!=",
"C",
".",
"SP_ERROR_OK",
"{",
"return",
"Error",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // spError converts an error from libspotify into a Go error. | [
"spError",
"converts",
"an",
"error",
"from",
"libspotify",
"into",
"a",
"Go",
"error",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/error.go#L140-L145 |
153,485 | ONSdigital/go-ns | identity/identity.go | Handler | func Handler(zebedeeURL string) func(http.Handler) http.Handler {
authClient := clientsidentity.NewAPIClient(nil, zebedeeURL)
return HandlerForHTTPClient(authClient)
} | go | func Handler(zebedeeURL string) func(http.Handler) http.Handler {
authClient := clientsidentity.NewAPIClient(nil, zebedeeURL)
return HandlerForHTTPClient(authClient)
} | [
"func",
"Handler",
"(",
"zebedeeURL",
"string",
")",
"func",
"(",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"authClient",
":=",
"clientsidentity",
".",
"NewAPIClient",
"(",
"nil",
",",
"zebedeeURL",
")",
"\n",
"return",
"HandlerForHTTPClient",
... | // Handler controls the authenticating of a request | [
"Handler",
"controls",
"the",
"authenticating",
"of",
"a",
"request"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/identity/identity.go#L12-L15 |
153,486 | ONSdigital/go-ns | identity/identity.go | HandlerForHTTPClient | func HandlerForHTTPClient(cli clientsidentity.Clienter) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.DebugR(req, "identity middleware called", nil)
ctx, statusCode, authFailure, err := cli.CheckRequest(req)
logData := log.Data{"auth_status_code": statusCode}
if err != nil {
log.ErrorR(req, err, logData)
request.DrainBody(req)
w.WriteHeader(statusCode)
return
}
if authFailure != nil {
log.ErrorR(req, authFailure, logData)
request.DrainBody(req)
w.WriteHeader(statusCode)
return
}
req = req.WithContext(ctx)
log.DebugR(req, "identity middleware finished, calling downstream handler", nil)
h.ServeHTTP(w, req)
})
}
} | go | func HandlerForHTTPClient(cli clientsidentity.Clienter) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.DebugR(req, "identity middleware called", nil)
ctx, statusCode, authFailure, err := cli.CheckRequest(req)
logData := log.Data{"auth_status_code": statusCode}
if err != nil {
log.ErrorR(req, err, logData)
request.DrainBody(req)
w.WriteHeader(statusCode)
return
}
if authFailure != nil {
log.ErrorR(req, authFailure, logData)
request.DrainBody(req)
w.WriteHeader(statusCode)
return
}
req = req.WithContext(ctx)
log.DebugR(req, "identity middleware finished, calling downstream handler", nil)
h.ServeHTTP(w, req)
})
}
} | [
"func",
"HandlerForHTTPClient",
"(",
"cli",
"clientsidentity",
".",
"Clienter",
")",
"func",
"(",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"func",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"h... | // HandlerForHTTPClient allows a handler to be created that uses the given HTTP client | [
"HandlerForHTTPClient",
"allows",
"a",
"handler",
"to",
"be",
"created",
"that",
"uses",
"the",
"given",
"HTTP",
"client"
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/identity/identity.go#L18-L49 |
153,487 | ONSdigital/go-ns | healthcheck/mock_healthcheck/mock_httpclient.go | Get | func (mock *HttpClientMock) Get(url string) (*http.Response, error) {
if mock.GetFunc == nil {
panic("moq: HttpClientMock.GetFunc is nil but httpClient.Get was just called")
}
callInfo := struct {
URL string
}{
URL: url,
}
lockhttpClientMockGet.Lock()
mock.calls.Get = append(mock.calls.Get, callInfo)
lockhttpClientMockGet.Unlock()
return mock.GetFunc(url)
} | go | func (mock *HttpClientMock) Get(url string) (*http.Response, error) {
if mock.GetFunc == nil {
panic("moq: HttpClientMock.GetFunc is nil but httpClient.Get was just called")
}
callInfo := struct {
URL string
}{
URL: url,
}
lockhttpClientMockGet.Lock()
mock.calls.Get = append(mock.calls.Get, callInfo)
lockhttpClientMockGet.Unlock()
return mock.GetFunc(url)
} | [
"func",
"(",
"mock",
"*",
"HttpClientMock",
")",
"Get",
"(",
"url",
"string",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"mock",
".",
"GetFunc",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"callInf... | // Get calls GetFunc. | [
"Get",
"calls",
"GetFunc",
"."
] | 81b393bfc6e80674df603b7fde2f31a35e81b9dd | https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/healthcheck/mock_healthcheck/mock_httpclient.go#L45-L58 |
153,488 | op/go-libspotify | spotify/libspotify.go | sessionCall | func sessionCall(spSession unsafe.Pointer, callback func(*Session)) {
s := (*C.sp_session)(spSession)
session := (*Session)(C.sp_session_userdata(s))
callback(session)
} | go | func sessionCall(spSession unsafe.Pointer, callback func(*Session)) {
s := (*C.sp_session)(spSession)
session := (*Session)(C.sp_session_userdata(s))
callback(session)
} | [
"func",
"sessionCall",
"(",
"spSession",
"unsafe",
".",
"Pointer",
",",
"callback",
"func",
"(",
"*",
"Session",
")",
")",
"{",
"s",
":=",
"(",
"*",
"C",
".",
"sp_session",
")",
"(",
"spSession",
")",
"\n",
"session",
":=",
"(",
"*",
"Session",
")",
... | // sessionCall maps the C Spotify session structure to the Go session and
// executes the given function. | [
"sessionCall",
"maps",
"the",
"C",
"Spotify",
"session",
"structure",
"to",
"the",
"Go",
"session",
"and",
"executes",
"the",
"given",
"function",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L182-L186 |
153,489 | op/go-libspotify | spotify/libspotify.go | NewSession | func NewSession(config *Config) (*Session, error) {
session := &Session{
shutdown: make(chan struct{}),
// Event channels, same order as api.h
loggedIn: make(chan error, 1),
loggedOut: make(chan struct{}, 1),
metadataUpdates: make(map[updatesListener]struct{}),
connectionErrors: make(chan error, 1),
messagesToUser: make(chan string, 1),
notifyMainThread: make(chan struct{}, 1),
playTokenLost: make(chan struct{}, 1),
rawLogMessages: make(chan string, 128),
logMessages: make(chan *LogMessage, 128),
endOfTrack: make(chan struct{}, 1),
streamingErrors: make(chan error, 1),
userInfoUpdates: make(map[updatesListener]struct{}),
offlineStatusUpdates: make(chan struct{}, 1),
offlineErrors: make(chan error, 1),
credentialsBlobs: make(chan []byte, 1),
connectionStates: make(chan struct{}, 1),
scrobbleErrors: make(chan error, 1),
privateSessionChanges: make(chan bool, 1),
audioConsumer: config.AudioConsumer,
}
if err := session.setupConfig(config); err != nil {
return nil, err
}
// libspotify expects certain methods to be called from the same thread as was
// used when the sp_session_create was called. Hence we do lock down one
// thread to only process events and some of these special calls.
//
// AFAIK this is the only way we can decide which thread a given goroutine
// executes on.
errc := make(chan error, 1)
go func() {
// TODO make sure we have enough threads available
runtime.LockOSThread()
err := spError(C.sp_session_create(&session.config, &session.sp_session))
errc <- err
if err != nil {
return
}
session.processEvents()
}()
if err := <-errc; err != nil {
return nil, err
}
go session.processBackground()
return session, nil
} | go | func NewSession(config *Config) (*Session, error) {
session := &Session{
shutdown: make(chan struct{}),
// Event channels, same order as api.h
loggedIn: make(chan error, 1),
loggedOut: make(chan struct{}, 1),
metadataUpdates: make(map[updatesListener]struct{}),
connectionErrors: make(chan error, 1),
messagesToUser: make(chan string, 1),
notifyMainThread: make(chan struct{}, 1),
playTokenLost: make(chan struct{}, 1),
rawLogMessages: make(chan string, 128),
logMessages: make(chan *LogMessage, 128),
endOfTrack: make(chan struct{}, 1),
streamingErrors: make(chan error, 1),
userInfoUpdates: make(map[updatesListener]struct{}),
offlineStatusUpdates: make(chan struct{}, 1),
offlineErrors: make(chan error, 1),
credentialsBlobs: make(chan []byte, 1),
connectionStates: make(chan struct{}, 1),
scrobbleErrors: make(chan error, 1),
privateSessionChanges: make(chan bool, 1),
audioConsumer: config.AudioConsumer,
}
if err := session.setupConfig(config); err != nil {
return nil, err
}
// libspotify expects certain methods to be called from the same thread as was
// used when the sp_session_create was called. Hence we do lock down one
// thread to only process events and some of these special calls.
//
// AFAIK this is the only way we can decide which thread a given goroutine
// executes on.
errc := make(chan error, 1)
go func() {
// TODO make sure we have enough threads available
runtime.LockOSThread()
err := spError(C.sp_session_create(&session.config, &session.sp_session))
errc <- err
if err != nil {
return
}
session.processEvents()
}()
if err := <-errc; err != nil {
return nil, err
}
go session.processBackground()
return session, nil
} | [
"func",
"NewSession",
"(",
"config",
"*",
"Config",
")",
"(",
"*",
"Session",
",",
"error",
")",
"{",
"session",
":=",
"&",
"Session",
"{",
"shutdown",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"// Event channels, same order as api.h",
"logge... | // NewSession creates a new session based on the given configuration. | [
"NewSession",
"creates",
"a",
"new",
"session",
"based",
"on",
"the",
"given",
"configuration",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L189-L253 |
153,490 | op/go-libspotify | spotify/libspotify.go | setupConfig | func (s *Session) setupConfig(config *Config) error {
if config.ApplicationKey == nil {
return ErrMissingApplicationKey
}
s.config.api_version = C.SPOTIFY_API_VERSION
s.config.cache_location = C.CString(config.CacheLocation)
if s.config.cache_location == nil {
return syscall.ENOMEM
}
s.config.settings_location = C.CString(config.SettingsLocation)
if s.config.settings_location == nil {
return syscall.ENOMEM
}
appKey := C.CString(string(config.ApplicationKey))
s.config.application_key = unsafe.Pointer(appKey)
if s.config.application_key == nil {
return syscall.ENOMEM
}
s.config.application_key_size = C.size_t(len(config.ApplicationKey))
userAgent := config.UserAgent
if len(userAgent) == 0 {
userAgent = "go-libspotify"
if len(config.ApplicationName) > 0 {
userAgent += "/" + config.ApplicationName
}
}
s.config.user_agent = C.CString(userAgent)
if s.config.user_agent == nil {
return syscall.ENOMEM
}
// Setup the callbacks structure used for all sessions. The difference
// between each session object is the userdata object which points into the
// Go Session object.
once.Do(func() { C.set_callbacks(&callbacks) })
s.config.callbacks = &callbacks
s.config.userdata = unsafe.Pointer(s)
if config.CompressPlaylists {
s.config.compress_playlists = 1
}
if config.DisablePlaylistMetadataCache {
s.config.dont_save_metadata_for_playlists = 1
}
if config.InitiallyUnloadPlaylists {
s.config.initially_unload_playlists = 1
}
return nil
} | go | func (s *Session) setupConfig(config *Config) error {
if config.ApplicationKey == nil {
return ErrMissingApplicationKey
}
s.config.api_version = C.SPOTIFY_API_VERSION
s.config.cache_location = C.CString(config.CacheLocation)
if s.config.cache_location == nil {
return syscall.ENOMEM
}
s.config.settings_location = C.CString(config.SettingsLocation)
if s.config.settings_location == nil {
return syscall.ENOMEM
}
appKey := C.CString(string(config.ApplicationKey))
s.config.application_key = unsafe.Pointer(appKey)
if s.config.application_key == nil {
return syscall.ENOMEM
}
s.config.application_key_size = C.size_t(len(config.ApplicationKey))
userAgent := config.UserAgent
if len(userAgent) == 0 {
userAgent = "go-libspotify"
if len(config.ApplicationName) > 0 {
userAgent += "/" + config.ApplicationName
}
}
s.config.user_agent = C.CString(userAgent)
if s.config.user_agent == nil {
return syscall.ENOMEM
}
// Setup the callbacks structure used for all sessions. The difference
// between each session object is the userdata object which points into the
// Go Session object.
once.Do(func() { C.set_callbacks(&callbacks) })
s.config.callbacks = &callbacks
s.config.userdata = unsafe.Pointer(s)
if config.CompressPlaylists {
s.config.compress_playlists = 1
}
if config.DisablePlaylistMetadataCache {
s.config.dont_save_metadata_for_playlists = 1
}
if config.InitiallyUnloadPlaylists {
s.config.initially_unload_playlists = 1
}
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"setupConfig",
"(",
"config",
"*",
"Config",
")",
"error",
"{",
"if",
"config",
".",
"ApplicationKey",
"==",
"nil",
"{",
"return",
"ErrMissingApplicationKey",
"\n",
"}",
"\n\n",
"s",
".",
"config",
".",
"api_version",... | // setupConfig sets the config up to be used when connecting the session. | [
"setupConfig",
"sets",
"the",
"config",
"up",
"to",
"be",
"used",
"when",
"connecting",
"the",
"session",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L256-L309 |
153,491 | op/go-libspotify | spotify/libspotify.go | Close | func (s *Session) Close() error {
var err error
s.dealloc.Do(func() {
// Send shutdown events to log and event processor
s.shutdown <- struct{}{}
s.shutdown <- struct{}{}
s.wg.Wait()
err = spError(C.sp_session_release(s.sp_session))
s.free()
})
return nil
} | go | func (s *Session) Close() error {
var err error
s.dealloc.Do(func() {
// Send shutdown events to log and event processor
s.shutdown <- struct{}{}
s.shutdown <- struct{}{}
s.wg.Wait()
err = spError(C.sp_session_release(s.sp_session))
s.free()
})
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"s",
".",
"dealloc",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"// Send shutdown events to log and event processor",
"s",
".",
"shutdown",
"<-",
"struct",
"... | // Close closes the session, making the session unusable for any future calls.
// This call releases the session internally back to libspotify and shuts the
// background processing thread down. | [
"Close",
"closes",
"the",
"session",
"making",
"the",
"session",
"unusable",
"for",
"any",
"future",
"calls",
".",
"This",
"call",
"releases",
"the",
"session",
"internally",
"back",
"to",
"libspotify",
"and",
"shuts",
"the",
"background",
"processing",
"thread"... | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L333-L345 |
153,492 | op/go-libspotify | spotify/libspotify.go | Login | func (s *Session) Login(c Credentials, remember bool) error {
cusername := C.CString(c.Username)
defer C.free(unsafe.Pointer(cusername))
var crememberme C.bool = 0
if remember {
crememberme = 1
}
var cpassword, cblob *C.char
if len(c.Password) > 0 {
cpassword = C.CString(c.Password)
defer C.free(unsafe.Pointer(cpassword))
}
if len(c.Blob) > 0 {
cblob = C.CString(string(c.Blob))
defer C.free(unsafe.Pointer(cblob))
}
s.mu.Lock()
defer s.mu.Unlock()
rc := C.sp_session_login(
s.sp_session,
cusername,
cpassword,
crememberme,
cblob,
)
return spError(rc)
} | go | func (s *Session) Login(c Credentials, remember bool) error {
cusername := C.CString(c.Username)
defer C.free(unsafe.Pointer(cusername))
var crememberme C.bool = 0
if remember {
crememberme = 1
}
var cpassword, cblob *C.char
if len(c.Password) > 0 {
cpassword = C.CString(c.Password)
defer C.free(unsafe.Pointer(cpassword))
}
if len(c.Blob) > 0 {
cblob = C.CString(string(c.Blob))
defer C.free(unsafe.Pointer(cblob))
}
s.mu.Lock()
defer s.mu.Unlock()
rc := C.sp_session_login(
s.sp_session,
cusername,
cpassword,
crememberme,
cblob,
)
return spError(rc)
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Login",
"(",
"c",
"Credentials",
",",
"remember",
"bool",
")",
"error",
"{",
"cusername",
":=",
"C",
".",
"CString",
"(",
"c",
".",
"Username",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Point... | // Login logs the the specified username and password combo. This
// initiates the login in the background.
//
// An application MUST NEVER store the user's password in clear
// text. If automatic relogin is required, use Relogin. | [
"Login",
"logs",
"the",
"the",
"specified",
"username",
"and",
"password",
"combo",
".",
"This",
"initiates",
"the",
"login",
"in",
"the",
"background",
".",
"An",
"application",
"MUST",
"NEVER",
"store",
"the",
"user",
"s",
"password",
"in",
"clear",
"text"... | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L352-L379 |
153,493 | op/go-libspotify | spotify/libspotify.go | LoginUsername | func (s *Session) LoginUsername() string {
return C.GoString(C.sp_session_user_name(s.sp_session))
} | go | func (s *Session) LoginUsername() string {
return C.GoString(C.sp_session_user_name(s.sp_session))
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"LoginUsername",
"(",
")",
"string",
"{",
"return",
"C",
".",
"GoString",
"(",
"C",
".",
"sp_session_user_name",
"(",
"s",
".",
"sp_session",
")",
")",
"\n",
"}"
] | // LoginUsername returns the user's login username. | [
"LoginUsername",
"returns",
"the",
"user",
"s",
"login",
"username",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L401-L403 |
153,494 | op/go-libspotify | spotify/libspotify.go | CurrentUser | func (s *Session) CurrentUser() (*User, error) {
sp_user := C.sp_session_user(s.sp_session)
if sp_user == nil {
return nil, errors.New("spotify: no user logged in")
}
return newUser(s, sp_user), nil
} | go | func (s *Session) CurrentUser() (*User, error) {
sp_user := C.sp_session_user(s.sp_session)
if sp_user == nil {
return nil, errors.New("spotify: no user logged in")
}
return newUser(s, sp_user), nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"CurrentUser",
"(",
")",
"(",
"*",
"User",
",",
"error",
")",
"{",
"sp_user",
":=",
"C",
".",
"sp_session_user",
"(",
"s",
".",
"sp_session",
")",
"\n",
"if",
"sp_user",
"==",
"nil",
"{",
"return",
"nil",
",",... | // CurrentUser returns a user object for the currently logged in user. | [
"CurrentUser",
"returns",
"a",
"user",
"object",
"for",
"the",
"currently",
"logged",
"in",
"user",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L412-L418 |
153,495 | op/go-libspotify | spotify/libspotify.go | ConnectionState | func (s *Session) ConnectionState() ConnectionState {
state := C.sp_session_connectionstate(s.sp_session)
return ConnectionState(state)
} | go | func (s *Session) ConnectionState() ConnectionState {
state := C.sp_session_connectionstate(s.sp_session)
return ConnectionState(state)
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"ConnectionState",
"(",
")",
"ConnectionState",
"{",
"state",
":=",
"C",
".",
"sp_session_connectionstate",
"(",
"s",
".",
"sp_session",
")",
"\n",
"return",
"ConnectionState",
"(",
"state",
")",
"\n",
"}"
] | // ConnectionState returns the current connection state for the
// session. | [
"ConnectionState",
"returns",
"the",
"current",
"connection",
"state",
"for",
"the",
"session",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L454-L457 |
153,496 | op/go-libspotify | spotify/libspotify.go | String | func (l *Link) String() string {
// Determine how big string we need and get the string out.
size := C.sp_link_as_string(l.sp_link, nil, 0)
if C.size_t(size) == 0 {
return ""
}
buf := (*C.char)(C.malloc(C.size_t(size) + 1))
if buf == nil {
return "<invalid>"
}
defer C.free(unsafe.Pointer(buf))
C.sp_link_as_string(l.sp_link, buf, size+1)
return C.GoString(buf)
} | go | func (l *Link) String() string {
// Determine how big string we need and get the string out.
size := C.sp_link_as_string(l.sp_link, nil, 0)
if C.size_t(size) == 0 {
return ""
}
buf := (*C.char)(C.malloc(C.size_t(size) + 1))
if buf == nil {
return "<invalid>"
}
defer C.free(unsafe.Pointer(buf))
C.sp_link_as_string(l.sp_link, buf, size+1)
return C.GoString(buf)
} | [
"func",
"(",
"l",
"*",
"Link",
")",
"String",
"(",
")",
"string",
"{",
"// Determine how big string we need and get the string out.",
"size",
":=",
"C",
".",
"sp_link_as_string",
"(",
"l",
".",
"sp_link",
",",
"nil",
",",
"0",
")",
"\n",
"if",
"C",
".",
"s... | // String implements the Stringer interface and returns the Link URI. | [
"String",
"implements",
"the",
"Stringer",
"interface",
"and",
"returns",
"the",
"Link",
"URI",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L1534-L1547 |
153,497 | op/go-libspotify | spotify/libspotify.go | TrackOffset | func (l *Link) TrackOffset() time.Duration {
var offsetMs C.int
C.sp_link_as_track_and_offset(l.sp_link, &offsetMs)
return time.Duration(offsetMs) / time.Millisecond
} | go | func (l *Link) TrackOffset() time.Duration {
var offsetMs C.int
C.sp_link_as_track_and_offset(l.sp_link, &offsetMs)
return time.Duration(offsetMs) / time.Millisecond
} | [
"func",
"(",
"l",
"*",
"Link",
")",
"TrackOffset",
"(",
")",
"time",
".",
"Duration",
"{",
"var",
"offsetMs",
"C",
".",
"int",
"\n",
"C",
".",
"sp_link_as_track_and_offset",
"(",
"l",
".",
"sp_link",
",",
"&",
"offsetMs",
")",
"\n",
"return",
"time",
... | // TrackOffset returns the offset for the track link. | [
"TrackOffset",
"returns",
"the",
"offset",
"for",
"the",
"track",
"link",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L1562-L1566 |
153,498 | op/go-libspotify | spotify/libspotify.go | Availability | func (t *Track) Availability() TrackAvailability {
avail := C.sp_track_get_availability(
t.session.sp_session,
t.sp_track,
)
return TrackAvailability(avail)
} | go | func (t *Track) Availability() TrackAvailability {
avail := C.sp_track_get_availability(
t.session.sp_session,
t.sp_track,
)
return TrackAvailability(avail)
} | [
"func",
"(",
"t",
"*",
"Track",
")",
"Availability",
"(",
")",
"TrackAvailability",
"{",
"avail",
":=",
"C",
".",
"sp_track_get_availability",
"(",
"t",
".",
"session",
".",
"sp_session",
",",
"t",
".",
"sp_track",
",",
")",
"\n",
"return",
"TrackAvailabil... | // Availability returns the track availability. | [
"Availability",
"returns",
"the",
"track",
"availability",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L1819-L1825 |
153,499 | op/go-libspotify | spotify/libspotify.go | IsLocal | func (t *Track) IsLocal() bool {
local := C.sp_track_is_local(
t.session.sp_session,
t.sp_track,
)
return local == 1
} | go | func (t *Track) IsLocal() bool {
local := C.sp_track_is_local(
t.session.sp_session,
t.sp_track,
)
return local == 1
} | [
"func",
"(",
"t",
"*",
"Track",
")",
"IsLocal",
"(",
")",
"bool",
"{",
"local",
":=",
"C",
".",
"sp_track_is_local",
"(",
"t",
".",
"session",
".",
"sp_session",
",",
"t",
".",
"sp_track",
",",
")",
"\n",
"return",
"local",
"==",
"1",
"\n",
"}"
] | // IsLocal returns true if the track is a local file. | [
"IsLocal",
"returns",
"true",
"if",
"the",
"track",
"is",
"a",
"local",
"file",
"."
] | 12dd11fb33ecf760c356b65dc1116bc92589dea4 | https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/spotify/libspotify.go#L1828-L1834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.