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
2,100
cloudflare/golibs
kt/kt.go
Get
func (c *Conn) Get(key string) (string, error) { s, err := c.GetBytes(key) if err != nil { return "", err } return string(s), nil }
go
func (c *Conn) Get(key string) (string, error) { s, err := c.GetBytes(key) if err != nil { return "", err } return string(s), nil }
[ "func", "(", "c", "*", "Conn", ")", "Get", "(", "key", "string", ")", "(", "string", ",", "error", ")", "{", "s", ",", "err", ":=", "c", ".", "GetBytes", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "s", ")", ",", "nil", "\n", "}" ]
// Get retrieves the data stored at key. ErrNotFound is // returned if no such data exists
[ "Get", "retrieves", "the", "data", "stored", "at", "key", ".", "ErrNotFound", "is", "returned", "if", "no", "such", "data", "exists" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L277-L283
2,101
cloudflare/golibs
kt/kt.go
Set
func (c *Conn) Set(key string, value []byte) error { code, body, err := c.doREST("PUT", key, value) if err != nil { return err } if code != 201 { return &Error{string(body), code} } return nil }
go
func (c *Conn) Set(key string, value []byte) error { code, body, err := c.doREST("PUT", key, value) if err != nil { return err } if code != 201 { return &Error{string(body), code} } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Set", "(", "key", "string", ",", "value", "[", "]", "byte", ")", "error", "{", "code", ",", "body", ",", "err", ":=", "c", ".", "doREST", "(", "\"", "\"", ",", "key", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "code", "!=", "201", "{", "return", "&", "Error", "{", "string", "(", "body", ")", ",", "code", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Set stores the data at key
[ "Set", "stores", "the", "data", "at", "key" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L305-L315
2,102
cloudflare/golibs
kt/kt.go
GetBulkBytes
func (c *Conn) GetBulkBytes(keys map[string][]byte) error { // The format for querying multiple keys in KT is to send a // TSV value for each key with a _ as a prefix. // KT then returns the value as a TSV set with _ in front of the keys keystransmit := make([]KV, 0, len(keys)) for k, _ := range keys { // we set the value to nil because we want a sentinel value // for when no data was found. This is important for // when we remove the not found keys from the map keys[k] = nil keystransmit = append(keystransmit, KV{"_" + k, zeroslice}) } code, m, err := c.doRPC("/rpc/get_bulk", keystransmit) if err != nil { return err } if code != 200 { return makeError(m) } for _, kv := range m { if kv.Key[0] != '_' { continue } keys[kv.Key[1:]] = kv.Value } for k, v := range keys { if v == nil { delete(keys, k) } } return nil }
go
func (c *Conn) GetBulkBytes(keys map[string][]byte) error { // The format for querying multiple keys in KT is to send a // TSV value for each key with a _ as a prefix. // KT then returns the value as a TSV set with _ in front of the keys keystransmit := make([]KV, 0, len(keys)) for k, _ := range keys { // we set the value to nil because we want a sentinel value // for when no data was found. This is important for // when we remove the not found keys from the map keys[k] = nil keystransmit = append(keystransmit, KV{"_" + k, zeroslice}) } code, m, err := c.doRPC("/rpc/get_bulk", keystransmit) if err != nil { return err } if code != 200 { return makeError(m) } for _, kv := range m { if kv.Key[0] != '_' { continue } keys[kv.Key[1:]] = kv.Value } for k, v := range keys { if v == nil { delete(keys, k) } } return nil }
[ "func", "(", "c", "*", "Conn", ")", "GetBulkBytes", "(", "keys", "map", "[", "string", "]", "[", "]", "byte", ")", "error", "{", "// The format for querying multiple keys in KT is to send a", "// TSV value for each key with a _ as a prefix.", "// KT then returns the value as a TSV set with _ in front of the keys", "keystransmit", ":=", "make", "(", "[", "]", "KV", ",", "0", ",", "len", "(", "keys", ")", ")", "\n", "for", "k", ",", "_", ":=", "range", "keys", "{", "// we set the value to nil because we want a sentinel value", "// for when no data was found. This is important for", "// when we remove the not found keys from the map", "keys", "[", "k", "]", "=", "nil", "\n", "keystransmit", "=", "append", "(", "keystransmit", ",", "KV", "{", "\"", "\"", "+", "k", ",", "zeroslice", "}", ")", "\n", "}", "\n", "code", ",", "m", ",", "err", ":=", "c", ".", "doRPC", "(", "\"", "\"", ",", "keystransmit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "code", "!=", "200", "{", "return", "makeError", "(", "m", ")", "\n", "}", "\n", "for", "_", ",", "kv", ":=", "range", "m", "{", "if", "kv", ".", "Key", "[", "0", "]", "!=", "'_'", "{", "continue", "\n", "}", "\n", "keys", "[", "kv", ".", "Key", "[", "1", ":", "]", "]", "=", "kv", ".", "Value", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "keys", "{", "if", "v", "==", "nil", "{", "delete", "(", "keys", ",", "k", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetBulkBytes retrieves the keys in the map. The results will be filled in on function return. // If a key was not found in the database, it will be removed from the map.
[ "GetBulkBytes", "retrieves", "the", "keys", "in", "the", "map", ".", "The", "results", "will", "be", "filled", "in", "on", "function", "return", ".", "If", "a", "key", "was", "not", "found", "in", "the", "database", "it", "will", "be", "removed", "from", "the", "map", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L321-L353
2,103
cloudflare/golibs
kt/kt.go
SetBulk
func (c *Conn) SetBulk(values map[string]string) (int64, error) { vals := make([]KV, 0, len(values)) for k, v := range values { vals = append(vals, KV{"_" + k, []byte(v)}) } code, m, err := c.doRPC("/rpc/set_bulk", vals) if err != nil { return 0, err } if code != 200 { return 0, makeError(m) } return strconv.ParseInt(string(findRec(m, "num").Value), 10, 64) }
go
func (c *Conn) SetBulk(values map[string]string) (int64, error) { vals := make([]KV, 0, len(values)) for k, v := range values { vals = append(vals, KV{"_" + k, []byte(v)}) } code, m, err := c.doRPC("/rpc/set_bulk", vals) if err != nil { return 0, err } if code != 200 { return 0, makeError(m) } return strconv.ParseInt(string(findRec(m, "num").Value), 10, 64) }
[ "func", "(", "c", "*", "Conn", ")", "SetBulk", "(", "values", "map", "[", "string", "]", "string", ")", "(", "int64", ",", "error", ")", "{", "vals", ":=", "make", "(", "[", "]", "KV", ",", "0", ",", "len", "(", "values", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "values", "{", "vals", "=", "append", "(", "vals", ",", "KV", "{", "\"", "\"", "+", "k", ",", "[", "]", "byte", "(", "v", ")", "}", ")", "\n", "}", "\n", "code", ",", "m", ",", "err", ":=", "c", ".", "doRPC", "(", "\"", "\"", ",", "vals", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "code", "!=", "200", "{", "return", "0", ",", "makeError", "(", "m", ")", "\n", "}", "\n", "return", "strconv", ".", "ParseInt", "(", "string", "(", "findRec", "(", "m", ",", "\"", "\"", ")", ".", "Value", ")", ",", "10", ",", "64", ")", "\n", "}" ]
// SetBulk stores the values in the map.
[ "SetBulk", "stores", "the", "values", "in", "the", "map", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L356-L369
2,104
cloudflare/golibs
kt/kt.go
RemoveBulk
func (c *Conn) RemoveBulk(keys []string) (int64, error) { vals := make([]KV, 0, len(keys)) for _, k := range keys { vals = append(vals, KV{"_" + k, zeroslice}) } code, m, err := c.doRPC("/rpc/remove_bulk", vals) if err != nil { return 0, err } if code != 200 { return 0, makeError(m) } return strconv.ParseInt(string(findRec(m, "num").Value), 10, 64) }
go
func (c *Conn) RemoveBulk(keys []string) (int64, error) { vals := make([]KV, 0, len(keys)) for _, k := range keys { vals = append(vals, KV{"_" + k, zeroslice}) } code, m, err := c.doRPC("/rpc/remove_bulk", vals) if err != nil { return 0, err } if code != 200 { return 0, makeError(m) } return strconv.ParseInt(string(findRec(m, "num").Value), 10, 64) }
[ "func", "(", "c", "*", "Conn", ")", "RemoveBulk", "(", "keys", "[", "]", "string", ")", "(", "int64", ",", "error", ")", "{", "vals", ":=", "make", "(", "[", "]", "KV", ",", "0", ",", "len", "(", "keys", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "vals", "=", "append", "(", "vals", ",", "KV", "{", "\"", "\"", "+", "k", ",", "zeroslice", "}", ")", "\n", "}", "\n", "code", ",", "m", ",", "err", ":=", "c", ".", "doRPC", "(", "\"", "\"", ",", "vals", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "code", "!=", "200", "{", "return", "0", ",", "makeError", "(", "m", ")", "\n", "}", "\n", "return", "strconv", ".", "ParseInt", "(", "string", "(", "findRec", "(", "m", ",", "\"", "\"", ")", ".", "Value", ")", ",", "10", ",", "64", ")", "\n", "}" ]
// RemoveBulk deletes the values
[ "RemoveBulk", "deletes", "the", "values" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L372-L385
2,105
cloudflare/golibs
kt/kt.go
MatchPrefix
func (c *Conn) MatchPrefix(key string, maxrecords int64) ([]string, error) { keystransmit := []KV{ {"prefix", []byte(key)}, {"max", []byte(strconv.FormatInt(maxrecords, 10))}, } code, m, err := c.doRPC("/rpc/match_prefix", keystransmit) if err != nil { return nil, err } if code != 200 { return nil, makeError(m) } res := make([]string, 0, len(m)) for _, kv := range m { if kv.Key[0] == '_' { res = append(res, string(kv.Key[1:])) } } if len(res) == 0 { // yeah, gokabinet was weird here. return nil, ErrSuccess } return res, nil }
go
func (c *Conn) MatchPrefix(key string, maxrecords int64) ([]string, error) { keystransmit := []KV{ {"prefix", []byte(key)}, {"max", []byte(strconv.FormatInt(maxrecords, 10))}, } code, m, err := c.doRPC("/rpc/match_prefix", keystransmit) if err != nil { return nil, err } if code != 200 { return nil, makeError(m) } res := make([]string, 0, len(m)) for _, kv := range m { if kv.Key[0] == '_' { res = append(res, string(kv.Key[1:])) } } if len(res) == 0 { // yeah, gokabinet was weird here. return nil, ErrSuccess } return res, nil }
[ "func", "(", "c", "*", "Conn", ")", "MatchPrefix", "(", "key", "string", ",", "maxrecords", "int64", ")", "(", "[", "]", "string", ",", "error", ")", "{", "keystransmit", ":=", "[", "]", "KV", "{", "{", "\"", "\"", ",", "[", "]", "byte", "(", "key", ")", "}", ",", "{", "\"", "\"", ",", "[", "]", "byte", "(", "strconv", ".", "FormatInt", "(", "maxrecords", ",", "10", ")", ")", "}", ",", "}", "\n", "code", ",", "m", ",", "err", ":=", "c", ".", "doRPC", "(", "\"", "\"", ",", "keystransmit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "code", "!=", "200", "{", "return", "nil", ",", "makeError", "(", "m", ")", "\n", "}", "\n", "res", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "for", "_", ",", "kv", ":=", "range", "m", "{", "if", "kv", ".", "Key", "[", "0", "]", "==", "'_'", "{", "res", "=", "append", "(", "res", ",", "string", "(", "kv", ".", "Key", "[", "1", ":", "]", ")", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "res", ")", "==", "0", "{", "// yeah, gokabinet was weird here.", "return", "nil", ",", "ErrSuccess", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// MatchPrefix performs the match_prefix operation against the server // It returns a sorted list of strings. // The error may be ErrSuccess in the case that no records were found. // This is for compatibility with the old gokabinet library.
[ "MatchPrefix", "performs", "the", "match_prefix", "operation", "against", "the", "server", "It", "returns", "a", "sorted", "list", "of", "strings", ".", "The", "error", "may", "be", "ErrSuccess", "in", "the", "case", "that", "no", "records", "were", "found", ".", "This", "is", "for", "compatibility", "with", "the", "old", "gokabinet", "library", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L391-L414
2,106
cloudflare/golibs
kt/kt.go
doRPC
func (c *Conn) doRPC(path string, values []KV) (code int, vals []KV, err error) { url := &url.URL{ Scheme: c.scheme, Host: c.host, Path: path, } body, enc := TSVEncode(values) headers := identityheaders if enc == Base64Enc { headers = base64headers } resp, t, err := c.roundTrip("POST", url, headers, body) if err != nil { return 0, nil, err } resultBody, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if !t.Stop() { return 0, nil, ErrTimeout } if err != nil { return 0, nil, err } m, err := DecodeValues(resultBody, resp.Header.Get("Content-Type")) if err != nil { return 0, nil, err } return resp.StatusCode, m, nil }
go
func (c *Conn) doRPC(path string, values []KV) (code int, vals []KV, err error) { url := &url.URL{ Scheme: c.scheme, Host: c.host, Path: path, } body, enc := TSVEncode(values) headers := identityheaders if enc == Base64Enc { headers = base64headers } resp, t, err := c.roundTrip("POST", url, headers, body) if err != nil { return 0, nil, err } resultBody, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if !t.Stop() { return 0, nil, ErrTimeout } if err != nil { return 0, nil, err } m, err := DecodeValues(resultBody, resp.Header.Get("Content-Type")) if err != nil { return 0, nil, err } return resp.StatusCode, m, nil }
[ "func", "(", "c", "*", "Conn", ")", "doRPC", "(", "path", "string", ",", "values", "[", "]", "KV", ")", "(", "code", "int", ",", "vals", "[", "]", "KV", ",", "err", "error", ")", "{", "url", ":=", "&", "url", ".", "URL", "{", "Scheme", ":", "c", ".", "scheme", ",", "Host", ":", "c", ".", "host", ",", "Path", ":", "path", ",", "}", "\n", "body", ",", "enc", ":=", "TSVEncode", "(", "values", ")", "\n", "headers", ":=", "identityheaders", "\n", "if", "enc", "==", "Base64Enc", "{", "headers", "=", "base64headers", "\n", "}", "\n", "resp", ",", "t", ",", "err", ":=", "c", ".", "roundTrip", "(", "\"", "\"", ",", "url", ",", "headers", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "resultBody", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "!", "t", ".", "Stop", "(", ")", "{", "return", "0", ",", "nil", ",", "ErrTimeout", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "m", ",", "err", ":=", "DecodeValues", "(", "resultBody", ",", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "return", "resp", ".", "StatusCode", ",", "m", ",", "nil", "\n", "}" ]
// Do an RPC call against the KT endpoint.
[ "Do", "an", "RPC", "call", "against", "the", "KT", "endpoint", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L434-L462
2,107
cloudflare/golibs
kt/kt.go
DecodeValues
func DecodeValues(buf []byte, contenttype string) ([]KV, error) { if len(buf) == 0 { return nil, nil } // Ideally, we should parse the mime media type here, // but this is an expensive operation because mime is just // that awful. // // KT can return values in 3 different formats, Tab separated values (TSV) without any field encoding, // TSV with fields base64 encoded or TSV with URL encoding. // KT does not give you any option as to the format that it returns, so we have to implement all of them // // KT responses are pretty simple and we can rely // on it putting the parameter of colenc=[BU] at // the end of the string. Just look for B, U or s // (last character of tab-separated-values) // to figure out which field encoding is used. var decodef decodefunc switch contenttype[len(contenttype)-1] { case 'B': decodef = base64Decode case 'U': decodef = urlDecode case 's': decodef = identityDecode default: return nil, &Error{Message: fmt.Sprintf("responded with unknown Content-Type: %s", contenttype)} } // Because of the encoding, we can tell how many records there // are by scanning through the input and counting the \n's var recCount int for _, v := range buf { if v == '\n' { recCount++ } } result := make([]KV, 0, recCount) b := bytes.NewBuffer(buf) for { key, err := b.ReadBytes('\t') if err != nil { return result, nil } key = decodef(key[:len(key)-1]) value, err := b.ReadBytes('\n') if len(value) > 0 { fieldlen := len(value) - 1 if value[len(value)-1] != '\n' { fieldlen = len(value) } value = decodef(value[:fieldlen]) result = append(result, KV{string(key), value}) } if err != nil { return result, nil } } }
go
func DecodeValues(buf []byte, contenttype string) ([]KV, error) { if len(buf) == 0 { return nil, nil } // Ideally, we should parse the mime media type here, // but this is an expensive operation because mime is just // that awful. // // KT can return values in 3 different formats, Tab separated values (TSV) without any field encoding, // TSV with fields base64 encoded or TSV with URL encoding. // KT does not give you any option as to the format that it returns, so we have to implement all of them // // KT responses are pretty simple and we can rely // on it putting the parameter of colenc=[BU] at // the end of the string. Just look for B, U or s // (last character of tab-separated-values) // to figure out which field encoding is used. var decodef decodefunc switch contenttype[len(contenttype)-1] { case 'B': decodef = base64Decode case 'U': decodef = urlDecode case 's': decodef = identityDecode default: return nil, &Error{Message: fmt.Sprintf("responded with unknown Content-Type: %s", contenttype)} } // Because of the encoding, we can tell how many records there // are by scanning through the input and counting the \n's var recCount int for _, v := range buf { if v == '\n' { recCount++ } } result := make([]KV, 0, recCount) b := bytes.NewBuffer(buf) for { key, err := b.ReadBytes('\t') if err != nil { return result, nil } key = decodef(key[:len(key)-1]) value, err := b.ReadBytes('\n') if len(value) > 0 { fieldlen := len(value) - 1 if value[len(value)-1] != '\n' { fieldlen = len(value) } value = decodef(value[:fieldlen]) result = append(result, KV{string(key), value}) } if err != nil { return result, nil } } }
[ "func", "DecodeValues", "(", "buf", "[", "]", "byte", ",", "contenttype", "string", ")", "(", "[", "]", "KV", ",", "error", ")", "{", "if", "len", "(", "buf", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "// Ideally, we should parse the mime media type here,", "// but this is an expensive operation because mime is just", "// that awful.", "//", "// KT can return values in 3 different formats, Tab separated values (TSV) without any field encoding,", "// TSV with fields base64 encoded or TSV with URL encoding.", "// KT does not give you any option as to the format that it returns, so we have to implement all of them", "//", "// KT responses are pretty simple and we can rely", "// on it putting the parameter of colenc=[BU] at", "// the end of the string. Just look for B, U or s", "// (last character of tab-separated-values)", "// to figure out which field encoding is used.", "var", "decodef", "decodefunc", "\n", "switch", "contenttype", "[", "len", "(", "contenttype", ")", "-", "1", "]", "{", "case", "'B'", ":", "decodef", "=", "base64Decode", "\n", "case", "'U'", ":", "decodef", "=", "urlDecode", "\n", "case", "'s'", ":", "decodef", "=", "identityDecode", "\n", "default", ":", "return", "nil", ",", "&", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "contenttype", ")", "}", "\n", "}", "\n\n", "// Because of the encoding, we can tell how many records there", "// are by scanning through the input and counting the \\n's", "var", "recCount", "int", "\n", "for", "_", ",", "v", ":=", "range", "buf", "{", "if", "v", "==", "'\\n'", "{", "recCount", "++", "\n", "}", "\n", "}", "\n", "result", ":=", "make", "(", "[", "]", "KV", ",", "0", ",", "recCount", ")", "\n", "b", ":=", "bytes", ".", "NewBuffer", "(", "buf", ")", "\n", "for", "{", "key", ",", "err", ":=", "b", ".", "ReadBytes", "(", "'\\t'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "nil", "\n", "}", "\n", "key", "=", "decodef", "(", "key", "[", ":", "len", "(", "key", ")", "-", "1", "]", ")", "\n", "value", ",", "err", ":=", "b", ".", "ReadBytes", "(", "'\\n'", ")", "\n", "if", "len", "(", "value", ")", ">", "0", "{", "fieldlen", ":=", "len", "(", "value", ")", "-", "1", "\n", "if", "value", "[", "len", "(", "value", ")", "-", "1", "]", "!=", "'\\n'", "{", "fieldlen", "=", "len", "(", "value", ")", "\n", "}", "\n", "value", "=", "decodef", "(", "value", "[", ":", "fieldlen", "]", ")", "\n", "result", "=", "append", "(", "result", ",", "KV", "{", "string", "(", "key", ")", ",", "value", "}", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// DecodeValues takes a response from an KT RPC call decodes it into a list of key // value pairs.
[ "DecodeValues", "takes", "a", "response", "from", "an", "KT", "RPC", "call", "decodes", "it", "into", "a", "list", "of", "key", "value", "pairs", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L575-L633
2,108
cloudflare/golibs
kt/kt.go
base64Decode
func base64Decode(b []byte) []byte { n, _ := base64.StdEncoding.Decode(b, b) return b[:n] }
go
func base64Decode(b []byte) []byte { n, _ := base64.StdEncoding.Decode(b, b) return b[:n] }
[ "func", "base64Decode", "(", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "n", ",", "_", ":=", "base64", ".", "StdEncoding", ".", "Decode", "(", "b", ",", "b", ")", "\n", "return", "b", "[", ":", "n", "]", "\n", "}" ]
// Base64 decode each of the field
[ "Base64", "decode", "each", "of", "the", "field" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L647-L650
2,109
cloudflare/golibs
kt/kt.go
urlDecode
func urlDecode(b []byte) []byte { res := b resi := 0 for i := 0; i < len(b); i++ { if b[i] != '%' { res[resi] = b[i] resi++ continue } res[resi] = unhex(b[i+1])<<4 | unhex(b[i+2]) resi++ i += 2 } return res[:resi] }
go
func urlDecode(b []byte) []byte { res := b resi := 0 for i := 0; i < len(b); i++ { if b[i] != '%' { res[resi] = b[i] resi++ continue } res[resi] = unhex(b[i+1])<<4 | unhex(b[i+2]) resi++ i += 2 } return res[:resi] }
[ "func", "urlDecode", "(", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "res", ":=", "b", "\n", "resi", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "b", ")", ";", "i", "++", "{", "if", "b", "[", "i", "]", "!=", "'%'", "{", "res", "[", "resi", "]", "=", "b", "[", "i", "]", "\n", "resi", "++", "\n", "continue", "\n", "}", "\n", "res", "[", "resi", "]", "=", "unhex", "(", "b", "[", "i", "+", "1", "]", ")", "<<", "4", "|", "unhex", "(", "b", "[", "i", "+", "2", "]", ")", "\n", "resi", "++", "\n", "i", "+=", "2", "\n", "}", "\n", "return", "res", "[", ":", "resi", "]", "\n", "}" ]
// Decode % escaped URL format
[ "Decode", "%", "escaped", "URL", "format" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L653-L667
2,110
mattbaird/elastigo
lib/indicesdeletemapping.go
DeleteMapping
func (c *Conn) DeleteMapping(index string, typeName string) (BaseResponse, error) { var retval BaseResponse if len(index) == 0 { return retval, fmt.Errorf("You must specify at least one index to delete a mapping from") } if len(typeName) == 0 { return retval, fmt.Errorf("You must specify at least one mapping to delete") } // As documented at http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-delete-mapping.html url := fmt.Sprintf("/%s/%s", index, typeName) body, err := c.DoCommand("DELETE", url, nil, nil) if err != nil { return retval, err } jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { return retval, jsonErr } return retval, err }
go
func (c *Conn) DeleteMapping(index string, typeName string) (BaseResponse, error) { var retval BaseResponse if len(index) == 0 { return retval, fmt.Errorf("You must specify at least one index to delete a mapping from") } if len(typeName) == 0 { return retval, fmt.Errorf("You must specify at least one mapping to delete") } // As documented at http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-delete-mapping.html url := fmt.Sprintf("/%s/%s", index, typeName) body, err := c.DoCommand("DELETE", url, nil, nil) if err != nil { return retval, err } jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { return retval, jsonErr } return retval, err }
[ "func", "(", "c", "*", "Conn", ")", "DeleteMapping", "(", "index", "string", ",", "typeName", "string", ")", "(", "BaseResponse", ",", "error", ")", "{", "var", "retval", "BaseResponse", "\n\n", "if", "len", "(", "index", ")", "==", "0", "{", "return", "retval", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "typeName", ")", "==", "0", "{", "return", "retval", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// As documented at http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-delete-mapping.html", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "index", ",", "typeName", ")", "\n\n", "body", ",", "err", ":=", "c", ".", "DoCommand", "(", "\"", "\"", ",", "url", ",", "nil", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "retval", ",", "err", "\n", "}", "\n\n", "jsonErr", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "retval", ")", "\n", "if", "jsonErr", "!=", "nil", "{", "return", "retval", ",", "jsonErr", "\n", "}", "\n\n", "return", "retval", ",", "err", "\n", "}" ]
// The delete API allows you to delete a mapping through an API.
[ "The", "delete", "API", "allows", "you", "to", "delete", "a", "mapping", "through", "an", "API", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/indicesdeletemapping.go#L20-L45
2,111
mattbaird/elastigo
lib/corebulk.go
NewBulkIndexerErrors
func (c *Conn) NewBulkIndexerErrors(maxConns, retrySeconds int) *BulkIndexer { b := c.NewBulkIndexer(maxConns) b.RetryForSeconds = retrySeconds b.ErrorChannel = make(chan *ErrorBuffer, 20) return b }
go
func (c *Conn) NewBulkIndexerErrors(maxConns, retrySeconds int) *BulkIndexer { b := c.NewBulkIndexer(maxConns) b.RetryForSeconds = retrySeconds b.ErrorChannel = make(chan *ErrorBuffer, 20) return b }
[ "func", "(", "c", "*", "Conn", ")", "NewBulkIndexerErrors", "(", "maxConns", ",", "retrySeconds", "int", ")", "*", "BulkIndexer", "{", "b", ":=", "c", ".", "NewBulkIndexer", "(", "maxConns", ")", "\n", "b", ".", "RetryForSeconds", "=", "retrySeconds", "\n", "b", ".", "ErrorChannel", "=", "make", "(", "chan", "*", "ErrorBuffer", ",", "20", ")", "\n", "return", "b", "\n", "}" ]
// A bulk indexer with more control over error handling // @maxConns is the max number of in flight http requests // @retrySeconds is # of seconds to wait before retrying falied requests // // done := make(chan bool) // BulkIndexerGlobalRun(100, done)
[ "A", "bulk", "indexer", "with", "more", "control", "over", "error", "handling" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/corebulk.go#L123-L128
2,112
mattbaird/elastigo
lib/corebulk.go
Start
func (b *BulkIndexer) Start() { b.shutdownChan = make(chan chan struct{}) go func() { // XXX(j): Refactor this stuff to use an interface. if b.Sender == nil { b.Sender = b.Send } // Backwards compatibility b.startHttpSender() b.startDocChannel() b.startTimer() ch := <-b.shutdownChan time.Sleep(2 * time.Millisecond) b.Flush() b.shutdown() ch <- struct{}{} }() }
go
func (b *BulkIndexer) Start() { b.shutdownChan = make(chan chan struct{}) go func() { // XXX(j): Refactor this stuff to use an interface. if b.Sender == nil { b.Sender = b.Send } // Backwards compatibility b.startHttpSender() b.startDocChannel() b.startTimer() ch := <-b.shutdownChan time.Sleep(2 * time.Millisecond) b.Flush() b.shutdown() ch <- struct{}{} }() }
[ "func", "(", "b", "*", "BulkIndexer", ")", "Start", "(", ")", "{", "b", ".", "shutdownChan", "=", "make", "(", "chan", "chan", "struct", "{", "}", ")", "\n\n", "go", "func", "(", ")", "{", "// XXX(j): Refactor this stuff to use an interface.", "if", "b", ".", "Sender", "==", "nil", "{", "b", ".", "Sender", "=", "b", ".", "Send", "\n", "}", "\n", "// Backwards compatibility", "b", ".", "startHttpSender", "(", ")", "\n", "b", ".", "startDocChannel", "(", ")", "\n", "b", ".", "startTimer", "(", ")", "\n", "ch", ":=", "<-", "b", ".", "shutdownChan", "\n", "time", ".", "Sleep", "(", "2", "*", "time", ".", "Millisecond", ")", "\n", "b", ".", "Flush", "(", ")", "\n", "b", ".", "shutdown", "(", ")", "\n", "ch", "<-", "struct", "{", "}", "{", "}", "\n", "}", "(", ")", "\n", "}" ]
// Starts this bulk Indexer running, this Run opens a go routine so is // Non blocking
[ "Starts", "this", "bulk", "Indexer", "running", "this", "Run", "opens", "a", "go", "routine", "so", "is", "Non", "blocking" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/corebulk.go#L132-L150
2,113
mattbaird/elastigo
lib/corebulk.go
Stop
func (b *BulkIndexer) Stop() { ch := make(chan struct{}, 1) b.shutdownChan <- ch select { case <-ch: // done case <-time.After(time.Second * time.Duration(MAX_SHUTDOWN_SECS)): // timeout! } }
go
func (b *BulkIndexer) Stop() { ch := make(chan struct{}, 1) b.shutdownChan <- ch select { case <-ch: // done case <-time.After(time.Second * time.Duration(MAX_SHUTDOWN_SECS)): // timeout! } }
[ "func", "(", "b", "*", "BulkIndexer", ")", "Stop", "(", ")", "{", "ch", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "b", ".", "shutdownChan", "<-", "ch", "\n", "select", "{", "case", "<-", "ch", ":", "// done", "case", "<-", "time", ".", "After", "(", "time", ".", "Second", "*", "time", ".", "Duration", "(", "MAX_SHUTDOWN_SECS", ")", ")", ":", "// timeout!", "}", "\n", "}" ]
// Stop stops the bulk indexer, blocking the caller until it is complete.
[ "Stop", "stops", "the", "bulk", "indexer", "blocking", "the", "caller", "until", "it", "is", "complete", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/corebulk.go#L153-L162
2,114
mattbaird/elastigo
lib/corebulk.go
Flush
func (b *BulkIndexer) Flush() { b.mu.Lock() if b.docCt > 0 { b.send(b.buf) } b.mu.Unlock() }
go
func (b *BulkIndexer) Flush() { b.mu.Lock() if b.docCt > 0 { b.send(b.buf) } b.mu.Unlock() }
[ "func", "(", "b", "*", "BulkIndexer", ")", "Flush", "(", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "b", ".", "docCt", ">", "0", "{", "b", ".", "send", "(", "b", ".", "buf", ")", "\n", "}", "\n", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// Flush all current documents to ElasticSearch
[ "Flush", "all", "current", "documents", "to", "ElasticSearch" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/corebulk.go#L169-L175
2,115
mattbaird/elastigo
lib/corebulk.go
Send
func (b *BulkIndexer) Send(buf *bytes.Buffer) error { type responseStruct struct { Took int64 `json:"took"` Errors bool `json:"errors"` Items []map[string]interface{} `json:"items"` } response := responseStruct{} body, err := b.conn.DoCommand("POST", fmt.Sprintf("/_bulk?refresh=%t", b.Refresh), nil, buf) if err != nil { atomic.AddUint64(&b.numErrors, 1) return err } // check for response errors, bulk insert will give 200 OK but then include errors in response jsonErr := json.Unmarshal(body, &response) if jsonErr == nil { if response.Errors { atomic.AddUint64(&b.numErrors, uint64(len(response.Items))) return fmt.Errorf("Bulk Insertion Error. Failed item count [%d]", len(response.Items)) } } return nil }
go
func (b *BulkIndexer) Send(buf *bytes.Buffer) error { type responseStruct struct { Took int64 `json:"took"` Errors bool `json:"errors"` Items []map[string]interface{} `json:"items"` } response := responseStruct{} body, err := b.conn.DoCommand("POST", fmt.Sprintf("/_bulk?refresh=%t", b.Refresh), nil, buf) if err != nil { atomic.AddUint64(&b.numErrors, 1) return err } // check for response errors, bulk insert will give 200 OK but then include errors in response jsonErr := json.Unmarshal(body, &response) if jsonErr == nil { if response.Errors { atomic.AddUint64(&b.numErrors, uint64(len(response.Items))) return fmt.Errorf("Bulk Insertion Error. Failed item count [%d]", len(response.Items)) } } return nil }
[ "func", "(", "b", "*", "BulkIndexer", ")", "Send", "(", "buf", "*", "bytes", ".", "Buffer", ")", "error", "{", "type", "responseStruct", "struct", "{", "Took", "int64", "`json:\"took\"`", "\n", "Errors", "bool", "`json:\"errors\"`", "\n", "Items", "[", "]", "map", "[", "string", "]", "interface", "{", "}", "`json:\"items\"`", "\n", "}", "\n\n", "response", ":=", "responseStruct", "{", "}", "\n\n", "body", ",", "err", ":=", "b", ".", "conn", ".", "DoCommand", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Refresh", ")", ",", "nil", ",", "buf", ")", "\n\n", "if", "err", "!=", "nil", "{", "atomic", ".", "AddUint64", "(", "&", "b", ".", "numErrors", ",", "1", ")", "\n", "return", "err", "\n", "}", "\n", "// check for response errors, bulk insert will give 200 OK but then include errors in response", "jsonErr", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "response", ")", "\n", "if", "jsonErr", "==", "nil", "{", "if", "response", ".", "Errors", "{", "atomic", ".", "AddUint64", "(", "&", "b", ".", "numErrors", ",", "uint64", "(", "len", "(", "response", ".", "Items", ")", ")", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "response", ".", "Items", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// This does the actual send of a buffer, which has already been formatted // into bytes of ES formatted bulk data
[ "This", "does", "the", "actual", "send", "of", "a", "buffer", "which", "has", "already", "been", "formatted", "into", "bytes", "of", "ES", "formatted", "bulk", "data" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/corebulk.go#L327-L351
2,116
mattbaird/elastigo
lib/catindexinfo.go
GetCatIndexInfo
func (c *Conn) GetCatIndexInfo(pattern string) (catIndices []CatIndexInfo) { catIndices = make([]CatIndexInfo, 0) //force it to only show the fileds we know about args := map[string]interface{}{"bytes": "b", "h": "health,status,index,pri,rep,docs.count,docs.deleted,store.size,pri.store.size"} indices, err := c.DoCommand("GET", "/_cat/indices/"+pattern, args, nil) if err == nil { indexLines := strings.Split(string(indices[:]), "\n") for _, index := range indexLines { ci, _ := NewCatIndexInfo(index) if nil != ci { catIndices = append(catIndices, *ci) } } } return catIndices }
go
func (c *Conn) GetCatIndexInfo(pattern string) (catIndices []CatIndexInfo) { catIndices = make([]CatIndexInfo, 0) //force it to only show the fileds we know about args := map[string]interface{}{"bytes": "b", "h": "health,status,index,pri,rep,docs.count,docs.deleted,store.size,pri.store.size"} indices, err := c.DoCommand("GET", "/_cat/indices/"+pattern, args, nil) if err == nil { indexLines := strings.Split(string(indices[:]), "\n") for _, index := range indexLines { ci, _ := NewCatIndexInfo(index) if nil != ci { catIndices = append(catIndices, *ci) } } } return catIndices }
[ "func", "(", "c", "*", "Conn", ")", "GetCatIndexInfo", "(", "pattern", "string", ")", "(", "catIndices", "[", "]", "CatIndexInfo", ")", "{", "catIndices", "=", "make", "(", "[", "]", "CatIndexInfo", ",", "0", ")", "\n", "//force it to only show the fileds we know about", "args", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", "}", "\n", "indices", ",", "err", ":=", "c", ".", "DoCommand", "(", "\"", "\"", ",", "\"", "\"", "+", "pattern", ",", "args", ",", "nil", ")", "\n", "if", "err", "==", "nil", "{", "indexLines", ":=", "strings", ".", "Split", "(", "string", "(", "indices", "[", ":", "]", ")", ",", "\"", "\\n", "\"", ")", "\n", "for", "_", ",", "index", ":=", "range", "indexLines", "{", "ci", ",", "_", ":=", "NewCatIndexInfo", "(", "index", ")", "\n", "if", "nil", "!=", "ci", "{", "catIndices", "=", "append", "(", "catIndices", ",", "*", "ci", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "catIndices", "\n", "}" ]
// Pull all the index info from the connection
[ "Pull", "all", "the", "index", "info", "from", "the", "connection" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/catindexinfo.go#L65-L80
2,117
mattbaird/elastigo
lib/baserequest.go
Exists
func (c *Conn) Exists(index string, _type string, id string, args map[string]interface{}) (BaseResponse, error) { var response map[string]interface{} var body []byte var url string var retval BaseResponse var httpStatusCode int query, err := Escape(args) if err != nil { return retval, err } if len(_type) > 0 { url = fmt.Sprintf("/%s/%s/%s", index, _type, id) } else { url = fmt.Sprintf("/%s/%s", index, id) } req, err := c.NewRequest("HEAD", url, query) if err != nil { // some sort of generic error handler } httpStatusCode, body, err = req.Do(&response) if httpStatusCode > 304 { if error, ok := response["error"]; ok { status, _ := response["status"] log.Printf("Error: %v (%v)\n", error, status) } } else { // marshall into json jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { log.Println(jsonErr) } } return retval, err }
go
func (c *Conn) Exists(index string, _type string, id string, args map[string]interface{}) (BaseResponse, error) { var response map[string]interface{} var body []byte var url string var retval BaseResponse var httpStatusCode int query, err := Escape(args) if err != nil { return retval, err } if len(_type) > 0 { url = fmt.Sprintf("/%s/%s/%s", index, _type, id) } else { url = fmt.Sprintf("/%s/%s", index, id) } req, err := c.NewRequest("HEAD", url, query) if err != nil { // some sort of generic error handler } httpStatusCode, body, err = req.Do(&response) if httpStatusCode > 304 { if error, ok := response["error"]; ok { status, _ := response["status"] log.Printf("Error: %v (%v)\n", error, status) } } else { // marshall into json jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { log.Println(jsonErr) } } return retval, err }
[ "func", "(", "c", "*", "Conn", ")", "Exists", "(", "index", "string", ",", "_type", "string", ",", "id", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "BaseResponse", ",", "error", ")", "{", "var", "response", "map", "[", "string", "]", "interface", "{", "}", "\n", "var", "body", "[", "]", "byte", "\n", "var", "url", "string", "\n", "var", "retval", "BaseResponse", "\n", "var", "httpStatusCode", "int", "\n\n", "query", ",", "err", ":=", "Escape", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "retval", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "_type", ")", ">", "0", "{", "url", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "index", ",", "_type", ",", "id", ")", "\n", "}", "else", "{", "url", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "index", ",", "id", ")", "\n", "}", "\n", "req", ",", "err", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "query", ")", "\n", "if", "err", "!=", "nil", "{", "// some sort of generic error handler", "}", "\n", "httpStatusCode", ",", "body", ",", "err", "=", "req", ".", "Do", "(", "&", "response", ")", "\n", "if", "httpStatusCode", ">", "304", "{", "if", "error", ",", "ok", ":=", "response", "[", "\"", "\"", "]", ";", "ok", "{", "status", ",", "_", ":=", "response", "[", "\"", "\"", "]", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "error", ",", "status", ")", "\n", "}", "\n", "}", "else", "{", "// marshall into json", "jsonErr", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "retval", ")", "\n", "if", "jsonErr", "!=", "nil", "{", "log", ".", "Println", "(", "jsonErr", ")", "\n", "}", "\n", "}", "\n", "return", "retval", ",", "err", "\n", "}" ]
// Exists allows the caller to check for the existence of a document using HEAD // This appears to be broken in the current version of elasticsearch 0.19.10, currently // returning nothing
[ "Exists", "allows", "the", "caller", "to", "check", "for", "the", "existence", "of", "a", "document", "using", "HEAD", "This", "appears", "to", "be", "broken", "in", "the", "current", "version", "of", "elasticsearch", "0", ".", "19", ".", "10", "currently", "returning", "nothing" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/baserequest.go#L110-L145
2,118
mattbaird/elastigo
lib/coreget.go
GetCustom
func (c *Conn) GetCustom(index string, _type string, id string, args map[string]interface{}, source *json.RawMessage) (BaseResponse, error) { return c.get(index, _type, id, args, source) }
go
func (c *Conn) GetCustom(index string, _type string, id string, args map[string]interface{}, source *json.RawMessage) (BaseResponse, error) { return c.get(index, _type, id, args, source) }
[ "func", "(", "c", "*", "Conn", ")", "GetCustom", "(", "index", "string", ",", "_type", "string", ",", "id", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ",", "source", "*", "json", ".", "RawMessage", ")", "(", "BaseResponse", ",", "error", ")", "{", "return", "c", ".", "get", "(", "index", ",", "_type", ",", "id", ",", "args", ",", "source", ")", "\n", "}" ]
// Same as Get but with custom source type.
[ "Same", "as", "Get", "but", "with", "custom", "source", "type", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/coreget.go#L57-L59
2,119
mattbaird/elastigo
lib/coreget.go
GetSource
func (c *Conn) GetSource(index string, _type string, id string, args map[string]interface{}, source interface{}) error { url := fmt.Sprintf("/%s/%s/%s/_source", index, _type, id) body, err := c.DoCommand("GET", url, args, nil) if err == nil { err = json.Unmarshal(body, &source) } return err }
go
func (c *Conn) GetSource(index string, _type string, id string, args map[string]interface{}, source interface{}) error { url := fmt.Sprintf("/%s/%s/%s/_source", index, _type, id) body, err := c.DoCommand("GET", url, args, nil) if err == nil { err = json.Unmarshal(body, &source) } return err }
[ "func", "(", "c", "*", "Conn", ")", "GetSource", "(", "index", "string", ",", "_type", "string", ",", "id", "string", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ",", "source", "interface", "{", "}", ")", "error", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "index", ",", "_type", ",", "id", ")", "\n", "body", ",", "err", ":=", "c", ".", "DoCommand", "(", "\"", "\"", ",", "url", ",", "args", ",", "nil", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "source", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// GetSource retrieves the document by id and converts it to provided interface
[ "GetSource", "retrieves", "the", "document", "by", "id", "and", "converts", "it", "to", "provided", "interface" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/coreget.go#L62-L69
2,120
mattbaird/elastigo
lib/cataliasinfo.go
GetCatAliasInfo
func (c *Conn) GetCatAliasInfo(pattern string) (catAliases []CatAliasInfo) { catAliases = make([]CatAliasInfo, 0) //force it to only show the fields we know about aliases, err := c.DoCommand("GET", "/_cat/aliases/"+pattern, nil, nil) if err == nil { aliasLines := strings.Split(string(aliases[:]), "\n") for _, alias := range aliasLines { ci, _ := NewCatAliasInfo(alias) if nil != ci { catAliases = append(catAliases, *ci) } } } return catAliases }
go
func (c *Conn) GetCatAliasInfo(pattern string) (catAliases []CatAliasInfo) { catAliases = make([]CatAliasInfo, 0) //force it to only show the fields we know about aliases, err := c.DoCommand("GET", "/_cat/aliases/"+pattern, nil, nil) if err == nil { aliasLines := strings.Split(string(aliases[:]), "\n") for _, alias := range aliasLines { ci, _ := NewCatAliasInfo(alias) if nil != ci { catAliases = append(catAliases, *ci) } } } return catAliases }
[ "func", "(", "c", "*", "Conn", ")", "GetCatAliasInfo", "(", "pattern", "string", ")", "(", "catAliases", "[", "]", "CatAliasInfo", ")", "{", "catAliases", "=", "make", "(", "[", "]", "CatAliasInfo", ",", "0", ")", "\n", "//force it to only show the fields we know about", "aliases", ",", "err", ":=", "c", ".", "DoCommand", "(", "\"", "\"", ",", "\"", "\"", "+", "pattern", ",", "nil", ",", "nil", ")", "\n", "if", "err", "==", "nil", "{", "aliasLines", ":=", "strings", ".", "Split", "(", "string", "(", "aliases", "[", ":", "]", ")", ",", "\"", "\\n", "\"", ")", "\n", "for", "_", ",", "alias", ":=", "range", "aliasLines", "{", "ci", ",", "_", ":=", "NewCatAliasInfo", "(", "alias", ")", "\n", "if", "nil", "!=", "ci", "{", "catAliases", "=", "append", "(", "catAliases", ",", "*", "ci", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "catAliases", "\n", "}" ]
// Pull all the alias info from the connection
[ "Pull", "all", "the", "alias", "info", "from", "the", "connection" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/cataliasinfo.go#L25-L39
2,121
mattbaird/elastigo
lib/searchfilter.go
addFilters
func (f *FilterWrap) addFilters(fl []interface{}) { if len(fl) > 1 { fc := fl[0] switch fc.(type) { case BoolClause, string: f.boolClause = fc.(string) fl = fl[1:] } } f.filters = append(f.filters, fl...) }
go
func (f *FilterWrap) addFilters(fl []interface{}) { if len(fl) > 1 { fc := fl[0] switch fc.(type) { case BoolClause, string: f.boolClause = fc.(string) fl = fl[1:] } } f.filters = append(f.filters, fl...) }
[ "func", "(", "f", "*", "FilterWrap", ")", "addFilters", "(", "fl", "[", "]", "interface", "{", "}", ")", "{", "if", "len", "(", "fl", ")", ">", "1", "{", "fc", ":=", "fl", "[", "0", "]", "\n", "switch", "fc", ".", "(", "type", ")", "{", "case", "BoolClause", ",", "string", ":", "f", ".", "boolClause", "=", "fc", ".", "(", "string", ")", "\n", "fl", "=", "fl", "[", "1", ":", "]", "\n", "}", "\n", "}", "\n", "f", ".", "filters", "=", "append", "(", "f", ".", "filters", ",", "fl", "...", ")", "\n", "}" ]
// Custom marshalling to support the query dsl
[ "Custom", "marshalling", "to", "support", "the", "query", "dsl" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L77-L87
2,122
mattbaird/elastigo
lib/searchfilter.go
MarshalJSON
func (f *FilterWrap) MarshalJSON() ([]byte, error) { var root interface{} if len(f.filters) > 1 { root = map[string]interface{}{f.boolClause: f.filters} } else if len(f.filters) == 1 { root = f.filters[0] } return json.Marshal(root) }
go
func (f *FilterWrap) MarshalJSON() ([]byte, error) { var root interface{} if len(f.filters) > 1 { root = map[string]interface{}{f.boolClause: f.filters} } else if len(f.filters) == 1 { root = f.filters[0] } return json.Marshal(root) }
[ "func", "(", "f", "*", "FilterWrap", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "root", "interface", "{", "}", "\n", "if", "len", "(", "f", ".", "filters", ")", ">", "1", "{", "root", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "f", ".", "boolClause", ":", "f", ".", "filters", "}", "\n", "}", "else", "if", "len", "(", "f", ".", "filters", ")", "==", "1", "{", "root", "=", "f", ".", "filters", "[", "0", "]", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "root", ")", "\n", "}" ]
// MarshalJSON override for FilterWrap to match the expected ES syntax with the bool at the root
[ "MarshalJSON", "override", "for", "FilterWrap", "to", "match", "the", "expected", "ES", "syntax", "with", "the", "bool", "at", "the", "root" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L90-L98
2,123
mattbaird/elastigo
lib/searchfilter.go
Term
func (f *FilterOp) Term(field string, value interface{}) *FilterOp { if len(f.TermMap) == 0 { f.TermMap = make(map[string]interface{}) } f.TermMap[field] = value return f }
go
func (f *FilterOp) Term(field string, value interface{}) *FilterOp { if len(f.TermMap) == 0 { f.TermMap = make(map[string]interface{}) } f.TermMap[field] = value return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Term", "(", "field", "string", ",", "value", "interface", "{", "}", ")", "*", "FilterOp", "{", "if", "len", "(", "f", ".", "TermMap", ")", "==", "0", "{", "f", ".", "TermMap", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "\n\n", "f", ".", "TermMap", "[", "field", "]", "=", "value", "\n", "return", "f", "\n", "}" ]
// Term will add a term to the filter. // Multiple Term filters can be added, and ES will OR them. // If the term already exists in the FilterOp, the value will be overridden.
[ "Term", "will", "add", "a", "term", "to", "the", "filter", ".", "Multiple", "Term", "filters", "can", "be", "added", "and", "ES", "will", "OR", "them", ".", "If", "the", "term", "already", "exists", "in", "the", "FilterOp", "the", "value", "will", "be", "overridden", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L251-L258
2,124
mattbaird/elastigo
lib/searchfilter.go
And
func (f *FilterOp) And(filters ...*FilterOp) *FilterOp { if len(f.AndFilters) == 0 { f.AndFilters = filters[:] } else { f.AndFilters = append(f.AndFilters, filters...) } return f }
go
func (f *FilterOp) And(filters ...*FilterOp) *FilterOp { if len(f.AndFilters) == 0 { f.AndFilters = filters[:] } else { f.AndFilters = append(f.AndFilters, filters...) } return f }
[ "func", "(", "f", "*", "FilterOp", ")", "And", "(", "filters", "...", "*", "FilterOp", ")", "*", "FilterOp", "{", "if", "len", "(", "f", ".", "AndFilters", ")", "==", "0", "{", "f", ".", "AndFilters", "=", "filters", "[", ":", "]", "\n", "}", "else", "{", "f", ".", "AndFilters", "=", "append", "(", "f", ".", "AndFilters", ",", "filters", "...", ")", "\n", "}", "\n\n", "return", "f", "\n", "}" ]
// And will add an AND op to the filter. One or more FilterOps can be passed in.
[ "And", "will", "add", "an", "AND", "op", "to", "the", "filter", ".", "One", "or", "more", "FilterOps", "can", "be", "passed", "in", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L261-L269
2,125
mattbaird/elastigo
lib/searchfilter.go
Or
func (f *FilterOp) Or(filters ...*FilterOp) *FilterOp { if len(f.OrFilters) == 0 { f.OrFilters = filters[:] } else { f.OrFilters = append(f.OrFilters, filters...) } return f }
go
func (f *FilterOp) Or(filters ...*FilterOp) *FilterOp { if len(f.OrFilters) == 0 { f.OrFilters = filters[:] } else { f.OrFilters = append(f.OrFilters, filters...) } return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Or", "(", "filters", "...", "*", "FilterOp", ")", "*", "FilterOp", "{", "if", "len", "(", "f", ".", "OrFilters", ")", "==", "0", "{", "f", ".", "OrFilters", "=", "filters", "[", ":", "]", "\n", "}", "else", "{", "f", ".", "OrFilters", "=", "append", "(", "f", ".", "OrFilters", ",", "filters", "...", ")", "\n", "}", "\n\n", "return", "f", "\n", "}" ]
// Or will add an OR op to the filter. One or more FilterOps can be passed in.
[ "Or", "will", "add", "an", "OR", "op", "to", "the", "filter", ".", "One", "or", "more", "FilterOps", "can", "be", "passed", "in", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L272-L280
2,126
mattbaird/elastigo
lib/searchfilter.go
Not
func (f *FilterOp) Not(filters ...*FilterOp) *FilterOp { if len(f.NotFilters) == 0 { f.NotFilters = filters[:] } else { f.NotFilters = append(f.NotFilters, filters...) } return f }
go
func (f *FilterOp) Not(filters ...*FilterOp) *FilterOp { if len(f.NotFilters) == 0 { f.NotFilters = filters[:] } else { f.NotFilters = append(f.NotFilters, filters...) } return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Not", "(", "filters", "...", "*", "FilterOp", ")", "*", "FilterOp", "{", "if", "len", "(", "f", ".", "NotFilters", ")", "==", "0", "{", "f", ".", "NotFilters", "=", "filters", "[", ":", "]", "\n\n", "}", "else", "{", "f", ".", "NotFilters", "=", "append", "(", "f", ".", "NotFilters", ",", "filters", "...", ")", "\n", "}", "\n\n", "return", "f", "\n", "}" ]
// Not will add a NOT op to the filter. One or more FilterOps can be passed in.
[ "Not", "will", "add", "a", "NOT", "op", "to", "the", "filter", ".", "One", "or", "more", "FilterOps", "can", "be", "passed", "in", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L283-L292
2,127
mattbaird/elastigo
lib/searchfilter.go
NewGeoField
func NewGeoField(field string, latitude float32, longitude float32) GeoField { return GeoField{ GeoLocation: GeoLocation{Latitude: latitude, Longitude: longitude}, Field: field} }
go
func NewGeoField(field string, latitude float32, longitude float32) GeoField { return GeoField{ GeoLocation: GeoLocation{Latitude: latitude, Longitude: longitude}, Field: field} }
[ "func", "NewGeoField", "(", "field", "string", ",", "latitude", "float32", ",", "longitude", "float32", ")", "GeoField", "{", "return", "GeoField", "{", "GeoLocation", ":", "GeoLocation", "{", "Latitude", ":", "latitude", ",", "Longitude", ":", "longitude", "}", ",", "Field", ":", "field", "}", "\n", "}" ]
// NewGeoField is a helper function to create values for the GeoDistance filters
[ "NewGeoField", "is", "a", "helper", "function", "to", "create", "values", "for", "the", "GeoDistance", "filters" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L324-L328
2,128
mattbaird/elastigo
lib/searchfilter.go
Range
func (f *FilterOp) Range(field string, gte interface{}, gt interface{}, lte interface{}, lt interface{}, timeZone string) *FilterOp { if f.RangeMap == nil { f.RangeMap = make(map[string]RangeFilter) } f.RangeMap[field] = RangeFilter{ Gte: gte, Gt: gt, Lte: lte, Lt: lt, TimeZone: timeZone} return f }
go
func (f *FilterOp) Range(field string, gte interface{}, gt interface{}, lte interface{}, lt interface{}, timeZone string) *FilterOp { if f.RangeMap == nil { f.RangeMap = make(map[string]RangeFilter) } f.RangeMap[field] = RangeFilter{ Gte: gte, Gt: gt, Lte: lte, Lt: lt, TimeZone: timeZone} return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Range", "(", "field", "string", ",", "gte", "interface", "{", "}", ",", "gt", "interface", "{", "}", ",", "lte", "interface", "{", "}", ",", "lt", "interface", "{", "}", ",", "timeZone", "string", ")", "*", "FilterOp", "{", "if", "f", ".", "RangeMap", "==", "nil", "{", "f", ".", "RangeMap", "=", "make", "(", "map", "[", "string", "]", "RangeFilter", ")", "\n", "}", "\n\n", "f", ".", "RangeMap", "[", "field", "]", "=", "RangeFilter", "{", "Gte", ":", "gte", ",", "Gt", ":", "gt", ",", "Lte", ":", "lte", ",", "Lt", ":", "lt", ",", "TimeZone", ":", "timeZone", "}", "\n\n", "return", "f", "\n", "}" ]
// Range adds a range filter for the given field. // See the RangeFilter struct documentation for information about the parameters.
[ "Range", "adds", "a", "range", "filter", "for", "the", "given", "field", ".", "See", "the", "RangeFilter", "struct", "documentation", "for", "information", "about", "the", "parameters", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L350-L365
2,129
mattbaird/elastigo
lib/searchfilter.go
Type
func (f *FilterOp) Type(fieldType string) *FilterOp { f.TypeProp = &TypeFilter{Value: fieldType} return f }
go
func (f *FilterOp) Type(fieldType string) *FilterOp { f.TypeProp = &TypeFilter{Value: fieldType} return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Type", "(", "fieldType", "string", ")", "*", "FilterOp", "{", "f", ".", "TypeProp", "=", "&", "TypeFilter", "{", "Value", ":", "fieldType", "}", "\n", "return", "f", "\n", "}" ]
// Type adds a TYPE op to the filter.
[ "Type", "adds", "a", "TYPE", "op", "to", "the", "filter", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L368-L371
2,130
mattbaird/elastigo
lib/searchfilter.go
Ids
func (f *FilterOp) Ids(ids ...interface{}) *FilterOp { f.IdsProp = &IdsFilter{Values: ids} return f }
go
func (f *FilterOp) Ids(ids ...interface{}) *FilterOp { f.IdsProp = &IdsFilter{Values: ids} return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Ids", "(", "ids", "...", "interface", "{", "}", ")", "*", "FilterOp", "{", "f", ".", "IdsProp", "=", "&", "IdsFilter", "{", "Values", ":", "ids", "}", "\n", "return", "f", "\n", "}" ]
// Ids adds a IDS op to the filter.
[ "Ids", "adds", "a", "IDS", "op", "to", "the", "filter", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L374-L377
2,131
mattbaird/elastigo
lib/searchfilter.go
IdsByTypes
func (f *FilterOp) IdsByTypes(types []string, ids ...interface{}) *FilterOp { f.IdsProp = &IdsFilter{Type: types, Values: ids} return f }
go
func (f *FilterOp) IdsByTypes(types []string, ids ...interface{}) *FilterOp { f.IdsProp = &IdsFilter{Type: types, Values: ids} return f }
[ "func", "(", "f", "*", "FilterOp", ")", "IdsByTypes", "(", "types", "[", "]", "string", ",", "ids", "...", "interface", "{", "}", ")", "*", "FilterOp", "{", "f", ".", "IdsProp", "=", "&", "IdsFilter", "{", "Type", ":", "types", ",", "Values", ":", "ids", "}", "\n", "return", "f", "\n", "}" ]
// IdsByTypes adds a IDS op to the filter, but also allows passing in an array of types for the query.
[ "IdsByTypes", "adds", "a", "IDS", "op", "to", "the", "filter", "but", "also", "allows", "passing", "in", "an", "array", "of", "types", "for", "the", "query", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L380-L383
2,132
mattbaird/elastigo
lib/searchfilter.go
Exists
func (f *FilterOp) Exists(field string) *FilterOp { f.ExistsProp = &propertyPathMarker{Field: field} return f }
go
func (f *FilterOp) Exists(field string) *FilterOp { f.ExistsProp = &propertyPathMarker{Field: field} return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Exists", "(", "field", "string", ")", "*", "FilterOp", "{", "f", ".", "ExistsProp", "=", "&", "propertyPathMarker", "{", "Field", ":", "field", "}", "\n", "return", "f", "\n", "}" ]
// Exists adds an EXISTS op to the filter.
[ "Exists", "adds", "an", "EXISTS", "op", "to", "the", "filter", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L386-L389
2,133
mattbaird/elastigo
lib/searchfilter.go
Missing
func (f *FilterOp) Missing(field string) *FilterOp { f.MissingProp = &propertyPathMarker{Field: field} return f }
go
func (f *FilterOp) Missing(field string) *FilterOp { f.MissingProp = &propertyPathMarker{Field: field} return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Missing", "(", "field", "string", ")", "*", "FilterOp", "{", "f", ".", "MissingProp", "=", "&", "propertyPathMarker", "{", "Field", ":", "field", "}", "\n", "return", "f", "\n", "}" ]
// Missing adds an MISSING op to the filter.
[ "Missing", "adds", "an", "MISSING", "op", "to", "the", "filter", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L392-L395
2,134
mattbaird/elastigo
lib/searchfilter.go
Limit
func (f *FilterOp) Limit(maxResults int) *FilterOp { f.LimitProp = &LimitFilter{Value: maxResults} return f }
go
func (f *FilterOp) Limit(maxResults int) *FilterOp { f.LimitProp = &LimitFilter{Value: maxResults} return f }
[ "func", "(", "f", "*", "FilterOp", ")", "Limit", "(", "maxResults", "int", ")", "*", "FilterOp", "{", "f", ".", "LimitProp", "=", "&", "LimitFilter", "{", "Value", ":", "maxResults", "}", "\n", "return", "f", "\n", "}" ]
// Limit adds an LIMIT op to the filter.
[ "Limit", "adds", "an", "LIMIT", "op", "to", "the", "filter", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchfilter.go#L398-L401
2,135
mattbaird/elastigo
lib/connection.go
initializeHostPool
func (c *Conn) initializeHostPool() { // If no hosts are set, fallback to defaults if len(c.Hosts) == 0 { c.Hosts = append(c.Hosts, fmt.Sprintf("%s:%s", c.Domain, c.Port)) } // Epsilon Greedy is an algorithm that allows HostPool not only to // track failure state, but also to learn about "better" options in // terms of speed, and to pick from available hosts based on how well // they perform. This gives a weighted request rate to better // performing hosts, while still distributing requests to all hosts // (proportionate to their performance). The interface is the same as // the standard HostPool, but be sure to mark the HostResponse // immediately after executing the request to the host, as that will // stop the implicitly running request timer. // // A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132 if c.hp != nil { c.hp.Close() } c.hp = hostpool.NewEpsilonGreedy( c.Hosts, c.DecayDuration, &hostpool.LinearEpsilonValueCalculator{}) }
go
func (c *Conn) initializeHostPool() { // If no hosts are set, fallback to defaults if len(c.Hosts) == 0 { c.Hosts = append(c.Hosts, fmt.Sprintf("%s:%s", c.Domain, c.Port)) } // Epsilon Greedy is an algorithm that allows HostPool not only to // track failure state, but also to learn about "better" options in // terms of speed, and to pick from available hosts based on how well // they perform. This gives a weighted request rate to better // performing hosts, while still distributing requests to all hosts // (proportionate to their performance). The interface is the same as // the standard HostPool, but be sure to mark the HostResponse // immediately after executing the request to the host, as that will // stop the implicitly running request timer. // // A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132 if c.hp != nil { c.hp.Close() } c.hp = hostpool.NewEpsilonGreedy( c.Hosts, c.DecayDuration, &hostpool.LinearEpsilonValueCalculator{}) }
[ "func", "(", "c", "*", "Conn", ")", "initializeHostPool", "(", ")", "{", "// If no hosts are set, fallback to defaults", "if", "len", "(", "c", ".", "Hosts", ")", "==", "0", "{", "c", ".", "Hosts", "=", "append", "(", "c", ".", "Hosts", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Domain", ",", "c", ".", "Port", ")", ")", "\n", "}", "\n\n", "// Epsilon Greedy is an algorithm that allows HostPool not only to", "// track failure state, but also to learn about \"better\" options in", "// terms of speed, and to pick from available hosts based on how well", "// they perform. This gives a weighted request rate to better", "// performing hosts, while still distributing requests to all hosts", "// (proportionate to their performance). The interface is the same as", "// the standard HostPool, but be sure to mark the HostResponse", "// immediately after executing the request to the host, as that will", "// stop the implicitly running request timer.", "//", "// A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132", "if", "c", ".", "hp", "!=", "nil", "{", "c", ".", "hp", ".", "Close", "(", ")", "\n", "}", "\n", "c", ".", "hp", "=", "hostpool", ".", "NewEpsilonGreedy", "(", "c", ".", "Hosts", ",", "c", ".", "DecayDuration", ",", "&", "hostpool", ".", "LinearEpsilonValueCalculator", "{", "}", ")", "\n", "}" ]
// Set up the host pool to be used
[ "Set", "up", "the", "host", "pool", "to", "be", "used" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/connection.go#L109-L132
2,136
mattbaird/elastigo
lib/connection.go
splitHostnamePartsFromHost
func splitHostnamePartsFromHost(fullHost string, defaultPortNum string) (string, string) { h := strings.Split(fullHost, ":") if len(h) == 2 { return h[0], h[1] } return h[0], defaultPortNum }
go
func splitHostnamePartsFromHost(fullHost string, defaultPortNum string) (string, string) { h := strings.Split(fullHost, ":") if len(h) == 2 { return h[0], h[1] } return h[0], defaultPortNum }
[ "func", "splitHostnamePartsFromHost", "(", "fullHost", "string", ",", "defaultPortNum", "string", ")", "(", "string", ",", "string", ")", "{", "h", ":=", "strings", ".", "Split", "(", "fullHost", ",", "\"", "\"", ")", "\n\n", "if", "len", "(", "h", ")", "==", "2", "{", "return", "h", "[", "0", "]", ",", "h", "[", "1", "]", "\n", "}", "\n\n", "return", "h", "[", "0", "]", ",", "defaultPortNum", "\n", "}" ]
// Split apart the hostname on colon // Return the host and a default port if there is no separator
[ "Split", "apart", "the", "hostname", "on", "colon", "Return", "the", "host", "and", "a", "default", "port", "if", "there", "is", "no", "separator" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/connection.go#L177-L186
2,137
mattbaird/elastigo
lib/indicesaliases.go
AddAlias
func (c *Conn) AddAlias(index string, alias string) (BaseResponse, error) { var url string var retval BaseResponse if len(index) > 0 { url = "/_aliases" } else { return retval, fmt.Errorf("You must specify an index to create the alias on") } jsonAliases := JsonAliases{} jsonAliasAdd := JsonAliasAdd{} jsonAliasAdd.Add.Alias = alias jsonAliasAdd.Add.Index = index jsonAliases.Actions = append(jsonAliases.Actions, jsonAliasAdd) requestBody, err := json.Marshal(jsonAliases) if err != nil { return retval, err } body, err := c.DoCommand("POST", url, nil, requestBody) if err != nil { return retval, err } jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { return retval, jsonErr } return retval, err }
go
func (c *Conn) AddAlias(index string, alias string) (BaseResponse, error) { var url string var retval BaseResponse if len(index) > 0 { url = "/_aliases" } else { return retval, fmt.Errorf("You must specify an index to create the alias on") } jsonAliases := JsonAliases{} jsonAliasAdd := JsonAliasAdd{} jsonAliasAdd.Add.Alias = alias jsonAliasAdd.Add.Index = index jsonAliases.Actions = append(jsonAliases.Actions, jsonAliasAdd) requestBody, err := json.Marshal(jsonAliases) if err != nil { return retval, err } body, err := c.DoCommand("POST", url, nil, requestBody) if err != nil { return retval, err } jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { return retval, jsonErr } return retval, err }
[ "func", "(", "c", "*", "Conn", ")", "AddAlias", "(", "index", "string", ",", "alias", "string", ")", "(", "BaseResponse", ",", "error", ")", "{", "var", "url", "string", "\n", "var", "retval", "BaseResponse", "\n\n", "if", "len", "(", "index", ")", ">", "0", "{", "url", "=", "\"", "\"", "\n", "}", "else", "{", "return", "retval", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "jsonAliases", ":=", "JsonAliases", "{", "}", "\n", "jsonAliasAdd", ":=", "JsonAliasAdd", "{", "}", "\n", "jsonAliasAdd", ".", "Add", ".", "Alias", "=", "alias", "\n", "jsonAliasAdd", ".", "Add", ".", "Index", "=", "index", "\n", "jsonAliases", ".", "Actions", "=", "append", "(", "jsonAliases", ".", "Actions", ",", "jsonAliasAdd", ")", "\n", "requestBody", ",", "err", ":=", "json", ".", "Marshal", "(", "jsonAliases", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "retval", ",", "err", "\n", "}", "\n\n", "body", ",", "err", ":=", "c", ".", "DoCommand", "(", "\"", "\"", ",", "url", ",", "nil", ",", "requestBody", ")", "\n", "if", "err", "!=", "nil", "{", "return", "retval", ",", "err", "\n", "}", "\n\n", "jsonErr", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "retval", ")", "\n", "if", "jsonErr", "!=", "nil", "{", "return", "retval", ",", "jsonErr", "\n", "}", "\n\n", "return", "retval", ",", "err", "\n", "}" ]
// The API allows you to create an index alias through an API.
[ "The", "API", "allows", "you", "to", "create", "an", "index", "alias", "through", "an", "API", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/indicesaliases.go#L33-L65
2,138
mattbaird/elastigo
lib/coreindex.go
IndexWithParameters
func (c *Conn) IndexWithParameters(index string, _type string, id string, parentId string, version int, op_type string, routing string, timestamp string, ttl int, percolate string, timeout string, refresh bool, args map[string]interface{}, data interface{}) (BaseResponse, error) { var url string var retval BaseResponse url, err := GetIndexUrl(index, _type, id, parentId, version, op_type, routing, timestamp, ttl, percolate, timeout, refresh) if err != nil { return retval, err } var method string if len(id) == 0 { method = "POST" } else { method = "PUT" } body, err := c.DoCommand(method, url, args, data) if err != nil { return retval, err } if err == nil { // marshall into json jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { return retval, jsonErr } } return retval, err }
go
func (c *Conn) IndexWithParameters(index string, _type string, id string, parentId string, version int, op_type string, routing string, timestamp string, ttl int, percolate string, timeout string, refresh bool, args map[string]interface{}, data interface{}) (BaseResponse, error) { var url string var retval BaseResponse url, err := GetIndexUrl(index, _type, id, parentId, version, op_type, routing, timestamp, ttl, percolate, timeout, refresh) if err != nil { return retval, err } var method string if len(id) == 0 { method = "POST" } else { method = "PUT" } body, err := c.DoCommand(method, url, args, data) if err != nil { return retval, err } if err == nil { // marshall into json jsonErr := json.Unmarshal(body, &retval) if jsonErr != nil { return retval, jsonErr } } return retval, err }
[ "func", "(", "c", "*", "Conn", ")", "IndexWithParameters", "(", "index", "string", ",", "_type", "string", ",", "id", "string", ",", "parentId", "string", ",", "version", "int", ",", "op_type", "string", ",", "routing", "string", ",", "timestamp", "string", ",", "ttl", "int", ",", "percolate", "string", ",", "timeout", "string", ",", "refresh", "bool", ",", "args", "map", "[", "string", "]", "interface", "{", "}", ",", "data", "interface", "{", "}", ")", "(", "BaseResponse", ",", "error", ")", "{", "var", "url", "string", "\n", "var", "retval", "BaseResponse", "\n", "url", ",", "err", ":=", "GetIndexUrl", "(", "index", ",", "_type", ",", "id", ",", "parentId", ",", "version", ",", "op_type", ",", "routing", ",", "timestamp", ",", "ttl", ",", "percolate", ",", "timeout", ",", "refresh", ")", "\n", "if", "err", "!=", "nil", "{", "return", "retval", ",", "err", "\n", "}", "\n", "var", "method", "string", "\n", "if", "len", "(", "id", ")", "==", "0", "{", "method", "=", "\"", "\"", "\n", "}", "else", "{", "method", "=", "\"", "\"", "\n", "}", "\n", "body", ",", "err", ":=", "c", ".", "DoCommand", "(", "method", ",", "url", ",", "args", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "retval", ",", "err", "\n", "}", "\n", "if", "err", "==", "nil", "{", "// marshall into json", "jsonErr", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "retval", ")", "\n", "if", "jsonErr", "!=", "nil", "{", "return", "retval", ",", "jsonErr", "\n", "}", "\n", "}", "\n", "return", "retval", ",", "err", "\n", "}" ]
// IndexWithParameters takes all the potential parameters available
[ "IndexWithParameters", "takes", "all", "the", "potential", "parameters", "available" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/coreindex.go#L41-L68
2,139
mattbaird/elastigo
lib/searchquery.go
SetLenient
func (q *QueryDsl) SetLenient(lenient bool) *QueryDsl { q.QueryEmbed.Qs.Lenient = lenient return q }
go
func (q *QueryDsl) SetLenient(lenient bool) *QueryDsl { q.QueryEmbed.Qs.Lenient = lenient return q }
[ "func", "(", "q", "*", "QueryDsl", ")", "SetLenient", "(", "lenient", "bool", ")", "*", "QueryDsl", "{", "q", ".", "QueryEmbed", ".", "Qs", ".", "Lenient", "=", "lenient", "\n", "return", "q", "\n", "}" ]
// SetLenient sets whether the query should ignore format based failures, // such as passing in text to a number field.
[ "SetLenient", "sets", "whether", "the", "query", "should", "ignore", "format", "based", "failures", "such", "as", "passing", "in", "text", "to", "a", "number", "field", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchquery.go#L149-L152
2,140
mattbaird/elastigo
lib/searchquery.go
Filter
func (q *QueryDsl) Filter(f *FilterOp) *QueryDsl { q.FilterVal = f return q }
go
func (q *QueryDsl) Filter(f *FilterOp) *QueryDsl { q.FilterVal = f return q }
[ "func", "(", "q", "*", "QueryDsl", ")", "Filter", "(", "f", "*", "FilterOp", ")", "*", "QueryDsl", "{", "q", ".", "FilterVal", "=", "f", "\n", "return", "q", "\n", "}" ]
// Filter this query
[ "Filter", "this", "query" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchquery.go#L176-L179
2,141
mattbaird/elastigo
lib/searchquery.go
MultiMatch
func (q *QueryDsl) MultiMatch(s string, fields []string) *QueryDsl { q.QueryEmbed.MultiMatch = &MultiMatch{Query: s, Fields: fields} return q }
go
func (q *QueryDsl) MultiMatch(s string, fields []string) *QueryDsl { q.QueryEmbed.MultiMatch = &MultiMatch{Query: s, Fields: fields} return q }
[ "func", "(", "q", "*", "QueryDsl", ")", "MultiMatch", "(", "s", "string", ",", "fields", "[", "]", "string", ")", "*", "QueryDsl", "{", "q", ".", "QueryEmbed", ".", "MultiMatch", "=", "&", "MultiMatch", "{", "Query", ":", "s", ",", "Fields", ":", "fields", "}", "\n", "return", "q", "\n", "}" ]
// MultiMatch allows searching against multiple fields.
[ "MultiMatch", "allows", "searching", "against", "multiple", "fields", "." ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchquery.go#L182-L185
2,142
mattbaird/elastigo
lib/searchquery.go
NewQueryString
func NewQueryString(field, query string) QueryString { return QueryString{"", field, query, "", "", nil, false} }
go
func NewQueryString(field, query string) QueryString { return QueryString{"", field, query, "", "", nil, false} }
[ "func", "NewQueryString", "(", "field", ",", "query", "string", ")", "QueryString", "{", "return", "QueryString", "{", "\"", "\"", ",", "field", ",", "query", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "false", "}", "\n", "}" ]
// QueryString based search
[ "QueryString", "based", "search" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchquery.go#L202-L204
2,143
mattbaird/elastigo
lib/searchsearch.go
Search
func (s *SearchDsl) Search(srch string) *SearchDsl { s.QueryVal = Query().Search(srch) return s }
go
func (s *SearchDsl) Search(srch string) *SearchDsl { s.QueryVal = Query().Search(srch) return s }
[ "func", "(", "s", "*", "SearchDsl", ")", "Search", "(", "srch", "string", ")", "*", "SearchDsl", "{", "s", ".", "QueryVal", "=", "Query", "(", ")", ".", "Search", "(", "srch", ")", "\n", "return", "s", "\n", "}" ]
// Search is a simple interface to search, doesn't have the power of query // but uses a simple query_string search
[ "Search", "is", "a", "simple", "interface", "to", "search", "doesn", "t", "have", "the", "power", "of", "query", "but", "uses", "a", "simple", "query_string", "search" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/searchsearch.go#L107-L110
2,144
mattbaird/elastigo
lib/catshardinfo.go
String
func (s *CatShards) String() string { var buffer bytes.Buffer if s != nil { for _, cs := range *s { buffer.WriteString(fmt.Sprintf("%v\n", cs)) } } return buffer.String() }
go
func (s *CatShards) String() string { var buffer bytes.Buffer if s != nil { for _, cs := range *s { buffer.WriteString(fmt.Sprintf("%v\n", cs)) } } return buffer.String() }
[ "func", "(", "s", "*", "CatShards", ")", "String", "(", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n\n", "if", "s", "!=", "nil", "{", "for", "_", ",", "cs", ":=", "range", "*", "s", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "cs", ")", ")", "\n", "}", "\n", "}", "\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// Stringify the shards
[ "Stringify", "the", "shards" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/catshardinfo.go#L14-L23
2,145
mattbaird/elastigo
lib/catshardinfo.go
String
func (s *CatShardInfo) String() string { if s == nil { return ":::::::" } return fmt.Sprintf("%v:%v:%v:%v:%v:%v:%v:%v", s.IndexName, s.Shard, s.Primary, s.State, s.Docs, s.Store, s.NodeIP, s.NodeName) }
go
func (s *CatShardInfo) String() string { if s == nil { return ":::::::" } return fmt.Sprintf("%v:%v:%v:%v:%v:%v:%v:%v", s.IndexName, s.Shard, s.Primary, s.State, s.Docs, s.Store, s.NodeIP, s.NodeName) }
[ "func", "(", "s", "*", "CatShardInfo", ")", "String", "(", ")", "string", "{", "if", "s", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "IndexName", ",", "s", ".", "Shard", ",", "s", ".", "Primary", ",", "s", ".", "State", ",", "s", ".", "Docs", ",", "s", ".", "Store", ",", "s", ".", "NodeIP", ",", "s", ".", "NodeName", ")", "\n", "}" ]
// Print shard info
[ "Print", "shard", "info" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/catshardinfo.go#L82-L88
2,146
mattbaird/elastigo
lib/catshardinfo.go
GetCatShards
func (c *Conn) GetCatShards() (shards CatShards) { shards = make(CatShards, 0) //force it to only respond with the columns we know about and in a forced order args := map[string]interface{}{"bytes": "b", "h": "index,shard,prirep,state,docs,store,ip,node"} s, err := c.DoCommand("GET", "/_cat/shards", args, nil) if err == nil { catShardLines := strings.Split(string(s[:]), "\n") for _, shardLine := range catShardLines { shard, _ := NewCatShardInfo(shardLine) if nil != shard { shards = append(shards, *shard) } } } return shards }
go
func (c *Conn) GetCatShards() (shards CatShards) { shards = make(CatShards, 0) //force it to only respond with the columns we know about and in a forced order args := map[string]interface{}{"bytes": "b", "h": "index,shard,prirep,state,docs,store,ip,node"} s, err := c.DoCommand("GET", "/_cat/shards", args, nil) if err == nil { catShardLines := strings.Split(string(s[:]), "\n") for _, shardLine := range catShardLines { shard, _ := NewCatShardInfo(shardLine) if nil != shard { shards = append(shards, *shard) } } } return shards }
[ "func", "(", "c", "*", "Conn", ")", "GetCatShards", "(", ")", "(", "shards", "CatShards", ")", "{", "shards", "=", "make", "(", "CatShards", ",", "0", ")", "\n", "//force it to only respond with the columns we know about and in a forced order", "args", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", "}", "\n", "s", ",", "err", ":=", "c", ".", "DoCommand", "(", "\"", "\"", ",", "\"", "\"", ",", "args", ",", "nil", ")", "\n", "if", "err", "==", "nil", "{", "catShardLines", ":=", "strings", ".", "Split", "(", "string", "(", "s", "[", ":", "]", ")", ",", "\"", "\\n", "\"", ")", "\n", "for", "_", ",", "shardLine", ":=", "range", "catShardLines", "{", "shard", ",", "_", ":=", "NewCatShardInfo", "(", "shardLine", ")", "\n", "if", "nil", "!=", "shard", "{", "shards", "=", "append", "(", "shards", ",", "*", "shard", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "shards", "\n", "}" ]
// Get all the shards, even the bad ones
[ "Get", "all", "the", "shards", "even", "the", "bad", "ones" ]
2fe47fd29e4b70353f852ede77a196830d2924ec
https://github.com/mattbaird/elastigo/blob/2fe47fd29e4b70353f852ede77a196830d2924ec/lib/catshardinfo.go#L91-L106
2,147
jpillora/backoff
backoff.go
Duration
func (b *Backoff) Duration() time.Duration { d := b.ForAttempt(b.attempt) b.attempt++ return d }
go
func (b *Backoff) Duration() time.Duration { d := b.ForAttempt(b.attempt) b.attempt++ return d }
[ "func", "(", "b", "*", "Backoff", ")", "Duration", "(", ")", "time", ".", "Duration", "{", "d", ":=", "b", ".", "ForAttempt", "(", "b", ".", "attempt", ")", "\n", "b", ".", "attempt", "++", "\n", "return", "d", "\n", "}" ]
// Duration returns the duration for the current attempt before incrementing // the attempt counter. See ForAttempt.
[ "Duration", "returns", "the", "duration", "for", "the", "current", "attempt", "before", "incrementing", "the", "attempt", "counter", ".", "See", "ForAttempt", "." ]
3050d21c67d7c46b07ca1b5e1be0b26669c8d04c
https://github.com/jpillora/backoff/blob/3050d21c67d7c46b07ca1b5e1be0b26669c8d04c/backoff.go#L27-L31
2,148
jpillora/backoff
backoff.go
ForAttempt
func (b *Backoff) ForAttempt(attempt float64) time.Duration { // Zero-values are nonsensical, so we use // them to apply defaults min := b.Min if min <= 0 { min = 100 * time.Millisecond } max := b.Max if max <= 0 { max = 10 * time.Second } if min >= max { // short-circuit return max } factor := b.Factor if factor <= 0 { factor = 2 } //calculate this duration minf := float64(min) durf := minf * math.Pow(factor, attempt) if b.Jitter { durf = rand.Float64()*(durf-minf) + minf } //ensure float64 wont overflow int64 if durf > maxInt64 { return max } dur := time.Duration(durf) //keep within bounds if dur < min { return min } if dur > max { return max } return dur }
go
func (b *Backoff) ForAttempt(attempt float64) time.Duration { // Zero-values are nonsensical, so we use // them to apply defaults min := b.Min if min <= 0 { min = 100 * time.Millisecond } max := b.Max if max <= 0 { max = 10 * time.Second } if min >= max { // short-circuit return max } factor := b.Factor if factor <= 0 { factor = 2 } //calculate this duration minf := float64(min) durf := minf * math.Pow(factor, attempt) if b.Jitter { durf = rand.Float64()*(durf-minf) + minf } //ensure float64 wont overflow int64 if durf > maxInt64 { return max } dur := time.Duration(durf) //keep within bounds if dur < min { return min } if dur > max { return max } return dur }
[ "func", "(", "b", "*", "Backoff", ")", "ForAttempt", "(", "attempt", "float64", ")", "time", ".", "Duration", "{", "// Zero-values are nonsensical, so we use", "// them to apply defaults", "min", ":=", "b", ".", "Min", "\n", "if", "min", "<=", "0", "{", "min", "=", "100", "*", "time", ".", "Millisecond", "\n", "}", "\n", "max", ":=", "b", ".", "Max", "\n", "if", "max", "<=", "0", "{", "max", "=", "10", "*", "time", ".", "Second", "\n", "}", "\n", "if", "min", ">=", "max", "{", "// short-circuit", "return", "max", "\n", "}", "\n", "factor", ":=", "b", ".", "Factor", "\n", "if", "factor", "<=", "0", "{", "factor", "=", "2", "\n", "}", "\n", "//calculate this duration", "minf", ":=", "float64", "(", "min", ")", "\n", "durf", ":=", "minf", "*", "math", ".", "Pow", "(", "factor", ",", "attempt", ")", "\n", "if", "b", ".", "Jitter", "{", "durf", "=", "rand", ".", "Float64", "(", ")", "*", "(", "durf", "-", "minf", ")", "+", "minf", "\n", "}", "\n", "//ensure float64 wont overflow int64", "if", "durf", ">", "maxInt64", "{", "return", "max", "\n", "}", "\n", "dur", ":=", "time", ".", "Duration", "(", "durf", ")", "\n", "//keep within bounds", "if", "dur", "<", "min", "{", "return", "min", "\n", "}", "\n", "if", "dur", ">", "max", "{", "return", "max", "\n", "}", "\n", "return", "dur", "\n", "}" ]
// ForAttempt returns the duration for a specific attempt. This is useful if // you have a large number of independent Backoffs, but don't want use // unnecessary memory storing the Backoff parameters per Backoff. The first // attempt should be 0. // // ForAttempt is concurrent-safe.
[ "ForAttempt", "returns", "the", "duration", "for", "a", "specific", "attempt", ".", "This", "is", "useful", "if", "you", "have", "a", "large", "number", "of", "independent", "Backoffs", "but", "don", "t", "want", "use", "unnecessary", "memory", "storing", "the", "Backoff", "parameters", "per", "Backoff", ".", "The", "first", "attempt", "should", "be", "0", ".", "ForAttempt", "is", "concurrent", "-", "safe", "." ]
3050d21c67d7c46b07ca1b5e1be0b26669c8d04c
https://github.com/jpillora/backoff/blob/3050d21c67d7c46b07ca1b5e1be0b26669c8d04c/backoff.go#L41-L79
2,149
jpillora/backoff
backoff.go
Copy
func (b *Backoff) Copy() *Backoff { return &Backoff{ Factor: b.Factor, Jitter: b.Jitter, Min: b.Min, Max: b.Max, } }
go
func (b *Backoff) Copy() *Backoff { return &Backoff{ Factor: b.Factor, Jitter: b.Jitter, Min: b.Min, Max: b.Max, } }
[ "func", "(", "b", "*", "Backoff", ")", "Copy", "(", ")", "*", "Backoff", "{", "return", "&", "Backoff", "{", "Factor", ":", "b", ".", "Factor", ",", "Jitter", ":", "b", ".", "Jitter", ",", "Min", ":", "b", ".", "Min", ",", "Max", ":", "b", ".", "Max", ",", "}", "\n", "}" ]
// Copy returns a backoff with equals constraints as the original
[ "Copy", "returns", "a", "backoff", "with", "equals", "constraints", "as", "the", "original" ]
3050d21c67d7c46b07ca1b5e1be0b26669c8d04c
https://github.com/jpillora/backoff/blob/3050d21c67d7c46b07ca1b5e1be0b26669c8d04c/backoff.go#L92-L99
2,150
yosssi/gmq
mqtt/packet/connack.go
NewCONNACKFromBytes
func NewCONNACKFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validateCONNACKBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Create a CONNACK Packet. p := &CONNACK{ sessionPresent: variableHeader[0]<<7 == 0x80, connectReturnCode: variableHeader[1], } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
go
func NewCONNACKFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validateCONNACKBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Create a CONNACK Packet. p := &CONNACK{ sessionPresent: variableHeader[0]<<7 == 0x80, connectReturnCode: variableHeader[1], } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
[ "func", "NewCONNACKFromBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validateCONNACKBytes", "(", "fixedHeader", ",", "variableHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a CONNACK Packet.", "p", ":=", "&", "CONNACK", "{", "sessionPresent", ":", "variableHeader", "[", "0", "]", "<<", "7", "==", "0x80", ",", "connectReturnCode", ":", "variableHeader", "[", "1", "]", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "variableHeader", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewCONNACKFromBytes creates the CONNACK Packet // from the byte data and returns it.
[ "NewCONNACKFromBytes", "creates", "the", "CONNACK", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/connack.go#L42-L62
2,151
yosssi/gmq
mqtt/packet/connack.go
validateCONNACKBytes
func validateCONNACKBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenCONNACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypeCONNACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenCONNACKVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenCONNACKVariableHeader { return ErrInvalidVariableHeaderLen } // Check the reserved bits of the variable header. if variableHeader[0]>>1 != 0x00 { return ErrInvalidVariableHeader } // Check the Connect Return code of the variable header. switch variableHeader[1] { case connRetAccepted, connRetUnacceptableProtocolVersion, connRetIdentifierRejected, connRetServerUnavailable, connRetBadUserNameOrPassword, connRetNotAuthorized: default: return ErrInvalidConnectReturnCode } return nil }
go
func validateCONNACKBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenCONNACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypeCONNACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenCONNACKVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenCONNACKVariableHeader { return ErrInvalidVariableHeaderLen } // Check the reserved bits of the variable header. if variableHeader[0]>>1 != 0x00 { return ErrInvalidVariableHeader } // Check the Connect Return code of the variable header. switch variableHeader[1] { case connRetAccepted, connRetUnacceptableProtocolVersion, connRetIdentifierRejected, connRetServerUnavailable, connRetBadUserNameOrPassword, connRetNotAuthorized: default: return ErrInvalidConnectReturnCode } return nil }
[ "func", "validateCONNACKBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "!=", "lenCONNACKFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypeCONNACK", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "<<", "4", "!=", "0x00", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the Remaining Length of the fixed header.", "if", "fixedHeader", "[", "1", "]", "!=", "lenCONNACKVariableHeader", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// Check the length of the variable header.", "if", "len", "(", "variableHeader", ")", "!=", "lenCONNACKVariableHeader", "{", "return", "ErrInvalidVariableHeaderLen", "\n", "}", "\n\n", "// Check the reserved bits of the variable header.", "if", "variableHeader", "[", "0", "]", ">>", "1", "!=", "0x00", "{", "return", "ErrInvalidVariableHeader", "\n", "}", "\n\n", "// Check the Connect Return code of the variable header.", "switch", "variableHeader", "[", "1", "]", "{", "case", "connRetAccepted", ",", "connRetUnacceptableProtocolVersion", ",", "connRetIdentifierRejected", ",", "connRetServerUnavailable", ",", "connRetBadUserNameOrPassword", ",", "connRetNotAuthorized", ":", "default", ":", "return", "ErrInvalidConnectReturnCode", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateCONNACKBytes validates the fixed header and the variable header.
[ "validateCONNACKBytes", "validates", "the", "fixed", "header", "and", "the", "variable", "header", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/connack.go#L65-L116
2,152
yosssi/gmq
cmd/gmq-cli/command_sub.go
newCommandSub
func newCommandSub(args []string, cli *client.Client) (command, error) { // Create a flag set. var flg flag.FlagSet // Define the flags. topicFilter := flg.String("t", "", "Topic Filter") qos := flg.Uint("q", uint(mqtt.QoS0), "QoS") // Parse the flag. if err := flg.Parse(args); err != nil { return nil, errCmdArgsParse } // Create a sub command. cmd := &commandSub{ cli: cli, subscribeOpts: &client.SubscribeOptions{ SubReqs: []*client.SubReq{ &client.SubReq{ TopicFilter: []byte(*topicFilter), QoS: byte(*qos), Handler: messageHandler, }, }, }, } // Return the command. return cmd, nil }
go
func newCommandSub(args []string, cli *client.Client) (command, error) { // Create a flag set. var flg flag.FlagSet // Define the flags. topicFilter := flg.String("t", "", "Topic Filter") qos := flg.Uint("q", uint(mqtt.QoS0), "QoS") // Parse the flag. if err := flg.Parse(args); err != nil { return nil, errCmdArgsParse } // Create a sub command. cmd := &commandSub{ cli: cli, subscribeOpts: &client.SubscribeOptions{ SubReqs: []*client.SubReq{ &client.SubReq{ TopicFilter: []byte(*topicFilter), QoS: byte(*qos), Handler: messageHandler, }, }, }, } // Return the command. return cmd, nil }
[ "func", "newCommandSub", "(", "args", "[", "]", "string", ",", "cli", "*", "client", ".", "Client", ")", "(", "command", ",", "error", ")", "{", "// Create a flag set.", "var", "flg", "flag", ".", "FlagSet", "\n\n", "// Define the flags.", "topicFilter", ":=", "flg", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "qos", ":=", "flg", ".", "Uint", "(", "\"", "\"", ",", "uint", "(", "mqtt", ".", "QoS0", ")", ",", "\"", "\"", ")", "\n\n", "// Parse the flag.", "if", "err", ":=", "flg", ".", "Parse", "(", "args", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errCmdArgsParse", "\n", "}", "\n\n", "// Create a sub command.", "cmd", ":=", "&", "commandSub", "{", "cli", ":", "cli", ",", "subscribeOpts", ":", "&", "client", ".", "SubscribeOptions", "{", "SubReqs", ":", "[", "]", "*", "client", ".", "SubReq", "{", "&", "client", ".", "SubReq", "{", "TopicFilter", ":", "[", "]", "byte", "(", "*", "topicFilter", ")", ",", "QoS", ":", "byte", "(", "*", "qos", ")", ",", "Handler", ":", "messageHandler", ",", "}", ",", "}", ",", "}", ",", "}", "\n\n", "// Return the command.", "return", "cmd", ",", "nil", "\n", "}" ]
// newCommandSub creates and returns a sub command.
[ "newCommandSub", "creates", "and", "returns", "a", "sub", "command", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/cmd/gmq-cli/command_sub.go#L26-L55
2,153
yosssi/gmq
mqtt/packet/decode.go
decodeUint16
func decodeUint16(b []byte) (uint16, error) { // Check the length of the slice of bytes. if len(b) != 2 { return 0, ErrInvalidByteLen } return uint16(b[0])<<8 | uint16(b[1]), nil }
go
func decodeUint16(b []byte) (uint16, error) { // Check the length of the slice of bytes. if len(b) != 2 { return 0, ErrInvalidByteLen } return uint16(b[0])<<8 | uint16(b[1]), nil }
[ "func", "decodeUint16", "(", "b", "[", "]", "byte", ")", "(", "uint16", ",", "error", ")", "{", "// Check the length of the slice of bytes.", "if", "len", "(", "b", ")", "!=", "2", "{", "return", "0", ",", "ErrInvalidByteLen", "\n", "}", "\n\n", "return", "uint16", "(", "b", "[", "0", "]", ")", "<<", "8", "|", "uint16", "(", "b", "[", "1", "]", ")", ",", "nil", "\n", "}" ]
// decodeUint16 converts the slice of bytes in big-endian order // into an unsigned 16-bit integer.
[ "decodeUint16", "converts", "the", "slice", "of", "bytes", "in", "big", "-", "endian", "order", "into", "an", "unsigned", "16", "-", "bit", "integer", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/decode.go#L10-L17
2,154
yosssi/gmq
cmd/gmq-cli/command_pub.go
newCommandPub
func newCommandPub(args []string, cli *client.Client) (command, error) { // Create a flag set. var flg flag.FlagSet // Define the flags. qos := flg.Uint("q", uint(mqtt.QoS0), "QoS") retain := flg.Bool("r", false, "Retain") topicName := flg.String("t", "", "Topic Name") message := flg.String("m", "", "Application Message") // Parse the flag. if err := flg.Parse(args); err != nil { return nil, errCmdArgsParse } // Create a pub command. cmd := &commandPub{ cli: cli, publishOpts: &client.PublishOptions{ QoS: byte(*qos), Retain: *retain, TopicName: []byte(*topicName), Message: []byte(*message), }, } // Return the command. return cmd, nil }
go
func newCommandPub(args []string, cli *client.Client) (command, error) { // Create a flag set. var flg flag.FlagSet // Define the flags. qos := flg.Uint("q", uint(mqtt.QoS0), "QoS") retain := flg.Bool("r", false, "Retain") topicName := flg.String("t", "", "Topic Name") message := flg.String("m", "", "Application Message") // Parse the flag. if err := flg.Parse(args); err != nil { return nil, errCmdArgsParse } // Create a pub command. cmd := &commandPub{ cli: cli, publishOpts: &client.PublishOptions{ QoS: byte(*qos), Retain: *retain, TopicName: []byte(*topicName), Message: []byte(*message), }, } // Return the command. return cmd, nil }
[ "func", "newCommandPub", "(", "args", "[", "]", "string", ",", "cli", "*", "client", ".", "Client", ")", "(", "command", ",", "error", ")", "{", "// Create a flag set.", "var", "flg", "flag", ".", "FlagSet", "\n\n", "// Define the flags.", "qos", ":=", "flg", ".", "Uint", "(", "\"", "\"", ",", "uint", "(", "mqtt", ".", "QoS0", ")", ",", "\"", "\"", ")", "\n", "retain", ":=", "flg", ".", "Bool", "(", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "topicName", ":=", "flg", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "message", ":=", "flg", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Parse the flag.", "if", "err", ":=", "flg", ".", "Parse", "(", "args", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errCmdArgsParse", "\n", "}", "\n\n", "// Create a pub command.", "cmd", ":=", "&", "commandPub", "{", "cli", ":", "cli", ",", "publishOpts", ":", "&", "client", ".", "PublishOptions", "{", "QoS", ":", "byte", "(", "*", "qos", ")", ",", "Retain", ":", "*", "retain", ",", "TopicName", ":", "[", "]", "byte", "(", "*", "topicName", ")", ",", "Message", ":", "[", "]", "byte", "(", "*", "message", ")", ",", "}", ",", "}", "\n\n", "// Return the command.", "return", "cmd", ",", "nil", "\n", "}" ]
// newCommandPub creates and returns a pub command.
[ "newCommandPub", "creates", "and", "returns", "a", "pub", "command", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/cmd/gmq-cli/command_pub.go#L25-L53
2,155
yosssi/gmq
mqtt/packet/suback.go
NewSUBACKFromBytes
func NewSUBACKFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Validate the byte data. if err := validateSUBACKBytes(fixedHeader, remaining); err != nil { return nil, err } // Extract the variable header. variableHeader := remaining[0:lenSUBACKVariableHeader] // Extract the payload. payload := remaining[lenSUBACKVariableHeader:] // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBACK Packet. p := &SUBACK{ PacketID: packetID, ReturnCodes: payload, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Set the payload to the Packet. p.payload = payload // Return the Packet. return p, nil }
go
func NewSUBACKFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Validate the byte data. if err := validateSUBACKBytes(fixedHeader, remaining); err != nil { return nil, err } // Extract the variable header. variableHeader := remaining[0:lenSUBACKVariableHeader] // Extract the payload. payload := remaining[lenSUBACKVariableHeader:] // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBACK Packet. p := &SUBACK{ PacketID: packetID, ReturnCodes: payload, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Set the payload to the Packet. p.payload = payload // Return the Packet. return p, nil }
[ "func", "NewSUBACKFromBytes", "(", "fixedHeader", "FixedHeader", ",", "remaining", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validateSUBACKBytes", "(", "fixedHeader", ",", "remaining", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Extract the variable header.", "variableHeader", ":=", "remaining", "[", "0", ":", "lenSUBACKVariableHeader", "]", "\n\n", "// Extract the payload.", "payload", ":=", "remaining", "[", "lenSUBACKVariableHeader", ":", "]", "\n\n", "// Decode the Packet Identifier.", "// No error occur because of the precedent validation and", "// the returned error is not be taken care of.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Create a PUBACK Packet.", "p", ":=", "&", "SUBACK", "{", "PacketID", ":", "packetID", ",", "ReturnCodes", ":", "payload", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "variableHeader", "\n\n", "// Set the payload to the Packet.", "p", ".", "payload", "=", "payload", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewSUBACKFromBytes creates a SUBACK Packet // from the byte data and returns it.
[ "NewSUBACKFromBytes", "creates", "a", "SUBACK", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/suback.go#L32-L66
2,156
yosssi/gmq
mqtt/packet/suback.go
validateSUBACKBytes
func validateSUBACKBytes(fixedHeader FixedHeader, remaining []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) < minLenSUBACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypeSUBACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the length of the remaining. if len(remaining) < lenSUBACKVariableHeader+1 { return ErrInvalidRemainingLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(remaining[0:lenSUBACKVariableHeader]) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } // Check each Return Code. for _, b := range remaining[lenSUBACKVariableHeader:] { if !mqtt.ValidQoS(b) && b != SUBACKRetFailure { return ErrInvalidSUBACKReturnCode } } return nil }
go
func validateSUBACKBytes(fixedHeader FixedHeader, remaining []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) < minLenSUBACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypeSUBACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the length of the remaining. if len(remaining) < lenSUBACKVariableHeader+1 { return ErrInvalidRemainingLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(remaining[0:lenSUBACKVariableHeader]) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } // Check each Return Code. for _, b := range remaining[lenSUBACKVariableHeader:] { if !mqtt.ValidQoS(b) && b != SUBACKRetFailure { return ErrInvalidSUBACKReturnCode } } return nil }
[ "func", "validateSUBACKBytes", "(", "fixedHeader", "FixedHeader", ",", "remaining", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "<", "minLenSUBACKFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypeSUBACK", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "<<", "4", "!=", "0x00", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the length of the remaining.", "if", "len", "(", "remaining", ")", "<", "lenSUBACKVariableHeader", "+", "1", "{", "return", "ErrInvalidRemainingLen", "\n", "}", "\n\n", "// Extract the Packet Identifier.", "packetID", ",", "_", ":=", "decodeUint16", "(", "remaining", "[", "0", ":", "lenSUBACKVariableHeader", "]", ")", "\n\n", "// Check the Packet Identifier.", "if", "packetID", "==", "0", "{", "return", "ErrInvalidPacketID", "\n", "}", "\n\n", "// Check each Return Code.", "for", "_", ",", "b", ":=", "range", "remaining", "[", "lenSUBACKVariableHeader", ":", "]", "{", "if", "!", "mqtt", ".", "ValidQoS", "(", "b", ")", "&&", "b", "!=", "SUBACKRetFailure", "{", "return", "ErrInvalidSUBACKReturnCode", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateSUBACKBytes validates the fixed header and the remaining.
[ "validateSUBACKBytes", "validates", "the", "fixed", "header", "and", "the", "remaining", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/suback.go#L69-L112
2,157
yosssi/gmq
mqtt/packet/pubrec.go
NewPUBREC
func NewPUBREC(opts *PUBRECOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBRECOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBREC Packet. p := &PUBREC{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewPUBREC(opts *PUBRECOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBRECOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBREC Packet. p := &PUBREC{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewPUBREC", "(", "opts", "*", "PUBRECOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "PUBRECOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a PUBREC Packet.", "p", ":=", "&", "PUBREC", "{", "PacketID", ":", "opts", ".", "PacketID", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the Fixed header to the Packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBREC creates and returns a PUBACK Packet.
[ "NewPUBREC", "creates", "and", "returns", "a", "PUBACK", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubrec.go#L32-L56
2,158
yosssi/gmq
mqtt/packet/pubrec.go
NewPUBRECFromBytes
func NewPUBRECFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBRECBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBREC Packet. p := &PUBREC{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
go
func NewPUBRECFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBRECBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBREC Packet. p := &PUBREC{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
[ "func", "NewPUBRECFromBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validatePUBRECBytes", "(", "fixedHeader", ",", "variableHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Decode the Packet Identifier.", "// No error occur because of the precedent validation and", "// the returned error is not be taken care of.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Create a PUBREC Packet.", "p", ":=", "&", "PUBREC", "{", "PacketID", ":", "packetID", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "variableHeader", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBRECFromBytes creates a PUBREC Packet // from the byte data and returns it.
[ "NewPUBRECFromBytes", "creates", "a", "PUBREC", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubrec.go#L60-L84
2,159
yosssi/gmq
mqtt/packet/pubrec.go
validatePUBRECBytes
func validatePUBRECBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBRECFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBREC { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBRECVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBRECVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
go
func validatePUBRECBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBRECFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBREC { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBRECVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBRECVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
[ "func", "validatePUBRECBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "!=", "lenPUBRECFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypePUBREC", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "<<", "4", "!=", "0x00", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the Remaining Length of the fixed header.", "if", "fixedHeader", "[", "1", "]", "!=", "lenPUBRECVariableHeader", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// Check the length of the variable header.", "if", "len", "(", "variableHeader", ")", "!=", "lenPUBRECVariableHeader", "{", "return", "ErrInvalidVariableHeaderLen", "\n", "}", "\n\n", "// Extract the Packet Identifier.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Check the Packet Identifier.", "if", "packetID", "==", "0", "{", "return", "ErrInvalidPacketID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validatePUBRECBytes validates the fixed header and the variable header.
[ "validatePUBRECBytes", "validates", "the", "fixed", "header", "and", "the", "variable", "header", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubrec.go#L87-L128
2,160
yosssi/gmq
mqtt/packet/connect.go
connectFlags
func (p *CONNECT) connectFlags() byte { // Create a byte which represents the Connect Flags. var b byte // Set 1 to the Bit 7 if the Packet has the User Name. if len(p.userName) > 0 { b |= 0x80 } // Set 1 to the Bit 6 if the Packet has the Password. if len(p.password) > 0 { b |= 0x40 } // Set 1 to the Bit 5 if the Will Retain is true. if p.willRetain { b |= 0x20 } // Set the value of the Will QoS to the Bit 4 and 3. b |= p.willQoS << 3 // Set 1 to the Bit 2 if the Packet has the Will Topic and the Will Message. if p.will() { b |= 0x04 } // Set 1 to the Bit 1 if the Clean Session is true. if p.cleanSession { b |= 0x02 } // Return the byte. return b }
go
func (p *CONNECT) connectFlags() byte { // Create a byte which represents the Connect Flags. var b byte // Set 1 to the Bit 7 if the Packet has the User Name. if len(p.userName) > 0 { b |= 0x80 } // Set 1 to the Bit 6 if the Packet has the Password. if len(p.password) > 0 { b |= 0x40 } // Set 1 to the Bit 5 if the Will Retain is true. if p.willRetain { b |= 0x20 } // Set the value of the Will QoS to the Bit 4 and 3. b |= p.willQoS << 3 // Set 1 to the Bit 2 if the Packet has the Will Topic and the Will Message. if p.will() { b |= 0x04 } // Set 1 to the Bit 1 if the Clean Session is true. if p.cleanSession { b |= 0x02 } // Return the byte. return b }
[ "func", "(", "p", "*", "CONNECT", ")", "connectFlags", "(", ")", "byte", "{", "// Create a byte which represents the Connect Flags.", "var", "b", "byte", "\n\n", "// Set 1 to the Bit 7 if the Packet has the User Name.", "if", "len", "(", "p", ".", "userName", ")", ">", "0", "{", "b", "|=", "0x80", "\n", "}", "\n\n", "// Set 1 to the Bit 6 if the Packet has the Password.", "if", "len", "(", "p", ".", "password", ")", ">", "0", "{", "b", "|=", "0x40", "\n", "}", "\n\n", "// Set 1 to the Bit 5 if the Will Retain is true.", "if", "p", ".", "willRetain", "{", "b", "|=", "0x20", "\n", "}", "\n\n", "// Set the value of the Will QoS to the Bit 4 and 3.", "b", "|=", "p", ".", "willQoS", "<<", "3", "\n\n", "// Set 1 to the Bit 2 if the Packet has the Will Topic and the Will Message.", "if", "p", ".", "will", "(", ")", "{", "b", "|=", "0x04", "\n", "}", "\n\n", "// Set 1 to the Bit 1 if the Clean Session is true.", "if", "p", ".", "cleanSession", "{", "b", "|=", "0x02", "\n", "}", "\n\n", "// Return the byte.", "return", "b", "\n", "}" ]
// connectFlags creates and returns a byte which represents the Connect Flags.
[ "connectFlags", "creates", "and", "returns", "a", "byte", "which", "represents", "the", "Connect", "Flags", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/connect.go#L79-L113
2,161
yosssi/gmq
mqtt/packet/connect.go
will
func (p *CONNECT) will() bool { return len(p.willTopic) > 0 && len(p.willMessage) > 0 }
go
func (p *CONNECT) will() bool { return len(p.willTopic) > 0 && len(p.willMessage) > 0 }
[ "func", "(", "p", "*", "CONNECT", ")", "will", "(", ")", "bool", "{", "return", "len", "(", "p", ".", "willTopic", ")", ">", "0", "&&", "len", "(", "p", ".", "willMessage", ")", ">", "0", "\n", "}" ]
// will return true if both the Will Topic and the Will Message are not zero-byte.
[ "will", "return", "true", "if", "both", "the", "Will", "Topic", "and", "the", "Will", "Message", "are", "not", "zero", "-", "byte", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/connect.go#L116-L118
2,162
yosssi/gmq
mqtt/packet/connect.go
NewCONNECT
func NewCONNECT(opts *CONNECTOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &CONNECTOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a CONNECT Packet. p := &CONNECT{ clientID: opts.ClientID, userName: opts.UserName, password: opts.Password, cleanSession: opts.CleanSession, keepAlive: opts.KeepAlive, willTopic: opts.WillTopic, willMessage: opts.WillMessage, willQoS: opts.WillQoS, willRetain: opts.WillRetain, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the fixed header to the packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewCONNECT(opts *CONNECTOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &CONNECTOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a CONNECT Packet. p := &CONNECT{ clientID: opts.ClientID, userName: opts.UserName, password: opts.Password, cleanSession: opts.CleanSession, keepAlive: opts.KeepAlive, willTopic: opts.WillTopic, willMessage: opts.WillMessage, willQoS: opts.WillQoS, willRetain: opts.WillRetain, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the fixed header to the packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewCONNECT", "(", "opts", "*", "CONNECTOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "CONNECTOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a CONNECT Packet.", "p", ":=", "&", "CONNECT", "{", "clientID", ":", "opts", ".", "ClientID", ",", "userName", ":", "opts", ".", "UserName", ",", "password", ":", "opts", ".", "Password", ",", "cleanSession", ":", "opts", ".", "CleanSession", ",", "keepAlive", ":", "opts", ".", "KeepAlive", ",", "willTopic", ":", "opts", ".", "WillTopic", ",", "willMessage", ":", "opts", ".", "WillMessage", ",", "willQoS", ":", "opts", ".", "WillQoS", ",", "willRetain", ":", "opts", ".", "WillRetain", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the payload to the Packet.", "p", ".", "setPayload", "(", ")", "\n\n", "// Set the fixed header to the packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewCONNECT creates and returns a CONNECT Packet.
[ "NewCONNECT", "creates", "and", "returns", "a", "CONNECT", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/connect.go#L121-L156
2,163
yosssi/gmq
mqtt/packet/subscribe.go
NewSUBSCRIBE
func NewSUBSCRIBE(opts *SUBSCRIBEOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &SUBSCRIBEOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a SUBSCRIBE Packet. p := &SUBSCRIBE{ PacketID: opts.PacketID, SubReqs: opts.SubReqs, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewSUBSCRIBE(opts *SUBSCRIBEOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &SUBSCRIBEOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a SUBSCRIBE Packet. p := &SUBSCRIBE{ PacketID: opts.PacketID, SubReqs: opts.SubReqs, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewSUBSCRIBE", "(", "opts", "*", "SUBSCRIBEOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "SUBSCRIBEOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a SUBSCRIBE Packet.", "p", ":=", "&", "SUBSCRIBE", "{", "PacketID", ":", "opts", ".", "PacketID", ",", "SubReqs", ":", "opts", ".", "SubReqs", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the payload to the Packet.", "p", ".", "setPayload", "(", ")", "\n\n", "// Set the Fixed header to the Packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewSUBSCRIBE creates and returns a SUBSCRIBE Packet.
[ "NewSUBSCRIBE", "creates", "and", "returns", "a", "SUBSCRIBE", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/subscribe.go#L40-L68
2,164
yosssi/gmq
mqtt/packet/packet.go
NewFromBytes
func NewFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Extract the MQTT Control Packet type from the fixed header. ptype, err := fixedHeader.ptype() if err != nil { return nil, err } // Create and return a Packet. switch ptype { case TypeCONNACK: return NewCONNACKFromBytes(fixedHeader, remaining) case TypePUBLISH: return NewPUBLISHFromBytes(fixedHeader, remaining) case TypePUBACK: return NewPUBACKFromBytes(fixedHeader, remaining) case TypePUBREC: return NewPUBRECFromBytes(fixedHeader, remaining) case TypePUBREL: return NewPUBRELFromBytes(fixedHeader, remaining) case TypePUBCOMP: return NewPUBCOMPFromBytes(fixedHeader, remaining) case TypeSUBACK: return NewSUBACKFromBytes(fixedHeader, remaining) case TypeUNSUBACK: return NewUNSUBACKFromBytes(fixedHeader, remaining) case TypePINGRESP: return NewPINGRESPFromBytes(fixedHeader, remaining) default: return nil, ErrInvalidPacketType } }
go
func NewFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Extract the MQTT Control Packet type from the fixed header. ptype, err := fixedHeader.ptype() if err != nil { return nil, err } // Create and return a Packet. switch ptype { case TypeCONNACK: return NewCONNACKFromBytes(fixedHeader, remaining) case TypePUBLISH: return NewPUBLISHFromBytes(fixedHeader, remaining) case TypePUBACK: return NewPUBACKFromBytes(fixedHeader, remaining) case TypePUBREC: return NewPUBRECFromBytes(fixedHeader, remaining) case TypePUBREL: return NewPUBRELFromBytes(fixedHeader, remaining) case TypePUBCOMP: return NewPUBCOMPFromBytes(fixedHeader, remaining) case TypeSUBACK: return NewSUBACKFromBytes(fixedHeader, remaining) case TypeUNSUBACK: return NewUNSUBACKFromBytes(fixedHeader, remaining) case TypePINGRESP: return NewPINGRESPFromBytes(fixedHeader, remaining) default: return nil, ErrInvalidPacketType } }
[ "func", "NewFromBytes", "(", "fixedHeader", "FixedHeader", ",", "remaining", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Extract the MQTT Control Packet type from the fixed header.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create and return a Packet.", "switch", "ptype", "{", "case", "TypeCONNACK", ":", "return", "NewCONNACKFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypePUBLISH", ":", "return", "NewPUBLISHFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypePUBACK", ":", "return", "NewPUBACKFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypePUBREC", ":", "return", "NewPUBRECFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypePUBREL", ":", "return", "NewPUBRELFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypePUBCOMP", ":", "return", "NewPUBCOMPFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypeSUBACK", ":", "return", "NewSUBACKFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypeUNSUBACK", ":", "return", "NewUNSUBACKFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "case", "TypePINGRESP", ":", "return", "NewPINGRESPFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "default", ":", "return", "nil", ",", "ErrInvalidPacketType", "\n", "}", "\n", "}" ]
// NewFromBytes creates a Packet from the byte data and returns it.
[ "NewFromBytes", "creates", "a", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/packet.go#L19-L49
2,165
yosssi/gmq
mqtt/client/connection.go
newConnection
func newConnection(network, address string, tlsConfig *tls.Config) (*connection, error) { // Define the local variables. var conn net.Conn var err error // Connect to the address on the named network. if tlsConfig != nil { conn, err = tls.Dial(network, address, tlsConfig) } else { conn, err = net.Dial(network, address) } if err != nil { return nil, err } // Create a Network Connection. c := &connection{ Conn: conn, r: bufio.NewReader(conn), w: bufio.NewWriter(conn), connack: make(chan struct{}, 1), send: make(chan packet.Packet, sendBufSize), sendEnd: make(chan struct{}, 1), unackSubs: make(map[string]MessageHandler), ackedSubs: make(map[string]MessageHandler), } // Return the Network Connection. return c, nil }
go
func newConnection(network, address string, tlsConfig *tls.Config) (*connection, error) { // Define the local variables. var conn net.Conn var err error // Connect to the address on the named network. if tlsConfig != nil { conn, err = tls.Dial(network, address, tlsConfig) } else { conn, err = net.Dial(network, address) } if err != nil { return nil, err } // Create a Network Connection. c := &connection{ Conn: conn, r: bufio.NewReader(conn), w: bufio.NewWriter(conn), connack: make(chan struct{}, 1), send: make(chan packet.Packet, sendBufSize), sendEnd: make(chan struct{}, 1), unackSubs: make(map[string]MessageHandler), ackedSubs: make(map[string]MessageHandler), } // Return the Network Connection. return c, nil }
[ "func", "newConnection", "(", "network", ",", "address", "string", ",", "tlsConfig", "*", "tls", ".", "Config", ")", "(", "*", "connection", ",", "error", ")", "{", "// Define the local variables.", "var", "conn", "net", ".", "Conn", "\n", "var", "err", "error", "\n\n", "// Connect to the address on the named network.", "if", "tlsConfig", "!=", "nil", "{", "conn", ",", "err", "=", "tls", ".", "Dial", "(", "network", ",", "address", ",", "tlsConfig", ")", "\n", "}", "else", "{", "conn", ",", "err", "=", "net", ".", "Dial", "(", "network", ",", "address", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a Network Connection.", "c", ":=", "&", "connection", "{", "Conn", ":", "conn", ",", "r", ":", "bufio", ".", "NewReader", "(", "conn", ")", ",", "w", ":", "bufio", ".", "NewWriter", "(", "conn", ")", ",", "connack", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "send", ":", "make", "(", "chan", "packet", ".", "Packet", ",", "sendBufSize", ")", ",", "sendEnd", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "unackSubs", ":", "make", "(", "map", "[", "string", "]", "MessageHandler", ")", ",", "ackedSubs", ":", "make", "(", "map", "[", "string", "]", "MessageHandler", ")", ",", "}", "\n\n", "// Return the Network Connection.", "return", "c", ",", "nil", "\n", "}" ]
// newConnection connects to the address on the named network, // creates a Network Connection and returns it.
[ "newConnection", "connects", "to", "the", "address", "on", "the", "named", "network", "creates", "a", "Network", "Connection", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/connection.go#L55-L84
2,166
yosssi/gmq
mqtt/packet/strings.go
appendLenStr
func appendLenStr(b []byte, s []byte) []byte { b = append(b, encodeUint16(uint16(len(s)))...) b = append(b, s...) return b }
go
func appendLenStr(b []byte, s []byte) []byte { b = append(b, encodeUint16(uint16(len(s)))...) b = append(b, s...) return b }
[ "func", "appendLenStr", "(", "b", "[", "]", "byte", ",", "s", "[", "]", "byte", ")", "[", "]", "byte", "{", "b", "=", "append", "(", "b", ",", "encodeUint16", "(", "uint16", "(", "len", "(", "s", ")", ")", ")", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "s", "...", ")", "\n", "return", "b", "\n", "}" ]
// appendLenStr appends the length of the strings // and the strings to the byte slice.
[ "appendLenStr", "appends", "the", "length", "of", "the", "strings", "and", "the", "strings", "to", "the", "byte", "slice", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/strings.go#L8-L12
2,167
yosssi/gmq
mqtt/packet/publish.go
NewPUBLISH
func NewPUBLISH(opts *PUBLISHOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBLISHOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBLISH Packet. p := &PUBLISH{ DUP: opts.DUP, QoS: opts.QoS, retain: opts.Retain, TopicName: opts.TopicName, PacketID: opts.PacketID, Message: opts.Message, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewPUBLISH(opts *PUBLISHOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBLISHOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBLISH Packet. p := &PUBLISH{ DUP: opts.DUP, QoS: opts.QoS, retain: opts.Retain, TopicName: opts.TopicName, PacketID: opts.PacketID, Message: opts.Message, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewPUBLISH", "(", "opts", "*", "PUBLISHOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "PUBLISHOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a PUBLISH Packet.", "p", ":=", "&", "PUBLISH", "{", "DUP", ":", "opts", ".", "DUP", ",", "QoS", ":", "opts", ".", "QoS", ",", "retain", ":", "opts", ".", "Retain", ",", "TopicName", ":", "opts", ".", "TopicName", ",", "PacketID", ":", "opts", ".", "PacketID", ",", "Message", ":", "opts", ".", "Message", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the payload to the Packet.", "p", ".", "setPayload", "(", ")", "\n\n", "// Set the Fixed header to the Packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBLISH creates and returns a PUBLISH Packet.
[ "NewPUBLISH", "creates", "and", "returns", "a", "PUBLISH", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/publish.go#L80-L112
2,168
yosssi/gmq
mqtt/packet/publish.go
NewPUBLISHFromBytes
func NewPUBLISHFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Validate the byte data. if err := validatePUBLISHBytes(fixedHeader, remaining); err != nil { return nil, err } // Get the first byte from the fixedHeader. b := fixedHeader[0] // Create a PUBLISH Packet. p := &PUBLISH{ DUP: b&0x08 == 0x08, QoS: b & 0x06 >> 1, retain: b&0x01 == 0x01, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Extract the length of the Topic Name. lenTopicName, _ := decodeUint16(remaining[0:2]) // Calculate the length of the variable header. var lenVariableHeader int if p.QoS == mqtt.QoS0 { lenVariableHeader = 2 + int(lenTopicName) } else { lenVariableHeader = 2 + int(lenTopicName) + 2 } // Set the variable header to the Packet. p.variableHeader = remaining[:lenVariableHeader] // Set the payload to the Packet. p.payload = remaining[lenVariableHeader:] // Set the Topic Name to the Packet. p.TopicName = remaining[2 : 2+lenTopicName] // Extract the Packet Identifier. var packetID uint16 if p.QoS != mqtt.QoS0 { packetID, _ = decodeUint16(remaining[2+lenTopicName : 2+lenTopicName+2]) } // Set the Packet Identifier to the Packet. p.PacketID = packetID // Set the Application Message to the Packet. p.Message = p.payload // Return the Packet. return p, nil }
go
func NewPUBLISHFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Validate the byte data. if err := validatePUBLISHBytes(fixedHeader, remaining); err != nil { return nil, err } // Get the first byte from the fixedHeader. b := fixedHeader[0] // Create a PUBLISH Packet. p := &PUBLISH{ DUP: b&0x08 == 0x08, QoS: b & 0x06 >> 1, retain: b&0x01 == 0x01, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Extract the length of the Topic Name. lenTopicName, _ := decodeUint16(remaining[0:2]) // Calculate the length of the variable header. var lenVariableHeader int if p.QoS == mqtt.QoS0 { lenVariableHeader = 2 + int(lenTopicName) } else { lenVariableHeader = 2 + int(lenTopicName) + 2 } // Set the variable header to the Packet. p.variableHeader = remaining[:lenVariableHeader] // Set the payload to the Packet. p.payload = remaining[lenVariableHeader:] // Set the Topic Name to the Packet. p.TopicName = remaining[2 : 2+lenTopicName] // Extract the Packet Identifier. var packetID uint16 if p.QoS != mqtt.QoS0 { packetID, _ = decodeUint16(remaining[2+lenTopicName : 2+lenTopicName+2]) } // Set the Packet Identifier to the Packet. p.PacketID = packetID // Set the Application Message to the Packet. p.Message = p.payload // Return the Packet. return p, nil }
[ "func", "NewPUBLISHFromBytes", "(", "fixedHeader", "FixedHeader", ",", "remaining", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validatePUBLISHBytes", "(", "fixedHeader", ",", "remaining", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Get the first byte from the fixedHeader.", "b", ":=", "fixedHeader", "[", "0", "]", "\n\n", "// Create a PUBLISH Packet.", "p", ":=", "&", "PUBLISH", "{", "DUP", ":", "b", "&", "0x08", "==", "0x08", ",", "QoS", ":", "b", "&", "0x06", ">>", "1", ",", "retain", ":", "b", "&", "0x01", "==", "0x01", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Extract the length of the Topic Name.", "lenTopicName", ",", "_", ":=", "decodeUint16", "(", "remaining", "[", "0", ":", "2", "]", ")", "\n\n", "// Calculate the length of the variable header.", "var", "lenVariableHeader", "int", "\n\n", "if", "p", ".", "QoS", "==", "mqtt", ".", "QoS0", "{", "lenVariableHeader", "=", "2", "+", "int", "(", "lenTopicName", ")", "\n", "}", "else", "{", "lenVariableHeader", "=", "2", "+", "int", "(", "lenTopicName", ")", "+", "2", "\n", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "remaining", "[", ":", "lenVariableHeader", "]", "\n\n", "// Set the payload to the Packet.", "p", ".", "payload", "=", "remaining", "[", "lenVariableHeader", ":", "]", "\n\n", "// Set the Topic Name to the Packet.", "p", ".", "TopicName", "=", "remaining", "[", "2", ":", "2", "+", "lenTopicName", "]", "\n\n", "// Extract the Packet Identifier.", "var", "packetID", "uint16", "\n\n", "if", "p", ".", "QoS", "!=", "mqtt", ".", "QoS0", "{", "packetID", ",", "_", "=", "decodeUint16", "(", "remaining", "[", "2", "+", "lenTopicName", ":", "2", "+", "lenTopicName", "+", "2", "]", ")", "\n", "}", "\n\n", "// Set the Packet Identifier to the Packet.", "p", ".", "PacketID", "=", "packetID", "\n\n", "// Set the Application Message to the Packet.", "p", ".", "Message", "=", "p", ".", "payload", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBLISHFromBytes creates the PUBLISH Packet // from the byte data and returns it.
[ "NewPUBLISHFromBytes", "creates", "the", "PUBLISH", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/publish.go#L116-L171
2,169
yosssi/gmq
mqtt/packet/publish.go
validatePUBLISHBytes
func validatePUBLISHBytes(fixedHeader FixedHeader, remaining []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) < minLenPUBLISHFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBLISH { return ErrInvalidPacketType } // Get the QoS. qos := (fixedHeader[0] & 0x06) >> 1 // Check the QoS. if !mqtt.ValidQoS(qos) { return ErrInvalidQoS } // Check the length of the remaining. if l := len(remaining); l < minLenPUBLISHVariableHeader || l > maxRemainingLength { return ErrInvalidRemainingLen } // Extract the length of the Topic Name. lenTopicName, _ := decodeUint16(remaining[0:2]) // Calculate the length of the variable header. var lenVariableHeader int if qos == mqtt.QoS0 { lenVariableHeader = 2 + int(lenTopicName) } else { lenVariableHeader = 2 + int(lenTopicName) + 2 } // Check the length of the remaining. if len(remaining) < lenVariableHeader { return ErrInvalidRemainingLength } // End the validation if the QoS equals to QoS 0. if qos == mqtt.QoS0 { return nil } // Extract the Packet Identifier. packetID, _ := decodeUint16(remaining[2+int(lenTopicName) : 2+int(lenTopicName)+2]) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
go
func validatePUBLISHBytes(fixedHeader FixedHeader, remaining []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) < minLenPUBLISHFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBLISH { return ErrInvalidPacketType } // Get the QoS. qos := (fixedHeader[0] & 0x06) >> 1 // Check the QoS. if !mqtt.ValidQoS(qos) { return ErrInvalidQoS } // Check the length of the remaining. if l := len(remaining); l < minLenPUBLISHVariableHeader || l > maxRemainingLength { return ErrInvalidRemainingLen } // Extract the length of the Topic Name. lenTopicName, _ := decodeUint16(remaining[0:2]) // Calculate the length of the variable header. var lenVariableHeader int if qos == mqtt.QoS0 { lenVariableHeader = 2 + int(lenTopicName) } else { lenVariableHeader = 2 + int(lenTopicName) + 2 } // Check the length of the remaining. if len(remaining) < lenVariableHeader { return ErrInvalidRemainingLength } // End the validation if the QoS equals to QoS 0. if qos == mqtt.QoS0 { return nil } // Extract the Packet Identifier. packetID, _ := decodeUint16(remaining[2+int(lenTopicName) : 2+int(lenTopicName)+2]) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
[ "func", "validatePUBLISHBytes", "(", "fixedHeader", "FixedHeader", ",", "remaining", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "<", "minLenPUBLISHFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypePUBLISH", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Get the QoS.", "qos", ":=", "(", "fixedHeader", "[", "0", "]", "&", "0x06", ")", ">>", "1", "\n\n", "// Check the QoS.", "if", "!", "mqtt", ".", "ValidQoS", "(", "qos", ")", "{", "return", "ErrInvalidQoS", "\n", "}", "\n\n", "// Check the length of the remaining.", "if", "l", ":=", "len", "(", "remaining", ")", ";", "l", "<", "minLenPUBLISHVariableHeader", "||", "l", ">", "maxRemainingLength", "{", "return", "ErrInvalidRemainingLen", "\n", "}", "\n\n", "// Extract the length of the Topic Name.", "lenTopicName", ",", "_", ":=", "decodeUint16", "(", "remaining", "[", "0", ":", "2", "]", ")", "\n\n", "// Calculate the length of the variable header.", "var", "lenVariableHeader", "int", "\n\n", "if", "qos", "==", "mqtt", ".", "QoS0", "{", "lenVariableHeader", "=", "2", "+", "int", "(", "lenTopicName", ")", "\n", "}", "else", "{", "lenVariableHeader", "=", "2", "+", "int", "(", "lenTopicName", ")", "+", "2", "\n", "}", "\n\n", "// Check the length of the remaining.", "if", "len", "(", "remaining", ")", "<", "lenVariableHeader", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// End the validation if the QoS equals to QoS 0.", "if", "qos", "==", "mqtt", ".", "QoS0", "{", "return", "nil", "\n", "}", "\n\n", "// Extract the Packet Identifier.", "packetID", ",", "_", ":=", "decodeUint16", "(", "remaining", "[", "2", "+", "int", "(", "lenTopicName", ")", ":", "2", "+", "int", "(", "lenTopicName", ")", "+", "2", "]", ")", "\n\n", "// Check the Packet Identifier.", "if", "packetID", "==", "0", "{", "return", "ErrInvalidPacketID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validatePUBLISHBytes validates the fixed header and the variable header.
[ "validatePUBLISHBytes", "validates", "the", "fixed", "header", "and", "the", "variable", "header", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/publish.go#L174-L235
2,170
yosssi/gmq
cmd/gmq-cli/main.go
printError
func printError(err error) { // Do nothing is the error is errCmdArgsParse. if err == errCmdArgsParse { return } fmt.Fprintln(os.Stderr, err) // Print the help of the GMQ Client commands if the error is errInvalidCmdName. if err == errInvalidCmdName { fmt.Println() printHelp() } }
go
func printError(err error) { // Do nothing is the error is errCmdArgsParse. if err == errCmdArgsParse { return } fmt.Fprintln(os.Stderr, err) // Print the help of the GMQ Client commands if the error is errInvalidCmdName. if err == errInvalidCmdName { fmt.Println() printHelp() } }
[ "func", "printError", "(", "err", "error", ")", "{", "// Do nothing is the error is errCmdArgsParse.", "if", "err", "==", "errCmdArgsParse", "{", "return", "\n", "}", "\n\n", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n\n", "// Print the help of the GMQ Client commands if the error is errInvalidCmdName.", "if", "err", "==", "errInvalidCmdName", "{", "fmt", ".", "Println", "(", ")", "\n", "printHelp", "(", ")", "\n", "}", "\n", "}" ]
// printError prints the error to the standard error.
[ "printError", "prints", "the", "error", "to", "the", "standard", "error", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/cmd/gmq-cli/main.go#L101-L114
2,171
yosssi/gmq
cmd/gmq-cli/main.go
cmdNameArgs
func cmdNameArgs(s string) (string, []string) { // Split the string into the tokens. tokens := strings.Split(strings.TrimSpace(s), " ") // Get the command name from the tokens. cmdName := tokens[0] // Get the command arguments from the tokens. cmdArgs := make([]string, 0, len(tokens[1:])) for _, t := range tokens[1:] { // Skip the remaining processes if the token is zero value. if t == "" { continue } // Set the token to the command arguments. cmdArgs = append(cmdArgs, t) } return cmdName, cmdArgs }
go
func cmdNameArgs(s string) (string, []string) { // Split the string into the tokens. tokens := strings.Split(strings.TrimSpace(s), " ") // Get the command name from the tokens. cmdName := tokens[0] // Get the command arguments from the tokens. cmdArgs := make([]string, 0, len(tokens[1:])) for _, t := range tokens[1:] { // Skip the remaining processes if the token is zero value. if t == "" { continue } // Set the token to the command arguments. cmdArgs = append(cmdArgs, t) } return cmdName, cmdArgs }
[ "func", "cmdNameArgs", "(", "s", "string", ")", "(", "string", ",", "[", "]", "string", ")", "{", "// Split the string into the tokens.", "tokens", ":=", "strings", ".", "Split", "(", "strings", ".", "TrimSpace", "(", "s", ")", ",", "\"", "\"", ")", "\n\n", "// Get the command name from the tokens.", "cmdName", ":=", "tokens", "[", "0", "]", "\n\n", "// Get the command arguments from the tokens.", "cmdArgs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "tokens", "[", "1", ":", "]", ")", ")", "\n", "for", "_", ",", "t", ":=", "range", "tokens", "[", "1", ":", "]", "{", "// Skip the remaining processes if the token is zero value.", "if", "t", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "// Set the token to the command arguments.", "cmdArgs", "=", "append", "(", "cmdArgs", ",", "t", ")", "\n", "}", "\n\n", "return", "cmdName", ",", "cmdArgs", "\n", "}" ]
// cmdNameArgs extracts the command name and the command arguments from // the parameter string.
[ "cmdNameArgs", "extracts", "the", "command", "name", "and", "the", "command", "arguments", "from", "the", "parameter", "string", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/cmd/gmq-cli/main.go#L118-L138
2,172
yosssi/gmq
mqtt/packet/pubcomp.go
NewPUBCOMP
func NewPUBCOMP(opts *PUBCOMPOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBCOMPOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBCOMP Packet. p := &PUBCOMP{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewPUBCOMP(opts *PUBCOMPOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBCOMPOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBCOMP Packet. p := &PUBCOMP{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewPUBCOMP", "(", "opts", "*", "PUBCOMPOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "PUBCOMPOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a PUBCOMP Packet.", "p", ":=", "&", "PUBCOMP", "{", "PacketID", ":", "opts", ".", "PacketID", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the Fixed header to the Packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBCOMP creates and returns a PUBCOMP Packet.
[ "NewPUBCOMP", "creates", "and", "returns", "a", "PUBCOMP", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubcomp.go#L32-L56
2,173
yosssi/gmq
mqtt/packet/pubcomp.go
NewPUBCOMPFromBytes
func NewPUBCOMPFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBCOMPBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBCOMP Packet. p := &PUBCOMP{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
go
func NewPUBCOMPFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBCOMPBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBCOMP Packet. p := &PUBCOMP{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
[ "func", "NewPUBCOMPFromBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validatePUBCOMPBytes", "(", "fixedHeader", ",", "variableHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Decode the Packet Identifier.", "// No error occur because of the precedent validation and", "// the returned error is not be taken care of.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Create a PUBCOMP Packet.", "p", ":=", "&", "PUBCOMP", "{", "PacketID", ":", "packetID", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "variableHeader", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBCOMPFromBytes creates a PUBCOMP Packet // from the byte data and returns it.
[ "NewPUBCOMPFromBytes", "creates", "a", "PUBCOMP", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubcomp.go#L60-L84
2,174
yosssi/gmq
mqtt/packet/pubcomp.go
validatePUBCOMPBytes
func validatePUBCOMPBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBCOMPFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBCOMP { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBCOMPVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBCOMPVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
go
func validatePUBCOMPBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBCOMPFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBCOMP { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBCOMPVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBCOMPVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
[ "func", "validatePUBCOMPBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "!=", "lenPUBCOMPFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypePUBCOMP", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "<<", "4", "!=", "0x00", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the Remaining Length of the fixed header.", "if", "fixedHeader", "[", "1", "]", "!=", "lenPUBCOMPVariableHeader", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// Check the length of the variable header.", "if", "len", "(", "variableHeader", ")", "!=", "lenPUBCOMPVariableHeader", "{", "return", "ErrInvalidVariableHeaderLen", "\n", "}", "\n\n", "// Extract the Packet Identifier.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Check the Packet Identifier.", "if", "packetID", "==", "0", "{", "return", "ErrInvalidPacketID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validatePUBCOMPBytes validates the fixed header and the variable header.
[ "validatePUBCOMPBytes", "validates", "the", "fixed", "header", "and", "the", "variable", "header", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubcomp.go#L87-L128
2,175
yosssi/gmq
cmd/gmq-cli/command.go
newCommand
func newCommand(cmdName string, cmdArgs []string, cli *client.Client) (command, error) { switch cmdName { case cmdNameConn: return newCommandConn(cmdArgs, cli) case cmdNameDisconn: return newCommandDisconn(cli), nil case cmdNameHelp: return newCommandHelp(), nil case cmdNamePub: return newCommandPub(cmdArgs, cli) case cmdNameQuit: return newCommandQuit(cli), nil case cmdNameSub: return newCommandSub(cmdArgs, cli) case cmdNameUnsub: return newCommandUnsub(cmdArgs, cli) } return nil, errInvalidCmdName }
go
func newCommand(cmdName string, cmdArgs []string, cli *client.Client) (command, error) { switch cmdName { case cmdNameConn: return newCommandConn(cmdArgs, cli) case cmdNameDisconn: return newCommandDisconn(cli), nil case cmdNameHelp: return newCommandHelp(), nil case cmdNamePub: return newCommandPub(cmdArgs, cli) case cmdNameQuit: return newCommandQuit(cli), nil case cmdNameSub: return newCommandSub(cmdArgs, cli) case cmdNameUnsub: return newCommandUnsub(cmdArgs, cli) } return nil, errInvalidCmdName }
[ "func", "newCommand", "(", "cmdName", "string", ",", "cmdArgs", "[", "]", "string", ",", "cli", "*", "client", ".", "Client", ")", "(", "command", ",", "error", ")", "{", "switch", "cmdName", "{", "case", "cmdNameConn", ":", "return", "newCommandConn", "(", "cmdArgs", ",", "cli", ")", "\n", "case", "cmdNameDisconn", ":", "return", "newCommandDisconn", "(", "cli", ")", ",", "nil", "\n", "case", "cmdNameHelp", ":", "return", "newCommandHelp", "(", ")", ",", "nil", "\n", "case", "cmdNamePub", ":", "return", "newCommandPub", "(", "cmdArgs", ",", "cli", ")", "\n", "case", "cmdNameQuit", ":", "return", "newCommandQuit", "(", "cli", ")", ",", "nil", "\n", "case", "cmdNameSub", ":", "return", "newCommandSub", "(", "cmdArgs", ",", "cli", ")", "\n", "case", "cmdNameUnsub", ":", "return", "newCommandUnsub", "(", "cmdArgs", ",", "cli", ")", "\n", "}", "\n\n", "return", "nil", ",", "errInvalidCmdName", "\n", "}" ]
// newCommand creates and returns a command.
[ "newCommand", "creates", "and", "returns", "a", "command", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/cmd/gmq-cli/command.go#L21-L40
2,176
yosssi/gmq
mqtt/packet/encode.go
encodeLength
func encodeLength(n uint32) uint32 { var value, digit uint32 for n > 0 { if value != 0 { value <<= 8 } digit = n % 128 n /= 128 if n > 0 { digit |= 0x80 } value |= digit } return value }
go
func encodeLength(n uint32) uint32 { var value, digit uint32 for n > 0 { if value != 0 { value <<= 8 } digit = n % 128 n /= 128 if n > 0 { digit |= 0x80 } value |= digit } return value }
[ "func", "encodeLength", "(", "n", "uint32", ")", "uint32", "{", "var", "value", ",", "digit", "uint32", "\n\n", "for", "n", ">", "0", "{", "if", "value", "!=", "0", "{", "value", "<<=", "8", "\n", "}", "\n\n", "digit", "=", "n", "%", "128", "\n\n", "n", "/=", "128", "\n\n", "if", "n", ">", "0", "{", "digit", "|=", "0x80", "\n", "}", "\n\n", "value", "|=", "digit", "\n", "}", "\n\n", "return", "value", "\n", "}" ]
// encodeLength encodes the unsigned integer // by using a variable length encoding scheme.
[ "encodeLength", "encodes", "the", "unsigned", "integer", "by", "using", "a", "variable", "length", "encoding", "scheme", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/encode.go#L11-L31
2,177
yosssi/gmq
mqtt/packet/pingresp.go
NewPINGRESPFromBytes
func NewPINGRESPFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Validate the byte data. if err := validatePINGRESPBytes(fixedHeader, remaining); err != nil { return nil, err } // Create a PINGRESP Packet. p := &PINGRESP{} // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Return the Packet. return p, nil }
go
func NewPINGRESPFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) { // Validate the byte data. if err := validatePINGRESPBytes(fixedHeader, remaining); err != nil { return nil, err } // Create a PINGRESP Packet. p := &PINGRESP{} // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Return the Packet. return p, nil }
[ "func", "NewPINGRESPFromBytes", "(", "fixedHeader", "FixedHeader", ",", "remaining", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validatePINGRESPBytes", "(", "fixedHeader", ",", "remaining", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a PINGRESP Packet.", "p", ":=", "&", "PINGRESP", "{", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPINGRESPFromBytes creates a PINGRESP Packet from // the byte data and returns it.
[ "NewPINGRESPFromBytes", "creates", "a", "PINGRESP", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pingresp.go#L13-L27
2,178
yosssi/gmq
mqtt/packet/pingresp.go
validatePINGRESPBytes
func validatePINGRESPBytes(fixedHeader FixedHeader, remaining []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPINGRESPFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePINGRESP { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != 0x00 { return ErrInvalidRemainingLength } // Check the length of the remaining. if len(remaining) != 0 { return ErrInvalidRemainingLen } return nil }
go
func validatePINGRESPBytes(fixedHeader FixedHeader, remaining []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPINGRESPFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePINGRESP { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != 0x00 { return ErrInvalidRemainingLength } // Check the length of the remaining. if len(remaining) != 0 { return ErrInvalidRemainingLen } return nil }
[ "func", "validatePINGRESPBytes", "(", "fixedHeader", "FixedHeader", ",", "remaining", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "!=", "lenPINGRESPFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypePINGRESP", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "<<", "4", "!=", "0x00", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the Remaining Length of the fixed header.", "if", "fixedHeader", "[", "1", "]", "!=", "0x00", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// Check the length of the remaining.", "if", "len", "(", "remaining", ")", "!=", "0", "{", "return", "ErrInvalidRemainingLen", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validatePINGRESPBytes validates the fixed header and the remaining.
[ "validatePINGRESPBytes", "validates", "the", "fixed", "header", "and", "the", "remaining", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pingresp.go#L30-L63
2,179
yosssi/gmq
mqtt/qos.go
ValidQoS
func ValidQoS(qos byte) bool { return qos == QoS0 || qos == QoS1 || qos == QoS2 }
go
func ValidQoS(qos byte) bool { return qos == QoS0 || qos == QoS1 || qos == QoS2 }
[ "func", "ValidQoS", "(", "qos", "byte", ")", "bool", "{", "return", "qos", "==", "QoS0", "||", "qos", "==", "QoS1", "||", "qos", "==", "QoS2", "\n", "}" ]
// ValidQoS returns true if the input QoS equals to // QoS0, QoS1 or QoS2.
[ "ValidQoS", "returns", "true", "if", "the", "input", "QoS", "equals", "to", "QoS0", "QoS1", "or", "QoS2", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/qos.go#L15-L17
2,180
yosssi/gmq
mqtt/packet/sub_req.go
validate
func (s *SubReq) validate() error { // Check the length of the Topic Filter. l := len(s.TopicFilter) if l == 0 { return ErrNoTopicFilter } if l > maxStringsLen { return ErrTopicFilterExceedsMaxStringsLen } // Check the QoS. if !mqtt.ValidQoS(s.QoS) { return ErrInvalidQoS } return nil }
go
func (s *SubReq) validate() error { // Check the length of the Topic Filter. l := len(s.TopicFilter) if l == 0 { return ErrNoTopicFilter } if l > maxStringsLen { return ErrTopicFilterExceedsMaxStringsLen } // Check the QoS. if !mqtt.ValidQoS(s.QoS) { return ErrInvalidQoS } return nil }
[ "func", "(", "s", "*", "SubReq", ")", "validate", "(", ")", "error", "{", "// Check the length of the Topic Filter.", "l", ":=", "len", "(", "s", ".", "TopicFilter", ")", "\n\n", "if", "l", "==", "0", "{", "return", "ErrNoTopicFilter", "\n", "}", "\n\n", "if", "l", ">", "maxStringsLen", "{", "return", "ErrTopicFilterExceedsMaxStringsLen", "\n", "}", "\n\n", "// Check the QoS.", "if", "!", "mqtt", ".", "ValidQoS", "(", "s", ".", "QoS", ")", "{", "return", "ErrInvalidQoS", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validate validates the subscription request.
[ "validate", "validates", "the", "subscription", "request", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/sub_req.go#L24-L42
2,181
yosssi/gmq
mqtt/packet/pubrel.go
NewPUBREL
func NewPUBREL(opts *PUBRELOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBRELOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBREL Packet. p := &PUBREL{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewPUBREL(opts *PUBRELOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBRELOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBREL Packet. p := &PUBREL{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewPUBREL", "(", "opts", "*", "PUBRELOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "PUBRELOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a PUBREL Packet.", "p", ":=", "&", "PUBREL", "{", "PacketID", ":", "opts", ".", "PacketID", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the Fixed header to the Packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBREL creates and returns a PUBREL Packet.
[ "NewPUBREL", "creates", "and", "returns", "a", "PUBREL", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubrel.go#L32-L56
2,182
yosssi/gmq
mqtt/packet/pubrel.go
NewPUBRELFromBytes
func NewPUBRELFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBRELBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBREL Packet. p := &PUBREL{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
go
func NewPUBRELFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBRELBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBREL Packet. p := &PUBREL{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
[ "func", "NewPUBRELFromBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validatePUBRELBytes", "(", "fixedHeader", ",", "variableHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Decode the Packet Identifier.", "// No error occur because of the precedent validation and", "// the returned error is not be taken care of.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Create a PUBREL Packet.", "p", ":=", "&", "PUBREL", "{", "PacketID", ":", "packetID", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "variableHeader", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBRELFromBytes creates a PUBREL Packet // from the byte data and returns it.
[ "NewPUBRELFromBytes", "creates", "a", "PUBREL", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubrel.go#L60-L84
2,183
yosssi/gmq
mqtt/packet/pubrel.go
validatePUBRELBytes
func validatePUBRELBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBRELFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBREL { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]&0x02 != 0x02 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBRELVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBRELVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
go
func validatePUBRELBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBRELFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBREL { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]&0x02 != 0x02 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBRELVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBRELVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
[ "func", "validatePUBRELBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "!=", "lenPUBRELFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypePUBREL", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "&", "0x02", "!=", "0x02", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the Remaining Length of the fixed header.", "if", "fixedHeader", "[", "1", "]", "!=", "lenPUBRELVariableHeader", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// Check the length of the variable header.", "if", "len", "(", "variableHeader", ")", "!=", "lenPUBRELVariableHeader", "{", "return", "ErrInvalidVariableHeaderLen", "\n", "}", "\n\n", "// Extract the Packet Identifier.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Check the Packet Identifier.", "if", "packetID", "==", "0", "{", "return", "ErrInvalidPacketID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validatePUBRELBytes validates the fixed header and the variable header.
[ "validatePUBRELBytes", "validates", "the", "fixed", "header", "and", "the", "variable", "header", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/pubrel.go#L87-L128
2,184
yosssi/gmq
mqtt/packet/unsubscribe.go
NewUNSUBSCRIBE
func NewUNSUBSCRIBE(opts *UNSUBSCRIBEOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &UNSUBSCRIBEOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a SUBSCRIBE Packet. p := &UNSUBSCRIBE{ PacketID: opts.PacketID, TopicFilters: opts.TopicFilters, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewUNSUBSCRIBE(opts *UNSUBSCRIBEOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &UNSUBSCRIBEOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a SUBSCRIBE Packet. p := &UNSUBSCRIBE{ PacketID: opts.PacketID, TopicFilters: opts.TopicFilters, } // Set the variable header to the Packet. p.setVariableHeader() // Set the payload to the Packet. p.setPayload() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewUNSUBSCRIBE", "(", "opts", "*", "UNSUBSCRIBEOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "UNSUBSCRIBEOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a SUBSCRIBE Packet.", "p", ":=", "&", "UNSUBSCRIBE", "{", "PacketID", ":", "opts", ".", "PacketID", ",", "TopicFilters", ":", "opts", ".", "TopicFilters", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the payload to the Packet.", "p", ".", "setPayload", "(", ")", "\n\n", "// Set the Fixed header to the Packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewUNSUBSCRIBE creates and returns an UNSUBSCRIBE Packet.
[ "NewUNSUBSCRIBE", "creates", "and", "returns", "an", "UNSUBSCRIBE", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/unsubscribe.go#L37-L65
2,185
yosssi/gmq
mqtt/packet/puback.go
NewPUBACK
func NewPUBACK(opts *PUBACKOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBACKOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBACK Packet. p := &PUBACK{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
go
func NewPUBACK(opts *PUBACKOptions) (Packet, error) { // Initialize the options. if opts == nil { opts = &PUBACKOptions{} } // Validate the options. if err := opts.validate(); err != nil { return nil, err } // Create a PUBACK Packet. p := &PUBACK{ PacketID: opts.PacketID, } // Set the variable header to the Packet. p.setVariableHeader() // Set the Fixed header to the Packet. p.setFixedHeader() // Return the Packet. return p, nil }
[ "func", "NewPUBACK", "(", "opts", "*", "PUBACKOptions", ")", "(", "Packet", ",", "error", ")", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "PUBACKOptions", "{", "}", "\n", "}", "\n\n", "// Validate the options.", "if", "err", ":=", "opts", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create a PUBACK Packet.", "p", ":=", "&", "PUBACK", "{", "PacketID", ":", "opts", ".", "PacketID", ",", "}", "\n\n", "// Set the variable header to the Packet.", "p", ".", "setVariableHeader", "(", ")", "\n\n", "// Set the Fixed header to the Packet.", "p", ".", "setFixedHeader", "(", ")", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBACK creates and returns a PUBACK Packet.
[ "NewPUBACK", "creates", "and", "returns", "a", "PUBACK", "Packet", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/puback.go#L32-L56
2,186
yosssi/gmq
mqtt/packet/puback.go
NewPUBACKFromBytes
func NewPUBACKFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBACKBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBACK Packet. p := &PUBACK{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
go
func NewPUBACKFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validatePUBACKBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBACK Packet. p := &PUBACK{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
[ "func", "NewPUBACKFromBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validatePUBACKBytes", "(", "fixedHeader", ",", "variableHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Decode the Packet Identifier.", "// No error occur because of the precedent validation and", "// the returned error is not be taken care of.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Create a PUBACK Packet.", "p", ":=", "&", "PUBACK", "{", "PacketID", ":", "packetID", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "variableHeader", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewPUBACKFromBytes creates a PUBACK Packet // from the byte data and returns it.
[ "NewPUBACKFromBytes", "creates", "a", "PUBACK", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/puback.go#L60-L84
2,187
yosssi/gmq
mqtt/packet/puback.go
validatePUBACKBytes
func validatePUBACKBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBACKVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBACKVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
go
func validatePUBACKBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenPUBACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypePUBACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenPUBACKVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenPUBACKVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
[ "func", "validatePUBACKBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "!=", "lenPUBACKFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypePUBACK", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "<<", "4", "!=", "0x00", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the Remaining Length of the fixed header.", "if", "fixedHeader", "[", "1", "]", "!=", "lenPUBACKVariableHeader", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// Check the length of the variable header.", "if", "len", "(", "variableHeader", ")", "!=", "lenPUBACKVariableHeader", "{", "return", "ErrInvalidVariableHeaderLen", "\n", "}", "\n\n", "// Extract the Packet Identifier.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Check the Packet Identifier.", "if", "packetID", "==", "0", "{", "return", "ErrInvalidPacketID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validatePUBACKBytes validates the fixed header and the variable header.
[ "validatePUBACKBytes", "validates", "the", "fixed", "header", "and", "the", "variable", "header", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/puback.go#L87-L128
2,188
yosssi/gmq
mqtt/client/session.go
newSession
func newSession(cleanSession bool, clientID []byte) *session { return &session{ cleanSession: cleanSession, clientID: clientID, sendingPackets: make(map[uint16]packet.Packet), receivingPackets: make(map[uint16]packet.Packet), } }
go
func newSession(cleanSession bool, clientID []byte) *session { return &session{ cleanSession: cleanSession, clientID: clientID, sendingPackets: make(map[uint16]packet.Packet), receivingPackets: make(map[uint16]packet.Packet), } }
[ "func", "newSession", "(", "cleanSession", "bool", ",", "clientID", "[", "]", "byte", ")", "*", "session", "{", "return", "&", "session", "{", "cleanSession", ":", "cleanSession", ",", "clientID", ":", "clientID", ",", "sendingPackets", ":", "make", "(", "map", "[", "uint16", "]", "packet", ".", "Packet", ")", ",", "receivingPackets", ":", "make", "(", "map", "[", "uint16", "]", "packet", ".", "Packet", ")", ",", "}", "\n", "}" ]
// newSession creates and returns a Session.
[ "newSession", "creates", "and", "returns", "a", "Session", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/session.go#L21-L28
2,189
yosssi/gmq
mqtt/packet/fixed_header.go
ptype
func (fixedHeader FixedHeader) ptype() (byte, error) { // Check the length of the fixed header. if len(fixedHeader) < 1 { return 0x00, ErrInvalidFixedHeaderLen } // Extract the MQTT Control Packet type from // the fixed header and return it. return fixedHeader[0] >> 4, nil }
go
func (fixedHeader FixedHeader) ptype() (byte, error) { // Check the length of the fixed header. if len(fixedHeader) < 1 { return 0x00, ErrInvalidFixedHeaderLen } // Extract the MQTT Control Packet type from // the fixed header and return it. return fixedHeader[0] >> 4, nil }
[ "func", "(", "fixedHeader", "FixedHeader", ")", "ptype", "(", ")", "(", "byte", ",", "error", ")", "{", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "<", "1", "{", "return", "0x00", ",", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Extract the MQTT Control Packet type from", "// the fixed header and return it.", "return", "fixedHeader", "[", "0", "]", ">>", "4", ",", "nil", "\n", "}" ]
// ptype extracts the MQTT Control Packet type from // the fixed header and returns it.
[ "ptype", "extracts", "the", "MQTT", "Control", "Packet", "type", "from", "the", "fixed", "header", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/fixed_header.go#L13-L22
2,190
yosssi/gmq
mqtt/packet/unsuback.go
NewUNSUBACKFromBytes
func NewUNSUBACKFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validateUNSUBACKBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBACK Packet. p := &UNSUBACK{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
go
func NewUNSUBACKFromBytes(fixedHeader FixedHeader, variableHeader []byte) (Packet, error) { // Validate the byte data. if err := validateUNSUBACKBytes(fixedHeader, variableHeader); err != nil { return nil, err } // Decode the Packet Identifier. // No error occur because of the precedent validation and // the returned error is not be taken care of. packetID, _ := decodeUint16(variableHeader) // Create a PUBACK Packet. p := &UNSUBACK{ PacketID: packetID, } // Set the fixed header to the Packet. p.fixedHeader = fixedHeader // Set the variable header to the Packet. p.variableHeader = variableHeader // Return the Packet. return p, nil }
[ "func", "NewUNSUBACKFromBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "(", "Packet", ",", "error", ")", "{", "// Validate the byte data.", "if", "err", ":=", "validateUNSUBACKBytes", "(", "fixedHeader", ",", "variableHeader", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Decode the Packet Identifier.", "// No error occur because of the precedent validation and", "// the returned error is not be taken care of.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Create a PUBACK Packet.", "p", ":=", "&", "UNSUBACK", "{", "PacketID", ":", "packetID", ",", "}", "\n\n", "// Set the fixed header to the Packet.", "p", ".", "fixedHeader", "=", "fixedHeader", "\n\n", "// Set the variable header to the Packet.", "p", ".", "variableHeader", "=", "variableHeader", "\n\n", "// Return the Packet.", "return", "p", ",", "nil", "\n", "}" ]
// NewUNSUBACKFromBytes creates an UNSUBACK Packet // from the byte data and returns it.
[ "NewUNSUBACKFromBytes", "creates", "an", "UNSUBACK", "Packet", "from", "the", "byte", "data", "and", "returns", "it", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/unsuback.go#L18-L42
2,191
yosssi/gmq
mqtt/packet/unsuback.go
validateUNSUBACKBytes
func validateUNSUBACKBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenUNSUBACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypeUNSUBACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenUNSUBACKVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenUNSUBACKVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
go
func validateUNSUBACKBytes(fixedHeader FixedHeader, variableHeader []byte) error { // Extract the MQTT Control Packet type. ptype, err := fixedHeader.ptype() if err != nil { return err } // Check the length of the fixed header. if len(fixedHeader) != lenUNSUBACKFixedHeader { return ErrInvalidFixedHeaderLen } // Check the MQTT Control Packet type. if ptype != TypeUNSUBACK { return ErrInvalidPacketType } // Check the reserved bits of the fixed header. if fixedHeader[0]<<4 != 0x00 { return ErrInvalidFixedHeader } // Check the Remaining Length of the fixed header. if fixedHeader[1] != lenUNSUBACKVariableHeader { return ErrInvalidRemainingLength } // Check the length of the variable header. if len(variableHeader) != lenUNSUBACKVariableHeader { return ErrInvalidVariableHeaderLen } // Extract the Packet Identifier. packetID, _ := decodeUint16(variableHeader) // Check the Packet Identifier. if packetID == 0 { return ErrInvalidPacketID } return nil }
[ "func", "validateUNSUBACKBytes", "(", "fixedHeader", "FixedHeader", ",", "variableHeader", "[", "]", "byte", ")", "error", "{", "// Extract the MQTT Control Packet type.", "ptype", ",", "err", ":=", "fixedHeader", ".", "ptype", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check the length of the fixed header.", "if", "len", "(", "fixedHeader", ")", "!=", "lenUNSUBACKFixedHeader", "{", "return", "ErrInvalidFixedHeaderLen", "\n", "}", "\n\n", "// Check the MQTT Control Packet type.", "if", "ptype", "!=", "TypeUNSUBACK", "{", "return", "ErrInvalidPacketType", "\n", "}", "\n\n", "// Check the reserved bits of the fixed header.", "if", "fixedHeader", "[", "0", "]", "<<", "4", "!=", "0x00", "{", "return", "ErrInvalidFixedHeader", "\n", "}", "\n\n", "// Check the Remaining Length of the fixed header.", "if", "fixedHeader", "[", "1", "]", "!=", "lenUNSUBACKVariableHeader", "{", "return", "ErrInvalidRemainingLength", "\n", "}", "\n\n", "// Check the length of the variable header.", "if", "len", "(", "variableHeader", ")", "!=", "lenUNSUBACKVariableHeader", "{", "return", "ErrInvalidVariableHeaderLen", "\n", "}", "\n\n", "// Extract the Packet Identifier.", "packetID", ",", "_", ":=", "decodeUint16", "(", "variableHeader", ")", "\n\n", "// Check the Packet Identifier.", "if", "packetID", "==", "0", "{", "return", "ErrInvalidPacketID", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateUNSUBACKBytes validates the fixed header and the variable header.
[ "validateUNSUBACKBytes", "validates", "the", "fixed", "header", "and", "the", "variable", "header", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/packet/unsuback.go#L45-L86
2,192
yosssi/gmq
mqtt/client/client.go
Connect
func (cli *Client) Connect(opts *ConnectOptions) error { // Lock for the connection. cli.muConn.Lock() // Unlock. defer cli.muConn.Unlock() // Return an error if the Client has already connected to the Server. if cli.conn != nil { return ErrAlreadyConnected } // Initialize the options. if opts == nil { opts = &ConnectOptions{} } // Establish a Network Connection. conn, err := newConnection(opts.Network, opts.Address, opts.TLSConfig) if err != nil { return err } // Set the Network Connection to the Client. cli.conn = conn // Lock for reading and updating the Session. cli.muSess.Lock() // Create a Session or reuse the current Session. if opts.CleanSession || cli.sess == nil { // Create a Session and set it to the Client. cli.sess = newSession(opts.CleanSession, opts.ClientID) } else { // Reuse the Session and set its Client Identifier to the options. opts.ClientID = cli.sess.clientID } // Unlock. cli.muSess.Unlock() // Send a CONNECT Packet to the Server. err = cli.sendCONNECT(&packet.CONNECTOptions{ ClientID: opts.ClientID, UserName: opts.UserName, Password: opts.Password, CleanSession: opts.CleanSession, KeepAlive: opts.KeepAlive, WillTopic: opts.WillTopic, WillMessage: opts.WillMessage, WillQoS: opts.WillQoS, WillRetain: opts.WillRetain, }) if err != nil { // Close the Network Connection. cli.conn.Close() // Clean the Network Connection and the Session if necessary. cli.clean() return err } // Launch a goroutine which waits for receiving the CONNACK Packet. cli.conn.wg.Add(1) go cli.waitPacket(cli.conn.connack, opts.CONNACKTimeout, ErrCONNACKTimeout) // Launch a goroutine which receives a Packet from the Server. cli.conn.wg.Add(1) go cli.receivePackets() // Launch a goroutine which sends a Packet to the Server. cli.conn.wg.Add(1) go cli.sendPackets(time.Duration(opts.KeepAlive), opts.PINGRESPTimeout) // Resend the unacknowledged PUBLISH and PUBREL Packets to the Server // if the Clean Session is false. if !opts.CleanSession { // Lock for reading and updating the Session. cli.muSess.Lock() // Unlock. defer cli.muSess.Unlock() for id, p := range cli.sess.sendingPackets { // Extract the MQTT Control MQTT Control Packet type. ptype, err := p.Type() if err != nil { return err } switch ptype { case packet.TypePUBLISH: // Set the DUP flag of the PUBLISH Packet to true. p.(*packet.PUBLISH).DUP = true // Resend the PUBLISH Packet to the Server. cli.conn.send <- p case packet.TypePUBREL: // Resend the PUBREL Packet to the Server. cli.conn.send <- p default: // Delete the Packet from the Session. delete(cli.sess.sendingPackets, id) } } } return nil }
go
func (cli *Client) Connect(opts *ConnectOptions) error { // Lock for the connection. cli.muConn.Lock() // Unlock. defer cli.muConn.Unlock() // Return an error if the Client has already connected to the Server. if cli.conn != nil { return ErrAlreadyConnected } // Initialize the options. if opts == nil { opts = &ConnectOptions{} } // Establish a Network Connection. conn, err := newConnection(opts.Network, opts.Address, opts.TLSConfig) if err != nil { return err } // Set the Network Connection to the Client. cli.conn = conn // Lock for reading and updating the Session. cli.muSess.Lock() // Create a Session or reuse the current Session. if opts.CleanSession || cli.sess == nil { // Create a Session and set it to the Client. cli.sess = newSession(opts.CleanSession, opts.ClientID) } else { // Reuse the Session and set its Client Identifier to the options. opts.ClientID = cli.sess.clientID } // Unlock. cli.muSess.Unlock() // Send a CONNECT Packet to the Server. err = cli.sendCONNECT(&packet.CONNECTOptions{ ClientID: opts.ClientID, UserName: opts.UserName, Password: opts.Password, CleanSession: opts.CleanSession, KeepAlive: opts.KeepAlive, WillTopic: opts.WillTopic, WillMessage: opts.WillMessage, WillQoS: opts.WillQoS, WillRetain: opts.WillRetain, }) if err != nil { // Close the Network Connection. cli.conn.Close() // Clean the Network Connection and the Session if necessary. cli.clean() return err } // Launch a goroutine which waits for receiving the CONNACK Packet. cli.conn.wg.Add(1) go cli.waitPacket(cli.conn.connack, opts.CONNACKTimeout, ErrCONNACKTimeout) // Launch a goroutine which receives a Packet from the Server. cli.conn.wg.Add(1) go cli.receivePackets() // Launch a goroutine which sends a Packet to the Server. cli.conn.wg.Add(1) go cli.sendPackets(time.Duration(opts.KeepAlive), opts.PINGRESPTimeout) // Resend the unacknowledged PUBLISH and PUBREL Packets to the Server // if the Clean Session is false. if !opts.CleanSession { // Lock for reading and updating the Session. cli.muSess.Lock() // Unlock. defer cli.muSess.Unlock() for id, p := range cli.sess.sendingPackets { // Extract the MQTT Control MQTT Control Packet type. ptype, err := p.Type() if err != nil { return err } switch ptype { case packet.TypePUBLISH: // Set the DUP flag of the PUBLISH Packet to true. p.(*packet.PUBLISH).DUP = true // Resend the PUBLISH Packet to the Server. cli.conn.send <- p case packet.TypePUBREL: // Resend the PUBREL Packet to the Server. cli.conn.send <- p default: // Delete the Packet from the Session. delete(cli.sess.sendingPackets, id) } } } return nil }
[ "func", "(", "cli", "*", "Client", ")", "Connect", "(", "opts", "*", "ConnectOptions", ")", "error", "{", "// Lock for the connection.", "cli", ".", "muConn", ".", "Lock", "(", ")", "\n\n", "// Unlock.", "defer", "cli", ".", "muConn", ".", "Unlock", "(", ")", "\n\n", "// Return an error if the Client has already connected to the Server.", "if", "cli", ".", "conn", "!=", "nil", "{", "return", "ErrAlreadyConnected", "\n", "}", "\n\n", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "ConnectOptions", "{", "}", "\n", "}", "\n\n", "// Establish a Network Connection.", "conn", ",", "err", ":=", "newConnection", "(", "opts", ".", "Network", ",", "opts", ".", "Address", ",", "opts", ".", "TLSConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Set the Network Connection to the Client.", "cli", ".", "conn", "=", "conn", "\n\n", "// Lock for reading and updating the Session.", "cli", ".", "muSess", ".", "Lock", "(", ")", "\n\n", "// Create a Session or reuse the current Session.", "if", "opts", ".", "CleanSession", "||", "cli", ".", "sess", "==", "nil", "{", "// Create a Session and set it to the Client.", "cli", ".", "sess", "=", "newSession", "(", "opts", ".", "CleanSession", ",", "opts", ".", "ClientID", ")", "\n", "}", "else", "{", "// Reuse the Session and set its Client Identifier to the options.", "opts", ".", "ClientID", "=", "cli", ".", "sess", ".", "clientID", "\n", "}", "\n\n", "// Unlock.", "cli", ".", "muSess", ".", "Unlock", "(", ")", "\n\n", "// Send a CONNECT Packet to the Server.", "err", "=", "cli", ".", "sendCONNECT", "(", "&", "packet", ".", "CONNECTOptions", "{", "ClientID", ":", "opts", ".", "ClientID", ",", "UserName", ":", "opts", ".", "UserName", ",", "Password", ":", "opts", ".", "Password", ",", "CleanSession", ":", "opts", ".", "CleanSession", ",", "KeepAlive", ":", "opts", ".", "KeepAlive", ",", "WillTopic", ":", "opts", ".", "WillTopic", ",", "WillMessage", ":", "opts", ".", "WillMessage", ",", "WillQoS", ":", "opts", ".", "WillQoS", ",", "WillRetain", ":", "opts", ".", "WillRetain", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "// Close the Network Connection.", "cli", ".", "conn", ".", "Close", "(", ")", "\n\n", "// Clean the Network Connection and the Session if necessary.", "cli", ".", "clean", "(", ")", "\n\n", "return", "err", "\n", "}", "\n\n", "// Launch a goroutine which waits for receiving the CONNACK Packet.", "cli", ".", "conn", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "cli", ".", "waitPacket", "(", "cli", ".", "conn", ".", "connack", ",", "opts", ".", "CONNACKTimeout", ",", "ErrCONNACKTimeout", ")", "\n\n", "// Launch a goroutine which receives a Packet from the Server.", "cli", ".", "conn", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "cli", ".", "receivePackets", "(", ")", "\n\n", "// Launch a goroutine which sends a Packet to the Server.", "cli", ".", "conn", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "cli", ".", "sendPackets", "(", "time", ".", "Duration", "(", "opts", ".", "KeepAlive", ")", ",", "opts", ".", "PINGRESPTimeout", ")", "\n\n", "// Resend the unacknowledged PUBLISH and PUBREL Packets to the Server", "// if the Clean Session is false.", "if", "!", "opts", ".", "CleanSession", "{", "// Lock for reading and updating the Session.", "cli", ".", "muSess", ".", "Lock", "(", ")", "\n\n", "// Unlock.", "defer", "cli", ".", "muSess", ".", "Unlock", "(", ")", "\n\n", "for", "id", ",", "p", ":=", "range", "cli", ".", "sess", ".", "sendingPackets", "{", "// Extract the MQTT Control MQTT Control Packet type.", "ptype", ",", "err", ":=", "p", ".", "Type", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "switch", "ptype", "{", "case", "packet", ".", "TypePUBLISH", ":", "// Set the DUP flag of the PUBLISH Packet to true.", "p", ".", "(", "*", "packet", ".", "PUBLISH", ")", ".", "DUP", "=", "true", "\n", "// Resend the PUBLISH Packet to the Server.", "cli", ".", "conn", ".", "send", "<-", "p", "\n", "case", "packet", ".", "TypePUBREL", ":", "// Resend the PUBREL Packet to the Server.", "cli", ".", "conn", ".", "send", "<-", "p", "\n", "default", ":", "// Delete the Packet from the Session.", "delete", "(", "cli", ".", "sess", ".", "sendingPackets", ",", "id", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Connect establishes a Network Connection to the Server and // sends a CONNECT Packet to the Server.
[ "Connect", "establishes", "a", "Network", "Connection", "to", "the", "Server", "and", "sends", "a", "CONNECT", "Packet", "to", "the", "Server", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L59-L168
2,193
yosssi/gmq
mqtt/client/client.go
Disconnect
func (cli *Client) Disconnect() error { // Lock for the disconnection. cli.muConn.Lock() // Return an error if the Client has not yet connected to the Server. if cli.conn == nil { // Unlock. cli.muConn.Unlock() return ErrNotYetConnected } // Send a DISCONNECT Packet to the Server. // Ignore the error returned by the send method because // we proceed to the subsequent disconnecting processing // even if the send method returns the error. cli.send(packet.NewDISCONNECT()) // Close the Network Connection. if err := cli.conn.Close(); err != nil { // Unlock. cli.muConn.Unlock() return err } // Change the state of the Network Connection to disconnected. cli.conn.disconnected = true // Send the end signal to the goroutine via the channels. select { case cli.conn.sendEnd <- struct{}{}: default: } // Unlock. cli.muConn.Unlock() // Wait until all goroutines end. cli.conn.wg.Wait() // Lock for cleaning the Network Connection. cli.muConn.Lock() // Lock for cleaning the Session. cli.muSess.Lock() // Clean the Network Connection and the Session. cli.clean() // Unlock. cli.muSess.Unlock() // Unlock. cli.muConn.Unlock() return nil }
go
func (cli *Client) Disconnect() error { // Lock for the disconnection. cli.muConn.Lock() // Return an error if the Client has not yet connected to the Server. if cli.conn == nil { // Unlock. cli.muConn.Unlock() return ErrNotYetConnected } // Send a DISCONNECT Packet to the Server. // Ignore the error returned by the send method because // we proceed to the subsequent disconnecting processing // even if the send method returns the error. cli.send(packet.NewDISCONNECT()) // Close the Network Connection. if err := cli.conn.Close(); err != nil { // Unlock. cli.muConn.Unlock() return err } // Change the state of the Network Connection to disconnected. cli.conn.disconnected = true // Send the end signal to the goroutine via the channels. select { case cli.conn.sendEnd <- struct{}{}: default: } // Unlock. cli.muConn.Unlock() // Wait until all goroutines end. cli.conn.wg.Wait() // Lock for cleaning the Network Connection. cli.muConn.Lock() // Lock for cleaning the Session. cli.muSess.Lock() // Clean the Network Connection and the Session. cli.clean() // Unlock. cli.muSess.Unlock() // Unlock. cli.muConn.Unlock() return nil }
[ "func", "(", "cli", "*", "Client", ")", "Disconnect", "(", ")", "error", "{", "// Lock for the disconnection.", "cli", ".", "muConn", ".", "Lock", "(", ")", "\n\n", "// Return an error if the Client has not yet connected to the Server.", "if", "cli", ".", "conn", "==", "nil", "{", "// Unlock.", "cli", ".", "muConn", ".", "Unlock", "(", ")", "\n\n", "return", "ErrNotYetConnected", "\n", "}", "\n\n", "// Send a DISCONNECT Packet to the Server.", "// Ignore the error returned by the send method because", "// we proceed to the subsequent disconnecting processing", "// even if the send method returns the error.", "cli", ".", "send", "(", "packet", ".", "NewDISCONNECT", "(", ")", ")", "\n\n", "// Close the Network Connection.", "if", "err", ":=", "cli", ".", "conn", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "// Unlock.", "cli", ".", "muConn", ".", "Unlock", "(", ")", "\n\n", "return", "err", "\n", "}", "\n\n", "// Change the state of the Network Connection to disconnected.", "cli", ".", "conn", ".", "disconnected", "=", "true", "\n\n", "// Send the end signal to the goroutine via the channels.", "select", "{", "case", "cli", ".", "conn", ".", "sendEnd", "<-", "struct", "{", "}", "{", "}", ":", "default", ":", "}", "\n\n", "// Unlock.", "cli", ".", "muConn", ".", "Unlock", "(", ")", "\n\n", "// Wait until all goroutines end.", "cli", ".", "conn", ".", "wg", ".", "Wait", "(", ")", "\n\n", "// Lock for cleaning the Network Connection.", "cli", ".", "muConn", ".", "Lock", "(", ")", "\n\n", "// Lock for cleaning the Session.", "cli", ".", "muSess", ".", "Lock", "(", ")", "\n\n", "// Clean the Network Connection and the Session.", "cli", ".", "clean", "(", ")", "\n\n", "// Unlock.", "cli", ".", "muSess", ".", "Unlock", "(", ")", "\n\n", "// Unlock.", "cli", ".", "muConn", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Disconnect sends a DISCONNECT Packet to the Server and // closes the Network Connection.
[ "Disconnect", "sends", "a", "DISCONNECT", "Packet", "to", "the", "Server", "and", "closes", "the", "Network", "Connection", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L172-L229
2,194
yosssi/gmq
mqtt/client/client.go
Publish
func (cli *Client) Publish(opts *PublishOptions) error { // Lock for reading. cli.muConn.RLock() // Unlock. defer cli.muConn.RUnlock() // Check the Network Connection. if cli.conn == nil { return ErrNotYetConnected } // Initialize the options. if opts == nil { opts = &PublishOptions{} } // Create a PUBLISH Packet. p, err := cli.newPUBLISHPacket(opts) if err != nil { return err } // Send the Packet to the Server. cli.conn.send <- p return nil }
go
func (cli *Client) Publish(opts *PublishOptions) error { // Lock for reading. cli.muConn.RLock() // Unlock. defer cli.muConn.RUnlock() // Check the Network Connection. if cli.conn == nil { return ErrNotYetConnected } // Initialize the options. if opts == nil { opts = &PublishOptions{} } // Create a PUBLISH Packet. p, err := cli.newPUBLISHPacket(opts) if err != nil { return err } // Send the Packet to the Server. cli.conn.send <- p return nil }
[ "func", "(", "cli", "*", "Client", ")", "Publish", "(", "opts", "*", "PublishOptions", ")", "error", "{", "// Lock for reading.", "cli", ".", "muConn", ".", "RLock", "(", ")", "\n\n", "// Unlock.", "defer", "cli", ".", "muConn", ".", "RUnlock", "(", ")", "\n\n", "// Check the Network Connection.", "if", "cli", ".", "conn", "==", "nil", "{", "return", "ErrNotYetConnected", "\n", "}", "\n\n", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "PublishOptions", "{", "}", "\n", "}", "\n\n", "// Create a PUBLISH Packet.", "p", ",", "err", ":=", "cli", ".", "newPUBLISHPacket", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Send the Packet to the Server.", "cli", ".", "conn", ".", "send", "<-", "p", "\n\n", "return", "nil", "\n", "}" ]
// Publish sends a PUBLISH Packet to the Server.
[ "Publish", "sends", "a", "PUBLISH", "Packet", "to", "the", "Server", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L232-L259
2,195
yosssi/gmq
mqtt/client/client.go
Subscribe
func (cli *Client) Subscribe(opts *SubscribeOptions) error { // Lock for reading and updating. cli.muConn.Lock() // Unlock. defer cli.muConn.Unlock() // Check the Network Connection. if cli.conn == nil { return ErrNotYetConnected } // Check the existence of the options. if opts == nil || len(opts.SubReqs) == 0 { return packet.ErrInvalidNoSubReq } // Define a Packet Identifier. var packetID uint16 // Define an error. var err error // Lock for updating the Session. cli.muSess.Lock() defer cli.muSess.Unlock() // Generate a Packet Identifer. if packetID, err = cli.generatePacketID(); err != nil { return err } // Create subscription requests for the SUBSCRIBE Packet. var subReqs []*packet.SubReq for _, s := range opts.SubReqs { subReqs = append(subReqs, &packet.SubReq{ TopicFilter: s.TopicFilter, QoS: s.QoS, }) } // Create a SUBSCRIBE Packet. p, err := packet.NewSUBSCRIBE(&packet.SUBSCRIBEOptions{ PacketID: packetID, SubReqs: subReqs, }) if err != nil { return err } // Set the Packet to the Session. cli.sess.sendingPackets[packetID] = p // Set the subscription information to // the Network Connection. for _, s := range opts.SubReqs { cli.conn.unackSubs[string(s.TopicFilter)] = s.Handler } // Send the Packet to the Server. cli.conn.send <- p return nil }
go
func (cli *Client) Subscribe(opts *SubscribeOptions) error { // Lock for reading and updating. cli.muConn.Lock() // Unlock. defer cli.muConn.Unlock() // Check the Network Connection. if cli.conn == nil { return ErrNotYetConnected } // Check the existence of the options. if opts == nil || len(opts.SubReqs) == 0 { return packet.ErrInvalidNoSubReq } // Define a Packet Identifier. var packetID uint16 // Define an error. var err error // Lock for updating the Session. cli.muSess.Lock() defer cli.muSess.Unlock() // Generate a Packet Identifer. if packetID, err = cli.generatePacketID(); err != nil { return err } // Create subscription requests for the SUBSCRIBE Packet. var subReqs []*packet.SubReq for _, s := range opts.SubReqs { subReqs = append(subReqs, &packet.SubReq{ TopicFilter: s.TopicFilter, QoS: s.QoS, }) } // Create a SUBSCRIBE Packet. p, err := packet.NewSUBSCRIBE(&packet.SUBSCRIBEOptions{ PacketID: packetID, SubReqs: subReqs, }) if err != nil { return err } // Set the Packet to the Session. cli.sess.sendingPackets[packetID] = p // Set the subscription information to // the Network Connection. for _, s := range opts.SubReqs { cli.conn.unackSubs[string(s.TopicFilter)] = s.Handler } // Send the Packet to the Server. cli.conn.send <- p return nil }
[ "func", "(", "cli", "*", "Client", ")", "Subscribe", "(", "opts", "*", "SubscribeOptions", ")", "error", "{", "// Lock for reading and updating.", "cli", ".", "muConn", ".", "Lock", "(", ")", "\n\n", "// Unlock.", "defer", "cli", ".", "muConn", ".", "Unlock", "(", ")", "\n\n", "// Check the Network Connection.", "if", "cli", ".", "conn", "==", "nil", "{", "return", "ErrNotYetConnected", "\n", "}", "\n\n", "// Check the existence of the options.", "if", "opts", "==", "nil", "||", "len", "(", "opts", ".", "SubReqs", ")", "==", "0", "{", "return", "packet", ".", "ErrInvalidNoSubReq", "\n", "}", "\n\n", "// Define a Packet Identifier.", "var", "packetID", "uint16", "\n\n", "// Define an error.", "var", "err", "error", "\n\n", "// Lock for updating the Session.", "cli", ".", "muSess", ".", "Lock", "(", ")", "\n\n", "defer", "cli", ".", "muSess", ".", "Unlock", "(", ")", "\n\n", "// Generate a Packet Identifer.", "if", "packetID", ",", "err", "=", "cli", ".", "generatePacketID", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Create subscription requests for the SUBSCRIBE Packet.", "var", "subReqs", "[", "]", "*", "packet", ".", "SubReq", "\n\n", "for", "_", ",", "s", ":=", "range", "opts", ".", "SubReqs", "{", "subReqs", "=", "append", "(", "subReqs", ",", "&", "packet", ".", "SubReq", "{", "TopicFilter", ":", "s", ".", "TopicFilter", ",", "QoS", ":", "s", ".", "QoS", ",", "}", ")", "\n", "}", "\n\n", "// Create a SUBSCRIBE Packet.", "p", ",", "err", ":=", "packet", ".", "NewSUBSCRIBE", "(", "&", "packet", ".", "SUBSCRIBEOptions", "{", "PacketID", ":", "packetID", ",", "SubReqs", ":", "subReqs", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Set the Packet to the Session.", "cli", ".", "sess", ".", "sendingPackets", "[", "packetID", "]", "=", "p", "\n\n", "// Set the subscription information to", "// the Network Connection.", "for", "_", ",", "s", ":=", "range", "opts", ".", "SubReqs", "{", "cli", ".", "conn", ".", "unackSubs", "[", "string", "(", "s", ".", "TopicFilter", ")", "]", "=", "s", ".", "Handler", "\n", "}", "\n\n", "// Send the Packet to the Server.", "cli", ".", "conn", ".", "send", "<-", "p", "\n\n", "return", "nil", "\n", "}" ]
// Subscribe sends a SUBSCRIBE Packet to the Server.
[ "Subscribe", "sends", "a", "SUBSCRIBE", "Packet", "to", "the", "Server", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L262-L327
2,196
yosssi/gmq
mqtt/client/client.go
Unsubscribe
func (cli *Client) Unsubscribe(opts *UnsubscribeOptions) error { // Lock for reading and updating. cli.muConn.Lock() // Unlock. defer cli.muConn.Unlock() // Check the Network Connection. if cli.conn == nil { return ErrNotYetConnected } // Check the existence of the options. if opts == nil || len(opts.TopicFilters) == 0 { return packet.ErrNoTopicFilter } // Define a Packet Identifier. var packetID uint16 // Define an error. var err error // Lock for updating the Session. cli.muSess.Lock() defer cli.muSess.Unlock() // Generate a Packet Identifer. if packetID, err = cli.generatePacketID(); err != nil { return err } // Create an UNSUBSCRIBE Packet. p, err := packet.NewUNSUBSCRIBE(&packet.UNSUBSCRIBEOptions{ PacketID: packetID, TopicFilters: opts.TopicFilters, }) if err != nil { return err } // Set the Packet to the Session. cli.sess.sendingPackets[packetID] = p // Send the Packet to the Server. cli.conn.send <- p return nil }
go
func (cli *Client) Unsubscribe(opts *UnsubscribeOptions) error { // Lock for reading and updating. cli.muConn.Lock() // Unlock. defer cli.muConn.Unlock() // Check the Network Connection. if cli.conn == nil { return ErrNotYetConnected } // Check the existence of the options. if opts == nil || len(opts.TopicFilters) == 0 { return packet.ErrNoTopicFilter } // Define a Packet Identifier. var packetID uint16 // Define an error. var err error // Lock for updating the Session. cli.muSess.Lock() defer cli.muSess.Unlock() // Generate a Packet Identifer. if packetID, err = cli.generatePacketID(); err != nil { return err } // Create an UNSUBSCRIBE Packet. p, err := packet.NewUNSUBSCRIBE(&packet.UNSUBSCRIBEOptions{ PacketID: packetID, TopicFilters: opts.TopicFilters, }) if err != nil { return err } // Set the Packet to the Session. cli.sess.sendingPackets[packetID] = p // Send the Packet to the Server. cli.conn.send <- p return nil }
[ "func", "(", "cli", "*", "Client", ")", "Unsubscribe", "(", "opts", "*", "UnsubscribeOptions", ")", "error", "{", "// Lock for reading and updating.", "cli", ".", "muConn", ".", "Lock", "(", ")", "\n\n", "// Unlock.", "defer", "cli", ".", "muConn", ".", "Unlock", "(", ")", "\n\n", "// Check the Network Connection.", "if", "cli", ".", "conn", "==", "nil", "{", "return", "ErrNotYetConnected", "\n", "}", "\n\n", "// Check the existence of the options.", "if", "opts", "==", "nil", "||", "len", "(", "opts", ".", "TopicFilters", ")", "==", "0", "{", "return", "packet", ".", "ErrNoTopicFilter", "\n", "}", "\n\n", "// Define a Packet Identifier.", "var", "packetID", "uint16", "\n\n", "// Define an error.", "var", "err", "error", "\n\n", "// Lock for updating the Session.", "cli", ".", "muSess", ".", "Lock", "(", ")", "\n\n", "defer", "cli", ".", "muSess", ".", "Unlock", "(", ")", "\n\n", "// Generate a Packet Identifer.", "if", "packetID", ",", "err", "=", "cli", ".", "generatePacketID", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Create an UNSUBSCRIBE Packet.", "p", ",", "err", ":=", "packet", ".", "NewUNSUBSCRIBE", "(", "&", "packet", ".", "UNSUBSCRIBEOptions", "{", "PacketID", ":", "packetID", ",", "TopicFilters", ":", "opts", ".", "TopicFilters", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Set the Packet to the Session.", "cli", ".", "sess", ".", "sendingPackets", "[", "packetID", "]", "=", "p", "\n\n", "// Send the Packet to the Server.", "cli", ".", "conn", ".", "send", "<-", "p", "\n\n", "return", "nil", "\n", "}" ]
// Unsubscribe sends an UNSUBSCRIBE Packet to the Server.
[ "Unsubscribe", "sends", "an", "UNSUBSCRIBE", "Packet", "to", "the", "Server", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L330-L379
2,197
yosssi/gmq
mqtt/client/client.go
send
func (cli *Client) send(p packet.Packet) error { // Return an error if the Client has not yet connected to the Server. if cli.conn == nil { return ErrNotYetConnected } // Write the Packet to the buffered writer. if _, err := p.WriteTo(cli.conn.w); err != nil { return err } // Flush the buffered writer. return cli.conn.w.Flush() }
go
func (cli *Client) send(p packet.Packet) error { // Return an error if the Client has not yet connected to the Server. if cli.conn == nil { return ErrNotYetConnected } // Write the Packet to the buffered writer. if _, err := p.WriteTo(cli.conn.w); err != nil { return err } // Flush the buffered writer. return cli.conn.w.Flush() }
[ "func", "(", "cli", "*", "Client", ")", "send", "(", "p", "packet", ".", "Packet", ")", "error", "{", "// Return an error if the Client has not yet connected to the Server.", "if", "cli", ".", "conn", "==", "nil", "{", "return", "ErrNotYetConnected", "\n", "}", "\n\n", "// Write the Packet to the buffered writer.", "if", "_", ",", "err", ":=", "p", ".", "WriteTo", "(", "cli", ".", "conn", ".", "w", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Flush the buffered writer.", "return", "cli", ".", "conn", ".", "w", ".", "Flush", "(", ")", "\n", "}" ]
// send sends an MQTT Control Packet to the Server.
[ "send", "sends", "an", "MQTT", "Control", "Packet", "to", "the", "Server", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L391-L404
2,198
yosssi/gmq
mqtt/client/client.go
sendCONNECT
func (cli *Client) sendCONNECT(opts *packet.CONNECTOptions) error { // Initialize the options. if opts == nil { opts = &packet.CONNECTOptions{} } // Create a CONNECT Packet. p, err := packet.NewCONNECT(opts) if err != nil { return err } // Send a CONNECT Packet to the Server. return cli.send(p) }
go
func (cli *Client) sendCONNECT(opts *packet.CONNECTOptions) error { // Initialize the options. if opts == nil { opts = &packet.CONNECTOptions{} } // Create a CONNECT Packet. p, err := packet.NewCONNECT(opts) if err != nil { return err } // Send a CONNECT Packet to the Server. return cli.send(p) }
[ "func", "(", "cli", "*", "Client", ")", "sendCONNECT", "(", "opts", "*", "packet", ".", "CONNECTOptions", ")", "error", "{", "// Initialize the options.", "if", "opts", "==", "nil", "{", "opts", "=", "&", "packet", ".", "CONNECTOptions", "{", "}", "\n", "}", "\n\n", "// Create a CONNECT Packet.", "p", ",", "err", ":=", "packet", ".", "NewCONNECT", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Send a CONNECT Packet to the Server.", "return", "cli", ".", "send", "(", "p", ")", "\n", "}" ]
// sendCONNECT creates a CONNECT Packet and sends it to the Server.
[ "sendCONNECT", "creates", "a", "CONNECT", "Packet", "and", "sends", "it", "to", "the", "Server", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L407-L421
2,199
yosssi/gmq
mqtt/client/client.go
receive
func (cli *Client) receive() (packet.Packet, error) { // Return an error if the Client has not yet connected to the Server. if cli.conn == nil { return nil, ErrNotYetConnected } // Get the first byte of the Packet. b, err := cli.conn.r.ReadByte() if err != nil { return nil, err } // Create the Fixed header. fixedHeader := packet.FixedHeader([]byte{b}) // Get and decode the Remaining Length. var mp uint32 = 1 // multiplier var rl uint32 // the Remaining Length for { // Get the next byte of the Packet. b, err = cli.conn.r.ReadByte() if err != nil { return nil, err } fixedHeader = append(fixedHeader, b) rl += uint32(b&0x7F) * mp if b&0x80 == 0 { break } mp *= 128 } // Create the Remaining (the Variable header and the Payload). remaining := make([]byte, rl) if rl > 0 { // Get the remaining of the Packet. if _, err = io.ReadFull(cli.conn.r, remaining); err != nil { return nil, err } } // Create and return a Packet. return packet.NewFromBytes(fixedHeader, remaining) }
go
func (cli *Client) receive() (packet.Packet, error) { // Return an error if the Client has not yet connected to the Server. if cli.conn == nil { return nil, ErrNotYetConnected } // Get the first byte of the Packet. b, err := cli.conn.r.ReadByte() if err != nil { return nil, err } // Create the Fixed header. fixedHeader := packet.FixedHeader([]byte{b}) // Get and decode the Remaining Length. var mp uint32 = 1 // multiplier var rl uint32 // the Remaining Length for { // Get the next byte of the Packet. b, err = cli.conn.r.ReadByte() if err != nil { return nil, err } fixedHeader = append(fixedHeader, b) rl += uint32(b&0x7F) * mp if b&0x80 == 0 { break } mp *= 128 } // Create the Remaining (the Variable header and the Payload). remaining := make([]byte, rl) if rl > 0 { // Get the remaining of the Packet. if _, err = io.ReadFull(cli.conn.r, remaining); err != nil { return nil, err } } // Create and return a Packet. return packet.NewFromBytes(fixedHeader, remaining) }
[ "func", "(", "cli", "*", "Client", ")", "receive", "(", ")", "(", "packet", ".", "Packet", ",", "error", ")", "{", "// Return an error if the Client has not yet connected to the Server.", "if", "cli", ".", "conn", "==", "nil", "{", "return", "nil", ",", "ErrNotYetConnected", "\n", "}", "\n\n", "// Get the first byte of the Packet.", "b", ",", "err", ":=", "cli", ".", "conn", ".", "r", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create the Fixed header.", "fixedHeader", ":=", "packet", ".", "FixedHeader", "(", "[", "]", "byte", "{", "b", "}", ")", "\n\n", "// Get and decode the Remaining Length.", "var", "mp", "uint32", "=", "1", "// multiplier", "\n", "var", "rl", "uint32", "// the Remaining Length", "\n", "for", "{", "// Get the next byte of the Packet.", "b", ",", "err", "=", "cli", ".", "conn", ".", "r", ".", "ReadByte", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fixedHeader", "=", "append", "(", "fixedHeader", ",", "b", ")", "\n\n", "rl", "+=", "uint32", "(", "b", "&", "0x7F", ")", "*", "mp", "\n\n", "if", "b", "&", "0x80", "==", "0", "{", "break", "\n", "}", "\n\n", "mp", "*=", "128", "\n", "}", "\n\n", "// Create the Remaining (the Variable header and the Payload).", "remaining", ":=", "make", "(", "[", "]", "byte", ",", "rl", ")", "\n\n", "if", "rl", ">", "0", "{", "// Get the remaining of the Packet.", "if", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "cli", ".", "conn", ".", "r", ",", "remaining", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Create and return a Packet.", "return", "packet", ".", "NewFromBytes", "(", "fixedHeader", ",", "remaining", ")", "\n", "}" ]
// receive receives an MQTT Control Packet from the Server.
[ "receive", "receives", "an", "MQTT", "Control", "Packet", "from", "the", "Server", "." ]
b221999646da8ea48ff0796c2b0191aa510d062e
https://github.com/yosssi/gmq/blob/b221999646da8ea48ff0796c2b0191aa510d062e/mqtt/client/client.go#L424-L472