id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
11,800
xxtea/xxtea-go
xxtea/xxtea.go
encryptBase64ToUrlFormat
func encryptBase64ToUrlFormat(str string) string { str = strings.Replace(str, "+", "-", -1) str = strings.Replace(str, "/", "_", -1) str = strings.Replace(str, "=", "~", -1) return str }
go
func encryptBase64ToUrlFormat(str string) string { str = strings.Replace(str, "+", "-", -1) str = strings.Replace(str, "/", "_", -1) str = strings.Replace(str, "=", "~", -1) return str }
[ "func", "encryptBase64ToUrlFormat", "(", "str", "string", ")", "string", "{", "str", "=", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "str", "=", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "str", "=", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "return", "str", "\n", "}" ]
// Replace std character to URL character in base64 string
[ "Replace", "std", "character", "to", "URL", "character", "in", "base64", "string" ]
35c4b17eecf6c3c2350f8cecaf1b3f9f7fafc242
https://github.com/xxtea/xxtea-go/blob/35c4b17eecf6c3c2350f8cecaf1b3f9f7fafc242/xxtea/xxtea.go#L172-L177
11,801
xxtea/xxtea-go
xxtea/xxtea.go
decryptBase64ToStdFormat
func decryptBase64ToStdFormat(str string) string { str = strings.Replace(str, "-", "+", -1) str = strings.Replace(str, "_", "/", -1) str = strings.Replace(str, "~", "=", -1) return str }
go
func decryptBase64ToStdFormat(str string) string { str = strings.Replace(str, "-", "+", -1) str = strings.Replace(str, "_", "/", -1) str = strings.Replace(str, "~", "=", -1) return str }
[ "func", "decryptBase64ToStdFormat", "(", "str", "string", ")", "string", "{", "str", "=", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "str", "=", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "str", "=", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "return", "str", "\n", "}" ]
// Replace URL character to origin character in base64 string
[ "Replace", "URL", "character", "to", "origin", "character", "in", "base64", "string" ]
35c4b17eecf6c3c2350f8cecaf1b3f9f7fafc242
https://github.com/xxtea/xxtea-go/blob/35c4b17eecf6c3c2350f8cecaf1b3f9f7fafc242/xxtea/xxtea.go#L180-L185
11,802
dustin/gomemcached
mc_constants.go
IsQuiet
func (o CommandCode) IsQuiet() bool { switch o { case GETQ, GETKQ, SETQ, ADDQ, REPLACEQ, DELETEQ, INCREMENTQ, DECREMENTQ, QUITQ, FLUSHQ, APPENDQ, PREPENDQ, RSETQ, RAPPENDQ, RPREPENDQ, RDELETEQ, RINCRQ, RDECRQ: return true } return false }
go
func (o CommandCode) IsQuiet() bool { switch o { case GETQ, GETKQ, SETQ, ADDQ, REPLACEQ, DELETEQ, INCREMENTQ, DECREMENTQ, QUITQ, FLUSHQ, APPENDQ, PREPENDQ, RSETQ, RAPPENDQ, RPREPENDQ, RDELETEQ, RINCRQ, RDECRQ: return true } return false }
[ "func", "(", "o", "CommandCode", ")", "IsQuiet", "(", ")", "bool", "{", "switch", "o", "{", "case", "GETQ", ",", "GETKQ", ",", "SETQ", ",", "ADDQ", ",", "REPLACEQ", ",", "DELETEQ", ",", "INCREMENTQ", ",", "DECREMENTQ", ",", "QUITQ", ",", "FLUSHQ", ",", "APPENDQ", ",", "PREPENDQ", ",", "RSETQ", ",", "RAPPENDQ", ",", "RPREPENDQ", ",", "RDELETEQ", ",", "RINCRQ", ",", "RDECRQ", ":", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Return true if a command is a "quiet" command.
[ "Return", "true", "if", "a", "command", "is", "a", "quiet", "command", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_constants.go#L194-L217
11,803
dustin/gomemcached
mc_res.go
String
func (res MCResponse) String() string { return fmt.Sprintf("{MCResponse status=%v keylen=%d, extralen=%d, bodylen=%d}", res.Status, len(res.Key), len(res.Extras), len(res.Body)) }
go
func (res MCResponse) String() string { return fmt.Sprintf("{MCResponse status=%v keylen=%d, extralen=%d, bodylen=%d}", res.Status, len(res.Key), len(res.Extras), len(res.Body)) }
[ "func", "(", "res", "MCResponse", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "res", ".", "Status", ",", "len", "(", "res", ".", "Key", ")", ",", "len", "(", "res", ".", "Extras", ")", ",", "len", "(", "res", ".", "Body", ")", ")", "\n", "}" ]
// A debugging string representation of this response
[ "A", "debugging", "string", "representation", "of", "this", "response" ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_res.go#L26-L29
11,804
dustin/gomemcached
mc_res.go
Error
func (res *MCResponse) Error() string { return fmt.Sprintf("MCResponse status=%v, opcode=%v, opaque=%v, msg: %s", res.Status, res.Opcode, res.Opaque, string(res.Body)) }
go
func (res *MCResponse) Error() string { return fmt.Sprintf("MCResponse status=%v, opcode=%v, opaque=%v, msg: %s", res.Status, res.Opcode, res.Opaque, string(res.Body)) }
[ "func", "(", "res", "*", "MCResponse", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "res", ".", "Status", ",", "res", ".", "Opcode", ",", "res", ".", "Opaque", ",", "string", "(", "res", ".", "Body", ")", ")", "\n", "}" ]
// Response as an error.
[ "Response", "as", "an", "error", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_res.go#L32-L35
11,805
dustin/gomemcached
mc_res.go
IsFatal
func IsFatal(e error) bool { if e == nil { return false } switch errStatus(e) { case KEY_ENOENT, KEY_EEXISTS, NOT_STORED, TMPFAIL: return false } return true }
go
func IsFatal(e error) bool { if e == nil { return false } switch errStatus(e) { case KEY_ENOENT, KEY_EEXISTS, NOT_STORED, TMPFAIL: return false } return true }
[ "func", "IsFatal", "(", "e", "error", ")", "bool", "{", "if", "e", "==", "nil", "{", "return", "false", "\n", "}", "\n", "switch", "errStatus", "(", "e", ")", "{", "case", "KEY_ENOENT", ",", "KEY_EEXISTS", ",", "NOT_STORED", ",", "TMPFAIL", ":", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// False if this error isn't believed to be fatal to a connection.
[ "False", "if", "this", "error", "isn", "t", "believed", "to", "be", "fatal", "to", "a", "connection", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_res.go#L51-L60
11,806
dustin/gomemcached
mc_res.go
Size
func (res *MCResponse) Size() int { return HDR_LEN + len(res.Extras) + len(res.Key) + len(res.Body) }
go
func (res *MCResponse) Size() int { return HDR_LEN + len(res.Extras) + len(res.Key) + len(res.Body) }
[ "func", "(", "res", "*", "MCResponse", ")", "Size", "(", ")", "int", "{", "return", "HDR_LEN", "+", "len", "(", "res", ".", "Extras", ")", "+", "len", "(", "res", ".", "Key", ")", "+", "len", "(", "res", ".", "Body", ")", "\n", "}" ]
// Number of bytes this response consumes on the wire.
[ "Number", "of", "bytes", "this", "response", "consumes", "on", "the", "wire", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_res.go#L63-L65
11,807
dustin/gomemcached
mc_res.go
HeaderBytes
func (res *MCResponse) HeaderBytes() []byte { data := make([]byte, HDR_LEN+len(res.Extras)+len(res.Key)) res.fillHeaderBytes(data) return data }
go
func (res *MCResponse) HeaderBytes() []byte { data := make([]byte, HDR_LEN+len(res.Extras)+len(res.Key)) res.fillHeaderBytes(data) return data }
[ "func", "(", "res", "*", "MCResponse", ")", "HeaderBytes", "(", ")", "[", "]", "byte", "{", "data", ":=", "make", "(", "[", "]", "byte", ",", "HDR_LEN", "+", "len", "(", "res", ".", "Extras", ")", "+", "len", "(", "res", ".", "Key", ")", ")", "\n\n", "res", ".", "fillHeaderBytes", "(", "data", ")", "\n\n", "return", "data", "\n", "}" ]
// Get just the header bytes for this response.
[ "Get", "just", "the", "header", "bytes", "for", "this", "response", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_res.go#L112-L118
11,808
dustin/gomemcached
mc_res.go
Bytes
func (res *MCResponse) Bytes() []byte { data := make([]byte, res.Size()) pos := res.fillHeaderBytes(data) copy(data[pos:pos+len(res.Body)], res.Body) return data }
go
func (res *MCResponse) Bytes() []byte { data := make([]byte, res.Size()) pos := res.fillHeaderBytes(data) copy(data[pos:pos+len(res.Body)], res.Body) return data }
[ "func", "(", "res", "*", "MCResponse", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "data", ":=", "make", "(", "[", "]", "byte", ",", "res", ".", "Size", "(", ")", ")", "\n\n", "pos", ":=", "res", ".", "fillHeaderBytes", "(", "data", ")", "\n\n", "copy", "(", "data", "[", "pos", ":", "pos", "+", "len", "(", "res", ".", "Body", ")", "]", ",", "res", ".", "Body", ")", "\n\n", "return", "data", "\n", "}" ]
// The actual bytes transmitted for this response.
[ "The", "actual", "bytes", "transmitted", "for", "this", "response", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_res.go#L121-L129
11,809
dustin/gomemcached
mc_res.go
Transmit
func (res *MCResponse) Transmit(w io.Writer) (n int, err error) { if len(res.Body) < 128 { n, err = w.Write(res.Bytes()) } else { n, err = w.Write(res.HeaderBytes()) if err == nil { m := 0 m, err = w.Write(res.Body) m += n } } return }
go
func (res *MCResponse) Transmit(w io.Writer) (n int, err error) { if len(res.Body) < 128 { n, err = w.Write(res.Bytes()) } else { n, err = w.Write(res.HeaderBytes()) if err == nil { m := 0 m, err = w.Write(res.Body) m += n } } return }
[ "func", "(", "res", "*", "MCResponse", ")", "Transmit", "(", "w", "io", ".", "Writer", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "len", "(", "res", ".", "Body", ")", "<", "128", "{", "n", ",", "err", "=", "w", ".", "Write", "(", "res", ".", "Bytes", "(", ")", ")", "\n", "}", "else", "{", "n", ",", "err", "=", "w", ".", "Write", "(", "res", ".", "HeaderBytes", "(", ")", ")", "\n", "if", "err", "==", "nil", "{", "m", ":=", "0", "\n", "m", ",", "err", "=", "w", ".", "Write", "(", "res", ".", "Body", ")", "\n", "m", "+=", "n", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Send this response message across a writer.
[ "Send", "this", "response", "message", "across", "a", "writer", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_res.go#L132-L144
11,810
dustin/gomemcached
client/mc.go
Connect
func Connect(prot, dest string) (rv *Client, err error) { conn, err := dialFun(prot, dest) if err != nil { return nil, err } return Wrap(conn) }
go
func Connect(prot, dest string) (rv *Client, err error) { conn, err := dialFun(prot, dest) if err != nil { return nil, err } return Wrap(conn) }
[ "func", "Connect", "(", "prot", ",", "dest", "string", ")", "(", "rv", "*", "Client", ",", "err", "error", ")", "{", "conn", ",", "err", ":=", "dialFun", "(", "prot", ",", "dest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "Wrap", "(", "conn", ")", "\n", "}" ]
// Connect to a memcached server.
[ "Connect", "to", "a", "memcached", "server", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L30-L36
11,811
dustin/gomemcached
client/mc.go
Wrap
func Wrap(rwc io.ReadWriteCloser) (rv *Client, err error) { return &Client{ conn: rwc, healthy: true, hdrBuf: make([]byte, gomemcached.HDR_LEN), }, nil }
go
func Wrap(rwc io.ReadWriteCloser) (rv *Client, err error) { return &Client{ conn: rwc, healthy: true, hdrBuf: make([]byte, gomemcached.HDR_LEN), }, nil }
[ "func", "Wrap", "(", "rwc", "io", ".", "ReadWriteCloser", ")", "(", "rv", "*", "Client", ",", "err", "error", ")", "{", "return", "&", "Client", "{", "conn", ":", "rwc", ",", "healthy", ":", "true", ",", "hdrBuf", ":", "make", "(", "[", "]", "byte", ",", "gomemcached", ".", "HDR_LEN", ")", ",", "}", ",", "nil", "\n", "}" ]
// Wrap an existing transport.
[ "Wrap", "an", "existing", "transport", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L39-L45
11,812
dustin/gomemcached
client/mc.go
Send
func (c *Client) Send(req *gomemcached.MCRequest) (rv *gomemcached.MCResponse, err error) { _, err = transmitRequest(c.conn, req) if err != nil { c.healthy = false return } resp, _, err := getResponse(c.conn, c.hdrBuf) c.healthy = !gomemcached.IsFatal(err) return resp, err }
go
func (c *Client) Send(req *gomemcached.MCRequest) (rv *gomemcached.MCResponse, err error) { _, err = transmitRequest(c.conn, req) if err != nil { c.healthy = false return } resp, _, err := getResponse(c.conn, c.hdrBuf) c.healthy = !gomemcached.IsFatal(err) return resp, err }
[ "func", "(", "c", "*", "Client", ")", "Send", "(", "req", "*", "gomemcached", ".", "MCRequest", ")", "(", "rv", "*", "gomemcached", ".", "MCResponse", ",", "err", "error", ")", "{", "_", ",", "err", "=", "transmitRequest", "(", "c", ".", "conn", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "healthy", "=", "false", "\n", "return", "\n", "}", "\n", "resp", ",", "_", ",", "err", ":=", "getResponse", "(", "c", ".", "conn", ",", "c", ".", "hdrBuf", ")", "\n", "c", ".", "healthy", "=", "!", "gomemcached", ".", "IsFatal", "(", "err", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Send a custom request and get the response.
[ "Send", "a", "custom", "request", "and", "get", "the", "response", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L62-L71
11,813
dustin/gomemcached
client/mc.go
Transmit
func (c *Client) Transmit(req *gomemcached.MCRequest) error { _, err := transmitRequest(c.conn, req) if err != nil { c.healthy = false } return err }
go
func (c *Client) Transmit(req *gomemcached.MCRequest) error { _, err := transmitRequest(c.conn, req) if err != nil { c.healthy = false } return err }
[ "func", "(", "c", "*", "Client", ")", "Transmit", "(", "req", "*", "gomemcached", ".", "MCRequest", ")", "error", "{", "_", ",", "err", ":=", "transmitRequest", "(", "c", ".", "conn", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "healthy", "=", "false", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Transmit send a request, but does not wait for a response.
[ "Transmit", "send", "a", "request", "but", "does", "not", "wait", "for", "a", "response", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L74-L80
11,814
dustin/gomemcached
client/mc.go
Receive
func (c *Client) Receive() (*gomemcached.MCResponse, error) { resp, _, err := getResponse(c.conn, c.hdrBuf) if err != nil { c.healthy = false } return resp, err }
go
func (c *Client) Receive() (*gomemcached.MCResponse, error) { resp, _, err := getResponse(c.conn, c.hdrBuf) if err != nil { c.healthy = false } return resp, err }
[ "func", "(", "c", "*", "Client", ")", "Receive", "(", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "resp", ",", "_", ",", "err", ":=", "getResponse", "(", "c", ".", "conn", ",", "c", ".", "hdrBuf", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "healthy", "=", "false", "\n", "}", "\n", "return", "resp", ",", "err", "\n", "}" ]
// Receive a response
[ "Receive", "a", "response" ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L83-L89
11,815
dustin/gomemcached
client/mc.go
Get
func (c *Client) Get(vb uint16, key string) (*gomemcached.MCResponse, error) { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.GET, VBucket: vb, Key: []byte(key), }) }
go
func (c *Client) Get(vb uint16, key string) (*gomemcached.MCResponse, error) { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.GET, VBucket: vb, Key: []byte(key), }) }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "vb", "uint16", ",", "key", "string", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "return", "c", ".", "Send", "(", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "GET", ",", "VBucket", ":", "vb", ",", "Key", ":", "[", "]", "byte", "(", "key", ")", ",", "}", ")", "\n", "}" ]
// Get the value for a key.
[ "Get", "the", "value", "for", "a", "key", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L92-L98
11,816
dustin/gomemcached
client/mc.go
Del
func (c *Client) Del(vb uint16, key string) (*gomemcached.MCResponse, error) { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.DELETE, VBucket: vb, Key: []byte(key)}) }
go
func (c *Client) Del(vb uint16, key string) (*gomemcached.MCResponse, error) { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.DELETE, VBucket: vb, Key: []byte(key)}) }
[ "func", "(", "c", "*", "Client", ")", "Del", "(", "vb", "uint16", ",", "key", "string", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "return", "c", ".", "Send", "(", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "DELETE", ",", "VBucket", ":", "vb", ",", "Key", ":", "[", "]", "byte", "(", "key", ")", "}", ")", "\n", "}" ]
// Del deletes a key.
[ "Del", "deletes", "a", "key", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L101-L106
11,817
dustin/gomemcached
client/mc.go
AuthList
func (c *Client) AuthList() (*gomemcached.MCResponse, error) { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.SASL_LIST_MECHS}) }
go
func (c *Client) AuthList() (*gomemcached.MCResponse, error) { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.SASL_LIST_MECHS}) }
[ "func", "(", "c", "*", "Client", ")", "AuthList", "(", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "return", "c", ".", "Send", "(", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "SASL_LIST_MECHS", "}", ")", "\n", "}" ]
// AuthList lists SASL auth mechanisms.
[ "AuthList", "lists", "SASL", "auth", "mechanisms", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L109-L112
11,818
dustin/gomemcached
client/mc.go
Auth
func (c *Client) Auth(user, pass string) (*gomemcached.MCResponse, error) { res, err := c.AuthList() if err != nil { return res, err } authMech := string(res.Body) if strings.Index(authMech, "PLAIN") != -1 { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.SASL_AUTH, Key: []byte("PLAIN"), Body: []byte(fmt.Sprintf("\x00%s\x00%s", user, pass))}) } return res, fmt.Errorf("auth mechanism PLAIN not supported") }
go
func (c *Client) Auth(user, pass string) (*gomemcached.MCResponse, error) { res, err := c.AuthList() if err != nil { return res, err } authMech := string(res.Body) if strings.Index(authMech, "PLAIN") != -1 { return c.Send(&gomemcached.MCRequest{ Opcode: gomemcached.SASL_AUTH, Key: []byte("PLAIN"), Body: []byte(fmt.Sprintf("\x00%s\x00%s", user, pass))}) } return res, fmt.Errorf("auth mechanism PLAIN not supported") }
[ "func", "(", "c", "*", "Client", ")", "Auth", "(", "user", ",", "pass", "string", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "res", ",", "err", ":=", "c", ".", "AuthList", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "authMech", ":=", "string", "(", "res", ".", "Body", ")", "\n", "if", "strings", ".", "Index", "(", "authMech", ",", "\"", "\"", ")", "!=", "-", "1", "{", "return", "c", ".", "Send", "(", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "SASL_AUTH", ",", "Key", ":", "[", "]", "byte", "(", "\"", "\"", ")", ",", "Body", ":", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\\x00", "\\x00", "\"", ",", "user", ",", "pass", ")", ")", "}", ")", "\n", "}", "\n", "return", "res", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// Auth performs SASL PLAIN authentication against the server.
[ "Auth", "performs", "SASL", "PLAIN", "authentication", "against", "the", "server", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L115-L130
11,819
dustin/gomemcached
client/mc.go
Incr
func (c *Client) Incr(vb uint16, key string, amt, def uint64, exp int) (uint64, error) { req := &gomemcached.MCRequest{ Opcode: gomemcached.INCREMENT, VBucket: vb, Key: []byte(key), Extras: make([]byte, 8+8+4), } binary.BigEndian.PutUint64(req.Extras[:8], amt) binary.BigEndian.PutUint64(req.Extras[8:16], def) binary.BigEndian.PutUint32(req.Extras[16:20], uint32(exp)) resp, err := c.Send(req) if err != nil { return 0, err } return binary.BigEndian.Uint64(resp.Body), nil }
go
func (c *Client) Incr(vb uint16, key string, amt, def uint64, exp int) (uint64, error) { req := &gomemcached.MCRequest{ Opcode: gomemcached.INCREMENT, VBucket: vb, Key: []byte(key), Extras: make([]byte, 8+8+4), } binary.BigEndian.PutUint64(req.Extras[:8], amt) binary.BigEndian.PutUint64(req.Extras[8:16], def) binary.BigEndian.PutUint32(req.Extras[16:20], uint32(exp)) resp, err := c.Send(req) if err != nil { return 0, err } return binary.BigEndian.Uint64(resp.Body), nil }
[ "func", "(", "c", "*", "Client", ")", "Incr", "(", "vb", "uint16", ",", "key", "string", ",", "amt", ",", "def", "uint64", ",", "exp", "int", ")", "(", "uint64", ",", "error", ")", "{", "req", ":=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "INCREMENT", ",", "VBucket", ":", "vb", ",", "Key", ":", "[", "]", "byte", "(", "key", ")", ",", "Extras", ":", "make", "(", "[", "]", "byte", ",", "8", "+", "8", "+", "4", ")", ",", "}", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "req", ".", "Extras", "[", ":", "8", "]", ",", "amt", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "req", ".", "Extras", "[", "8", ":", "16", "]", ",", "def", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "req", ".", "Extras", "[", "16", ":", "20", "]", ",", "uint32", "(", "exp", ")", ")", "\n\n", "resp", ",", "err", ":=", "c", ".", "Send", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "binary", ".", "BigEndian", ".", "Uint64", "(", "resp", ".", "Body", ")", ",", "nil", "\n", "}" ]
// Incr increments the value at the given key.
[ "Incr", "increments", "the", "value", "at", "the", "given", "key", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L149-L168
11,820
dustin/gomemcached
client/mc.go
Set
func (c *Client) Set(vb uint16, key string, flags int, exp int, body []byte) (*gomemcached.MCResponse, error) { return c.store(gomemcached.SET, vb, key, flags, exp, body) }
go
func (c *Client) Set(vb uint16, key string, flags int, exp int, body []byte) (*gomemcached.MCResponse, error) { return c.store(gomemcached.SET, vb, key, flags, exp, body) }
[ "func", "(", "c", "*", "Client", ")", "Set", "(", "vb", "uint16", ",", "key", "string", ",", "flags", "int", ",", "exp", "int", ",", "body", "[", "]", "byte", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "return", "c", ".", "store", "(", "gomemcached", ".", "SET", ",", "vb", ",", "key", ",", "flags", ",", "exp", ",", "body", ")", "\n", "}" ]
// Set the value for a key.
[ "Set", "the", "value", "for", "a", "key", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L177-L180
11,821
dustin/gomemcached
client/mc.go
Append
func (c *Client) Append(vb uint16, key string, data []byte) (*gomemcached.MCResponse, error) { req := &gomemcached.MCRequest{ Opcode: gomemcached.APPEND, VBucket: vb, Key: []byte(key), Cas: 0, Opaque: 0, Body: data} return c.Send(req) }
go
func (c *Client) Append(vb uint16, key string, data []byte) (*gomemcached.MCResponse, error) { req := &gomemcached.MCRequest{ Opcode: gomemcached.APPEND, VBucket: vb, Key: []byte(key), Cas: 0, Opaque: 0, Body: data} return c.Send(req) }
[ "func", "(", "c", "*", "Client", ")", "Append", "(", "vb", "uint16", ",", "key", "string", ",", "data", "[", "]", "byte", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "req", ":=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "APPEND", ",", "VBucket", ":", "vb", ",", "Key", ":", "[", "]", "byte", "(", "key", ")", ",", "Cas", ":", "0", ",", "Opaque", ":", "0", ",", "Body", ":", "data", "}", "\n\n", "return", "c", ".", "Send", "(", "req", ")", "\n", "}" ]
// Append data to the value of a key.
[ "Append", "data", "to", "the", "value", "of", "a", "key", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L183-L193
11,822
dustin/gomemcached
client/mc.go
GetBulk
func (c *Client) GetBulk(vb uint16, keys []string) (map[string]*gomemcached.MCResponse, error) { rv := map[string]*gomemcached.MCResponse{} going := true defer func() { going = false }() errch := make(chan error, 2) go func() { defer func() { errch <- nil }() for going { res, err := c.Receive() if err != nil { errch <- err return } switch res.Opcode { case gomemcached.GET: going = false case gomemcached.GETQ: default: log.Panicf("Unexpected opcode in GETQ response: %+v", res) } rv[keys[res.Opaque]] = res } }() for i, k := range keys { op := gomemcached.GETQ if i == len(keys)-1 { op = gomemcached.GET } err := c.Transmit(&gomemcached.MCRequest{ Opcode: op, VBucket: vb, Key: []byte(k), Opaque: uint32(i), }) if err != nil { return rv, err } } return rv, <-errch }
go
func (c *Client) GetBulk(vb uint16, keys []string) (map[string]*gomemcached.MCResponse, error) { rv := map[string]*gomemcached.MCResponse{} going := true defer func() { going = false }() errch := make(chan error, 2) go func() { defer func() { errch <- nil }() for going { res, err := c.Receive() if err != nil { errch <- err return } switch res.Opcode { case gomemcached.GET: going = false case gomemcached.GETQ: default: log.Panicf("Unexpected opcode in GETQ response: %+v", res) } rv[keys[res.Opaque]] = res } }() for i, k := range keys { op := gomemcached.GETQ if i == len(keys)-1 { op = gomemcached.GET } err := c.Transmit(&gomemcached.MCRequest{ Opcode: op, VBucket: vb, Key: []byte(k), Opaque: uint32(i), }) if err != nil { return rv, err } } return rv, <-errch }
[ "func", "(", "c", "*", "Client", ")", "GetBulk", "(", "vb", "uint16", ",", "keys", "[", "]", "string", ")", "(", "map", "[", "string", "]", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "rv", ":=", "map", "[", "string", "]", "*", "gomemcached", ".", "MCResponse", "{", "}", "\n", "going", ":=", "true", "\n\n", "defer", "func", "(", ")", "{", "going", "=", "false", "\n", "}", "(", ")", "\n\n", "errch", ":=", "make", "(", "chan", "error", ",", "2", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "errch", "<-", "nil", "}", "(", ")", "\n", "for", "going", "{", "res", ",", "err", ":=", "c", ".", "Receive", "(", ")", "\n", "if", "err", "!=", "nil", "{", "errch", "<-", "err", "\n", "return", "\n", "}", "\n", "switch", "res", ".", "Opcode", "{", "case", "gomemcached", ".", "GET", ":", "going", "=", "false", "\n", "case", "gomemcached", ".", "GETQ", ":", "default", ":", "log", ".", "Panicf", "(", "\"", "\"", ",", "res", ")", "\n", "}", "\n", "rv", "[", "keys", "[", "res", ".", "Opaque", "]", "]", "=", "res", "\n", "}", "\n", "}", "(", ")", "\n\n", "for", "i", ",", "k", ":=", "range", "keys", "{", "op", ":=", "gomemcached", ".", "GETQ", "\n", "if", "i", "==", "len", "(", "keys", ")", "-", "1", "{", "op", "=", "gomemcached", ".", "GET", "\n", "}", "\n", "err", ":=", "c", ".", "Transmit", "(", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "op", ",", "VBucket", ":", "vb", ",", "Key", ":", "[", "]", "byte", "(", "k", ")", ",", "Opaque", ":", "uint32", "(", "i", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "rv", ",", "<-", "errch", "\n", "}" ]
// GetBulk gets keys in bulk
[ "GetBulk", "gets", "keys", "in", "bulk" ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L196-L243
11,823
dustin/gomemcached
client/mc.go
CheckPersistence
func (result ObserveResult) CheckPersistence(cas uint64, deletion bool) (persisted bool, overwritten bool) { switch { case result.Status == ObservedNotFound && deletion: persisted = true case result.Cas != cas: overwritten = true case result.Status == ObservedPersisted: persisted = true } return }
go
func (result ObserveResult) CheckPersistence(cas uint64, deletion bool) (persisted bool, overwritten bool) { switch { case result.Status == ObservedNotFound && deletion: persisted = true case result.Cas != cas: overwritten = true case result.Status == ObservedPersisted: persisted = true } return }
[ "func", "(", "result", "ObserveResult", ")", "CheckPersistence", "(", "cas", "uint64", ",", "deletion", "bool", ")", "(", "persisted", "bool", ",", "overwritten", "bool", ")", "{", "switch", "{", "case", "result", ".", "Status", "==", "ObservedNotFound", "&&", "deletion", ":", "persisted", "=", "true", "\n", "case", "result", ".", "Cas", "!=", "cas", ":", "overwritten", "=", "true", "\n", "case", "result", ".", "Status", "==", "ObservedPersisted", ":", "persisted", "=", "true", "\n", "}", "\n", "return", "\n", "}" ]
// CheckPersistence checks whether a stored value has been persisted to disk yet.
[ "CheckPersistence", "checks", "whether", "a", "stored", "value", "has", "been", "persisted", "to", "disk", "yet", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L306-L316
11,824
dustin/gomemcached
client/mc.go
CAS
func (c *Client) CAS(vb uint16, k string, f CasFunc, initexp int) (*gomemcached.MCResponse, error) { var state CASState for c.CASNext(vb, k, initexp, &state) { newValue, operation := f(state.Value) if operation == CASQuit || (operation == CASDelete && state.Value == nil) { return nil, operation } state.Value = newValue } return state.resp, state.Err }
go
func (c *Client) CAS(vb uint16, k string, f CasFunc, initexp int) (*gomemcached.MCResponse, error) { var state CASState for c.CASNext(vb, k, initexp, &state) { newValue, operation := f(state.Value) if operation == CASQuit || (operation == CASDelete && state.Value == nil) { return nil, operation } state.Value = newValue } return state.resp, state.Err }
[ "func", "(", "c", "*", "Client", ")", "CAS", "(", "vb", "uint16", ",", "k", "string", ",", "f", "CasFunc", ",", "initexp", "int", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "var", "state", "CASState", "\n", "for", "c", ".", "CASNext", "(", "vb", ",", "k", ",", "initexp", ",", "&", "state", ")", "{", "newValue", ",", "operation", ":=", "f", "(", "state", ".", "Value", ")", "\n", "if", "operation", "==", "CASQuit", "||", "(", "operation", "==", "CASDelete", "&&", "state", ".", "Value", "==", "nil", ")", "{", "return", "nil", ",", "operation", "\n", "}", "\n", "state", ".", "Value", "=", "newValue", "\n", "}", "\n", "return", "state", ".", "resp", ",", "state", ".", "Err", "\n", "}" ]
// CAS performs a CAS transform with the given function. // // If the value does not exist, a nil current value will be sent to f.
[ "CAS", "performs", "a", "CAS", "transform", "with", "the", "given", "function", ".", "If", "the", "value", "does", "not", "exist", "a", "nil", "current", "value", "will", "be", "sent", "to", "f", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L430-L441
11,825
dustin/gomemcached
client/mc.go
Stats
func (c *Client) Stats(key string) ([]StatValue, error) { rv := make([]StatValue, 0, 128) req := &gomemcached.MCRequest{ Opcode: gomemcached.STAT, Key: []byte(key), Opaque: 918494, } _, err := transmitRequest(c.conn, req) if err != nil { return rv, err } for { res, _, err := getResponse(c.conn, c.hdrBuf) if err != nil { return rv, err } k := string(res.Key) if k == "" { break } rv = append(rv, StatValue{ Key: k, Val: string(res.Body), }) } return rv, nil }
go
func (c *Client) Stats(key string) ([]StatValue, error) { rv := make([]StatValue, 0, 128) req := &gomemcached.MCRequest{ Opcode: gomemcached.STAT, Key: []byte(key), Opaque: 918494, } _, err := transmitRequest(c.conn, req) if err != nil { return rv, err } for { res, _, err := getResponse(c.conn, c.hdrBuf) if err != nil { return rv, err } k := string(res.Key) if k == "" { break } rv = append(rv, StatValue{ Key: k, Val: string(res.Body), }) } return rv, nil }
[ "func", "(", "c", "*", "Client", ")", "Stats", "(", "key", "string", ")", "(", "[", "]", "StatValue", ",", "error", ")", "{", "rv", ":=", "make", "(", "[", "]", "StatValue", ",", "0", ",", "128", ")", "\n\n", "req", ":=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "STAT", ",", "Key", ":", "[", "]", "byte", "(", "key", ")", ",", "Opaque", ":", "918494", ",", "}", "\n\n", "_", ",", "err", ":=", "transmitRequest", "(", "c", ".", "conn", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n\n", "for", "{", "res", ",", "_", ",", "err", ":=", "getResponse", "(", "c", ".", "conn", ",", "c", ".", "hdrBuf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "k", ":=", "string", "(", "res", ".", "Key", ")", "\n", "if", "k", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "rv", "=", "append", "(", "rv", ",", "StatValue", "{", "Key", ":", "k", ",", "Val", ":", "string", "(", "res", ".", "Body", ")", ",", "}", ")", "\n", "}", "\n\n", "return", "rv", ",", "nil", "\n", "}" ]
// Stats requests server-side stats. // // Use "" as the stat key for toplevel stats.
[ "Stats", "requests", "server", "-", "side", "stats", ".", "Use", "as", "the", "stat", "key", "for", "toplevel", "stats", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L454-L484
11,826
dustin/gomemcached
client/mc.go
StatsMap
func (c *Client) StatsMap(key string) (map[string]string, error) { rv := make(map[string]string) st, err := c.Stats(key) if err != nil { return rv, err } for _, sv := range st { rv[sv.Key] = sv.Val } return rv, nil }
go
func (c *Client) StatsMap(key string) (map[string]string, error) { rv := make(map[string]string) st, err := c.Stats(key) if err != nil { return rv, err } for _, sv := range st { rv[sv.Key] = sv.Val } return rv, nil }
[ "func", "(", "c", "*", "Client", ")", "StatsMap", "(", "key", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "rv", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "st", ",", "err", ":=", "c", ".", "Stats", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "for", "_", ",", "sv", ":=", "range", "st", "{", "rv", "[", "sv", ".", "Key", "]", "=", "sv", ".", "Val", "\n", "}", "\n", "return", "rv", ",", "nil", "\n", "}" ]
// StatsMap requests server-side stats similarly to Stats, but returns // them as a map. // // Use "" as the stat key for toplevel stats.
[ "StatsMap", "requests", "server", "-", "side", "stats", "similarly", "to", "Stats", "but", "returns", "them", "as", "a", "map", ".", "Use", "as", "the", "stat", "key", "for", "toplevel", "stats", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L490-L500
11,827
dustin/gomemcached
client/mc.go
Hijack
func (c *Client) Hijack() io.ReadWriteCloser { c.healthy = false return c.conn }
go
func (c *Client) Hijack() io.ReadWriteCloser { c.healthy = false return c.conn }
[ "func", "(", "c", "*", "Client", ")", "Hijack", "(", ")", "io", ".", "ReadWriteCloser", "{", "c", ".", "healthy", "=", "false", "\n", "return", "c", ".", "conn", "\n", "}" ]
// Hijack exposes the underlying connection from this client. // // It also marks the connection as unhealthy since the client will // have lost control over the connection and can't otherwise verify // things are in good shape for connection pools.
[ "Hijack", "exposes", "the", "underlying", "connection", "from", "this", "client", ".", "It", "also", "marks", "the", "connection", "as", "unhealthy", "since", "the", "client", "will", "have", "lost", "control", "over", "the", "connection", "and", "can", "t", "otherwise", "verify", "things", "are", "in", "good", "shape", "for", "connection", "pools", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/mc.go#L507-L510
11,828
dustin/gomemcached
client/transport.go
UnwrapMemcachedError
func UnwrapMemcachedError(rv *gomemcached.MCResponse, err error) (*gomemcached.MCResponse, error) { if rv == err { return rv, nil } return rv, err }
go
func UnwrapMemcachedError(rv *gomemcached.MCResponse, err error) (*gomemcached.MCResponse, error) { if rv == err { return rv, nil } return rv, err }
[ "func", "UnwrapMemcachedError", "(", "rv", "*", "gomemcached", ".", "MCResponse", ",", "err", "error", ")", "(", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "if", "rv", "==", "err", "{", "return", "rv", ",", "nil", "\n", "}", "\n", "return", "rv", ",", "err", "\n", "}" ]
// UnwrapMemcachedError converts memcached errors to normal responses. // // If the error is a memcached response, declare the error to be nil // so a client can handle the status without worrying about whether it // indicates success or failure.
[ "UnwrapMemcachedError", "converts", "memcached", "errors", "to", "normal", "responses", ".", "If", "the", "error", "is", "a", "memcached", "response", "declare", "the", "error", "to", "be", "nil", "so", "a", "client", "can", "handle", "the", "status", "without", "worrying", "about", "whether", "it", "indicates", "success", "or", "failure", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/transport.go#L17-L24
11,829
dustin/gomemcached
client/tap_feed.go
StartTapFeed
func (mc *Client) StartTapFeed(args TapArguments) (*TapFeed, error) { rq := &gomemcached.MCRequest{ Opcode: gomemcached.TAP_CONNECT, Key: []byte(args.ClientName), Extras: args.flags(), Body: args.bytes()} err := mc.Transmit(rq) if err != nil { return nil, err } ch := make(chan TapEvent) feed := &TapFeed{ C: ch, closer: make(chan bool), } go mc.runFeed(ch, feed) return feed, nil }
go
func (mc *Client) StartTapFeed(args TapArguments) (*TapFeed, error) { rq := &gomemcached.MCRequest{ Opcode: gomemcached.TAP_CONNECT, Key: []byte(args.ClientName), Extras: args.flags(), Body: args.bytes()} err := mc.Transmit(rq) if err != nil { return nil, err } ch := make(chan TapEvent) feed := &TapFeed{ C: ch, closer: make(chan bool), } go mc.runFeed(ch, feed) return feed, nil }
[ "func", "(", "mc", "*", "Client", ")", "StartTapFeed", "(", "args", "TapArguments", ")", "(", "*", "TapFeed", ",", "error", ")", "{", "rq", ":=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "TAP_CONNECT", ",", "Key", ":", "[", "]", "byte", "(", "args", ".", "ClientName", ")", ",", "Extras", ":", "args", ".", "flags", "(", ")", ",", "Body", ":", "args", ".", "bytes", "(", ")", "}", "\n\n", "err", ":=", "mc", ".", "Transmit", "(", "rq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ch", ":=", "make", "(", "chan", "TapEvent", ")", "\n", "feed", ":=", "&", "TapFeed", "{", "C", ":", "ch", ",", "closer", ":", "make", "(", "chan", "bool", ")", ",", "}", "\n", "go", "mc", ".", "runFeed", "(", "ch", ",", "feed", ")", "\n", "return", "feed", ",", "nil", "\n", "}" ]
// StartTapFeed starts a TAP feed on a client connection. // // The events can be read from the returned channel. The connection // can no longer be used for other purposes; it's now reserved for // receiving the TAP messages. To stop receiving events, close the // client connection.
[ "StartTapFeed", "starts", "a", "TAP", "feed", "on", "a", "client", "connection", ".", "The", "events", "can", "be", "read", "from", "the", "returned", "channel", ".", "The", "connection", "can", "no", "longer", "be", "used", "for", "other", "purposes", ";", "it", "s", "now", "reserved", "for", "receiving", "the", "TAP", "messages", ".", "To", "stop", "receiving", "events", "close", "the", "client", "connection", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/tap_feed.go#L234-L253
11,830
dustin/gomemcached
client/tap_feed.go
runFeed
func (mc *Client) runFeed(ch chan TapEvent, feed *TapFeed) { defer close(ch) var headerBuf [gomemcached.HDR_LEN]byte loop: for { // Read the next request from the server. // // (Can't call mc.Receive() because it reads a // _response_ not a request.) var pkt gomemcached.MCRequest n, err := pkt.Receive(mc.conn, headerBuf[:]) if TapRecvHook != nil { TapRecvHook(&pkt, n, err) } if err != nil { if err != io.EOF { feed.Error = err } break loop } //log.Printf("** TapFeed received %#v : %q", pkt, pkt.Body) if pkt.Opcode == gomemcached.TAP_CONNECT { // This is not an event from the server; it's // an error response to my connect request. feed.Error = fmt.Errorf("tap connection failed: %s", pkt.Body) break loop } event := makeTapEvent(pkt) if event != nil { if event.Opcode == tapEndStream { break loop } select { case ch <- *event: case <-feed.closer: break loop } } if len(pkt.Extras) >= 4 { reqFlags := binary.BigEndian.Uint16(pkt.Extras[2:]) if reqFlags&gomemcached.TAP_ACK != 0 { if _, err := mc.sendAck(&pkt); err != nil { feed.Error = err break loop } } } } if err := mc.Close(); err != nil { log.Printf("Error closing memcached client: %v", err) } }
go
func (mc *Client) runFeed(ch chan TapEvent, feed *TapFeed) { defer close(ch) var headerBuf [gomemcached.HDR_LEN]byte loop: for { // Read the next request from the server. // // (Can't call mc.Receive() because it reads a // _response_ not a request.) var pkt gomemcached.MCRequest n, err := pkt.Receive(mc.conn, headerBuf[:]) if TapRecvHook != nil { TapRecvHook(&pkt, n, err) } if err != nil { if err != io.EOF { feed.Error = err } break loop } //log.Printf("** TapFeed received %#v : %q", pkt, pkt.Body) if pkt.Opcode == gomemcached.TAP_CONNECT { // This is not an event from the server; it's // an error response to my connect request. feed.Error = fmt.Errorf("tap connection failed: %s", pkt.Body) break loop } event := makeTapEvent(pkt) if event != nil { if event.Opcode == tapEndStream { break loop } select { case ch <- *event: case <-feed.closer: break loop } } if len(pkt.Extras) >= 4 { reqFlags := binary.BigEndian.Uint16(pkt.Extras[2:]) if reqFlags&gomemcached.TAP_ACK != 0 { if _, err := mc.sendAck(&pkt); err != nil { feed.Error = err break loop } } } } if err := mc.Close(); err != nil { log.Printf("Error closing memcached client: %v", err) } }
[ "func", "(", "mc", "*", "Client", ")", "runFeed", "(", "ch", "chan", "TapEvent", ",", "feed", "*", "TapFeed", ")", "{", "defer", "close", "(", "ch", ")", "\n", "var", "headerBuf", "[", "gomemcached", ".", "HDR_LEN", "]", "byte", "\n", "loop", ":", "for", "{", "// Read the next request from the server.", "//", "// (Can't call mc.Receive() because it reads a", "// _response_ not a request.)", "var", "pkt", "gomemcached", ".", "MCRequest", "\n", "n", ",", "err", ":=", "pkt", ".", "Receive", "(", "mc", ".", "conn", ",", "headerBuf", "[", ":", "]", ")", "\n", "if", "TapRecvHook", "!=", "nil", "{", "TapRecvHook", "(", "&", "pkt", ",", "n", ",", "err", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "feed", ".", "Error", "=", "err", "\n", "}", "\n", "break", "loop", "\n", "}", "\n\n", "//log.Printf(\"** TapFeed received %#v : %q\", pkt, pkt.Body)", "if", "pkt", ".", "Opcode", "==", "gomemcached", ".", "TAP_CONNECT", "{", "// This is not an event from the server; it's", "// an error response to my connect request.", "feed", ".", "Error", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pkt", ".", "Body", ")", "\n", "break", "loop", "\n", "}", "\n\n", "event", ":=", "makeTapEvent", "(", "pkt", ")", "\n", "if", "event", "!=", "nil", "{", "if", "event", ".", "Opcode", "==", "tapEndStream", "{", "break", "loop", "\n", "}", "\n\n", "select", "{", "case", "ch", "<-", "*", "event", ":", "case", "<-", "feed", ".", "closer", ":", "break", "loop", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "pkt", ".", "Extras", ")", ">=", "4", "{", "reqFlags", ":=", "binary", ".", "BigEndian", ".", "Uint16", "(", "pkt", ".", "Extras", "[", "2", ":", "]", ")", "\n", "if", "reqFlags", "&", "gomemcached", ".", "TAP_ACK", "!=", "0", "{", "if", "_", ",", "err", ":=", "mc", ".", "sendAck", "(", "&", "pkt", ")", ";", "err", "!=", "nil", "{", "feed", ".", "Error", "=", "err", "\n", "break", "loop", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "mc", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Internal goroutine that reads from the socket and writes events to // the channel
[ "Internal", "goroutine", "that", "reads", "from", "the", "socket", "and", "writes", "events", "to", "the", "channel" ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/client/tap_feed.go#L260-L317
11,831
dustin/gomemcached
mc_req.go
Size
func (req *MCRequest) Size() int { return HDR_LEN + len(req.Extras) + len(req.Key) + len(req.Body) }
go
func (req *MCRequest) Size() int { return HDR_LEN + len(req.Extras) + len(req.Key) + len(req.Body) }
[ "func", "(", "req", "*", "MCRequest", ")", "Size", "(", ")", "int", "{", "return", "HDR_LEN", "+", "len", "(", "req", ".", "Extras", ")", "+", "len", "(", "req", ".", "Key", ")", "+", "len", "(", "req", ".", "Body", ")", "\n", "}" ]
// The number of bytes this request requires.
[ "The", "number", "of", "bytes", "this", "request", "requires", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_req.go#L28-L30
11,832
dustin/gomemcached
mc_req.go
String
func (req MCRequest) String() string { return fmt.Sprintf("{MCRequest opcode=%s, bodylen=%d, key='%s'}", req.Opcode, len(req.Body), req.Key) }
go
func (req MCRequest) String() string { return fmt.Sprintf("{MCRequest opcode=%s, bodylen=%d, key='%s'}", req.Opcode, len(req.Body), req.Key) }
[ "func", "(", "req", "MCRequest", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "req", ".", "Opcode", ",", "len", "(", "req", ".", "Body", ")", ",", "req", ".", "Key", ")", "\n", "}" ]
// A debugging string representation of this request
[ "A", "debugging", "string", "representation", "of", "this", "request" ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_req.go#L33-L36
11,833
dustin/gomemcached
mc_req.go
Bytes
func (req *MCRequest) Bytes() []byte { data := make([]byte, req.Size()) pos := req.fillHeaderBytes(data) if len(req.Body) > 0 { copy(data[pos:pos+len(req.Body)], req.Body) } return data }
go
func (req *MCRequest) Bytes() []byte { data := make([]byte, req.Size()) pos := req.fillHeaderBytes(data) if len(req.Body) > 0 { copy(data[pos:pos+len(req.Body)], req.Body) } return data }
[ "func", "(", "req", "*", "MCRequest", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "data", ":=", "make", "(", "[", "]", "byte", ",", "req", ".", "Size", "(", ")", ")", "\n\n", "pos", ":=", "req", ".", "fillHeaderBytes", "(", "data", ")", "\n\n", "if", "len", "(", "req", ".", "Body", ")", ">", "0", "{", "copy", "(", "data", "[", "pos", ":", "pos", "+", "len", "(", "req", ".", "Body", ")", "]", ",", "req", ".", "Body", ")", "\n", "}", "\n\n", "return", "data", "\n", "}" ]
// The wire representation of this request.
[ "The", "wire", "representation", "of", "this", "request", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_req.go#L94-L104
11,834
dustin/gomemcached
mc_req.go
Transmit
func (req *MCRequest) Transmit(w io.Writer) (n int, err error) { if len(req.Body) < 128 { n, err = w.Write(req.Bytes()) } else { n, err = w.Write(req.HeaderBytes()) if err == nil { m := 0 m, err = w.Write(req.Body) n += m } } return }
go
func (req *MCRequest) Transmit(w io.Writer) (n int, err error) { if len(req.Body) < 128 { n, err = w.Write(req.Bytes()) } else { n, err = w.Write(req.HeaderBytes()) if err == nil { m := 0 m, err = w.Write(req.Body) n += m } } return }
[ "func", "(", "req", "*", "MCRequest", ")", "Transmit", "(", "w", "io", ".", "Writer", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "len", "(", "req", ".", "Body", ")", "<", "128", "{", "n", ",", "err", "=", "w", ".", "Write", "(", "req", ".", "Bytes", "(", ")", ")", "\n", "}", "else", "{", "n", ",", "err", "=", "w", ".", "Write", "(", "req", ".", "HeaderBytes", "(", ")", ")", "\n", "if", "err", "==", "nil", "{", "m", ":=", "0", "\n", "m", ",", "err", "=", "w", ".", "Write", "(", "req", ".", "Body", ")", "\n", "n", "+=", "m", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Send this request message across a writer.
[ "Send", "this", "request", "message", "across", "a", "writer", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_req.go#L107-L119
11,835
dustin/gomemcached
mc_req.go
Receive
func (req *MCRequest) Receive(r io.Reader, hdrBytes []byte) (int, error) { if len(hdrBytes) < HDR_LEN { hdrBytes = []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} } n, err := io.ReadFull(r, hdrBytes) if err != nil { return n, err } if hdrBytes[0] != RES_MAGIC && hdrBytes[0] != REQ_MAGIC { return n, fmt.Errorf("Bad magic: 0x%02x", hdrBytes[0]) } klen := int(binary.BigEndian.Uint16(hdrBytes[2:])) elen := int(hdrBytes[4]) req.Opcode = CommandCode(hdrBytes[1]) // Vbucket at 6:7 req.VBucket = binary.BigEndian.Uint16(hdrBytes[6:]) bodyLen := int(binary.BigEndian.Uint32(hdrBytes[8:]) - uint32(klen) - uint32(elen)) if bodyLen > MaxBodyLen { return n, fmt.Errorf("%d is too big (max %d)", bodyLen, MaxBodyLen) } req.Opaque = binary.BigEndian.Uint32(hdrBytes[12:]) req.Cas = binary.BigEndian.Uint64(hdrBytes[16:]) buf := make([]byte, klen+elen+bodyLen) m, err := io.ReadFull(r, buf) n += m if err == nil { if req.Opcode >= TAP_MUTATION && req.Opcode <= TAP_CHECKPOINT_END && len(buf) > 1 { // In these commands there is "engine private" // data at the end of the extras. The first 2 // bytes of extra data give its length. elen += int(binary.BigEndian.Uint16(buf)) } if elen > 0 { req.Extras = buf[0:elen] } if klen > 0 { req.Key = buf[elen : klen+elen] } if klen+elen > 0 { req.Body = buf[klen+elen:] } } return n, err }
go
func (req *MCRequest) Receive(r io.Reader, hdrBytes []byte) (int, error) { if len(hdrBytes) < HDR_LEN { hdrBytes = []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} } n, err := io.ReadFull(r, hdrBytes) if err != nil { return n, err } if hdrBytes[0] != RES_MAGIC && hdrBytes[0] != REQ_MAGIC { return n, fmt.Errorf("Bad magic: 0x%02x", hdrBytes[0]) } klen := int(binary.BigEndian.Uint16(hdrBytes[2:])) elen := int(hdrBytes[4]) req.Opcode = CommandCode(hdrBytes[1]) // Vbucket at 6:7 req.VBucket = binary.BigEndian.Uint16(hdrBytes[6:]) bodyLen := int(binary.BigEndian.Uint32(hdrBytes[8:]) - uint32(klen) - uint32(elen)) if bodyLen > MaxBodyLen { return n, fmt.Errorf("%d is too big (max %d)", bodyLen, MaxBodyLen) } req.Opaque = binary.BigEndian.Uint32(hdrBytes[12:]) req.Cas = binary.BigEndian.Uint64(hdrBytes[16:]) buf := make([]byte, klen+elen+bodyLen) m, err := io.ReadFull(r, buf) n += m if err == nil { if req.Opcode >= TAP_MUTATION && req.Opcode <= TAP_CHECKPOINT_END && len(buf) > 1 { // In these commands there is "engine private" // data at the end of the extras. The first 2 // bytes of extra data give its length. elen += int(binary.BigEndian.Uint16(buf)) } if elen > 0 { req.Extras = buf[0:elen] } if klen > 0 { req.Key = buf[elen : klen+elen] } if klen+elen > 0 { req.Body = buf[klen+elen:] } } return n, err }
[ "func", "(", "req", "*", "MCRequest", ")", "Receive", "(", "r", "io", ".", "Reader", ",", "hdrBytes", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "len", "(", "hdrBytes", ")", "<", "HDR_LEN", "{", "hdrBytes", "=", "[", "]", "byte", "{", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "}", "\n", "}", "\n", "n", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "hdrBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "err", "\n", "}", "\n\n", "if", "hdrBytes", "[", "0", "]", "!=", "RES_MAGIC", "&&", "hdrBytes", "[", "0", "]", "!=", "REQ_MAGIC", "{", "return", "n", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hdrBytes", "[", "0", "]", ")", "\n", "}", "\n\n", "klen", ":=", "int", "(", "binary", ".", "BigEndian", ".", "Uint16", "(", "hdrBytes", "[", "2", ":", "]", ")", ")", "\n", "elen", ":=", "int", "(", "hdrBytes", "[", "4", "]", ")", "\n\n", "req", ".", "Opcode", "=", "CommandCode", "(", "hdrBytes", "[", "1", "]", ")", "\n", "// Vbucket at 6:7", "req", ".", "VBucket", "=", "binary", ".", "BigEndian", ".", "Uint16", "(", "hdrBytes", "[", "6", ":", "]", ")", "\n", "bodyLen", ":=", "int", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "hdrBytes", "[", "8", ":", "]", ")", "-", "uint32", "(", "klen", ")", "-", "uint32", "(", "elen", ")", ")", "\n", "if", "bodyLen", ">", "MaxBodyLen", "{", "return", "n", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "bodyLen", ",", "MaxBodyLen", ")", "\n", "}", "\n", "req", ".", "Opaque", "=", "binary", ".", "BigEndian", ".", "Uint32", "(", "hdrBytes", "[", "12", ":", "]", ")", "\n", "req", ".", "Cas", "=", "binary", ".", "BigEndian", ".", "Uint64", "(", "hdrBytes", "[", "16", ":", "]", ")", "\n\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "klen", "+", "elen", "+", "bodyLen", ")", "\n", "m", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", "\n", "n", "+=", "m", "\n", "if", "err", "==", "nil", "{", "if", "req", ".", "Opcode", ">=", "TAP_MUTATION", "&&", "req", ".", "Opcode", "<=", "TAP_CHECKPOINT_END", "&&", "len", "(", "buf", ")", ">", "1", "{", "// In these commands there is \"engine private\"", "// data at the end of the extras. The first 2", "// bytes of extra data give its length.", "elen", "+=", "int", "(", "binary", ".", "BigEndian", ".", "Uint16", "(", "buf", ")", ")", "\n", "}", "\n", "if", "elen", ">", "0", "{", "req", ".", "Extras", "=", "buf", "[", "0", ":", "elen", "]", "\n", "}", "\n", "if", "klen", ">", "0", "{", "req", ".", "Key", "=", "buf", "[", "elen", ":", "klen", "+", "elen", "]", "\n", "}", "\n", "if", "klen", "+", "elen", ">", "0", "{", "req", ".", "Body", "=", "buf", "[", "klen", "+", "elen", ":", "]", "\n", "}", "\n", "}", "\n\n", "return", "n", ",", "err", "\n", "}" ]
// Fill this MCRequest with the data from this reader.
[ "Fill", "this", "MCRequest", "with", "the", "data", "from", "this", "reader", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/mc_req.go#L122-L177
11,836
dustin/gomemcached
tap.go
SplitFlags
func (f TapConnectFlag) SplitFlags() []TapConnectFlag { rv := []TapConnectFlag{} for i := uint32(1); f != 0; i = i << 1 { if uint32(f)&i == i { rv = append(rv, TapConnectFlag(i)) } f = TapConnectFlag(uint32(f) & (^i)) } return rv }
go
func (f TapConnectFlag) SplitFlags() []TapConnectFlag { rv := []TapConnectFlag{} for i := uint32(1); f != 0; i = i << 1 { if uint32(f)&i == i { rv = append(rv, TapConnectFlag(i)) } f = TapConnectFlag(uint32(f) & (^i)) } return rv }
[ "func", "(", "f", "TapConnectFlag", ")", "SplitFlags", "(", ")", "[", "]", "TapConnectFlag", "{", "rv", ":=", "[", "]", "TapConnectFlag", "{", "}", "\n", "for", "i", ":=", "uint32", "(", "1", ")", ";", "f", "!=", "0", ";", "i", "=", "i", "<<", "1", "{", "if", "uint32", "(", "f", ")", "&", "i", "==", "i", "{", "rv", "=", "append", "(", "rv", ",", "TapConnectFlag", "(", "i", ")", ")", "\n", "}", "\n", "f", "=", "TapConnectFlag", "(", "uint32", "(", "f", ")", "&", "(", "^", "i", ")", ")", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// Split the ORed flags into the individual bit flags.
[ "Split", "the", "ORed", "flags", "into", "the", "individual", "bit", "flags", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/tap.go#L99-L108
11,837
dustin/gomemcached
tap.go
ParseTapCommands
func (req *MCRequest) ParseTapCommands() (TapConnect, error) { rv := TapConnect{ Flags: map[TapConnectFlag]interface{}{}, Name: string(req.Key), } if len(req.Extras) < 4 { return rv, fmt.Errorf("not enough extra bytes: %x", req.Extras) } flags := TapConnectFlag(binary.BigEndian.Uint32(req.Extras)) r := bytes.NewReader(req.Body) for _, f := range flags.SplitFlags() { fun := TapFlagParsers[f] if fun == nil { fun = TapParseBool } val, err := fun(r) if err != nil { return rv, err } rv.Flags[f] = val } var err error rv.RemainingBody, err = ioutil.ReadAll(r) return rv, err }
go
func (req *MCRequest) ParseTapCommands() (TapConnect, error) { rv := TapConnect{ Flags: map[TapConnectFlag]interface{}{}, Name: string(req.Key), } if len(req.Extras) < 4 { return rv, fmt.Errorf("not enough extra bytes: %x", req.Extras) } flags := TapConnectFlag(binary.BigEndian.Uint32(req.Extras)) r := bytes.NewReader(req.Body) for _, f := range flags.SplitFlags() { fun := TapFlagParsers[f] if fun == nil { fun = TapParseBool } val, err := fun(r) if err != nil { return rv, err } rv.Flags[f] = val } var err error rv.RemainingBody, err = ioutil.ReadAll(r) return rv, err }
[ "func", "(", "req", "*", "MCRequest", ")", "ParseTapCommands", "(", ")", "(", "TapConnect", ",", "error", ")", "{", "rv", ":=", "TapConnect", "{", "Flags", ":", "map", "[", "TapConnectFlag", "]", "interface", "{", "}", "{", "}", ",", "Name", ":", "string", "(", "req", ".", "Key", ")", ",", "}", "\n\n", "if", "len", "(", "req", ".", "Extras", ")", "<", "4", "{", "return", "rv", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "Extras", ")", "\n", "}", "\n\n", "flags", ":=", "TapConnectFlag", "(", "binary", ".", "BigEndian", ".", "Uint32", "(", "req", ".", "Extras", ")", ")", "\n\n", "r", ":=", "bytes", ".", "NewReader", "(", "req", ".", "Body", ")", "\n\n", "for", "_", ",", "f", ":=", "range", "flags", ".", "SplitFlags", "(", ")", "{", "fun", ":=", "TapFlagParsers", "[", "f", "]", "\n", "if", "fun", "==", "nil", "{", "fun", "=", "TapParseBool", "\n", "}", "\n\n", "val", ",", "err", ":=", "fun", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n\n", "rv", ".", "Flags", "[", "f", "]", "=", "val", "\n", "}", "\n\n", "var", "err", "error", "\n", "rv", ".", "RemainingBody", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n\n", "return", "rv", ",", "err", "\n", "}" ]
// Parse the tap request into the interesting bits we may need to do something with.
[ "Parse", "the", "tap", "request", "into", "the", "interesting", "bits", "we", "may", "need", "to", "do", "something", "with", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/tap.go#L129-L161
11,838
dustin/gomemcached
server/mc_conn_handler.go
FuncHandler
func FuncHandler(f func(io.Writer, *gomemcached.MCRequest) *gomemcached.MCResponse) RequestHandler { return funcHandler(f) }
go
func FuncHandler(f func(io.Writer, *gomemcached.MCRequest) *gomemcached.MCResponse) RequestHandler { return funcHandler(f) }
[ "func", "FuncHandler", "(", "f", "func", "(", "io", ".", "Writer", ",", "*", "gomemcached", ".", "MCRequest", ")", "*", "gomemcached", ".", "MCResponse", ")", "RequestHandler", "{", "return", "funcHandler", "(", "f", ")", "\n", "}" ]
// Convert a request handler function as a RequestHandler.
[ "Convert", "a", "request", "handler", "function", "as", "a", "RequestHandler", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/server/mc_conn_handler.go#L29-L31
11,839
dustin/gomemcached
server/mc_conn_handler.go
HandleIO
func HandleIO(s io.ReadWriteCloser, handler RequestHandler) error { defer func() { must(s.Close()) }() var err error for err == nil { err = HandleMessage(s, s, handler) } return err }
go
func HandleIO(s io.ReadWriteCloser, handler RequestHandler) error { defer func() { must(s.Close()) }() var err error for err == nil { err = HandleMessage(s, s, handler) } return err }
[ "func", "HandleIO", "(", "s", "io", ".", "ReadWriteCloser", ",", "handler", "RequestHandler", ")", "error", "{", "defer", "func", "(", ")", "{", "must", "(", "s", ".", "Close", "(", ")", ")", "}", "(", ")", "\n", "var", "err", "error", "\n", "for", "err", "==", "nil", "{", "err", "=", "HandleMessage", "(", "s", ",", "s", ",", "handler", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Handle until the handler returns a fatal message or a read or write // on the socket fails.
[ "Handle", "until", "the", "handler", "returns", "a", "fatal", "message", "or", "a", "read", "or", "write", "on", "the", "socket", "fails", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/server/mc_conn_handler.go#L41-L48
11,840
dustin/gomemcached
server/mc_conn_handler.go
HandleMessage
func HandleMessage(r io.Reader, w io.Writer, handler RequestHandler) error { req, err := ReadPacket(r) if err != nil { return err } res := handler.HandleMessage(w, &req) if res == nil { // Quiet command return nil } if !res.Fatal { res.Opcode = req.Opcode res.Opaque = req.Opaque _, err = res.Transmit(w) if err != nil { return err } return nil } return io.EOF }
go
func HandleMessage(r io.Reader, w io.Writer, handler RequestHandler) error { req, err := ReadPacket(r) if err != nil { return err } res := handler.HandleMessage(w, &req) if res == nil { // Quiet command return nil } if !res.Fatal { res.Opcode = req.Opcode res.Opaque = req.Opaque _, err = res.Transmit(w) if err != nil { return err } return nil } return io.EOF }
[ "func", "HandleMessage", "(", "r", "io", ".", "Reader", ",", "w", "io", ".", "Writer", ",", "handler", "RequestHandler", ")", "error", "{", "req", ",", "err", ":=", "ReadPacket", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "res", ":=", "handler", ".", "HandleMessage", "(", "w", ",", "&", "req", ")", "\n", "if", "res", "==", "nil", "{", "// Quiet command", "return", "nil", "\n", "}", "\n\n", "if", "!", "res", ".", "Fatal", "{", "res", ".", "Opcode", "=", "req", ".", "Opcode", "\n", "res", ".", "Opaque", "=", "req", ".", "Opaque", "\n", "_", ",", "err", "=", "res", ".", "Transmit", "(", "w", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "return", "io", ".", "EOF", "\n", "}" ]
// Handle an individual message.
[ "Handle", "an", "individual", "message", "." ]
a2284a01c143e355985d192edf3b62a053747c70
https://github.com/dustin/gomemcached/blob/a2284a01c143e355985d192edf3b62a053747c70/server/mc_conn_handler.go#L51-L74
11,841
Rican7/retry
retry.go
Retry
func Retry(action Action, strategies ...strategy.Strategy) error { var err error for attempt := uint(0); (0 == attempt || nil != err) && shouldAttempt(attempt, strategies...); attempt++ { err = action(attempt) } return err }
go
func Retry(action Action, strategies ...strategy.Strategy) error { var err error for attempt := uint(0); (0 == attempt || nil != err) && shouldAttempt(attempt, strategies...); attempt++ { err = action(attempt) } return err }
[ "func", "Retry", "(", "action", "Action", ",", "strategies", "...", "strategy", ".", "Strategy", ")", "error", "{", "var", "err", "error", "\n\n", "for", "attempt", ":=", "uint", "(", "0", ")", ";", "(", "0", "==", "attempt", "||", "nil", "!=", "err", ")", "&&", "shouldAttempt", "(", "attempt", ",", "strategies", "...", ")", ";", "attempt", "++", "{", "err", "=", "action", "(", "attempt", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// Retry takes an action and performs it, repetitively, until successful. // // Optionally, strategies may be passed that assess whether or not an attempt // should be made.
[ "Retry", "takes", "an", "action", "and", "performs", "it", "repetitively", "until", "successful", ".", "Optionally", "strategies", "may", "be", "passed", "that", "assess", "whether", "or", "not", "an", "attempt", "should", "be", "made", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/retry.go#L16-L24
11,842
Rican7/retry
retry.go
shouldAttempt
func shouldAttempt(attempt uint, strategies ...strategy.Strategy) bool { shouldAttempt := true for i := 0; shouldAttempt && i < len(strategies); i++ { shouldAttempt = shouldAttempt && strategies[i](attempt) } return shouldAttempt }
go
func shouldAttempt(attempt uint, strategies ...strategy.Strategy) bool { shouldAttempt := true for i := 0; shouldAttempt && i < len(strategies); i++ { shouldAttempt = shouldAttempt && strategies[i](attempt) } return shouldAttempt }
[ "func", "shouldAttempt", "(", "attempt", "uint", ",", "strategies", "...", "strategy", ".", "Strategy", ")", "bool", "{", "shouldAttempt", ":=", "true", "\n\n", "for", "i", ":=", "0", ";", "shouldAttempt", "&&", "i", "<", "len", "(", "strategies", ")", ";", "i", "++", "{", "shouldAttempt", "=", "shouldAttempt", "&&", "strategies", "[", "i", "]", "(", "attempt", ")", "\n", "}", "\n\n", "return", "shouldAttempt", "\n", "}" ]
// shouldAttempt evaluates the provided strategies with the given attempt to // determine if the Retry loop should make another attempt.
[ "shouldAttempt", "evaluates", "the", "provided", "strategies", "with", "the", "given", "attempt", "to", "determine", "if", "the", "Retry", "loop", "should", "make", "another", "attempt", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/retry.go#L28-L36
11,843
Rican7/retry
backoff/backoff.go
Incremental
func Incremental(initial, increment time.Duration) Algorithm { return func(attempt uint) time.Duration { return initial + (increment * time.Duration(attempt)) } }
go
func Incremental(initial, increment time.Duration) Algorithm { return func(attempt uint) time.Duration { return initial + (increment * time.Duration(attempt)) } }
[ "func", "Incremental", "(", "initial", ",", "increment", "time", ".", "Duration", ")", "Algorithm", "{", "return", "func", "(", "attempt", "uint", ")", "time", ".", "Duration", "{", "return", "initial", "+", "(", "increment", "*", "time", ".", "Duration", "(", "attempt", ")", ")", "\n", "}", "\n", "}" ]
// Incremental creates a Algorithm that increments the initial duration // by the given increment for each attempt.
[ "Incremental", "creates", "a", "Algorithm", "that", "increments", "the", "initial", "duration", "by", "the", "given", "increment", "for", "each", "attempt", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/backoff/backoff.go#L18-L22
11,844
Rican7/retry
backoff/backoff.go
Linear
func Linear(factor time.Duration) Algorithm { return func(attempt uint) time.Duration { return (factor * time.Duration(attempt)) } }
go
func Linear(factor time.Duration) Algorithm { return func(attempt uint) time.Duration { return (factor * time.Duration(attempt)) } }
[ "func", "Linear", "(", "factor", "time", ".", "Duration", ")", "Algorithm", "{", "return", "func", "(", "attempt", "uint", ")", "time", ".", "Duration", "{", "return", "(", "factor", "*", "time", ".", "Duration", "(", "attempt", ")", ")", "\n", "}", "\n", "}" ]
// Linear creates a Algorithm that linearly multiplies the factor // duration by the attempt number for each attempt.
[ "Linear", "creates", "a", "Algorithm", "that", "linearly", "multiplies", "the", "factor", "duration", "by", "the", "attempt", "number", "for", "each", "attempt", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/backoff/backoff.go#L26-L30
11,845
Rican7/retry
backoff/backoff.go
Exponential
func Exponential(factor time.Duration, base float64) Algorithm { return func(attempt uint) time.Duration { return (factor * time.Duration(math.Pow(base, float64(attempt)))) } }
go
func Exponential(factor time.Duration, base float64) Algorithm { return func(attempt uint) time.Duration { return (factor * time.Duration(math.Pow(base, float64(attempt)))) } }
[ "func", "Exponential", "(", "factor", "time", ".", "Duration", ",", "base", "float64", ")", "Algorithm", "{", "return", "func", "(", "attempt", "uint", ")", "time", ".", "Duration", "{", "return", "(", "factor", "*", "time", ".", "Duration", "(", "math", ".", "Pow", "(", "base", ",", "float64", "(", "attempt", ")", ")", ")", ")", "\n", "}", "\n", "}" ]
// Exponential creates a Algorithm that multiplies the factor duration by // an exponentially increasing factor for each attempt, where the factor is // calculated as the given base raised to the attempt number.
[ "Exponential", "creates", "a", "Algorithm", "that", "multiplies", "the", "factor", "duration", "by", "an", "exponentially", "increasing", "factor", "for", "each", "attempt", "where", "the", "factor", "is", "calculated", "as", "the", "given", "base", "raised", "to", "the", "attempt", "number", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/backoff/backoff.go#L35-L39
11,846
Rican7/retry
backoff/backoff.go
Fibonacci
func Fibonacci(factor time.Duration) Algorithm { return func(attempt uint) time.Duration { return (factor * time.Duration(fibonacciNumber(attempt))) } }
go
func Fibonacci(factor time.Duration) Algorithm { return func(attempt uint) time.Duration { return (factor * time.Duration(fibonacciNumber(attempt))) } }
[ "func", "Fibonacci", "(", "factor", "time", ".", "Duration", ")", "Algorithm", "{", "return", "func", "(", "attempt", "uint", ")", "time", ".", "Duration", "{", "return", "(", "factor", "*", "time", ".", "Duration", "(", "fibonacciNumber", "(", "attempt", ")", ")", ")", "\n", "}", "\n", "}" ]
// Fibonacci creates a Algorithm that multiplies the factor duration by // an increasing factor for each attempt, where the factor is the Nth number in // the Fibonacci sequence.
[ "Fibonacci", "creates", "a", "Algorithm", "that", "multiplies", "the", "factor", "duration", "by", "an", "increasing", "factor", "for", "each", "attempt", "where", "the", "factor", "is", "the", "Nth", "number", "in", "the", "Fibonacci", "sequence", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/backoff/backoff.go#L51-L55
11,847
Rican7/retry
backoff/backoff.go
fibonacciNumber
func fibonacciNumber(n uint) uint { if 0 == n { return 0 } else if 1 == n { return 1 } else { return fibonacciNumber(n-1) + fibonacciNumber(n-2) } }
go
func fibonacciNumber(n uint) uint { if 0 == n { return 0 } else if 1 == n { return 1 } else { return fibonacciNumber(n-1) + fibonacciNumber(n-2) } }
[ "func", "fibonacciNumber", "(", "n", "uint", ")", "uint", "{", "if", "0", "==", "n", "{", "return", "0", "\n", "}", "else", "if", "1", "==", "n", "{", "return", "1", "\n", "}", "else", "{", "return", "fibonacciNumber", "(", "n", "-", "1", ")", "+", "fibonacciNumber", "(", "n", "-", "2", ")", "\n", "}", "\n", "}" ]
// fibonacciNumber calculates the Fibonacci sequence number for the given // sequence position.
[ "fibonacciNumber", "calculates", "the", "Fibonacci", "sequence", "number", "for", "the", "given", "sequence", "position", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/backoff/backoff.go#L59-L67
11,848
Rican7/retry
jitter/jitter.go
NormalDistribution
func NormalDistribution(generator *rand.Rand, standardDeviation float64) Transformation { random := fallbackNewRandom(generator) return func(duration time.Duration) time.Duration { return time.Duration(random.NormFloat64()*standardDeviation + float64(duration)) } }
go
func NormalDistribution(generator *rand.Rand, standardDeviation float64) Transformation { random := fallbackNewRandom(generator) return func(duration time.Duration) time.Duration { return time.Duration(random.NormFloat64()*standardDeviation + float64(duration)) } }
[ "func", "NormalDistribution", "(", "generator", "*", "rand", ".", "Rand", ",", "standardDeviation", "float64", ")", "Transformation", "{", "random", ":=", "fallbackNewRandom", "(", "generator", ")", "\n\n", "return", "func", "(", "duration", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "random", ".", "NormFloat64", "(", ")", "*", "standardDeviation", "+", "float64", "(", "duration", ")", ")", "\n", "}", "\n", "}" ]
// NormalDistribution creates a Transformation that transforms a duration into a // result duration based on a normal distribution of the input and the given // standard deviation. // // The given generator is what is used to determine the random transformation. // If a nil generator is passed, a default one will be provided.
[ "NormalDistribution", "creates", "a", "Transformation", "that", "transforms", "a", "duration", "into", "a", "result", "duration", "based", "on", "a", "normal", "distribution", "of", "the", "input", "and", "the", "given", "standard", "deviation", ".", "The", "given", "generator", "is", "what", "is", "used", "to", "determine", "the", "random", "transformation", ".", "If", "a", "nil", "generator", "is", "passed", "a", "default", "one", "will", "be", "provided", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/jitter/jitter.go#L70-L76
11,849
Rican7/retry
jitter/jitter.go
fallbackNewRandom
func fallbackNewRandom(random *rand.Rand) *rand.Rand { // Return the passed in value if it's already not null if nil != random { return random } seed := time.Now().UnixNano() return rand.New(rand.NewSource(seed)) }
go
func fallbackNewRandom(random *rand.Rand) *rand.Rand { // Return the passed in value if it's already not null if nil != random { return random } seed := time.Now().UnixNano() return rand.New(rand.NewSource(seed)) }
[ "func", "fallbackNewRandom", "(", "random", "*", "rand", ".", "Rand", ")", "*", "rand", ".", "Rand", "{", "// Return the passed in value if it's already not null", "if", "nil", "!=", "random", "{", "return", "random", "\n", "}", "\n\n", "seed", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n\n", "return", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "seed", ")", ")", "\n", "}" ]
// fallbackNewRandom returns the passed in random instance if it's not nil, // and otherwise returns a new random instance seeded with the current time.
[ "fallbackNewRandom", "returns", "the", "passed", "in", "random", "instance", "if", "it", "s", "not", "nil", "and", "otherwise", "returns", "a", "new", "random", "instance", "seeded", "with", "the", "current", "time", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/jitter/jitter.go#L80-L89
11,850
Rican7/retry
strategy/strategy.go
Delay
func Delay(duration time.Duration) Strategy { return func(attempt uint) bool { if 0 == attempt { time.Sleep(duration) } return true } }
go
func Delay(duration time.Duration) Strategy { return func(attempt uint) bool { if 0 == attempt { time.Sleep(duration) } return true } }
[ "func", "Delay", "(", "duration", "time", ".", "Duration", ")", "Strategy", "{", "return", "func", "(", "attempt", "uint", ")", "bool", "{", "if", "0", "==", "attempt", "{", "time", ".", "Sleep", "(", "duration", ")", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n", "}" ]
// Delay creates a Strategy that waits the given duration before the first // attempt is made.
[ "Delay", "creates", "a", "Strategy", "that", "waits", "the", "given", "duration", "before", "the", "first", "attempt", "is", "made", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/strategy/strategy.go#L33-L41
11,851
Rican7/retry
strategy/strategy.go
Wait
func Wait(durations ...time.Duration) Strategy { return func(attempt uint) bool { if 0 < attempt && 0 < len(durations) { durationIndex := int(attempt - 1) if len(durations) <= durationIndex { durationIndex = len(durations) - 1 } time.Sleep(durations[durationIndex]) } return true } }
go
func Wait(durations ...time.Duration) Strategy { return func(attempt uint) bool { if 0 < attempt && 0 < len(durations) { durationIndex := int(attempt - 1) if len(durations) <= durationIndex { durationIndex = len(durations) - 1 } time.Sleep(durations[durationIndex]) } return true } }
[ "func", "Wait", "(", "durations", "...", "time", ".", "Duration", ")", "Strategy", "{", "return", "func", "(", "attempt", "uint", ")", "bool", "{", "if", "0", "<", "attempt", "&&", "0", "<", "len", "(", "durations", ")", "{", "durationIndex", ":=", "int", "(", "attempt", "-", "1", ")", "\n\n", "if", "len", "(", "durations", ")", "<=", "durationIndex", "{", "durationIndex", "=", "len", "(", "durations", ")", "-", "1", "\n", "}", "\n\n", "time", ".", "Sleep", "(", "durations", "[", "durationIndex", "]", ")", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n", "}" ]
// Wait creates a Strategy that waits the given durations for each attempt after // the first. If the number of attempts is greater than the number of durations // provided, then the strategy uses the last duration provided.
[ "Wait", "creates", "a", "Strategy", "that", "waits", "the", "given", "durations", "for", "each", "attempt", "after", "the", "first", ".", "If", "the", "number", "of", "attempts", "is", "greater", "than", "the", "number", "of", "durations", "provided", "then", "the", "strategy", "uses", "the", "last", "duration", "provided", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/strategy/strategy.go#L46-L60
11,852
Rican7/retry
strategy/strategy.go
BackoffWithJitter
func BackoffWithJitter(algorithm backoff.Algorithm, transformation jitter.Transformation) Strategy { return func(attempt uint) bool { if 0 < attempt { time.Sleep(transformation(algorithm(attempt))) } return true } }
go
func BackoffWithJitter(algorithm backoff.Algorithm, transformation jitter.Transformation) Strategy { return func(attempt uint) bool { if 0 < attempt { time.Sleep(transformation(algorithm(attempt))) } return true } }
[ "func", "BackoffWithJitter", "(", "algorithm", "backoff", ".", "Algorithm", ",", "transformation", "jitter", ".", "Transformation", ")", "Strategy", "{", "return", "func", "(", "attempt", "uint", ")", "bool", "{", "if", "0", "<", "attempt", "{", "time", ".", "Sleep", "(", "transformation", "(", "algorithm", "(", "attempt", ")", ")", ")", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n", "}" ]
// BackoffWithJitter creates a Strategy that waits before each attempt, with a // duration as defined by the given backoff.Algorithm and jitter.Transformation.
[ "BackoffWithJitter", "creates", "a", "Strategy", "that", "waits", "before", "each", "attempt", "with", "a", "duration", "as", "defined", "by", "the", "given", "backoff", ".", "Algorithm", "and", "jitter", ".", "Transformation", "." ]
272ad122d6e5ce1be757544007cf8bcd1c9c9ab0
https://github.com/Rican7/retry/blob/272ad122d6e5ce1be757544007cf8bcd1c9c9ab0/strategy/strategy.go#L70-L78
11,853
bndr/gopencils
api.go
Api
func Api(baseUrl string, options ...interface{}) *Resource { u, err := url.Parse(baseUrl) if err != nil { // TODO: don't panic.. panic("Api() - url.Parse(baseUrl) Error:" + err.Error()) } apiInstance := &ApiStruct{BaseUrl: u, BasicAuth: nil} for _, o := range options { switch v := o.(type) { case *BasicAuth: apiInstance.BasicAuth = v case *http.Client: apiInstance.Client = v case string: apiInstance.PathSuffix = v } } if apiInstance.Client == nil { apiInstance.Cookies, _ = cookiejar.New(nil) // Skip verify by default? tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{ Transport: tr, Jar: apiInstance.Cookies, } apiInstance.Client = client } return &Resource{Url: "", Api: apiInstance} }
go
func Api(baseUrl string, options ...interface{}) *Resource { u, err := url.Parse(baseUrl) if err != nil { // TODO: don't panic.. panic("Api() - url.Parse(baseUrl) Error:" + err.Error()) } apiInstance := &ApiStruct{BaseUrl: u, BasicAuth: nil} for _, o := range options { switch v := o.(type) { case *BasicAuth: apiInstance.BasicAuth = v case *http.Client: apiInstance.Client = v case string: apiInstance.PathSuffix = v } } if apiInstance.Client == nil { apiInstance.Cookies, _ = cookiejar.New(nil) // Skip verify by default? tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{ Transport: tr, Jar: apiInstance.Cookies, } apiInstance.Client = client } return &Resource{Url: "", Api: apiInstance} }
[ "func", "Api", "(", "baseUrl", "string", ",", "options", "...", "interface", "{", "}", ")", "*", "Resource", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "baseUrl", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO: don't panic..", "panic", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "apiInstance", ":=", "&", "ApiStruct", "{", "BaseUrl", ":", "u", ",", "BasicAuth", ":", "nil", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "options", "{", "switch", "v", ":=", "o", ".", "(", "type", ")", "{", "case", "*", "BasicAuth", ":", "apiInstance", ".", "BasicAuth", "=", "v", "\n", "case", "*", "http", ".", "Client", ":", "apiInstance", ".", "Client", "=", "v", "\n", "case", "string", ":", "apiInstance", ".", "PathSuffix", "=", "v", "\n", "}", "\n", "}", "\n\n", "if", "apiInstance", ".", "Client", "==", "nil", "{", "apiInstance", ".", "Cookies", ",", "_", "=", "cookiejar", ".", "New", "(", "nil", ")", "\n\n", "// Skip verify by default?", "tr", ":=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", "}", ",", "}", "\n\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "tr", ",", "Jar", ":", "apiInstance", ".", "Cookies", ",", "}", "\n", "apiInstance", ".", "Client", "=", "client", "\n", "}", "\n", "return", "&", "Resource", "{", "Url", ":", "\"", "\"", ",", "Api", ":", "apiInstance", "}", "\n", "}" ]
// Create a new API Instance and returns a Resource // Accepts URL as parameter, and either a Basic Auth or a OAuth2 Client.
[ "Create", "a", "new", "API", "Instance", "and", "returns", "a", "Resource", "Accepts", "URL", "as", "parameter", "and", "either", "a", "Basic", "Auth", "or", "a", "OAuth2", "Client", "." ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/api.go#L42-L77
11,854
bndr/gopencils
resource.go
Res
func (r *Resource) Res(options ...interface{}) *Resource { if len(options) > 0 { var url string if len(r.Url) > 0 { url = r.Url + "/" + options[0].(string) } else { url = options[0].(string) } header := r.Headers if header == nil { header = http.Header{} } newR := &Resource{Url: url, Api: r.Api, Headers: header} if len(options) > 1 { newR.Response = options[1] } return newR } return r }
go
func (r *Resource) Res(options ...interface{}) *Resource { if len(options) > 0 { var url string if len(r.Url) > 0 { url = r.Url + "/" + options[0].(string) } else { url = options[0].(string) } header := r.Headers if header == nil { header = http.Header{} } newR := &Resource{Url: url, Api: r.Api, Headers: header} if len(options) > 1 { newR.Response = options[1] } return newR } return r }
[ "func", "(", "r", "*", "Resource", ")", "Res", "(", "options", "...", "interface", "{", "}", ")", "*", "Resource", "{", "if", "len", "(", "options", ")", ">", "0", "{", "var", "url", "string", "\n", "if", "len", "(", "r", ".", "Url", ")", ">", "0", "{", "url", "=", "r", ".", "Url", "+", "\"", "\"", "+", "options", "[", "0", "]", ".", "(", "string", ")", "\n", "}", "else", "{", "url", "=", "options", "[", "0", "]", ".", "(", "string", ")", "\n", "}", "\n\n", "header", ":=", "r", ".", "Headers", "\n", "if", "header", "==", "nil", "{", "header", "=", "http", ".", "Header", "{", "}", "\n", "}", "\n", "newR", ":=", "&", "Resource", "{", "Url", ":", "url", ",", "Api", ":", "r", ".", "Api", ",", "Headers", ":", "header", "}", "\n\n", "if", "len", "(", "options", ")", ">", "1", "{", "newR", ".", "Response", "=", "options", "[", "1", "]", "\n", "}", "\n\n", "return", "newR", "\n", "}", "\n", "return", "r", "\n", "}" ]
// Creates a new Resource.
[ "Creates", "a", "new", "Resource", "." ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/resource.go#L43-L65
11,855
bndr/gopencils
resource.go
SetQuery
func (r *Resource) SetQuery(querystring map[string]string) *Resource { r.QueryValues = make(url.Values) for k, v := range querystring { r.QueryValues.Set(k, v) } return r }
go
func (r *Resource) SetQuery(querystring map[string]string) *Resource { r.QueryValues = make(url.Values) for k, v := range querystring { r.QueryValues.Set(k, v) } return r }
[ "func", "(", "r", "*", "Resource", ")", "SetQuery", "(", "querystring", "map", "[", "string", "]", "string", ")", "*", "Resource", "{", "r", ".", "QueryValues", "=", "make", "(", "url", ".", "Values", ")", "\n", "for", "k", ",", "v", ":=", "range", "querystring", "{", "r", ".", "QueryValues", ".", "Set", "(", "k", ",", "v", ")", "\n", "}", "\n", "return", "r", "\n", "}" ]
// Sets QueryValues for current Resource
[ "Sets", "QueryValues", "for", "current", "Resource" ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/resource.go#L95-L101
11,856
bndr/gopencils
resource.go
do
func (r *Resource) do(method string) (*Resource, error) { url := *r.Api.BaseUrl if len(url.Path) > 0 { url.Path += "/" + r.Url } else { url.Path = r.Url } if r.Api.PathSuffix != "" { url.Path += r.Api.PathSuffix } url.RawQuery = r.QueryValues.Encode() req, err := http.NewRequest(method, url.String(), r.Payload) if err != nil { return r, err } if r.Api.BasicAuth != nil { req.SetBasicAuth(r.Api.BasicAuth.Username, r.Api.BasicAuth.Password) } if r.Headers != nil { for k, _ := range r.Headers { req.Header.Set(k, r.Headers.Get(k)) } } resp, err := r.Api.Client.Do(req) if err != nil { return r, err } r.Raw = resp if resp.StatusCode >= 400 { return r, nil } for k, _ := range r.Raw.Header { r.SetHeader(k, r.Raw.Header.Get(k)); } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(r.Response) if err != nil { return r, err } return r, nil }
go
func (r *Resource) do(method string) (*Resource, error) { url := *r.Api.BaseUrl if len(url.Path) > 0 { url.Path += "/" + r.Url } else { url.Path = r.Url } if r.Api.PathSuffix != "" { url.Path += r.Api.PathSuffix } url.RawQuery = r.QueryValues.Encode() req, err := http.NewRequest(method, url.String(), r.Payload) if err != nil { return r, err } if r.Api.BasicAuth != nil { req.SetBasicAuth(r.Api.BasicAuth.Username, r.Api.BasicAuth.Password) } if r.Headers != nil { for k, _ := range r.Headers { req.Header.Set(k, r.Headers.Get(k)) } } resp, err := r.Api.Client.Do(req) if err != nil { return r, err } r.Raw = resp if resp.StatusCode >= 400 { return r, nil } for k, _ := range r.Raw.Header { r.SetHeader(k, r.Raw.Header.Get(k)); } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(r.Response) if err != nil { return r, err } return r, nil }
[ "func", "(", "r", "*", "Resource", ")", "do", "(", "method", "string", ")", "(", "*", "Resource", ",", "error", ")", "{", "url", ":=", "*", "r", ".", "Api", ".", "BaseUrl", "\n", "if", "len", "(", "url", ".", "Path", ")", ">", "0", "{", "url", ".", "Path", "+=", "\"", "\"", "+", "r", ".", "Url", "\n", "}", "else", "{", "url", ".", "Path", "=", "r", ".", "Url", "\n", "}", "\n", "if", "r", ".", "Api", ".", "PathSuffix", "!=", "\"", "\"", "{", "url", ".", "Path", "+=", "r", ".", "Api", ".", "PathSuffix", "\n", "}", "\n\n", "url", ".", "RawQuery", "=", "r", ".", "QueryValues", ".", "Encode", "(", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "url", ".", "String", "(", ")", ",", "r", ".", "Payload", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "err", "\n", "}", "\n\n", "if", "r", ".", "Api", ".", "BasicAuth", "!=", "nil", "{", "req", ".", "SetBasicAuth", "(", "r", ".", "Api", ".", "BasicAuth", ".", "Username", ",", "r", ".", "Api", ".", "BasicAuth", ".", "Password", ")", "\n", "}", "\n\n", "if", "r", ".", "Headers", "!=", "nil", "{", "for", "k", ",", "_", ":=", "range", "r", ".", "Headers", "{", "req", ".", "Header", ".", "Set", "(", "k", ",", "r", ".", "Headers", ".", "Get", "(", "k", ")", ")", "\n", "}", "\n", "}", "\n\n", "resp", ",", "err", ":=", "r", ".", "Api", ".", "Client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "err", "\n", "}", "\n\n", "r", ".", "Raw", "=", "resp", "\n\n", "if", "resp", ".", "StatusCode", ">=", "400", "{", "return", "r", ",", "nil", "\n", "}", "\n\n", "for", "k", ",", "_", ":=", "range", "r", ".", "Raw", ".", "Header", "{", "r", ".", "SetHeader", "(", "k", ",", "r", ".", "Raw", ".", "Header", ".", "Get", "(", "k", ")", ")", ";", "}", "\n\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "r", ".", "Response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "err", "\n", "}", "\n\n", "return", "r", ",", "nil", "\n", "}" ]
// Main method, opens the connection, sets basic auth, applies headers, // parses response json.
[ "Main", "method", "opens", "the", "connection", "sets", "basic", "auth", "applies", "headers", "parses", "response", "json", "." ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/resource.go#L185-L235
11,857
bndr/gopencils
resource.go
SetPayload
func (r *Resource) SetPayload(args interface{}) io.Reader { var b []byte b, _ = json.Marshal(args) r.SetHeader("Content-Type", "application/json") return bytes.NewBuffer(b) }
go
func (r *Resource) SetPayload(args interface{}) io.Reader { var b []byte b, _ = json.Marshal(args) r.SetHeader("Content-Type", "application/json") return bytes.NewBuffer(b) }
[ "func", "(", "r", "*", "Resource", ")", "SetPayload", "(", "args", "interface", "{", "}", ")", "io", ".", "Reader", "{", "var", "b", "[", "]", "byte", "\n", "b", ",", "_", "=", "json", ".", "Marshal", "(", "args", ")", "\n", "r", ".", "SetHeader", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "bytes", ".", "NewBuffer", "(", "b", ")", "\n", "}" ]
// Sets Payload for current Resource
[ "Sets", "Payload", "for", "current", "Resource" ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/resource.go#L238-L243
11,858
bndr/gopencils
resource.go
SetClient
func (r *Resource) SetClient(c *http.Client) { r.Api.Client = c }
go
func (r *Resource) SetClient(c *http.Client) { r.Api.Client = c }
[ "func", "(", "r", "*", "Resource", ")", "SetClient", "(", "c", "*", "http", ".", "Client", ")", "{", "r", ".", "Api", ".", "Client", "=", "c", "\n", "}" ]
// Overwrites the client that will be used for requests. // For example if you want to use your own client with OAuth2
[ "Overwrites", "the", "client", "that", "will", "be", "used", "for", "requests", ".", "For", "example", "if", "you", "want", "to", "use", "your", "own", "client", "with", "OAuth2" ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/resource.go#L252-L254
11,859
bndr/gopencils
examples/example_oauth.go
landing
func landing(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, config.AuthCodeURL("foo"), http.StatusFound) }
go
func landing(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, config.AuthCodeURL("foo"), http.StatusFound) }
[ "func", "landing", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "http", ".", "Redirect", "(", "w", ",", "r", ",", "config", ".", "AuthCodeURL", "(", "\"", "\"", ")", ",", "http", ".", "StatusFound", ")", "\n", "}" ]
// A landing page redirects to the OAuth provider to get the auth code.
[ "A", "landing", "page", "redirects", "to", "the", "OAuth", "provider", "to", "get", "the", "auth", "code", "." ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/examples/example_oauth.go#L31-L33
11,860
bndr/gopencils
examples/example_oauth.go
handler
func handler(w http.ResponseWriter, r *http.Request) { t := &oauth2.Transport{Config: config} t.Exchange(r.FormValue("code")) // The Transport now has a valid Token. Create an *http.Client // with which we can make authenticated API requests. c := t.Client() // Now you can pass the authenticated Client to gopencils, and // it will be used to make all the requests api := gopencils.Api("http://your-api-url.com/api/", c) // Create a pointer to our response struct, which will hold the response re := &respStruct{} // Maybe some payload to send along with the request? payload := map[string]interface{}{"Key1": "Value1"} // Perform a GET request // URL Requested: http://your-api-url.com/api/users api.Res("users", re).Get() // Perform a GET request with Querystring querystring := map[string]string{"page": "100"} // URL Requested: http://your-api-url.com/api/users/123/items?page=100 api.Res("users").Id(123).Res("items", re).Get(querystring) // Or perform a POST Request // URL Requested: http://your-api-url.com/api/items/123 with payload as json Data api.Res("items", re).Id(123).Post(payload) }
go
func handler(w http.ResponseWriter, r *http.Request) { t := &oauth2.Transport{Config: config} t.Exchange(r.FormValue("code")) // The Transport now has a valid Token. Create an *http.Client // with which we can make authenticated API requests. c := t.Client() // Now you can pass the authenticated Client to gopencils, and // it will be used to make all the requests api := gopencils.Api("http://your-api-url.com/api/", c) // Create a pointer to our response struct, which will hold the response re := &respStruct{} // Maybe some payload to send along with the request? payload := map[string]interface{}{"Key1": "Value1"} // Perform a GET request // URL Requested: http://your-api-url.com/api/users api.Res("users", re).Get() // Perform a GET request with Querystring querystring := map[string]string{"page": "100"} // URL Requested: http://your-api-url.com/api/users/123/items?page=100 api.Res("users").Id(123).Res("items", re).Get(querystring) // Or perform a POST Request // URL Requested: http://your-api-url.com/api/items/123 with payload as json Data api.Res("items", re).Id(123).Post(payload) }
[ "func", "handler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "t", ":=", "&", "oauth2", ".", "Transport", "{", "Config", ":", "config", "}", "\n", "t", ".", "Exchange", "(", "r", ".", "FormValue", "(", "\"", "\"", ")", ")", "\n", "// The Transport now has a valid Token. Create an *http.Client", "// with which we can make authenticated API requests.", "c", ":=", "t", ".", "Client", "(", ")", "\n\n", "// Now you can pass the authenticated Client to gopencils, and", "// it will be used to make all the requests", "api", ":=", "gopencils", ".", "Api", "(", "\"", "\"", ",", "c", ")", "\n\n", "// Create a pointer to our response struct, which will hold the response", "re", ":=", "&", "respStruct", "{", "}", "\n", "// Maybe some payload to send along with the request?", "payload", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "\"", "\"", "}", "\n\n", "// Perform a GET request", "// URL Requested: http://your-api-url.com/api/users", "api", ".", "Res", "(", "\"", "\"", ",", "re", ")", ".", "Get", "(", ")", "\n\n", "// Perform a GET request with Querystring", "querystring", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", "}", "\n", "// URL Requested: http://your-api-url.com/api/users/123/items?page=100", "api", ".", "Res", "(", "\"", "\"", ")", ".", "Id", "(", "123", ")", ".", "Res", "(", "\"", "\"", ",", "re", ")", ".", "Get", "(", "querystring", ")", "\n\n", "// Or perform a POST Request", "// URL Requested: http://your-api-url.com/api/items/123 with payload as json Data", "api", ".", "Res", "(", "\"", "\"", ",", "re", ")", ".", "Id", "(", "123", ")", ".", "Post", "(", "payload", ")", "\n", "}" ]
// The user will be redirected back to this handler, that takes the // "code" query parameter and Exchanges it for an access token.
[ "The", "user", "will", "be", "redirected", "back", "to", "this", "handler", "that", "takes", "the", "code", "query", "parameter", "and", "Exchanges", "it", "for", "an", "access", "token", "." ]
22e283ad76118c1e1f3812b4a3553809cd434e6a
https://github.com/bndr/gopencils/blob/22e283ad76118c1e1f3812b4a3553809cd434e6a/examples/example_oauth.go#L37-L65
11,861
gmallard/stompngo
senv/senv.go
Login
func Login() string { // Login l := os.Getenv("STOMP_LOGIN") if l != "" { login = l } if l == "NONE" { login = "" } return login }
go
func Login() string { // Login l := os.Getenv("STOMP_LOGIN") if l != "" { login = l } if l == "NONE" { login = "" } return login }
[ "func", "Login", "(", ")", "string", "{", "// Login", "l", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "l", "!=", "\"", "\"", "{", "login", "=", "l", "\n", "}", "\n", "if", "l", "==", "\"", "\"", "{", "login", "=", "\"", "\"", "\n", "}", "\n", "return", "login", "\n", "}" ]
// Login returns a default login ID.
[ "Login", "returns", "a", "default", "login", "ID", "." ]
b61c67049c28a4361e7b2cb69200d9d137411822
https://github.com/gmallard/stompngo/blob/b61c67049c28a4361e7b2cb69200d9d137411822/senv/senv.go#L85-L95
11,862
gmallard/stompngo
senv/senv.go
Nmsgs
func Nmsgs() int { // Number of messages nmLock.Lock() defer nmLock.Unlock() ns := os.Getenv("STOMP_NMSGS") if ns == "" { return nmsgs } n, e := strconv.ParseInt(ns, 10, 0) if e != nil { log.Printf("NMSGS Conversion error: %v\n", e) return nmsgs } nmsgs = int(n) return nmsgs }
go
func Nmsgs() int { // Number of messages nmLock.Lock() defer nmLock.Unlock() ns := os.Getenv("STOMP_NMSGS") if ns == "" { return nmsgs } n, e := strconv.ParseInt(ns, 10, 0) if e != nil { log.Printf("NMSGS Conversion error: %v\n", e) return nmsgs } nmsgs = int(n) return nmsgs }
[ "func", "Nmsgs", "(", ")", "int", "{", "// Number of messages", "nmLock", ".", "Lock", "(", ")", "\n", "defer", "nmLock", ".", "Unlock", "(", ")", "\n", "ns", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "ns", "==", "\"", "\"", "{", "return", "nmsgs", "\n", "}", "\n", "n", ",", "e", ":=", "strconv", ".", "ParseInt", "(", "ns", ",", "10", ",", "0", ")", "\n", "if", "e", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "e", ")", "\n", "return", "nmsgs", "\n", "}", "\n", "nmsgs", "=", "int", "(", "n", ")", "\n", "return", "nmsgs", "\n", "}" ]
// Number of messages
[ "Number", "of", "messages" ]
b61c67049c28a4361e7b2cb69200d9d137411822
https://github.com/gmallard/stompngo/blob/b61c67049c28a4361e7b2cb69200d9d137411822/senv/senv.go#L98-L113
11,863
gmallard/stompngo
senv/senv.go
Passcode
func Passcode() string { // Passcode pc := os.Getenv("STOMP_PASSCODE") if pc != "" { passcode = pc } if pc == "NONE" { passcode = "" } return passcode }
go
func Passcode() string { // Passcode pc := os.Getenv("STOMP_PASSCODE") if pc != "" { passcode = pc } if pc == "NONE" { passcode = "" } return passcode }
[ "func", "Passcode", "(", ")", "string", "{", "// Passcode", "pc", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "pc", "!=", "\"", "\"", "{", "passcode", "=", "pc", "\n", "}", "\n", "if", "pc", "==", "\"", "\"", "{", "passcode", "=", "\"", "\"", "\n", "}", "\n", "return", "passcode", "\n", "}" ]
// Passcode returns a default passcode.
[ "Passcode", "returns", "a", "default", "passcode", "." ]
b61c67049c28a4361e7b2cb69200d9d137411822
https://github.com/gmallard/stompngo/blob/b61c67049c28a4361e7b2cb69200d9d137411822/senv/senv.go#L116-L126
11,864
gmallard/stompngo
senv/senv.go
Vhost
func Vhost() string { // Vhost vhLock.Lock() defer vhLock.Unlock() vh := os.Getenv("STOMP_VHOST") if vh != "" { vhost = vh } else { vhost = Host() } return vhost }
go
func Vhost() string { // Vhost vhLock.Lock() defer vhLock.Unlock() vh := os.Getenv("STOMP_VHOST") if vh != "" { vhost = vh } else { vhost = Host() } return vhost }
[ "func", "Vhost", "(", ")", "string", "{", "// Vhost", "vhLock", ".", "Lock", "(", ")", "\n", "defer", "vhLock", ".", "Unlock", "(", ")", "\n", "vh", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "vh", "!=", "\"", "\"", "{", "vhost", "=", "vh", "\n", "}", "else", "{", "vhost", "=", "Host", "(", ")", "\n", "}", "\n", "return", "vhost", "\n", "}" ]
// Vhost returns a default vhost name.
[ "Vhost", "returns", "a", "default", "vhost", "name", "." ]
b61c67049c28a4361e7b2cb69200d9d137411822
https://github.com/gmallard/stompngo/blob/b61c67049c28a4361e7b2cb69200d9d137411822/senv/senv.go#L170-L181
11,865
toorop/go-bittrex
ws.go
SubscribeExchangeUpdate
func (b *Bittrex) SubscribeExchangeUpdate(market string, dataCh chan<- ExchangeState, stop <-chan bool) error { const timeout = 5 * time.Second client := signalr.NewWebsocketClient() client.OnClientMethod = func(hub string, method string, messages []json.RawMessage) { if hub != WS_HUB || method != "updateExchangeState" { return } parseStates(messages, dataCh, market) } err := doAsyncTimeout(func() error { return client.Connect("https", WS_BASE, []string{WS_HUB}) }, func(err error) { if err == nil { client.Close() } }, timeout) if err != nil { return err } defer client.Close() var msg json.RawMessage err = doAsyncTimeout(func() error { var err error msg, err = subForMarket(client, market) return err }, nil, timeout) if err != nil { return err } var st ExchangeState if err = json.Unmarshal(msg, &st); err != nil { return err } st.Initial = true st.MarketName = market sendStateAsync(dataCh, st) select { case <-stop: case <-client.DisconnectedChannel: } return nil }
go
func (b *Bittrex) SubscribeExchangeUpdate(market string, dataCh chan<- ExchangeState, stop <-chan bool) error { const timeout = 5 * time.Second client := signalr.NewWebsocketClient() client.OnClientMethod = func(hub string, method string, messages []json.RawMessage) { if hub != WS_HUB || method != "updateExchangeState" { return } parseStates(messages, dataCh, market) } err := doAsyncTimeout(func() error { return client.Connect("https", WS_BASE, []string{WS_HUB}) }, func(err error) { if err == nil { client.Close() } }, timeout) if err != nil { return err } defer client.Close() var msg json.RawMessage err = doAsyncTimeout(func() error { var err error msg, err = subForMarket(client, market) return err }, nil, timeout) if err != nil { return err } var st ExchangeState if err = json.Unmarshal(msg, &st); err != nil { return err } st.Initial = true st.MarketName = market sendStateAsync(dataCh, st) select { case <-stop: case <-client.DisconnectedChannel: } return nil }
[ "func", "(", "b", "*", "Bittrex", ")", "SubscribeExchangeUpdate", "(", "market", "string", ",", "dataCh", "chan", "<-", "ExchangeState", ",", "stop", "<-", "chan", "bool", ")", "error", "{", "const", "timeout", "=", "5", "*", "time", ".", "Second", "\n", "client", ":=", "signalr", ".", "NewWebsocketClient", "(", ")", "\n", "client", ".", "OnClientMethod", "=", "func", "(", "hub", "string", ",", "method", "string", ",", "messages", "[", "]", "json", ".", "RawMessage", ")", "{", "if", "hub", "!=", "WS_HUB", "||", "method", "!=", "\"", "\"", "{", "return", "\n", "}", "\n", "parseStates", "(", "messages", ",", "dataCh", ",", "market", ")", "\n", "}", "\n", "err", ":=", "doAsyncTimeout", "(", "func", "(", ")", "error", "{", "return", "client", ".", "Connect", "(", "\"", "\"", ",", "WS_BASE", ",", "[", "]", "string", "{", "WS_HUB", "}", ")", "\n", "}", ",", "func", "(", "err", "error", ")", "{", "if", "err", "==", "nil", "{", "client", ".", "Close", "(", ")", "\n", "}", "\n", "}", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "client", ".", "Close", "(", ")", "\n", "var", "msg", "json", ".", "RawMessage", "\n", "err", "=", "doAsyncTimeout", "(", "func", "(", ")", "error", "{", "var", "err", "error", "\n", "msg", ",", "err", "=", "subForMarket", "(", "client", ",", "market", ")", "\n", "return", "err", "\n", "}", ",", "nil", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "st", "ExchangeState", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "msg", ",", "&", "st", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "st", ".", "Initial", "=", "true", "\n", "st", ".", "MarketName", "=", "market", "\n", "sendStateAsync", "(", "dataCh", ",", "st", ")", "\n", "select", "{", "case", "<-", "stop", ":", "case", "<-", "client", ".", "DisconnectedChannel", ":", "}", "\n", "return", "nil", "\n", "}" ]
// SubscribeExchangeUpdate subscribes for updates of the market. // Updates will be sent to dataCh. // To stop subscription, send to, or close 'stop'.
[ "SubscribeExchangeUpdate", "subscribes", "for", "updates", "of", "the", "market", ".", "Updates", "will", "be", "sent", "to", "dataCh", ".", "To", "stop", "subscription", "send", "to", "or", "close", "stop", "." ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/ws.go#L86-L127
11,866
toorop/go-bittrex
client.go
NewClientWithCustomHttpConfig
func NewClientWithCustomHttpConfig(apiKey, apiSecret string, httpClient *http.Client) (c *client) { timeout := httpClient.Timeout if timeout <= 0 { timeout = 30 * time.Second } return &client{apiKey, apiSecret, httpClient, timeout, false} }
go
func NewClientWithCustomHttpConfig(apiKey, apiSecret string, httpClient *http.Client) (c *client) { timeout := httpClient.Timeout if timeout <= 0 { timeout = 30 * time.Second } return &client{apiKey, apiSecret, httpClient, timeout, false} }
[ "func", "NewClientWithCustomHttpConfig", "(", "apiKey", ",", "apiSecret", "string", ",", "httpClient", "*", "http", ".", "Client", ")", "(", "c", "*", "client", ")", "{", "timeout", ":=", "httpClient", ".", "Timeout", "\n", "if", "timeout", "<=", "0", "{", "timeout", "=", "30", "*", "time", ".", "Second", "\n", "}", "\n", "return", "&", "client", "{", "apiKey", ",", "apiSecret", ",", "httpClient", ",", "timeout", ",", "false", "}", "\n", "}" ]
// NewClientWithCustomHttpConfig returns a new Bittrex HTTP client using the predefined http client
[ "NewClientWithCustomHttpConfig", "returns", "a", "new", "Bittrex", "HTTP", "client", "using", "the", "predefined", "http", "client" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/client.go#L31-L37
11,867
toorop/go-bittrex
client.go
doTimeoutRequest
func (c *client) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) { // Do the request in the background so we can check the timeout type result struct { resp *http.Response err error } done := make(chan result, 1) go func() { if c.debug { c.dumpRequest(req) } resp, err := c.httpClient.Do(req) if c.debug { c.dumpResponse(resp) } done <- result{resp, err} }() // Wait for the read or the timeout select { case r := <-done: return r.resp, r.err case <-timer.C: return nil, errors.New("timeout on reading data from Bittrex API") } }
go
func (c *client) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) { // Do the request in the background so we can check the timeout type result struct { resp *http.Response err error } done := make(chan result, 1) go func() { if c.debug { c.dumpRequest(req) } resp, err := c.httpClient.Do(req) if c.debug { c.dumpResponse(resp) } done <- result{resp, err} }() // Wait for the read or the timeout select { case r := <-done: return r.resp, r.err case <-timer.C: return nil, errors.New("timeout on reading data from Bittrex API") } }
[ "func", "(", "c", "*", "client", ")", "doTimeoutRequest", "(", "timer", "*", "time", ".", "Timer", ",", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "// Do the request in the background so we can check the timeout", "type", "result", "struct", "{", "resp", "*", "http", ".", "Response", "\n", "err", "error", "\n", "}", "\n", "done", ":=", "make", "(", "chan", "result", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "if", "c", ".", "debug", "{", "c", ".", "dumpRequest", "(", "req", ")", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "httpClient", ".", "Do", "(", "req", ")", "\n", "if", "c", ".", "debug", "{", "c", ".", "dumpResponse", "(", "resp", ")", "\n", "}", "\n", "done", "<-", "result", "{", "resp", ",", "err", "}", "\n", "}", "(", ")", "\n", "// Wait for the read or the timeout", "select", "{", "case", "r", ":=", "<-", "done", ":", "return", "r", ".", "resp", ",", "r", ".", "err", "\n", "case", "<-", "timer", ".", "C", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// doTimeoutRequest do a HTTP request with timeout
[ "doTimeoutRequest", "do", "a", "HTTP", "request", "with", "timeout" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/client.go#L71-L95
11,868
toorop/go-bittrex
client.go
do
func (c *client) do(method string, resource string, payload string, authNeeded bool) (response []byte, err error) { connectTimer := time.NewTimer(c.httpTimeout) var rawurl string if strings.HasPrefix(resource, "http") { rawurl = resource } else { rawurl = fmt.Sprintf("%s%s/%s", API_BASE, API_VERSION, resource) } req, err := http.NewRequest(method, rawurl, strings.NewReader(payload)) if err != nil { return } if method == "POST" || method == "PUT" { req.Header.Add("Content-Type", "application/json;charset=utf-8") } req.Header.Add("Accept", "application/json") // Auth if authNeeded { if len(c.apiKey) == 0 || len(c.apiSecret) == 0 { err = errors.New("You need to set API Key and API Secret to call this method") return } nonce := time.Now().UnixNano() q := req.URL.Query() q.Set("apikey", c.apiKey) q.Set("nonce", fmt.Sprintf("%d", nonce)) req.URL.RawQuery = q.Encode() mac := hmac.New(sha512.New, []byte(c.apiSecret)) _, err = mac.Write([]byte(req.URL.String())) sig := hex.EncodeToString(mac.Sum(nil)) req.Header.Add("apisign", sig) } resp, err := c.doTimeoutRequest(connectTimer, req) if err != nil { return } defer resp.Body.Close() response, err = ioutil.ReadAll(resp.Body) //fmt.Println(fmt.Sprintf("reponse %s", response), err) if err != nil { return response, err } if resp.StatusCode != 200 { err = errors.New(resp.Status) } return response, err }
go
func (c *client) do(method string, resource string, payload string, authNeeded bool) (response []byte, err error) { connectTimer := time.NewTimer(c.httpTimeout) var rawurl string if strings.HasPrefix(resource, "http") { rawurl = resource } else { rawurl = fmt.Sprintf("%s%s/%s", API_BASE, API_VERSION, resource) } req, err := http.NewRequest(method, rawurl, strings.NewReader(payload)) if err != nil { return } if method == "POST" || method == "PUT" { req.Header.Add("Content-Type", "application/json;charset=utf-8") } req.Header.Add("Accept", "application/json") // Auth if authNeeded { if len(c.apiKey) == 0 || len(c.apiSecret) == 0 { err = errors.New("You need to set API Key and API Secret to call this method") return } nonce := time.Now().UnixNano() q := req.URL.Query() q.Set("apikey", c.apiKey) q.Set("nonce", fmt.Sprintf("%d", nonce)) req.URL.RawQuery = q.Encode() mac := hmac.New(sha512.New, []byte(c.apiSecret)) _, err = mac.Write([]byte(req.URL.String())) sig := hex.EncodeToString(mac.Sum(nil)) req.Header.Add("apisign", sig) } resp, err := c.doTimeoutRequest(connectTimer, req) if err != nil { return } defer resp.Body.Close() response, err = ioutil.ReadAll(resp.Body) //fmt.Println(fmt.Sprintf("reponse %s", response), err) if err != nil { return response, err } if resp.StatusCode != 200 { err = errors.New(resp.Status) } return response, err }
[ "func", "(", "c", "*", "client", ")", "do", "(", "method", "string", ",", "resource", "string", ",", "payload", "string", ",", "authNeeded", "bool", ")", "(", "response", "[", "]", "byte", ",", "err", "error", ")", "{", "connectTimer", ":=", "time", ".", "NewTimer", "(", "c", ".", "httpTimeout", ")", "\n\n", "var", "rawurl", "string", "\n", "if", "strings", ".", "HasPrefix", "(", "resource", ",", "\"", "\"", ")", "{", "rawurl", "=", "resource", "\n", "}", "else", "{", "rawurl", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "API_BASE", ",", "API_VERSION", ",", "resource", ")", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "rawurl", ",", "strings", ".", "NewReader", "(", "payload", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "method", "==", "\"", "\"", "||", "method", "==", "\"", "\"", "{", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Auth", "if", "authNeeded", "{", "if", "len", "(", "c", ".", "apiKey", ")", "==", "0", "||", "len", "(", "c", ".", "apiSecret", ")", "==", "0", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "nonce", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "q", ":=", "req", ".", "URL", ".", "Query", "(", ")", "\n", "q", ".", "Set", "(", "\"", "\"", ",", "c", ".", "apiKey", ")", "\n", "q", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "nonce", ")", ")", "\n", "req", ".", "URL", ".", "RawQuery", "=", "q", ".", "Encode", "(", ")", "\n", "mac", ":=", "hmac", ".", "New", "(", "sha512", ".", "New", ",", "[", "]", "byte", "(", "c", ".", "apiSecret", ")", ")", "\n", "_", ",", "err", "=", "mac", ".", "Write", "(", "[", "]", "byte", "(", "req", ".", "URL", ".", "String", "(", ")", ")", ")", "\n", "sig", ":=", "hex", ".", "EncodeToString", "(", "mac", ".", "Sum", "(", "nil", ")", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "sig", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "c", ".", "doTimeoutRequest", "(", "connectTimer", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "response", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "//fmt.Println(fmt.Sprintf(\"reponse %s\", response), err)", "if", "err", "!=", "nil", "{", "return", "response", ",", "err", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "200", "{", "err", "=", "errors", ".", "New", "(", "resp", ".", "Status", ")", "\n", "}", "\n", "return", "response", ",", "err", "\n", "}" ]
// do prepare and process HTTP request to Bittrex API
[ "do", "prepare", "and", "process", "HTTP", "request", "to", "Bittrex", "API" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/client.go#L98-L149
11,869
toorop/go-bittrex
bittrex.go
New
func New(apiKey, apiSecret string) *Bittrex { client := NewClient(apiKey, apiSecret) return &Bittrex{client} }
go
func New(apiKey, apiSecret string) *Bittrex { client := NewClient(apiKey, apiSecret) return &Bittrex{client} }
[ "func", "New", "(", "apiKey", ",", "apiSecret", "string", ")", "*", "Bittrex", "{", "client", ":=", "NewClient", "(", "apiKey", ",", "apiSecret", ")", "\n", "return", "&", "Bittrex", "{", "client", "}", "\n", "}" ]
// New returns an instantiated bittrex struct
[ "New", "returns", "an", "instantiated", "bittrex", "struct" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L23-L26
11,870
toorop/go-bittrex
bittrex.go
NewWithCustomHttpClient
func NewWithCustomHttpClient(apiKey, apiSecret string, httpClient *http.Client) *Bittrex { client := NewClientWithCustomHttpConfig(apiKey, apiSecret, httpClient) return &Bittrex{client} }
go
func NewWithCustomHttpClient(apiKey, apiSecret string, httpClient *http.Client) *Bittrex { client := NewClientWithCustomHttpConfig(apiKey, apiSecret, httpClient) return &Bittrex{client} }
[ "func", "NewWithCustomHttpClient", "(", "apiKey", ",", "apiSecret", "string", ",", "httpClient", "*", "http", ".", "Client", ")", "*", "Bittrex", "{", "client", ":=", "NewClientWithCustomHttpConfig", "(", "apiKey", ",", "apiSecret", ",", "httpClient", ")", "\n", "return", "&", "Bittrex", "{", "client", "}", "\n", "}" ]
// NewWithCustomHttpClient returns an instantiated bittrex struct with custom http client
[ "NewWithCustomHttpClient", "returns", "an", "instantiated", "bittrex", "struct", "with", "custom", "http", "client" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L29-L32
11,871
toorop/go-bittrex
bittrex.go
NewWithCustomTimeout
func NewWithCustomTimeout(apiKey, apiSecret string, timeout time.Duration) *Bittrex { client := NewClientWithCustomTimeout(apiKey, apiSecret, timeout) return &Bittrex{client} }
go
func NewWithCustomTimeout(apiKey, apiSecret string, timeout time.Duration) *Bittrex { client := NewClientWithCustomTimeout(apiKey, apiSecret, timeout) return &Bittrex{client} }
[ "func", "NewWithCustomTimeout", "(", "apiKey", ",", "apiSecret", "string", ",", "timeout", "time", ".", "Duration", ")", "*", "Bittrex", "{", "client", ":=", "NewClientWithCustomTimeout", "(", "apiKey", ",", "apiSecret", ",", "timeout", ")", "\n", "return", "&", "Bittrex", "{", "client", "}", "\n", "}" ]
// NewWithCustomTimeout returns an instantiated bittrex struct with custom timeout
[ "NewWithCustomTimeout", "returns", "an", "instantiated", "bittrex", "struct", "with", "custom", "timeout" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L35-L38
11,872
toorop/go-bittrex
bittrex.go
handleErr
func handleErr(r jsonResponse) error { if !r.Success { return errors.New(r.Message) } return nil }
go
func handleErr(r jsonResponse) error { if !r.Success { return errors.New(r.Message) } return nil }
[ "func", "handleErr", "(", "r", "jsonResponse", ")", "error", "{", "if", "!", "r", ".", "Success", "{", "return", "errors", ".", "New", "(", "r", ".", "Message", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// handleErr gets JSON response from Bittrex API en deal with error
[ "handleErr", "gets", "JSON", "response", "from", "Bittrex", "API", "en", "deal", "with", "error" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L41-L46
11,873
toorop/go-bittrex
bittrex.go
GetDistribution
func (b *Bittrex) GetDistribution(market string) (distribution Distribution, err error) { r, err := b.client.do("GET", "https://bittrex.com/Api/v2.0/pub/currency/GetBalanceDistribution?currencyName="+strings.ToUpper(market), "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &distribution) return }
go
func (b *Bittrex) GetDistribution(market string) (distribution Distribution, err error) { r, err := b.client.do("GET", "https://bittrex.com/Api/v2.0/pub/currency/GetBalanceDistribution?currencyName="+strings.ToUpper(market), "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &distribution) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetDistribution", "(", "market", "string", ")", "(", "distribution", "Distribution", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "\"", "\"", "+", "strings", ".", "ToUpper", "(", "market", ")", ",", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "distribution", ")", "\n", "return", "\n\n", "}" ]
// GetDistribution is used to get the distribution.
[ "GetDistribution", "is", "used", "to", "get", "the", "distribution", "." ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L59-L76
11,874
toorop/go-bittrex
bittrex.go
GetCurrencies
func (b *Bittrex) GetCurrencies() (currencies []Currency, err error) { r, err := b.client.do("GET", "public/getcurrencies", "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &currencies) return }
go
func (b *Bittrex) GetCurrencies() (currencies []Currency, err error) { r, err := b.client.do("GET", "public/getcurrencies", "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &currencies) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetCurrencies", "(", ")", "(", "currencies", "[", "]", "Currency", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "currencies", ")", "\n", "return", "\n", "}" ]
// GetCurrencies is used to get all supported currencies at Bittrex along with other meta data.
[ "GetCurrencies", "is", "used", "to", "get", "all", "supported", "currencies", "at", "Bittrex", "along", "with", "other", "meta", "data", "." ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L79-L93
11,875
toorop/go-bittrex
bittrex.go
GetMarkets
func (b *Bittrex) GetMarkets() (markets []Market, err error) { r, err := b.client.do("GET", "public/getmarkets", "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &markets) return }
go
func (b *Bittrex) GetMarkets() (markets []Market, err error) { r, err := b.client.do("GET", "public/getmarkets", "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &markets) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetMarkets", "(", ")", "(", "markets", "[", "]", "Market", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "markets", ")", "\n", "return", "\n", "}" ]
// GetMarkets is used to get the open and available trading markets at Bittrex along with other meta data.
[ "GetMarkets", "is", "used", "to", "get", "the", "open", "and", "available", "trading", "markets", "at", "Bittrex", "along", "with", "other", "meta", "data", "." ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L96-L110
11,876
toorop/go-bittrex
bittrex.go
GetTicker
func (b *Bittrex) GetTicker(market string) (ticker Ticker, err error) { r, err := b.client.do("GET", "public/getticker?market="+strings.ToUpper(market), "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &ticker) return }
go
func (b *Bittrex) GetTicker(market string) (ticker Ticker, err error) { r, err := b.client.do("GET", "public/getticker?market="+strings.ToUpper(market), "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &ticker) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetTicker", "(", "market", "string", ")", "(", "ticker", "Ticker", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "\"", "\"", "+", "strings", ".", "ToUpper", "(", "market", ")", ",", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "ticker", ")", "\n", "return", "\n", "}" ]
// GetTicker is used to get the current ticker values for a market.
[ "GetTicker", "is", "used", "to", "get", "the", "current", "ticker", "values", "for", "a", "market", "." ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L113-L127
11,877
toorop/go-bittrex
bittrex.go
GetMarketSummaries
func (b *Bittrex) GetMarketSummaries() (marketSummaries []MarketSummary, err error) { r, err := b.client.do("GET", "public/getmarketsummaries", "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &marketSummaries) return }
go
func (b *Bittrex) GetMarketSummaries() (marketSummaries []MarketSummary, err error) { r, err := b.client.do("GET", "public/getmarketsummaries", "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &marketSummaries) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetMarketSummaries", "(", ")", "(", "marketSummaries", "[", "]", "MarketSummary", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "marketSummaries", ")", "\n", "return", "\n", "}" ]
// GetMarketSummaries is used to get the last 24 hour summary of all active exchanges
[ "GetMarketSummaries", "is", "used", "to", "get", "the", "last", "24", "hour", "summary", "of", "all", "active", "exchanges" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L130-L144
11,878
toorop/go-bittrex
bittrex.go
GetMarketSummary
func (b *Bittrex) GetMarketSummary(market string) (marketSummary []MarketSummary, err error) { r, err := b.client.do("GET", fmt.Sprintf("public/getmarketsummary?market=%s", strings.ToUpper(market)), "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &marketSummary) return }
go
func (b *Bittrex) GetMarketSummary(market string) (marketSummary []MarketSummary, err error) { r, err := b.client.do("GET", fmt.Sprintf("public/getmarketsummary?market=%s", strings.ToUpper(market)), "", false) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &marketSummary) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetMarketSummary", "(", "market", "string", ")", "(", "marketSummary", "[", "]", "MarketSummary", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "ToUpper", "(", "market", ")", ")", ",", "\"", "\"", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "marketSummary", ")", "\n", "return", "\n", "}" ]
// GetMarketSummary is used to get the last 24 hour summary for a given market
[ "GetMarketSummary", "is", "used", "to", "get", "the", "last", "24", "hour", "summary", "for", "a", "given", "market" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L147-L161
11,879
toorop/go-bittrex
bittrex.go
BuyLimit
func (b *Bittrex) BuyLimit(market string, quantity, rate decimal.Decimal) (uuid string, err error) { r, err := b.client.do("GET", fmt.Sprintf("market/buylimit?market=%s&quantity=%s&rate=%s", market, quantity, rate), "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } var u Uuid err = json.Unmarshal(response.Result, &u) uuid = u.Id return }
go
func (b *Bittrex) BuyLimit(market string, quantity, rate decimal.Decimal) (uuid string, err error) { r, err := b.client.do("GET", fmt.Sprintf("market/buylimit?market=%s&quantity=%s&rate=%s", market, quantity, rate), "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } var u Uuid err = json.Unmarshal(response.Result, &u) uuid = u.Id return }
[ "func", "(", "b", "*", "Bittrex", ")", "BuyLimit", "(", "market", "string", ",", "quantity", ",", "rate", "decimal", ".", "Decimal", ")", "(", "uuid", "string", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "market", ",", "quantity", ",", "rate", ")", ",", "\"", "\"", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "u", "Uuid", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "u", ")", "\n", "uuid", "=", "u", ".", "Id", "\n", "return", "\n", "}" ]
// Market // BuyLimit is used to place a limited buy order in a specific market.
[ "Market", "BuyLimit", "is", "used", "to", "place", "a", "limited", "buy", "order", "in", "a", "specific", "market", "." ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L237-L253
11,880
toorop/go-bittrex
bittrex.go
CancelOrder
func (b *Bittrex) CancelOrder(orderID string) (err error) { r, err := b.client.do("GET", "market/cancel?uuid="+orderID, "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } err = handleErr(response) return }
go
func (b *Bittrex) CancelOrder(orderID string) (err error) { r, err := b.client.do("GET", "market/cancel?uuid="+orderID, "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } err = handleErr(response) return }
[ "func", "(", "b", "*", "Bittrex", ")", "CancelOrder", "(", "orderID", "string", ")", "(", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "\"", "\"", "+", "orderID", ",", "\"", "\"", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "handleErr", "(", "response", ")", "\n", "return", "\n", "}" ]
// CancelOrder is used to cancel a buy or sell order.
[ "CancelOrder", "is", "used", "to", "cancel", "a", "buy", "or", "sell", "order", "." ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L275-L286
11,881
toorop/go-bittrex
bittrex.go
GetOpenOrders
func (b *Bittrex) GetOpenOrders(market string) (openOrders []Order, err error) { resource := "market/getopenorders" if market != "all" { resource += "?market=" + strings.ToUpper(market) } r, err := b.client.do("GET", resource, "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = json.Unmarshal(r, &response); err != nil { return } err = json.Unmarshal(response.Result, &openOrders) return }
go
func (b *Bittrex) GetOpenOrders(market string) (openOrders []Order, err error) { resource := "market/getopenorders" if market != "all" { resource += "?market=" + strings.ToUpper(market) } r, err := b.client.do("GET", resource, "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = json.Unmarshal(r, &response); err != nil { return } err = json.Unmarshal(response.Result, &openOrders) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetOpenOrders", "(", "market", "string", ")", "(", "openOrders", "[", "]", "Order", ",", "err", "error", ")", "{", "resource", ":=", "\"", "\"", "\n", "if", "market", "!=", "\"", "\"", "{", "resource", "+=", "\"", "\"", "+", "strings", ".", "ToUpper", "(", "market", ")", "\n", "}", "\n", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "resource", ",", "\"", "\"", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "openOrders", ")", "\n", "return", "\n", "}" ]
// GetOpenOrders returns orders that you currently have opened. // If market is set to "all", GetOpenOrders return all orders // If market is set to a specific order, GetOpenOrders return orders for this market
[ "GetOpenOrders", "returns", "orders", "that", "you", "currently", "have", "opened", ".", "If", "market", "is", "set", "to", "all", "GetOpenOrders", "return", "all", "orders", "If", "market", "is", "set", "to", "a", "specific", "order", "GetOpenOrders", "return", "orders", "for", "this", "market" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L291-L309
11,882
toorop/go-bittrex
bittrex.go
GetBalances
func (b *Bittrex) GetBalances() (balances []Balance, err error) { r, err := b.client.do("GET", "account/getbalances", "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &balances) return }
go
func (b *Bittrex) GetBalances() (balances []Balance, err error) { r, err := b.client.do("GET", "account/getbalances", "", true) if err != nil { return } var response jsonResponse if err = json.Unmarshal(r, &response); err != nil { return } if err = handleErr(response); err != nil { return } err = json.Unmarshal(response.Result, &balances) return }
[ "func", "(", "b", "*", "Bittrex", ")", "GetBalances", "(", ")", "(", "balances", "[", "]", "Balance", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "b", ".", "client", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "response", "jsonResponse", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "r", ",", "&", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "handleErr", "(", "response", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "response", ".", "Result", ",", "&", "balances", ")", "\n", "return", "\n", "}" ]
// Account // GetBalances is used to retrieve all balances from your account
[ "Account", "GetBalances", "is", "used", "to", "retrieve", "all", "balances", "from", "your", "account" ]
b4a20c2db009afea9ceca5d1592e34618ce3b324
https://github.com/toorop/go-bittrex/blob/b4a20c2db009afea9ceca5d1592e34618ce3b324/bittrex.go#L314-L328
11,883
tstranex/u2f
register.go
Register
func Register(resp RegisterResponse, c Challenge, config *Config) (*Registration, error) { if config == nil { config = &Config{} } if time.Now().Sub(c.Timestamp) > timeout { return nil, errors.New("u2f: challenge has expired") } regData, err := decodeBase64(resp.RegistrationData) if err != nil { return nil, err } clientData, err := decodeBase64(resp.ClientData) if err != nil { return nil, err } reg, sig, err := parseRegistration(regData) if err != nil { return nil, err } if err := verifyClientData(clientData, c); err != nil { return nil, err } if err := verifyAttestationCert(*reg, config); err != nil { return nil, err } if err := verifyRegistrationSignature(*reg, sig, c.AppID, clientData); err != nil { return nil, err } return reg, nil }
go
func Register(resp RegisterResponse, c Challenge, config *Config) (*Registration, error) { if config == nil { config = &Config{} } if time.Now().Sub(c.Timestamp) > timeout { return nil, errors.New("u2f: challenge has expired") } regData, err := decodeBase64(resp.RegistrationData) if err != nil { return nil, err } clientData, err := decodeBase64(resp.ClientData) if err != nil { return nil, err } reg, sig, err := parseRegistration(regData) if err != nil { return nil, err } if err := verifyClientData(clientData, c); err != nil { return nil, err } if err := verifyAttestationCert(*reg, config); err != nil { return nil, err } if err := verifyRegistrationSignature(*reg, sig, c.AppID, clientData); err != nil { return nil, err } return reg, nil }
[ "func", "Register", "(", "resp", "RegisterResponse", ",", "c", "Challenge", ",", "config", "*", "Config", ")", "(", "*", "Registration", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "config", "=", "&", "Config", "{", "}", "\n", "}", "\n\n", "if", "time", ".", "Now", "(", ")", ".", "Sub", "(", "c", ".", "Timestamp", ")", ">", "timeout", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "regData", ",", "err", ":=", "decodeBase64", "(", "resp", ".", "RegistrationData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "clientData", ",", "err", ":=", "decodeBase64", "(", "resp", ".", "ClientData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "reg", ",", "sig", ",", "err", ":=", "parseRegistration", "(", "regData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "verifyClientData", "(", "clientData", ",", "c", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "verifyAttestationCert", "(", "*", "reg", ",", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "verifyRegistrationSignature", "(", "*", "reg", ",", "sig", ",", "c", ".", "AppID", ",", "clientData", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "reg", ",", "nil", "\n", "}" ]
// Register validates a RegisterResponse message to enrol a new token. // An error is returned if any part of the response fails to validate. // The returned Registration should be stored by the caller.
[ "Register", "validates", "a", "RegisterResponse", "message", "to", "enrol", "a", "new", "token", ".", "An", "error", "is", "returned", "if", "any", "part", "of", "the", "response", "fails", "to", "validate", ".", "The", "returned", "Registration", "should", "be", "stored", "by", "the", "caller", "." ]
d21a03e0b1d9fc1df59ff54e7a513655c1748b0c
https://github.com/tstranex/u2f/blob/d21a03e0b1d9fc1df59ff54e7a513655c1748b0c/register.go#L49-L86
11,884
tstranex/u2f
register.go
UnmarshalBinary
func (r *Registration) UnmarshalBinary(data []byte) error { reg, _, err := parseRegistration(data) if err != nil { return err } *r = *reg return nil }
go
func (r *Registration) UnmarshalBinary(data []byte) error { reg, _, err := parseRegistration(data) if err != nil { return err } *r = *reg return nil }
[ "func", "(", "r", "*", "Registration", ")", "UnmarshalBinary", "(", "data", "[", "]", "byte", ")", "error", "{", "reg", ",", "_", ",", "err", ":=", "parseRegistration", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "r", "=", "*", "reg", "\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary implements encoding.BinaryMarshaler.
[ "UnmarshalBinary", "implements", "encoding", ".", "BinaryMarshaler", "." ]
d21a03e0b1d9fc1df59ff54e7a513655c1748b0c
https://github.com/tstranex/u2f/blob/d21a03e0b1d9fc1df59ff54e7a513655c1748b0c/register.go#L139-L146
11,885
tstranex/u2f
register.go
NewWebRegisterRequest
func NewWebRegisterRequest(c *Challenge, regs []Registration) *WebRegisterRequest { req := RegisterRequest{ Version: u2fVersion, Challenge: encodeBase64(c.Challenge), } rr := WebRegisterRequest{ AppID: c.AppID, RegisterRequests: []RegisterRequest{req}, } for _, r := range regs { rk := getRegisteredKey(c.AppID, r) rr.RegisteredKeys = append(rr.RegisteredKeys, rk) } return &rr }
go
func NewWebRegisterRequest(c *Challenge, regs []Registration) *WebRegisterRequest { req := RegisterRequest{ Version: u2fVersion, Challenge: encodeBase64(c.Challenge), } rr := WebRegisterRequest{ AppID: c.AppID, RegisterRequests: []RegisterRequest{req}, } for _, r := range regs { rk := getRegisteredKey(c.AppID, r) rr.RegisteredKeys = append(rr.RegisteredKeys, rk) } return &rr }
[ "func", "NewWebRegisterRequest", "(", "c", "*", "Challenge", ",", "regs", "[", "]", "Registration", ")", "*", "WebRegisterRequest", "{", "req", ":=", "RegisterRequest", "{", "Version", ":", "u2fVersion", ",", "Challenge", ":", "encodeBase64", "(", "c", ".", "Challenge", ")", ",", "}", "\n\n", "rr", ":=", "WebRegisterRequest", "{", "AppID", ":", "c", ".", "AppID", ",", "RegisterRequests", ":", "[", "]", "RegisterRequest", "{", "req", "}", ",", "}", "\n\n", "for", "_", ",", "r", ":=", "range", "regs", "{", "rk", ":=", "getRegisteredKey", "(", "c", ".", "AppID", ",", "r", ")", "\n", "rr", ".", "RegisteredKeys", "=", "append", "(", "rr", ".", "RegisteredKeys", ",", "rk", ")", "\n", "}", "\n\n", "return", "&", "rr", "\n", "}" ]
// NewWebRegisterRequest creates a request to enrol a new token. // regs is the list of the user's existing registration. The browser will // refuse to re-register a device if it has an existing registration.
[ "NewWebRegisterRequest", "creates", "a", "request", "to", "enrol", "a", "new", "token", ".", "regs", "is", "the", "list", "of", "the", "user", "s", "existing", "registration", ".", "The", "browser", "will", "refuse", "to", "re", "-", "register", "a", "device", "if", "it", "has", "an", "existing", "registration", "." ]
d21a03e0b1d9fc1df59ff54e7a513655c1748b0c
https://github.com/tstranex/u2f/blob/d21a03e0b1d9fc1df59ff54e7a513655c1748b0c/register.go#L213-L230
11,886
tstranex/u2f
auth.go
SignRequest
func (c *Challenge) SignRequest(regs []Registration) *WebSignRequest { var sr WebSignRequest sr.AppID = c.AppID sr.Challenge = encodeBase64(c.Challenge) for _, r := range regs { rk := getRegisteredKey(c.AppID, r) sr.RegisteredKeys = append(sr.RegisteredKeys, rk) } return &sr }
go
func (c *Challenge) SignRequest(regs []Registration) *WebSignRequest { var sr WebSignRequest sr.AppID = c.AppID sr.Challenge = encodeBase64(c.Challenge) for _, r := range regs { rk := getRegisteredKey(c.AppID, r) sr.RegisteredKeys = append(sr.RegisteredKeys, rk) } return &sr }
[ "func", "(", "c", "*", "Challenge", ")", "SignRequest", "(", "regs", "[", "]", "Registration", ")", "*", "WebSignRequest", "{", "var", "sr", "WebSignRequest", "\n", "sr", ".", "AppID", "=", "c", ".", "AppID", "\n", "sr", ".", "Challenge", "=", "encodeBase64", "(", "c", ".", "Challenge", ")", "\n", "for", "_", ",", "r", ":=", "range", "regs", "{", "rk", ":=", "getRegisteredKey", "(", "c", ".", "AppID", ",", "r", ")", "\n", "sr", ".", "RegisteredKeys", "=", "append", "(", "sr", ".", "RegisteredKeys", ",", "rk", ")", "\n", "}", "\n", "return", "&", "sr", "\n", "}" ]
// SignRequest creates a request to initiate an authentication.
[ "SignRequest", "creates", "a", "request", "to", "initiate", "an", "authentication", "." ]
d21a03e0b1d9fc1df59ff54e7a513655c1748b0c
https://github.com/tstranex/u2f/blob/d21a03e0b1d9fc1df59ff54e7a513655c1748b0c/auth.go#L18-L27
11,887
tstranex/u2f
util.go
NewChallenge
func NewChallenge(appID string, trustedFacets []string) (*Challenge, error) { challenge := make([]byte, 32) n, err := rand.Read(challenge) if err != nil { return nil, err } if n != 32 { return nil, errors.New("u2f: unable to generate random bytes") } var c Challenge c.Challenge = challenge c.Timestamp = time.Now() c.AppID = appID c.TrustedFacets = trustedFacets return &c, nil }
go
func NewChallenge(appID string, trustedFacets []string) (*Challenge, error) { challenge := make([]byte, 32) n, err := rand.Read(challenge) if err != nil { return nil, err } if n != 32 { return nil, errors.New("u2f: unable to generate random bytes") } var c Challenge c.Challenge = challenge c.Timestamp = time.Now() c.AppID = appID c.TrustedFacets = trustedFacets return &c, nil }
[ "func", "NewChallenge", "(", "appID", "string", ",", "trustedFacets", "[", "]", "string", ")", "(", "*", "Challenge", ",", "error", ")", "{", "challenge", ":=", "make", "(", "[", "]", "byte", ",", "32", ")", "\n", "n", ",", "err", ":=", "rand", ".", "Read", "(", "challenge", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "n", "!=", "32", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "c", "Challenge", "\n", "c", ".", "Challenge", "=", "challenge", "\n", "c", ".", "Timestamp", "=", "time", ".", "Now", "(", ")", "\n", "c", ".", "AppID", "=", "appID", "\n", "c", ".", "TrustedFacets", "=", "trustedFacets", "\n", "return", "&", "c", ",", "nil", "\n", "}" ]
// NewChallenge generates a challenge for the given application.
[ "NewChallenge", "generates", "a", "challenge", "for", "the", "given", "application", "." ]
d21a03e0b1d9fc1df59ff54e7a513655c1748b0c
https://github.com/tstranex/u2f/blob/d21a03e0b1d9fc1df59ff54e7a513655c1748b0c/util.go#L83-L99
11,888
bep/debounce
debounce.go
New
func New(after time.Duration) func(f func()) { d := &debouncer{after: after} return func(f func()) { d.add(f) } }
go
func New(after time.Duration) func(f func()) { d := &debouncer{after: after} return func(f func()) { d.add(f) } }
[ "func", "New", "(", "after", "time", ".", "Duration", ")", "func", "(", "f", "func", "(", ")", ")", "{", "d", ":=", "&", "debouncer", "{", "after", ":", "after", "}", "\n\n", "return", "func", "(", "f", "func", "(", ")", ")", "{", "d", ".", "add", "(", "f", ")", "\n", "}", "\n", "}" ]
// New returns a debounced function that takes another functions as its argument. // This function will be called when the debounced function stops being called // for the given duration. // The debounced function can be invoked with different functions, if needed, // the last one will win.
[ "New", "returns", "a", "debounced", "function", "that", "takes", "another", "functions", "as", "its", "argument", ".", "This", "function", "will", "be", "called", "when", "the", "debounced", "function", "stops", "being", "called", "for", "the", "given", "duration", ".", "The", "debounced", "function", "can", "be", "invoked", "with", "different", "functions", "if", "needed", "the", "last", "one", "will", "win", "." ]
bf07a0f9e25545ee1b5974845f70185f91b72a00
https://github.com/bep/debounce/blob/bf07a0f9e25545ee1b5974845f70185f91b72a00/debounce.go#L21-L27
11,889
cloudfoundry-community/go-cfenv
envmap.go
splitEnv
func splitEnv(item string) (key, val string) { splits := strings.Split(item, "=") key = splits[0] val = strings.Join(splits[1:], "=") return }
go
func splitEnv(item string) (key, val string) { splits := strings.Split(item, "=") key = splits[0] val = strings.Join(splits[1:], "=") return }
[ "func", "splitEnv", "(", "item", "string", ")", "(", "key", ",", "val", "string", ")", "{", "splits", ":=", "strings", ".", "Split", "(", "item", ",", "\"", "\"", ")", "\n", "key", "=", "splits", "[", "0", "]", "\n", "val", "=", "strings", ".", "Join", "(", "splits", "[", "1", ":", "]", ",", "\"", "\"", ")", "\n", "return", "\n", "}" ]
// splitEnv splits item, a key=value string, into its key and value components.
[ "splitEnv", "splits", "item", "a", "key", "=", "value", "string", "into", "its", "key", "and", "value", "components", "." ]
20ea9de4dd5d3e052f2df72aab439453d7445f31
https://github.com/cloudfoundry-community/go-cfenv/blob/20ea9de4dd5d3e052f2df72aab439453d7445f31/envmap.go#L6-L11
11,890
cloudfoundry-community/go-cfenv
service.go
WithTag
func (s *Services) WithTag(tag string) ([]Service, error) { result := []Service{} for _, services := range *s { for i := range services { service := services[i] for _, t := range service.Tags { if strings.EqualFold(tag, t) { result = append(result, service) break } } } } if len(result) > 0 { return result, nil } return nil, fmt.Errorf("no services with tag %s", tag) }
go
func (s *Services) WithTag(tag string) ([]Service, error) { result := []Service{} for _, services := range *s { for i := range services { service := services[i] for _, t := range service.Tags { if strings.EqualFold(tag, t) { result = append(result, service) break } } } } if len(result) > 0 { return result, nil } return nil, fmt.Errorf("no services with tag %s", tag) }
[ "func", "(", "s", "*", "Services", ")", "WithTag", "(", "tag", "string", ")", "(", "[", "]", "Service", ",", "error", ")", "{", "result", ":=", "[", "]", "Service", "{", "}", "\n", "for", "_", ",", "services", ":=", "range", "*", "s", "{", "for", "i", ":=", "range", "services", "{", "service", ":=", "services", "[", "i", "]", "\n", "for", "_", ",", "t", ":=", "range", "service", ".", "Tags", "{", "if", "strings", ".", "EqualFold", "(", "tag", ",", "t", ")", "{", "result", "=", "append", "(", "result", ",", "service", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "result", ")", ">", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}" ]
// WithTag finds services with the specified tag.
[ "WithTag", "finds", "services", "with", "the", "specified", "tag", "." ]
20ea9de4dd5d3e052f2df72aab439453d7445f31
https://github.com/cloudfoundry-community/go-cfenv/blob/20ea9de4dd5d3e052f2df72aab439453d7445f31/service.go#L37-L56
11,891
cloudfoundry-community/go-cfenv
service.go
WithTagUsingPattern
func (s *Services) WithTagUsingPattern(tagPattern string) ([]Service, error) { result := []Service{} for _, services := range *s { for i := range services { service := services[i] for _, t := range service.Tags { if s.match(tagPattern, t) { result = append(result, service) break } } } } if len(result) > 0 { return result, nil } return nil, fmt.Errorf("no services with tag pattern %s", tagPattern) }
go
func (s *Services) WithTagUsingPattern(tagPattern string) ([]Service, error) { result := []Service{} for _, services := range *s { for i := range services { service := services[i] for _, t := range service.Tags { if s.match(tagPattern, t) { result = append(result, service) break } } } } if len(result) > 0 { return result, nil } return nil, fmt.Errorf("no services with tag pattern %s", tagPattern) }
[ "func", "(", "s", "*", "Services", ")", "WithTagUsingPattern", "(", "tagPattern", "string", ")", "(", "[", "]", "Service", ",", "error", ")", "{", "result", ":=", "[", "]", "Service", "{", "}", "\n", "for", "_", ",", "services", ":=", "range", "*", "s", "{", "for", "i", ":=", "range", "services", "{", "service", ":=", "services", "[", "i", "]", "\n", "for", "_", ",", "t", ":=", "range", "service", ".", "Tags", "{", "if", "s", ".", "match", "(", "tagPattern", ",", "t", ")", "{", "result", "=", "append", "(", "result", ",", "service", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "result", ")", ">", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tagPattern", ")", "\n", "}" ]
// WithTag finds services with a tag pattern.
[ "WithTag", "finds", "services", "with", "a", "tag", "pattern", "." ]
20ea9de4dd5d3e052f2df72aab439453d7445f31
https://github.com/cloudfoundry-community/go-cfenv/blob/20ea9de4dd5d3e052f2df72aab439453d7445f31/service.go#L59-L78
11,892
cloudfoundry-community/go-cfenv
service.go
WithLabel
func (s *Services) WithLabel(label string) ([]Service, error) { for l, services := range *s { if strings.EqualFold(label, l) { return services, nil } } return nil, fmt.Errorf("no services with label %s", label) }
go
func (s *Services) WithLabel(label string) ([]Service, error) { for l, services := range *s { if strings.EqualFold(label, l) { return services, nil } } return nil, fmt.Errorf("no services with label %s", label) }
[ "func", "(", "s", "*", "Services", ")", "WithLabel", "(", "label", "string", ")", "(", "[", "]", "Service", ",", "error", ")", "{", "for", "l", ",", "services", ":=", "range", "*", "s", "{", "if", "strings", ".", "EqualFold", "(", "label", ",", "l", ")", "{", "return", "services", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "label", ")", "\n", "}" ]
// WithLabel finds the service with the specified label.
[ "WithLabel", "finds", "the", "service", "with", "the", "specified", "label", "." ]
20ea9de4dd5d3e052f2df72aab439453d7445f31
https://github.com/cloudfoundry-community/go-cfenv/blob/20ea9de4dd5d3e052f2df72aab439453d7445f31/service.go#L81-L89
11,893
cloudfoundry-community/go-cfenv
service.go
WithNameUsingPattern
func (s *Services) WithNameUsingPattern(namePattern string) ([]Service, error) { result := []Service{} for _, services := range *s { for i := range services { service := services[i] if s.match(namePattern, service.Name) { result = append(result, service) } } } if len(result) > 0 { return result, nil } return nil, fmt.Errorf("no service with name pattern %s", namePattern) }
go
func (s *Services) WithNameUsingPattern(namePattern string) ([]Service, error) { result := []Service{} for _, services := range *s { for i := range services { service := services[i] if s.match(namePattern, service.Name) { result = append(result, service) } } } if len(result) > 0 { return result, nil } return nil, fmt.Errorf("no service with name pattern %s", namePattern) }
[ "func", "(", "s", "*", "Services", ")", "WithNameUsingPattern", "(", "namePattern", "string", ")", "(", "[", "]", "Service", ",", "error", ")", "{", "result", ":=", "[", "]", "Service", "{", "}", "\n", "for", "_", ",", "services", ":=", "range", "*", "s", "{", "for", "i", ":=", "range", "services", "{", "service", ":=", "services", "[", "i", "]", "\n", "if", "s", ".", "match", "(", "namePattern", ",", "service", ".", "Name", ")", "{", "result", "=", "append", "(", "result", ",", "service", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "result", ")", ">", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "namePattern", ")", "\n", "}" ]
// WithName finds the service with a name pattern.
[ "WithName", "finds", "the", "service", "with", "a", "name", "pattern", "." ]
20ea9de4dd5d3e052f2df72aab439453d7445f31
https://github.com/cloudfoundry-community/go-cfenv/blob/20ea9de4dd5d3e052f2df72aab439453d7445f31/service.go#L99-L113
11,894
cloudfoundry-community/go-cfenv
service.go
WithName
func (s *Services) WithName(name string) (*Service, error) { for _, services := range *s { for i := range services { service := services[i] if strings.EqualFold(name, service.Name) { return &service, nil } } } return nil, fmt.Errorf("no service with name %s", name) }
go
func (s *Services) WithName(name string) (*Service, error) { for _, services := range *s { for i := range services { service := services[i] if strings.EqualFold(name, service.Name) { return &service, nil } } } return nil, fmt.Errorf("no service with name %s", name) }
[ "func", "(", "s", "*", "Services", ")", "WithName", "(", "name", "string", ")", "(", "*", "Service", ",", "error", ")", "{", "for", "_", ",", "services", ":=", "range", "*", "s", "{", "for", "i", ":=", "range", "services", "{", "service", ":=", "services", "[", "i", "]", "\n", "if", "strings", ".", "EqualFold", "(", "name", ",", "service", ".", "Name", ")", "{", "return", "&", "service", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}" ]
// WithName finds the service with the specified name.
[ "WithName", "finds", "the", "service", "with", "the", "specified", "name", "." ]
20ea9de4dd5d3e052f2df72aab439453d7445f31
https://github.com/cloudfoundry-community/go-cfenv/blob/20ea9de4dd5d3e052f2df72aab439453d7445f31/service.go#L116-L127
11,895
bobesa/go-domain-util
domainutil/util.go
HasSubdomain
func HasSubdomain(domain string) bool { domain, top := stripURLParts(domain), Domain(domain) return domain != top && top != "" }
go
func HasSubdomain(domain string) bool { domain, top := stripURLParts(domain), Domain(domain) return domain != top && top != "" }
[ "func", "HasSubdomain", "(", "domain", "string", ")", "bool", "{", "domain", ",", "top", ":=", "stripURLParts", "(", "domain", ")", ",", "Domain", "(", "domain", ")", "\n", "return", "domain", "!=", "top", "&&", "top", "!=", "\"", "\"", "\n", "}" ]
// HasSubdomain reports whether domain contains any subdomain.
[ "HasSubdomain", "reports", "whether", "domain", "contains", "any", "subdomain", "." ]
1d708c097a6a59a3e6432affc53cf41808b35c8b
https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L10-L13
11,896
bobesa/go-domain-util
domainutil/util.go
Subdomain
func Subdomain(url string) string { domain, top := stripURLParts(url), Domain(url) lt, ld := len(top), len(domain) if lt < ld && top != "" { return domain[:(ld-lt)-1] } return "" }
go
func Subdomain(url string) string { domain, top := stripURLParts(url), Domain(url) lt, ld := len(top), len(domain) if lt < ld && top != "" { return domain[:(ld-lt)-1] } return "" }
[ "func", "Subdomain", "(", "url", "string", ")", "string", "{", "domain", ",", "top", ":=", "stripURLParts", "(", "url", ")", ",", "Domain", "(", "url", ")", "\n", "lt", ",", "ld", ":=", "len", "(", "top", ")", ",", "len", "(", "domain", ")", "\n", "if", "lt", "<", "ld", "&&", "top", "!=", "\"", "\"", "{", "return", "domain", "[", ":", "(", "ld", "-", "lt", ")", "-", "1", "]", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Subdomain returns subdomain from provided url. // If subdomain is not found in provided url, this function returns empty string.
[ "Subdomain", "returns", "subdomain", "from", "provided", "url", ".", "If", "subdomain", "is", "not", "found", "in", "provided", "url", "this", "function", "returns", "empty", "string", "." ]
1d708c097a6a59a3e6432affc53cf41808b35c8b
https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L17-L24
11,897
bobesa/go-domain-util
domainutil/util.go
DomainPrefix
func DomainPrefix(url string) string { domain := Domain(url) if len(domain) != 0 { return domain[:strings.Index(domain, ".")] } return "" }
go
func DomainPrefix(url string) string { domain := Domain(url) if len(domain) != 0 { return domain[:strings.Index(domain, ".")] } return "" }
[ "func", "DomainPrefix", "(", "url", "string", ")", "string", "{", "domain", ":=", "Domain", "(", "url", ")", "\n", "if", "len", "(", "domain", ")", "!=", "0", "{", "return", "domain", "[", ":", "strings", ".", "Index", "(", "domain", ",", "\"", "\"", ")", "]", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// DomainPrefix returns second-level domain from provided url. // If no SLD is found in provided url, this function returns empty string.
[ "DomainPrefix", "returns", "second", "-", "level", "domain", "from", "provided", "url", ".", "If", "no", "SLD", "is", "found", "in", "provided", "url", "this", "function", "returns", "empty", "string", "." ]
1d708c097a6a59a3e6432affc53cf41808b35c8b
https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L28-L34
11,898
bobesa/go-domain-util
domainutil/util.go
DomainSuffix
func DomainSuffix(url string) string { domain := Domain(url) if len(domain) != 0 { return domain[strings.Index(domain, ".")+1:] } return "" }
go
func DomainSuffix(url string) string { domain := Domain(url) if len(domain) != 0 { return domain[strings.Index(domain, ".")+1:] } return "" }
[ "func", "DomainSuffix", "(", "url", "string", ")", "string", "{", "domain", ":=", "Domain", "(", "url", ")", "\n", "if", "len", "(", "domain", ")", "!=", "0", "{", "return", "domain", "[", "strings", ".", "Index", "(", "domain", ",", "\"", "\"", ")", "+", "1", ":", "]", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// DomainSuffix returns domain suffix from provided url. // If no TLD is found in provided url, this function returns empty string.
[ "DomainSuffix", "returns", "domain", "suffix", "from", "provided", "url", ".", "If", "no", "TLD", "is", "found", "in", "provided", "url", "this", "function", "returns", "empty", "string", "." ]
1d708c097a6a59a3e6432affc53cf41808b35c8b
https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L38-L44
11,899
bobesa/go-domain-util
domainutil/util.go
Domain
func Domain(url string) string { domain, top := stripURLParts(url), "" parts := strings.Split(domain, ".") currentTld := *tlds foundTld := false // Cycle trough parts in reverse if len(parts) > 1 { for i := len(parts) - 1; i >= 0; i-- { // Generate top domain output if top != "" { top = "." + top } top = parts[i] + top // Check for TLD if currentTld == nil { return top // Return current output because we no longer have the TLD } else if tldEntry, found := currentTld[parts[i]]; found { if tldEntry != nil { currentTld = *tldEntry } else { currentTld = nil } foundTld = true continue } else if foundTld { return top // Return current output if tld was found before } // Return empty string if no tld was found ever return "" } } return "" }
go
func Domain(url string) string { domain, top := stripURLParts(url), "" parts := strings.Split(domain, ".") currentTld := *tlds foundTld := false // Cycle trough parts in reverse if len(parts) > 1 { for i := len(parts) - 1; i >= 0; i-- { // Generate top domain output if top != "" { top = "." + top } top = parts[i] + top // Check for TLD if currentTld == nil { return top // Return current output because we no longer have the TLD } else if tldEntry, found := currentTld[parts[i]]; found { if tldEntry != nil { currentTld = *tldEntry } else { currentTld = nil } foundTld = true continue } else if foundTld { return top // Return current output if tld was found before } // Return empty string if no tld was found ever return "" } } return "" }
[ "func", "Domain", "(", "url", "string", ")", "string", "{", "domain", ",", "top", ":=", "stripURLParts", "(", "url", ")", ",", "\"", "\"", "\n", "parts", ":=", "strings", ".", "Split", "(", "domain", ",", "\"", "\"", ")", "\n", "currentTld", ":=", "*", "tlds", "\n", "foundTld", ":=", "false", "\n\n", "// Cycle trough parts in reverse", "if", "len", "(", "parts", ")", ">", "1", "{", "for", "i", ":=", "len", "(", "parts", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "// Generate top domain output", "if", "top", "!=", "\"", "\"", "{", "top", "=", "\"", "\"", "+", "top", "\n", "}", "\n", "top", "=", "parts", "[", "i", "]", "+", "top", "\n\n", "// Check for TLD", "if", "currentTld", "==", "nil", "{", "return", "top", "// Return current output because we no longer have the TLD", "\n", "}", "else", "if", "tldEntry", ",", "found", ":=", "currentTld", "[", "parts", "[", "i", "]", "]", ";", "found", "{", "if", "tldEntry", "!=", "nil", "{", "currentTld", "=", "*", "tldEntry", "\n", "}", "else", "{", "currentTld", "=", "nil", "\n", "}", "\n", "foundTld", "=", "true", "\n", "continue", "\n", "}", "else", "if", "foundTld", "{", "return", "top", "// Return current output if tld was found before", "\n", "}", "\n\n", "// Return empty string if no tld was found ever", "return", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// Domain returns top level domain from url string. // If no domain is found in provided url, this function returns empty string. // If no TLD is found in provided url, this function returns empty string.
[ "Domain", "returns", "top", "level", "domain", "from", "url", "string", ".", "If", "no", "domain", "is", "found", "in", "provided", "url", "this", "function", "returns", "empty", "string", ".", "If", "no", "TLD", "is", "found", "in", "provided", "url", "this", "function", "returns", "empty", "string", "." ]
1d708c097a6a59a3e6432affc53cf41808b35c8b
https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L49-L85