repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
lestrrat-go/jwx
jwt/jwt.go
ParseBytes
func ParseBytes(s []byte, options ...Option) (*Token, error) { return Parse(bytes.NewReader(s), options...) }
go
func ParseBytes(s []byte, options ...Option) (*Token, error) { return Parse(bytes.NewReader(s), options...) }
[ "func", "ParseBytes", "(", "s", "[", "]", "byte", ",", "options", "...", "Option", ")", "(", "*", "Token", ",", "error", ")", "{", "return", "Parse", "(", "bytes", ".", "NewReader", "(", "s", ")", ",", "options", "...", ")", "\n", "}" ]
// ParseString calls Parse with the given byte sequence
[ "ParseString", "calls", "Parse", "with", "the", "given", "byte", "sequence" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwt/jwt.go#L24-L26
train
lestrrat-go/jwx
jwt/jwt.go
Sign
func (t *Token) Sign(method jwa.SignatureAlgorithm, key interface{}) ([]byte, error) { buf, err := json.Marshal(t) if err != nil { return nil, errors.Wrap(err, `failed to marshal token`) } var hdr jws.StandardHeaders if hdr.Set(`alg`, method.String()) != nil { return nil, errors.Wrap(err, `failed to sign payload`) } if hdr.Set(`typ`, `JWT`) != nil { return nil, errors.Wrap(err, `failed to sign payload`) } sign, err := jws.Sign(buf, method, key, jws.WithHeaders(&hdr)) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } return sign, nil }
go
func (t *Token) Sign(method jwa.SignatureAlgorithm, key interface{}) ([]byte, error) { buf, err := json.Marshal(t) if err != nil { return nil, errors.Wrap(err, `failed to marshal token`) } var hdr jws.StandardHeaders if hdr.Set(`alg`, method.String()) != nil { return nil, errors.Wrap(err, `failed to sign payload`) } if hdr.Set(`typ`, `JWT`) != nil { return nil, errors.Wrap(err, `failed to sign payload`) } sign, err := jws.Sign(buf, method, key, jws.WithHeaders(&hdr)) if err != nil { return nil, errors.Wrap(err, `failed to sign payload`) } return sign, nil }
[ "func", "(", "t", "*", "Token", ")", "Sign", "(", "method", "jwa", ".", "SignatureAlgorithm", ",", "key", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to marshal token`", ")", "\n", "}", "\n\n", "var", "hdr", "jws", ".", "StandardHeaders", "\n", "if", "hdr", ".", "Set", "(", "`alg`", ",", "method", ".", "String", "(", ")", ")", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to sign payload`", ")", "\n", "}", "\n", "if", "hdr", ".", "Set", "(", "`typ`", ",", "`JWT`", ")", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to sign payload`", ")", "\n", "}", "\n", "sign", ",", "err", ":=", "jws", ".", "Sign", "(", "buf", ",", "method", ",", "key", ",", "jws", ".", "WithHeaders", "(", "&", "hdr", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to sign payload`", ")", "\n", "}", "\n\n", "return", "sign", ",", "nil", "\n", "}" ]
// Sign is a convenience function to create a signed JWT token serialized in // compact form. `key` must match the key type required by the given // signature method `method`
[ "Sign", "is", "a", "convenience", "function", "to", "create", "a", "signed", "JWT", "token", "serialized", "in", "compact", "form", ".", "key", "must", "match", "the", "key", "type", "required", "by", "the", "given", "signature", "method", "method" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwt/jwt.go#L87-L106
train
lestrrat-go/jwx
buffer/buffer.go
FromUint
func FromUint(v uint64) Buffer { data := make([]byte, 8) binary.BigEndian.PutUint64(data, v) i := 0 for ; i < len(data); i++ { if data[i] != 0x0 { break } } return Buffer(data[i:]) }
go
func FromUint(v uint64) Buffer { data := make([]byte, 8) binary.BigEndian.PutUint64(data, v) i := 0 for ; i < len(data); i++ { if data[i] != 0x0 { break } } return Buffer(data[i:]) }
[ "func", "FromUint", "(", "v", "uint64", ")", "Buffer", "{", "data", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "data", ",", "v", ")", "\n\n", "i", ":=", "0", "\n", "for", ";", "i", "<", "len", "(", "data", ")", ";", "i", "++", "{", "if", "data", "[", "i", "]", "!=", "0x0", "{", "break", "\n", "}", "\n", "}", "\n", "return", "Buffer", "(", "data", "[", "i", ":", "]", ")", "\n", "}" ]
// FromUint creates a `Buffer` from an unsigned int
[ "FromUint", "creates", "a", "Buffer", "from", "an", "unsigned", "int" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/buffer/buffer.go#L21-L32
train
lestrrat-go/jwx
buffer/buffer.go
FromBase64
func FromBase64(v []byte) (Buffer, error) { b := Buffer{} if err := b.Base64Decode(v); err != nil { return Buffer(nil), errors.Wrap(err, "failed to decode from base64") } return b, nil }
go
func FromBase64(v []byte) (Buffer, error) { b := Buffer{} if err := b.Base64Decode(v); err != nil { return Buffer(nil), errors.Wrap(err, "failed to decode from base64") } return b, nil }
[ "func", "FromBase64", "(", "v", "[", "]", "byte", ")", "(", "Buffer", ",", "error", ")", "{", "b", ":=", "Buffer", "{", "}", "\n", "if", "err", ":=", "b", ".", "Base64Decode", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "Buffer", "(", "nil", ")", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "b", ",", "nil", "\n", "}" ]
// FromBase64 constructs a new Buffer from a base64 encoded data
[ "FromBase64", "constructs", "a", "new", "Buffer", "from", "a", "base64", "encoded", "data" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/buffer/buffer.go#L35-L42
train
lestrrat-go/jwx
buffer/buffer.go
NData
func (b Buffer) NData() []byte { buf := make([]byte, 4+b.Len()) binary.BigEndian.PutUint32(buf, uint32(b.Len())) copy(buf[4:], b.Bytes()) return buf }
go
func (b Buffer) NData() []byte { buf := make([]byte, 4+b.Len()) binary.BigEndian.PutUint32(buf, uint32(b.Len())) copy(buf[4:], b.Bytes()) return buf }
[ "func", "(", "b", "Buffer", ")", "NData", "(", ")", "[", "]", "byte", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "4", "+", "b", ".", "Len", "(", ")", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "buf", ",", "uint32", "(", "b", ".", "Len", "(", ")", ")", ")", "\n\n", "copy", "(", "buf", "[", "4", ":", "]", ",", "b", ".", "Bytes", "(", ")", ")", "\n", "return", "buf", "\n", "}" ]
// NData returns Datalen || Data, where Datalen is a 32 bit counter for // the length of the following data, and Data is the octets that comprise // the buffer data
[ "NData", "returns", "Datalen", "||", "Data", "where", "Datalen", "is", "a", "32", "bit", "counter", "for", "the", "length", "of", "the", "following", "data", "and", "Data", "is", "the", "octets", "that", "comprise", "the", "buffer", "data" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/buffer/buffer.go#L61-L67
train
lestrrat-go/jwx
buffer/buffer.go
Base64Encode
func (b Buffer) Base64Encode() ([]byte, error) { enc := base64.RawURLEncoding out := make([]byte, enc.EncodedLen(len(b))) enc.Encode(out, b) return out, nil }
go
func (b Buffer) Base64Encode() ([]byte, error) { enc := base64.RawURLEncoding out := make([]byte, enc.EncodedLen(len(b))) enc.Encode(out, b) return out, nil }
[ "func", "(", "b", "Buffer", ")", "Base64Encode", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "enc", ":=", "base64", ".", "RawURLEncoding", "\n", "out", ":=", "make", "(", "[", "]", "byte", ",", "enc", ".", "EncodedLen", "(", "len", "(", "b", ")", ")", ")", "\n", "enc", ".", "Encode", "(", "out", ",", "b", ")", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Base64Encode encodes the contents of the Buffer using base64.RawURLEncoding
[ "Base64Encode", "encodes", "the", "contents", "of", "the", "Buffer", "using", "base64", ".", "RawURLEncoding" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/buffer/buffer.go#L80-L85
train
lestrrat-go/jwx
buffer/buffer.go
Base64Decode
func (b *Buffer) Base64Decode(v []byte) error { enc := base64.RawURLEncoding out := make([]byte, enc.DecodedLen(len(v))) n, err := enc.Decode(out, v) if err != nil { return errors.Wrap(err, "failed to decode from base64") } out = out[:n] *b = Buffer(out) return nil }
go
func (b *Buffer) Base64Decode(v []byte) error { enc := base64.RawURLEncoding out := make([]byte, enc.DecodedLen(len(v))) n, err := enc.Decode(out, v) if err != nil { return errors.Wrap(err, "failed to decode from base64") } out = out[:n] *b = Buffer(out) return nil }
[ "func", "(", "b", "*", "Buffer", ")", "Base64Decode", "(", "v", "[", "]", "byte", ")", "error", "{", "enc", ":=", "base64", ".", "RawURLEncoding", "\n", "out", ":=", "make", "(", "[", "]", "byte", ",", "enc", ".", "DecodedLen", "(", "len", "(", "v", ")", ")", ")", "\n", "n", ",", "err", ":=", "enc", ".", "Decode", "(", "out", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "out", "=", "out", "[", ":", "n", "]", "\n", "*", "b", "=", "Buffer", "(", "out", ")", "\n", "return", "nil", "\n", "}" ]
// Base64Decode decodes the contents of the Buffer using base64.RawURLEncoding
[ "Base64Decode", "decodes", "the", "contents", "of", "the", "Buffer", "using", "base64", ".", "RawURLEncoding" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/buffer/buffer.go#L88-L98
train
lestrrat-go/jwx
buffer/buffer.go
MarshalJSON
func (b Buffer) MarshalJSON() ([]byte, error) { v, err := b.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode to base64") } return json.Marshal(string(v)) }
go
func (b Buffer) MarshalJSON() ([]byte, error) { v, err := b.Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to encode to base64") } return json.Marshal(string(v)) }
[ "func", "(", "b", "Buffer", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "v", ",", "err", ":=", "b", ".", "Base64Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "string", "(", "v", ")", ")", "\n", "}" ]
// MarshalJSON marshals the buffer into JSON format after encoding the buffer // with base64.RawURLEncoding
[ "MarshalJSON", "marshals", "the", "buffer", "into", "JSON", "format", "after", "encoding", "the", "buffer", "with", "base64", ".", "RawURLEncoding" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/buffer/buffer.go#L102-L108
train
lestrrat-go/jwx
buffer/buffer.go
UnmarshalJSON
func (b *Buffer) UnmarshalJSON(data []byte) error { var x string if err := json.Unmarshal(data, &x); err != nil { return errors.Wrap(err, "failed to unmarshal JSON") } return b.Base64Decode([]byte(x)) }
go
func (b *Buffer) UnmarshalJSON(data []byte) error { var x string if err := json.Unmarshal(data, &x); err != nil { return errors.Wrap(err, "failed to unmarshal JSON") } return b.Base64Decode([]byte(x)) }
[ "func", "(", "b", "*", "Buffer", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "x", "string", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "x", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "b", ".", "Base64Decode", "(", "[", "]", "byte", "(", "x", ")", ")", "\n", "}" ]
// UnmarshalJSON unmarshals from a JSON string into a Buffer, after decoding it // with base64.RawURLEncoding
[ "UnmarshalJSON", "unmarshals", "from", "a", "JSON", "string", "into", "a", "Buffer", "after", "decoding", "it", "with", "base64", ".", "RawURLEncoding" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/buffer/buffer.go#L112-L118
train
lestrrat-go/jwx
jwe/key_generate.go
KeyGenerate
func (g StaticKeyGenerate) KeyGenerate() (ByteSource, error) { buf := make([]byte, g.KeySize()) copy(buf, g) return ByteKey(buf), nil }
go
func (g StaticKeyGenerate) KeyGenerate() (ByteSource, error) { buf := make([]byte, g.KeySize()) copy(buf, g) return ByteKey(buf), nil }
[ "func", "(", "g", "StaticKeyGenerate", ")", "KeyGenerate", "(", ")", "(", "ByteSource", ",", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "g", ".", "KeySize", "(", ")", ")", "\n", "copy", "(", "buf", ",", "g", ")", "\n", "return", "ByteKey", "(", "buf", ")", ",", "nil", "\n", "}" ]
// KeyGenerate returns the key
[ "KeyGenerate", "returns", "the", "key" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_generate.go#L27-L31
train
lestrrat-go/jwx
jwe/key_generate.go
KeyGenerate
func (g RandomKeyGenerate) KeyGenerate() (ByteSource, error) { buf := make([]byte, g.keysize) if _, err := io.ReadFull(rand.Reader, buf); err != nil { return nil, errors.Wrap(err, "failed to read from rand.Reader") } return ByteKey(buf), nil }
go
func (g RandomKeyGenerate) KeyGenerate() (ByteSource, error) { buf := make([]byte, g.keysize) if _, err := io.ReadFull(rand.Reader, buf); err != nil { return nil, errors.Wrap(err, "failed to read from rand.Reader") } return ByteKey(buf), nil }
[ "func", "(", "g", "RandomKeyGenerate", ")", "KeyGenerate", "(", ")", "(", "ByteSource", ",", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "g", ".", "keysize", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "rand", ".", "Reader", ",", "buf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "ByteKey", "(", "buf", ")", ",", "nil", "\n", "}" ]
// KeyGenerate generates a random new key
[ "KeyGenerate", "generates", "a", "random", "new", "key" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_generate.go#L45-L51
train
lestrrat-go/jwx
jwe/key_generate.go
NewEcdhesKeyGenerate
func NewEcdhesKeyGenerate(alg jwa.KeyEncryptionAlgorithm, pubkey *ecdsa.PublicKey) (*EcdhesKeyGenerate, error) { var keysize int switch alg { case jwa.ECDH_ES: return nil, errors.New("unimplemented") case jwa.ECDH_ES_A128KW: keysize = 16 case jwa.ECDH_ES_A192KW: keysize = 24 case jwa.ECDH_ES_A256KW: keysize = 32 default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid ECDH-ES key generation algorithm") } return &EcdhesKeyGenerate{ algorithm: alg, keysize: keysize, pubkey: pubkey, }, nil }
go
func NewEcdhesKeyGenerate(alg jwa.KeyEncryptionAlgorithm, pubkey *ecdsa.PublicKey) (*EcdhesKeyGenerate, error) { var keysize int switch alg { case jwa.ECDH_ES: return nil, errors.New("unimplemented") case jwa.ECDH_ES_A128KW: keysize = 16 case jwa.ECDH_ES_A192KW: keysize = 24 case jwa.ECDH_ES_A256KW: keysize = 32 default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid ECDH-ES key generation algorithm") } return &EcdhesKeyGenerate{ algorithm: alg, keysize: keysize, pubkey: pubkey, }, nil }
[ "func", "NewEcdhesKeyGenerate", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "pubkey", "*", "ecdsa", ".", "PublicKey", ")", "(", "*", "EcdhesKeyGenerate", ",", "error", ")", "{", "var", "keysize", "int", "\n", "switch", "alg", "{", "case", "jwa", ".", "ECDH_ES", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "jwa", ".", "ECDH_ES_A128KW", ":", "keysize", "=", "16", "\n", "case", "jwa", ".", "ECDH_ES_A192KW", ":", "keysize", "=", "24", "\n", "case", "jwa", ".", "ECDH_ES_A256KW", ":", "keysize", "=", "32", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Wrap", "(", "ErrUnsupportedAlgorithm", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "EcdhesKeyGenerate", "{", "algorithm", ":", "alg", ",", "keysize", ":", "keysize", ",", "pubkey", ":", "pubkey", ",", "}", ",", "nil", "\n", "}" ]
// NewEcdhesKeyGenerate creates a new key generator using ECDH-ES
[ "NewEcdhesKeyGenerate", "creates", "a", "new", "key", "generator", "using", "ECDH", "-", "ES" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_generate.go#L54-L74
train
lestrrat-go/jwx
jwe/key_generate.go
KeyGenerate
func (g EcdhesKeyGenerate) KeyGenerate() (ByteSource, error) { priv, err := ecdsa.GenerateKey(g.pubkey.Curve, rand.Reader) if err != nil { return nil, errors.Wrap(err, "failed to generate key for ECDH-ES") } pubinfo := make([]byte, 4) binary.BigEndian.PutUint32(pubinfo, uint32(g.keysize)*8) z, _ := priv.PublicKey.Curve.ScalarMult(g.pubkey.X, g.pubkey.Y, priv.D.Bytes()) kdf := concatkdf.New(crypto.SHA256, []byte(g.algorithm.String()), z.Bytes(), []byte{}, []byte{}, pubinfo, []byte{}) kek := make([]byte, g.keysize) kdf.Read(kek) return ByteWithECPrivateKey{ PrivateKey: priv, ByteKey: ByteKey(kek), }, nil }
go
func (g EcdhesKeyGenerate) KeyGenerate() (ByteSource, error) { priv, err := ecdsa.GenerateKey(g.pubkey.Curve, rand.Reader) if err != nil { return nil, errors.Wrap(err, "failed to generate key for ECDH-ES") } pubinfo := make([]byte, 4) binary.BigEndian.PutUint32(pubinfo, uint32(g.keysize)*8) z, _ := priv.PublicKey.Curve.ScalarMult(g.pubkey.X, g.pubkey.Y, priv.D.Bytes()) kdf := concatkdf.New(crypto.SHA256, []byte(g.algorithm.String()), z.Bytes(), []byte{}, []byte{}, pubinfo, []byte{}) kek := make([]byte, g.keysize) kdf.Read(kek) return ByteWithECPrivateKey{ PrivateKey: priv, ByteKey: ByteKey(kek), }, nil }
[ "func", "(", "g", "EcdhesKeyGenerate", ")", "KeyGenerate", "(", ")", "(", "ByteSource", ",", "error", ")", "{", "priv", ",", "err", ":=", "ecdsa", ".", "GenerateKey", "(", "g", ".", "pubkey", ".", "Curve", ",", "rand", ".", "Reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "pubinfo", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "pubinfo", ",", "uint32", "(", "g", ".", "keysize", ")", "*", "8", ")", "\n\n", "z", ",", "_", ":=", "priv", ".", "PublicKey", ".", "Curve", ".", "ScalarMult", "(", "g", ".", "pubkey", ".", "X", ",", "g", ".", "pubkey", ".", "Y", ",", "priv", ".", "D", ".", "Bytes", "(", ")", ")", "\n", "kdf", ":=", "concatkdf", ".", "New", "(", "crypto", ".", "SHA256", ",", "[", "]", "byte", "(", "g", ".", "algorithm", ".", "String", "(", ")", ")", ",", "z", ".", "Bytes", "(", ")", ",", "[", "]", "byte", "{", "}", ",", "[", "]", "byte", "{", "}", ",", "pubinfo", ",", "[", "]", "byte", "{", "}", ")", "\n", "kek", ":=", "make", "(", "[", "]", "byte", ",", "g", ".", "keysize", ")", "\n", "kdf", ".", "Read", "(", "kek", ")", "\n\n", "return", "ByteWithECPrivateKey", "{", "PrivateKey", ":", "priv", ",", "ByteKey", ":", "ByteKey", "(", "kek", ")", ",", "}", ",", "nil", "\n", "}" ]
// KeyGenerate generates new keys using ECDH-ES
[ "KeyGenerate", "generates", "new", "keys", "using", "ECDH", "-", "ES" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_generate.go#L82-L100
train
lestrrat-go/jwx
jwe/message.go
Get
func (h *Header) Get(key string) (interface{}, error) { switch key { case "alg": return h.Algorithm, nil case "apu": return h.AgreementPartyUInfo, nil case "apv": return h.AgreementPartyVInfo, nil case "enc": return h.ContentEncryption, nil case "epk": return h.EphemeralPublicKey, nil case "cty": return h.ContentType, nil case "kid": return h.KeyID, nil case "typ": return h.Type, nil case "x5t": return h.X509CertThumbprint, nil case "x5t#256": return h.X509CertThumbprintS256, nil case "x5c": return h.X509CertChain, nil case "crit": return h.Critical, nil case "jku": return h.JwkSetURL, nil case "x5u": return h.X509Url, nil default: v, ok := h.PrivateParams[key] if !ok { return nil, errors.New("invalid header name") } return v, nil } }
go
func (h *Header) Get(key string) (interface{}, error) { switch key { case "alg": return h.Algorithm, nil case "apu": return h.AgreementPartyUInfo, nil case "apv": return h.AgreementPartyVInfo, nil case "enc": return h.ContentEncryption, nil case "epk": return h.EphemeralPublicKey, nil case "cty": return h.ContentType, nil case "kid": return h.KeyID, nil case "typ": return h.Type, nil case "x5t": return h.X509CertThumbprint, nil case "x5t#256": return h.X509CertThumbprintS256, nil case "x5c": return h.X509CertChain, nil case "crit": return h.Critical, nil case "jku": return h.JwkSetURL, nil case "x5u": return h.X509Url, nil default: v, ok := h.PrivateParams[key] if !ok { return nil, errors.New("invalid header name") } return v, nil } }
[ "func", "(", "h", "*", "Header", ")", "Get", "(", "key", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "switch", "key", "{", "case", "\"", "\"", ":", "return", "h", ".", "Algorithm", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "AgreementPartyUInfo", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "AgreementPartyVInfo", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "ContentEncryption", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "EphemeralPublicKey", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "ContentType", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "KeyID", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "Type", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "X509CertThumbprint", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "X509CertThumbprintS256", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "X509CertChain", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "Critical", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "JwkSetURL", ",", "nil", "\n", "case", "\"", "\"", ":", "return", "h", ".", "X509Url", ",", "nil", "\n", "default", ":", "v", ",", "ok", ":=", "h", ".", "PrivateParams", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}", "\n", "}" ]
// Get returns the header key
[ "Get", "returns", "the", "header", "key" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/message.go#L39-L76
train
lestrrat-go/jwx
jwe/message.go
Base64Encode
func (e EncodedHeader) Base64Encode() ([]byte, error) { buf, err := json.Marshal(e.Header) if err != nil { return nil, errors.Wrap(err, "failed to marshal encoded header into JSON") } buf, err = buffer.Buffer(buf).Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to base64 encode encoded header") } return buf, nil }
go
func (e EncodedHeader) Base64Encode() ([]byte, error) { buf, err := json.Marshal(e.Header) if err != nil { return nil, errors.Wrap(err, "failed to marshal encoded header into JSON") } buf, err = buffer.Buffer(buf).Base64Encode() if err != nil { return nil, errors.Wrap(err, "failed to base64 encode encoded header") } return buf, nil }
[ "func", "(", "e", "EncodedHeader", ")", "Base64Encode", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "e", ".", "Header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "buf", ",", "err", "=", "buffer", ".", "Buffer", "(", "buf", ")", ".", "Base64Encode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "buf", ",", "nil", "\n", "}" ]
// Base64Encode creates the base64 encoded version of the JSON // representation of this header
[ "Base64Encode", "creates", "the", "base64", "encoded", "version", "of", "the", "JSON", "representation", "of", "this", "header" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/message.go#L395-L407
train
lestrrat-go/jwx
jwt/token_gen.go
UnmarshalJSON
func (t *Token) UnmarshalJSON(data []byte) error { var m map[string]interface{} if err := json.Unmarshal(data, &m); err != nil { return errors.Wrap(err, `failed to unmarshal token`) } for name, value := range m { if err := t.Set(name, value); err != nil { return errors.Wrapf(err, `failed to set value for %s`, name) } } return nil }
go
func (t *Token) UnmarshalJSON(data []byte) error { var m map[string]interface{} if err := json.Unmarshal(data, &m); err != nil { return errors.Wrap(err, `failed to unmarshal token`) } for name, value := range m { if err := t.Set(name, value); err != nil { return errors.Wrapf(err, `failed to set value for %s`, name) } } return nil }
[ "func", "(", "t", "*", "Token", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "m", "map", "[", "string", "]", "interface", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "m", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "`failed to unmarshal token`", ")", "\n", "}", "\n", "for", "name", ",", "value", ":=", "range", "m", "{", "if", "err", ":=", "t", ".", "Set", "(", "name", ",", "value", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "`failed to set value for %s`", ",", "name", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON deserializes data from a JSON data buffer into a Token
[ "UnmarshalJSON", "deserializes", "data", "from", "a", "JSON", "data", "buffer", "into", "a", "Token" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwt/token_gen.go#L311-L322
train
lestrrat-go/jwx
jwe/key_encrypt.go
NewKeyWrapEncrypt
func NewKeyWrapEncrypt(alg jwa.KeyEncryptionAlgorithm, sharedkey []byte) (KeyWrapEncrypt, error) { return KeyWrapEncrypt{ alg: alg, sharedkey: sharedkey, }, nil }
go
func NewKeyWrapEncrypt(alg jwa.KeyEncryptionAlgorithm, sharedkey []byte) (KeyWrapEncrypt, error) { return KeyWrapEncrypt{ alg: alg, sharedkey: sharedkey, }, nil }
[ "func", "NewKeyWrapEncrypt", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "sharedkey", "[", "]", "byte", ")", "(", "KeyWrapEncrypt", ",", "error", ")", "{", "return", "KeyWrapEncrypt", "{", "alg", ":", "alg", ",", "sharedkey", ":", "sharedkey", ",", "}", ",", "nil", "\n", "}" ]
// NewKeyWrapEncrypt creates a key-wrap encrypter using AES-CGM. // Although the name suggests otherwise, this does the decryption as well.
[ "NewKeyWrapEncrypt", "creates", "a", "key", "-", "wrap", "encrypter", "using", "AES", "-", "CGM", ".", "Although", "the", "name", "suggests", "otherwise", "this", "does", "the", "decryption", "as", "well", "." ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L25-L30
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyDecrypt
func (kw KeyWrapEncrypt) KeyDecrypt(enckey []byte) ([]byte, error) { block, err := aes.NewCipher(kw.sharedkey) if err != nil { return nil, errors.Wrap(err, "failed to create cipher from shared key") } cek, err := keyunwrap(block, enckey) if err != nil { return nil, errors.Wrap(err, "failed to unwrap data") } return cek, nil }
go
func (kw KeyWrapEncrypt) KeyDecrypt(enckey []byte) ([]byte, error) { block, err := aes.NewCipher(kw.sharedkey) if err != nil { return nil, errors.Wrap(err, "failed to create cipher from shared key") } cek, err := keyunwrap(block, enckey) if err != nil { return nil, errors.Wrap(err, "failed to unwrap data") } return cek, nil }
[ "func", "(", "kw", "KeyWrapEncrypt", ")", "KeyDecrypt", "(", "enckey", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "block", ",", "err", ":=", "aes", ".", "NewCipher", "(", "kw", ".", "sharedkey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "cek", ",", "err", ":=", "keyunwrap", "(", "block", ",", "enckey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "cek", ",", "nil", "\n", "}" ]
// KeyDecrypt decrypts the encrypted key using AES-CGM key unwrap
[ "KeyDecrypt", "decrypts", "the", "encrypted", "key", "using", "AES", "-", "CGM", "key", "unwrap" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L43-L54
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyEncrypt
func (kw KeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { block, err := aes.NewCipher(kw.sharedkey) if err != nil { return nil, errors.Wrap(err, "failed to create cipher from shared key") } encrypted, err := keywrap(block, cek) if err != nil { return nil, errors.Wrap(err, `keywrap: failed to wrap key`) } return ByteKey(encrypted), nil }
go
func (kw KeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { block, err := aes.NewCipher(kw.sharedkey) if err != nil { return nil, errors.Wrap(err, "failed to create cipher from shared key") } encrypted, err := keywrap(block, cek) if err != nil { return nil, errors.Wrap(err, `keywrap: failed to wrap key`) } return ByteKey(encrypted), nil }
[ "func", "(", "kw", "KeyWrapEncrypt", ")", "KeyEncrypt", "(", "cek", "[", "]", "byte", ")", "(", "ByteSource", ",", "error", ")", "{", "block", ",", "err", ":=", "aes", ".", "NewCipher", "(", "kw", ".", "sharedkey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "encrypted", ",", "err", ":=", "keywrap", "(", "block", ",", "cek", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`keywrap: failed to wrap key`", ")", "\n", "}", "\n", "return", "ByteKey", "(", "encrypted", ")", ",", "nil", "\n", "}" ]
// KeyEncrypt encrypts the given content encryption key
[ "KeyEncrypt", "encrypts", "the", "given", "content", "encryption", "key" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L57-L67
train
lestrrat-go/jwx
jwe/key_encrypt.go
NewEcdhesKeyWrapEncrypt
func NewEcdhesKeyWrapEncrypt(alg jwa.KeyEncryptionAlgorithm, key *ecdsa.PublicKey) (*EcdhesKeyWrapEncrypt, error) { generator, err := NewEcdhesKeyGenerate(alg, key) if err != nil { return nil, errors.Wrap(err, "failed to create key generator") } return &EcdhesKeyWrapEncrypt{ algorithm: alg, generator: generator, }, nil }
go
func NewEcdhesKeyWrapEncrypt(alg jwa.KeyEncryptionAlgorithm, key *ecdsa.PublicKey) (*EcdhesKeyWrapEncrypt, error) { generator, err := NewEcdhesKeyGenerate(alg, key) if err != nil { return nil, errors.Wrap(err, "failed to create key generator") } return &EcdhesKeyWrapEncrypt{ algorithm: alg, generator: generator, }, nil }
[ "func", "NewEcdhesKeyWrapEncrypt", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "key", "*", "ecdsa", ".", "PublicKey", ")", "(", "*", "EcdhesKeyWrapEncrypt", ",", "error", ")", "{", "generator", ",", "err", ":=", "NewEcdhesKeyGenerate", "(", "alg", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "EcdhesKeyWrapEncrypt", "{", "algorithm", ":", "alg", ",", "generator", ":", "generator", ",", "}", ",", "nil", "\n", "}" ]
// NewEcdhesKeyWrapEncrypt creates a new key encrypter based on ECDH-ES
[ "NewEcdhesKeyWrapEncrypt", "creates", "a", "new", "key", "encrypter", "based", "on", "ECDH", "-", "ES" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L70-L79
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyEncrypt
func (kw EcdhesKeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { kg, err := kw.generator.KeyGenerate() if err != nil { return nil, errors.Wrap(err, "failed to create key generator") } bwpk, ok := kg.(ByteWithECPrivateKey) if !ok { return nil, errors.New("key generator generated invalid key (expected ByteWithECPrivateKey)") } block, err := aes.NewCipher(bwpk.Bytes()) if err != nil { return nil, errors.Wrap(err, "failed to generate cipher from generated key") } jek, err := keywrap(block, cek) if err != nil { return nil, errors.Wrap(err, "failed to wrap data") } bwpk.ByteKey = ByteKey(jek) return bwpk, nil }
go
func (kw EcdhesKeyWrapEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { kg, err := kw.generator.KeyGenerate() if err != nil { return nil, errors.Wrap(err, "failed to create key generator") } bwpk, ok := kg.(ByteWithECPrivateKey) if !ok { return nil, errors.New("key generator generated invalid key (expected ByteWithECPrivateKey)") } block, err := aes.NewCipher(bwpk.Bytes()) if err != nil { return nil, errors.Wrap(err, "failed to generate cipher from generated key") } jek, err := keywrap(block, cek) if err != nil { return nil, errors.Wrap(err, "failed to wrap data") } bwpk.ByteKey = ByteKey(jek) return bwpk, nil }
[ "func", "(", "kw", "EcdhesKeyWrapEncrypt", ")", "KeyEncrypt", "(", "cek", "[", "]", "byte", ")", "(", "ByteSource", ",", "error", ")", "{", "kg", ",", "err", ":=", "kw", ".", "generator", ".", "KeyGenerate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "bwpk", ",", "ok", ":=", "kg", ".", "(", "ByteWithECPrivateKey", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "block", ",", "err", ":=", "aes", ".", "NewCipher", "(", "bwpk", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "jek", ",", "err", ":=", "keywrap", "(", "block", ",", "cek", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "bwpk", ".", "ByteKey", "=", "ByteKey", "(", "jek", ")", "\n\n", "return", "bwpk", ",", "nil", "\n", "}" ]
// KeyEncrypt encrypts the content encryption key using ECDH-ES
[ "KeyEncrypt", "encrypts", "the", "content", "encryption", "key", "using", "ECDH", "-", "ES" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L92-L116
train
lestrrat-go/jwx
jwe/key_encrypt.go
NewEcdhesKeyWrapDecrypt
func NewEcdhesKeyWrapDecrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *ecdsa.PublicKey, apu, apv []byte, privkey *ecdsa.PrivateKey) *EcdhesKeyWrapDecrypt { return &EcdhesKeyWrapDecrypt{ algorithm: alg, apu: apu, apv: apv, privkey: privkey, pubkey: pubkey, } }
go
func NewEcdhesKeyWrapDecrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *ecdsa.PublicKey, apu, apv []byte, privkey *ecdsa.PrivateKey) *EcdhesKeyWrapDecrypt { return &EcdhesKeyWrapDecrypt{ algorithm: alg, apu: apu, apv: apv, privkey: privkey, pubkey: pubkey, } }
[ "func", "NewEcdhesKeyWrapDecrypt", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "pubkey", "*", "ecdsa", ".", "PublicKey", ",", "apu", ",", "apv", "[", "]", "byte", ",", "privkey", "*", "ecdsa", ".", "PrivateKey", ")", "*", "EcdhesKeyWrapDecrypt", "{", "return", "&", "EcdhesKeyWrapDecrypt", "{", "algorithm", ":", "alg", ",", "apu", ":", "apu", ",", "apv", ":", "apv", ",", "privkey", ":", "privkey", ",", "pubkey", ":", "pubkey", ",", "}", "\n", "}" ]
// NewEcdhesKeyWrapDecrypt creates a new key decrypter using ECDH-ES
[ "NewEcdhesKeyWrapDecrypt", "creates", "a", "new", "key", "decrypter", "using", "ECDH", "-", "ES" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L119-L127
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyDecrypt
func (kw EcdhesKeyWrapDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) { var keysize uint32 switch kw.algorithm { case jwa.ECDH_ES_A128KW: keysize = 16 case jwa.ECDH_ES_A192KW: keysize = 24 case jwa.ECDH_ES_A256KW: keysize = 32 default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid ECDH-ES key wrap algorithm") } privkey := kw.privkey pubkey := kw.pubkey pubinfo := make([]byte, 4) binary.BigEndian.PutUint32(pubinfo, keysize*8) z, _ := privkey.PublicKey.Curve.ScalarMult(pubkey.X, pubkey.Y, privkey.D.Bytes()) kdf := concatkdf.New(crypto.SHA256, []byte(kw.algorithm.String()), z.Bytes(), kw.apu, kw.apv, pubinfo, []byte{}) kek := make([]byte, keysize) kdf.Read(kek) block, err := aes.NewCipher(kek) if err != nil { return nil, errors.Wrap(err, "failed to create cipher for ECDH-ES key wrap") } return keyunwrap(block, enckey) }
go
func (kw EcdhesKeyWrapDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) { var keysize uint32 switch kw.algorithm { case jwa.ECDH_ES_A128KW: keysize = 16 case jwa.ECDH_ES_A192KW: keysize = 24 case jwa.ECDH_ES_A256KW: keysize = 32 default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid ECDH-ES key wrap algorithm") } privkey := kw.privkey pubkey := kw.pubkey pubinfo := make([]byte, 4) binary.BigEndian.PutUint32(pubinfo, keysize*8) z, _ := privkey.PublicKey.Curve.ScalarMult(pubkey.X, pubkey.Y, privkey.D.Bytes()) kdf := concatkdf.New(crypto.SHA256, []byte(kw.algorithm.String()), z.Bytes(), kw.apu, kw.apv, pubinfo, []byte{}) kek := make([]byte, keysize) kdf.Read(kek) block, err := aes.NewCipher(kek) if err != nil { return nil, errors.Wrap(err, "failed to create cipher for ECDH-ES key wrap") } return keyunwrap(block, enckey) }
[ "func", "(", "kw", "EcdhesKeyWrapDecrypt", ")", "KeyDecrypt", "(", "enckey", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "keysize", "uint32", "\n", "switch", "kw", ".", "algorithm", "{", "case", "jwa", ".", "ECDH_ES_A128KW", ":", "keysize", "=", "16", "\n", "case", "jwa", ".", "ECDH_ES_A192KW", ":", "keysize", "=", "24", "\n", "case", "jwa", ".", "ECDH_ES_A256KW", ":", "keysize", "=", "32", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Wrap", "(", "ErrUnsupportedAlgorithm", ",", "\"", "\"", ")", "\n", "}", "\n\n", "privkey", ":=", "kw", ".", "privkey", "\n", "pubkey", ":=", "kw", ".", "pubkey", "\n\n", "pubinfo", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "pubinfo", ",", "keysize", "*", "8", ")", "\n\n", "z", ",", "_", ":=", "privkey", ".", "PublicKey", ".", "Curve", ".", "ScalarMult", "(", "pubkey", ".", "X", ",", "pubkey", ".", "Y", ",", "privkey", ".", "D", ".", "Bytes", "(", ")", ")", "\n", "kdf", ":=", "concatkdf", ".", "New", "(", "crypto", ".", "SHA256", ",", "[", "]", "byte", "(", "kw", ".", "algorithm", ".", "String", "(", ")", ")", ",", "z", ".", "Bytes", "(", ")", ",", "kw", ".", "apu", ",", "kw", ".", "apv", ",", "pubinfo", ",", "[", "]", "byte", "{", "}", ")", "\n", "kek", ":=", "make", "(", "[", "]", "byte", ",", "keysize", ")", "\n", "kdf", ".", "Read", "(", "kek", ")", "\n\n", "block", ",", "err", ":=", "aes", ".", "NewCipher", "(", "kek", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "keyunwrap", "(", "block", ",", "enckey", ")", "\n", "}" ]
// KeyDecrypt decrypts the encrypted key using ECDH-ES
[ "KeyDecrypt", "decrypts", "the", "encrypted", "key", "using", "ECDH", "-", "ES" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L135-L165
train
lestrrat-go/jwx
jwe/key_encrypt.go
NewRSAOAEPKeyEncrypt
func NewRSAOAEPKeyEncrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *rsa.PublicKey) (*RSAOAEPKeyEncrypt, error) { switch alg { case jwa.RSA_OAEP, jwa.RSA_OAEP_256: default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA OAEP encrypt algorithm") } return &RSAOAEPKeyEncrypt{ alg: alg, pubkey: pubkey, }, nil }
go
func NewRSAOAEPKeyEncrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *rsa.PublicKey) (*RSAOAEPKeyEncrypt, error) { switch alg { case jwa.RSA_OAEP, jwa.RSA_OAEP_256: default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA OAEP encrypt algorithm") } return &RSAOAEPKeyEncrypt{ alg: alg, pubkey: pubkey, }, nil }
[ "func", "NewRSAOAEPKeyEncrypt", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "pubkey", "*", "rsa", ".", "PublicKey", ")", "(", "*", "RSAOAEPKeyEncrypt", ",", "error", ")", "{", "switch", "alg", "{", "case", "jwa", ".", "RSA_OAEP", ",", "jwa", ".", "RSA_OAEP_256", ":", "default", ":", "return", "nil", ",", "errors", ".", "Wrap", "(", "ErrUnsupportedAlgorithm", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "RSAOAEPKeyEncrypt", "{", "alg", ":", "alg", ",", "pubkey", ":", "pubkey", ",", "}", ",", "nil", "\n", "}" ]
// NewRSAOAEPKeyEncrypt creates a new key encrypter using RSA OAEP
[ "NewRSAOAEPKeyEncrypt", "creates", "a", "new", "key", "encrypter", "using", "RSA", "OAEP" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L168-L178
train
lestrrat-go/jwx
jwe/key_encrypt.go
NewRSAPKCSKeyEncrypt
func NewRSAPKCSKeyEncrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *rsa.PublicKey) (*RSAPKCSKeyEncrypt, error) { switch alg { case jwa.RSA1_5: default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA PKCS encrypt algorithm") } return &RSAPKCSKeyEncrypt{ alg: alg, pubkey: pubkey, }, nil }
go
func NewRSAPKCSKeyEncrypt(alg jwa.KeyEncryptionAlgorithm, pubkey *rsa.PublicKey) (*RSAPKCSKeyEncrypt, error) { switch alg { case jwa.RSA1_5: default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA PKCS encrypt algorithm") } return &RSAPKCSKeyEncrypt{ alg: alg, pubkey: pubkey, }, nil }
[ "func", "NewRSAPKCSKeyEncrypt", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "pubkey", "*", "rsa", ".", "PublicKey", ")", "(", "*", "RSAPKCSKeyEncrypt", ",", "error", ")", "{", "switch", "alg", "{", "case", "jwa", ".", "RSA1_5", ":", "default", ":", "return", "nil", ",", "errors", ".", "Wrap", "(", "ErrUnsupportedAlgorithm", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "RSAPKCSKeyEncrypt", "{", "alg", ":", "alg", ",", "pubkey", ":", "pubkey", ",", "}", ",", "nil", "\n", "}" ]
// NewRSAPKCSKeyEncrypt creates a new key encrypter using PKCS1v15
[ "NewRSAPKCSKeyEncrypt", "creates", "a", "new", "key", "encrypter", "using", "PKCS1v15" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L181-L192
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyEncrypt
func (e RSAPKCSKeyEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { if e.alg != jwa.RSA1_5 { return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA PKCS encrypt algorithm") } encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, e.pubkey, cek) if err != nil { return nil, errors.Wrap(err, "failed to encrypt using PKCS1v15") } return ByteKey(encrypted), nil }
go
func (e RSAPKCSKeyEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { if e.alg != jwa.RSA1_5 { return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA PKCS encrypt algorithm") } encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, e.pubkey, cek) if err != nil { return nil, errors.Wrap(err, "failed to encrypt using PKCS1v15") } return ByteKey(encrypted), nil }
[ "func", "(", "e", "RSAPKCSKeyEncrypt", ")", "KeyEncrypt", "(", "cek", "[", "]", "byte", ")", "(", "ByteSource", ",", "error", ")", "{", "if", "e", ".", "alg", "!=", "jwa", ".", "RSA1_5", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "ErrUnsupportedAlgorithm", ",", "\"", "\"", ")", "\n", "}", "\n", "encrypted", ",", "err", ":=", "rsa", ".", "EncryptPKCS1v15", "(", "rand", ".", "Reader", ",", "e", ".", "pubkey", ",", "cek", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "ByteKey", "(", "encrypted", ")", ",", "nil", "\n", "}" ]
// KeyEncrypt encrypts the content encryption key using RSA PKCS1v15
[ "KeyEncrypt", "encrypts", "the", "content", "encryption", "key", "using", "RSA", "PKCS1v15" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L215-L224
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyEncrypt
func (e RSAOAEPKeyEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { var hash hash.Hash switch e.alg { case jwa.RSA_OAEP: hash = sha1.New() case jwa.RSA_OAEP_256: hash = sha256.New() default: return nil, errors.New("failed to generate key encrypter for RSA-OAEP: RSA_OAEP/RSA_OAEP_256 required") } encrypted, err := rsa.EncryptOAEP(hash, rand.Reader, e.pubkey, cek, []byte{}) if err != nil { return nil, errors.Wrap(err, `failed to OAEP encrypt`) } return ByteKey(encrypted), nil }
go
func (e RSAOAEPKeyEncrypt) KeyEncrypt(cek []byte) (ByteSource, error) { var hash hash.Hash switch e.alg { case jwa.RSA_OAEP: hash = sha1.New() case jwa.RSA_OAEP_256: hash = sha256.New() default: return nil, errors.New("failed to generate key encrypter for RSA-OAEP: RSA_OAEP/RSA_OAEP_256 required") } encrypted, err := rsa.EncryptOAEP(hash, rand.Reader, e.pubkey, cek, []byte{}) if err != nil { return nil, errors.Wrap(err, `failed to OAEP encrypt`) } return ByteKey(encrypted), nil }
[ "func", "(", "e", "RSAOAEPKeyEncrypt", ")", "KeyEncrypt", "(", "cek", "[", "]", "byte", ")", "(", "ByteSource", ",", "error", ")", "{", "var", "hash", "hash", ".", "Hash", "\n", "switch", "e", ".", "alg", "{", "case", "jwa", ".", "RSA_OAEP", ":", "hash", "=", "sha1", ".", "New", "(", ")", "\n", "case", "jwa", ".", "RSA_OAEP_256", ":", "hash", "=", "sha256", ".", "New", "(", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "encrypted", ",", "err", ":=", "rsa", ".", "EncryptOAEP", "(", "hash", ",", "rand", ".", "Reader", ",", "e", ".", "pubkey", ",", "cek", ",", "[", "]", "byte", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "`failed to OAEP encrypt`", ")", "\n", "}", "\n", "return", "ByteKey", "(", "encrypted", ")", ",", "nil", "\n", "}" ]
// KeyEncrypt encrypts the content encryption key using RSA OAEP
[ "KeyEncrypt", "encrypts", "the", "content", "encryption", "key", "using", "RSA", "OAEP" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L227-L242
train
lestrrat-go/jwx
jwe/key_encrypt.go
NewRSAPKCS15KeyDecrypt
func NewRSAPKCS15KeyDecrypt(alg jwa.KeyEncryptionAlgorithm, privkey *rsa.PrivateKey, keysize int) *RSAPKCS15KeyDecrypt { generator := NewRandomKeyGenerate(keysize * 2) return &RSAPKCS15KeyDecrypt{ alg: alg, privkey: privkey, generator: generator, } }
go
func NewRSAPKCS15KeyDecrypt(alg jwa.KeyEncryptionAlgorithm, privkey *rsa.PrivateKey, keysize int) *RSAPKCS15KeyDecrypt { generator := NewRandomKeyGenerate(keysize * 2) return &RSAPKCS15KeyDecrypt{ alg: alg, privkey: privkey, generator: generator, } }
[ "func", "NewRSAPKCS15KeyDecrypt", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "privkey", "*", "rsa", ".", "PrivateKey", ",", "keysize", "int", ")", "*", "RSAPKCS15KeyDecrypt", "{", "generator", ":=", "NewRandomKeyGenerate", "(", "keysize", "*", "2", ")", "\n", "return", "&", "RSAPKCS15KeyDecrypt", "{", "alg", ":", "alg", ",", "privkey", ":", "privkey", ",", "generator", ":", "generator", ",", "}", "\n", "}" ]
// NewRSAPKCS15KeyDecrypt creates a new decrypter using RSA PKCS1v15
[ "NewRSAPKCS15KeyDecrypt", "creates", "a", "new", "decrypter", "using", "RSA", "PKCS1v15" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L245-L252
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyDecrypt
func (d RSAPKCS15KeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) { if debug.Enabled { debug.Printf("START PKCS.KeyDecrypt") } // Hey, these notes and workarounds were stolen from go-jose defer func() { // DecryptPKCS1v15SessionKey sometimes panics on an invalid payload // because of an index out of bounds error, which we want to ignore. // This has been fixed in Go 1.3.1 (released 2014/08/13), the recover() // only exists for preventing crashes with unpatched versions. // See: https://groups.google.com/forum/#!topic/golang-dev/7ihX6Y6kx9k // See: https://code.google.com/p/go/source/detail?r=58ee390ff31602edb66af41ed10901ec95904d33 _ = recover() }() // Perform some input validation. expectedlen := d.privkey.PublicKey.N.BitLen() / 8 if expectedlen != len(enckey) { // Input size is incorrect, the encrypted payload should always match // the size of the public modulus (e.g. using a 2048 bit key will // produce 256 bytes of output). Reject this since it's invalid input. return nil, fmt.Errorf( "input size for key decrypt is incorrect (expected %d, got %d)", expectedlen, len(enckey), ) } var err error bk, err := d.generator.KeyGenerate() if err != nil { return nil, errors.New("failed to generate key") } cek := bk.Bytes() // When decrypting an RSA-PKCS1v1.5 payload, we must take precautions to // prevent chosen-ciphertext attacks as described in RFC 3218, "Preventing // the Million Message Attack on Cryptographic Message Syntax". We are // therefore deliberatly ignoring errors here. err = rsa.DecryptPKCS1v15SessionKey(rand.Reader, d.privkey, enckey, cek) if err != nil { return nil, errors.Wrap(err, "failed to decrypt via PKCS1v15") } return cek, nil }
go
func (d RSAPKCS15KeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) { if debug.Enabled { debug.Printf("START PKCS.KeyDecrypt") } // Hey, these notes and workarounds were stolen from go-jose defer func() { // DecryptPKCS1v15SessionKey sometimes panics on an invalid payload // because of an index out of bounds error, which we want to ignore. // This has been fixed in Go 1.3.1 (released 2014/08/13), the recover() // only exists for preventing crashes with unpatched versions. // See: https://groups.google.com/forum/#!topic/golang-dev/7ihX6Y6kx9k // See: https://code.google.com/p/go/source/detail?r=58ee390ff31602edb66af41ed10901ec95904d33 _ = recover() }() // Perform some input validation. expectedlen := d.privkey.PublicKey.N.BitLen() / 8 if expectedlen != len(enckey) { // Input size is incorrect, the encrypted payload should always match // the size of the public modulus (e.g. using a 2048 bit key will // produce 256 bytes of output). Reject this since it's invalid input. return nil, fmt.Errorf( "input size for key decrypt is incorrect (expected %d, got %d)", expectedlen, len(enckey), ) } var err error bk, err := d.generator.KeyGenerate() if err != nil { return nil, errors.New("failed to generate key") } cek := bk.Bytes() // When decrypting an RSA-PKCS1v1.5 payload, we must take precautions to // prevent chosen-ciphertext attacks as described in RFC 3218, "Preventing // the Million Message Attack on Cryptographic Message Syntax". We are // therefore deliberatly ignoring errors here. err = rsa.DecryptPKCS1v15SessionKey(rand.Reader, d.privkey, enckey, cek) if err != nil { return nil, errors.Wrap(err, "failed to decrypt via PKCS1v15") } return cek, nil }
[ "func", "(", "d", "RSAPKCS15KeyDecrypt", ")", "KeyDecrypt", "(", "enckey", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "debug", ".", "Enabled", "{", "debug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Hey, these notes and workarounds were stolen from go-jose", "defer", "func", "(", ")", "{", "// DecryptPKCS1v15SessionKey sometimes panics on an invalid payload", "// because of an index out of bounds error, which we want to ignore.", "// This has been fixed in Go 1.3.1 (released 2014/08/13), the recover()", "// only exists for preventing crashes with unpatched versions.", "// See: https://groups.google.com/forum/#!topic/golang-dev/7ihX6Y6kx9k", "// See: https://code.google.com/p/go/source/detail?r=58ee390ff31602edb66af41ed10901ec95904d33", "_", "=", "recover", "(", ")", "\n", "}", "(", ")", "\n\n", "// Perform some input validation.", "expectedlen", ":=", "d", ".", "privkey", ".", "PublicKey", ".", "N", ".", "BitLen", "(", ")", "/", "8", "\n", "if", "expectedlen", "!=", "len", "(", "enckey", ")", "{", "// Input size is incorrect, the encrypted payload should always match", "// the size of the public modulus (e.g. using a 2048 bit key will", "// produce 256 bytes of output). Reject this since it's invalid input.", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "expectedlen", ",", "len", "(", "enckey", ")", ",", ")", "\n", "}", "\n\n", "var", "err", "error", "\n\n", "bk", ",", "err", ":=", "d", ".", "generator", ".", "KeyGenerate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "cek", ":=", "bk", ".", "Bytes", "(", ")", "\n\n", "// When decrypting an RSA-PKCS1v1.5 payload, we must take precautions to", "// prevent chosen-ciphertext attacks as described in RFC 3218, \"Preventing", "// the Million Message Attack on Cryptographic Message Syntax\". We are", "// therefore deliberatly ignoring errors here.", "err", "=", "rsa", ".", "DecryptPKCS1v15SessionKey", "(", "rand", ".", "Reader", ",", "d", ".", "privkey", ",", "enckey", ",", "cek", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "cek", ",", "nil", "\n", "}" ]
// KeyDecrypt decryptes the encrypted key using RSA PKCS1v1.5
[ "KeyDecrypt", "decryptes", "the", "encrypted", "key", "using", "RSA", "PKCS1v1", ".", "5" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L260-L306
train
lestrrat-go/jwx
jwe/key_encrypt.go
NewRSAOAEPKeyDecrypt
func NewRSAOAEPKeyDecrypt(alg jwa.KeyEncryptionAlgorithm, privkey *rsa.PrivateKey) (*RSAOAEPKeyDecrypt, error) { switch alg { case jwa.RSA_OAEP, jwa.RSA_OAEP_256: default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA OAEP decrypt algorithm") } return &RSAOAEPKeyDecrypt{ alg: alg, privkey: privkey, }, nil }
go
func NewRSAOAEPKeyDecrypt(alg jwa.KeyEncryptionAlgorithm, privkey *rsa.PrivateKey) (*RSAOAEPKeyDecrypt, error) { switch alg { case jwa.RSA_OAEP, jwa.RSA_OAEP_256: default: return nil, errors.Wrap(ErrUnsupportedAlgorithm, "invalid RSA OAEP decrypt algorithm") } return &RSAOAEPKeyDecrypt{ alg: alg, privkey: privkey, }, nil }
[ "func", "NewRSAOAEPKeyDecrypt", "(", "alg", "jwa", ".", "KeyEncryptionAlgorithm", ",", "privkey", "*", "rsa", ".", "PrivateKey", ")", "(", "*", "RSAOAEPKeyDecrypt", ",", "error", ")", "{", "switch", "alg", "{", "case", "jwa", ".", "RSA_OAEP", ",", "jwa", ".", "RSA_OAEP_256", ":", "default", ":", "return", "nil", ",", "errors", ".", "Wrap", "(", "ErrUnsupportedAlgorithm", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "RSAOAEPKeyDecrypt", "{", "alg", ":", "alg", ",", "privkey", ":", "privkey", ",", "}", ",", "nil", "\n", "}" ]
// NewRSAOAEPKeyDecrypt creates a new key decrypter using RSA OAEP
[ "NewRSAOAEPKeyDecrypt", "creates", "a", "new", "key", "decrypter", "using", "RSA", "OAEP" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L309-L320
train
lestrrat-go/jwx
jwe/key_encrypt.go
KeyDecrypt
func (d RSAOAEPKeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) { if debug.Enabled { debug.Printf("START OAEP.KeyDecrypt") } var hash hash.Hash switch d.alg { case jwa.RSA_OAEP: hash = sha1.New() case jwa.RSA_OAEP_256: hash = sha256.New() default: return nil, errors.New("failed to generate key encrypter for RSA-OAEP: RSA_OAEP/RSA_OAEP_256 required") } return rsa.DecryptOAEP(hash, rand.Reader, d.privkey, enckey, []byte{}) }
go
func (d RSAOAEPKeyDecrypt) KeyDecrypt(enckey []byte) ([]byte, error) { if debug.Enabled { debug.Printf("START OAEP.KeyDecrypt") } var hash hash.Hash switch d.alg { case jwa.RSA_OAEP: hash = sha1.New() case jwa.RSA_OAEP_256: hash = sha256.New() default: return nil, errors.New("failed to generate key encrypter for RSA-OAEP: RSA_OAEP/RSA_OAEP_256 required") } return rsa.DecryptOAEP(hash, rand.Reader, d.privkey, enckey, []byte{}) }
[ "func", "(", "d", "RSAOAEPKeyDecrypt", ")", "KeyDecrypt", "(", "enckey", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "debug", ".", "Enabled", "{", "debug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "hash", "hash", ".", "Hash", "\n", "switch", "d", ".", "alg", "{", "case", "jwa", ".", "RSA_OAEP", ":", "hash", "=", "sha1", ".", "New", "(", ")", "\n", "case", "jwa", ".", "RSA_OAEP_256", ":", "hash", "=", "sha256", ".", "New", "(", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "rsa", ".", "DecryptOAEP", "(", "hash", ",", "rand", ".", "Reader", ",", "d", ".", "privkey", ",", "enckey", ",", "[", "]", "byte", "{", "}", ")", "\n", "}" ]
// KeyDecrypt decryptes the encrypted key using RSA OAEP
[ "KeyDecrypt", "decryptes", "the", "encrypted", "key", "using", "RSA", "OAEP" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L328-L342
train
lestrrat-go/jwx
jwe/key_encrypt.go
Decrypt
func (d DirectDecrypt) Decrypt() ([]byte, error) { cek := make([]byte, len(d.Key)) copy(cek, d.Key) return cek, nil }
go
func (d DirectDecrypt) Decrypt() ([]byte, error) { cek := make([]byte, len(d.Key)) copy(cek, d.Key) return cek, nil }
[ "func", "(", "d", "DirectDecrypt", ")", "Decrypt", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cek", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "d", ".", "Key", ")", ")", "\n", "copy", "(", "cek", ",", "d", ".", "Key", ")", "\n", "return", "cek", ",", "nil", "\n", "}" ]
// Decrypt for DirectDecrypt does not do anything other than // return a copy of the embedded key
[ "Decrypt", "for", "DirectDecrypt", "does", "not", "do", "anything", "other", "than", "return", "a", "copy", "of", "the", "embedded", "key" ]
0251e8147021ce27b0d3b1812b7c07265fe7a538
https://github.com/lestrrat-go/jwx/blob/0251e8147021ce27b0d3b1812b7c07265fe7a538/jwe/key_encrypt.go#L346-L350
train
jrallison/go-workers
hooks.go
DuringDrain
func DuringDrain(f func()) { access.Lock() defer access.Unlock() duringDrain = append(duringDrain, f) }
go
func DuringDrain(f func()) { access.Lock() defer access.Unlock() duringDrain = append(duringDrain, f) }
[ "func", "DuringDrain", "(", "f", "func", "(", ")", ")", "{", "access", ".", "Lock", "(", ")", "\n", "defer", "access", ".", "Unlock", "(", ")", "\n", "duringDrain", "=", "append", "(", "duringDrain", ",", "f", ")", "\n", "}" ]
// func AfterStart // func BeforeQuit // func AfterQuit
[ "func", "AfterStart", "func", "BeforeQuit", "func", "AfterQuit" ]
dbf81d0b75bbe2fd90ef66a07643dd70cb42a88a
https://github.com/jrallison/go-workers/blob/dbf81d0b75bbe2fd90ef66a07643dd70cb42a88a/hooks.go#L16-L20
train
eapache/go-resiliency
semaphore/semaphore.go
New
func New(tickets int, timeout time.Duration) *Semaphore { return &Semaphore{ sem: make(chan struct{}, tickets), timeout: timeout, } }
go
func New(tickets int, timeout time.Duration) *Semaphore { return &Semaphore{ sem: make(chan struct{}, tickets), timeout: timeout, } }
[ "func", "New", "(", "tickets", "int", ",", "timeout", "time", ".", "Duration", ")", "*", "Semaphore", "{", "return", "&", "Semaphore", "{", "sem", ":", "make", "(", "chan", "struct", "{", "}", ",", "tickets", ")", ",", "timeout", ":", "timeout", ",", "}", "\n", "}" ]
// New constructs a new Semaphore with the given ticket-count // and timeout.
[ "New", "constructs", "a", "new", "Semaphore", "with", "the", "given", "ticket", "-", "count", "and", "timeout", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/semaphore/semaphore.go#L21-L26
train
eapache/go-resiliency
semaphore/semaphore.go
Acquire
func (s *Semaphore) Acquire() error { select { case s.sem <- struct{}{}: return nil case <-time.After(s.timeout): return ErrNoTickets } }
go
func (s *Semaphore) Acquire() error { select { case s.sem <- struct{}{}: return nil case <-time.After(s.timeout): return ErrNoTickets } }
[ "func", "(", "s", "*", "Semaphore", ")", "Acquire", "(", ")", "error", "{", "select", "{", "case", "s", ".", "sem", "<-", "struct", "{", "}", "{", "}", ":", "return", "nil", "\n", "case", "<-", "time", ".", "After", "(", "s", ".", "timeout", ")", ":", "return", "ErrNoTickets", "\n", "}", "\n", "}" ]
// Acquire tries to acquire a ticket from the semaphore. If it can, it returns nil. // If it cannot after "timeout" amount of time, it returns ErrNoTickets. It is // safe to call Acquire concurrently on a single Semaphore.
[ "Acquire", "tries", "to", "acquire", "a", "ticket", "from", "the", "semaphore", ".", "If", "it", "can", "it", "returns", "nil", ".", "If", "it", "cannot", "after", "timeout", "amount", "of", "time", "it", "returns", "ErrNoTickets", ".", "It", "is", "safe", "to", "call", "Acquire", "concurrently", "on", "a", "single", "Semaphore", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/semaphore/semaphore.go#L31-L38
train
eapache/go-resiliency
breaker/breaker.go
New
func New(errorThreshold, successThreshold int, timeout time.Duration) *Breaker { return &Breaker{ errorThreshold: errorThreshold, successThreshold: successThreshold, timeout: timeout, } }
go
func New(errorThreshold, successThreshold int, timeout time.Duration) *Breaker { return &Breaker{ errorThreshold: errorThreshold, successThreshold: successThreshold, timeout: timeout, } }
[ "func", "New", "(", "errorThreshold", ",", "successThreshold", "int", ",", "timeout", "time", ".", "Duration", ")", "*", "Breaker", "{", "return", "&", "Breaker", "{", "errorThreshold", ":", "errorThreshold", ",", "successThreshold", ":", "successThreshold", ",", "timeout", ":", "timeout", ",", "}", "\n", "}" ]
// New constructs a new circuit-breaker that starts closed. // From closed, the breaker opens if "errorThreshold" errors are seen // without an error-free period of at least "timeout". From open, the // breaker half-closes after "timeout". From half-open, the breaker closes // after "successThreshold" consecutive successes, or opens on a single error.
[ "New", "constructs", "a", "new", "circuit", "-", "breaker", "that", "starts", "closed", ".", "From", "closed", "the", "breaker", "opens", "if", "errorThreshold", "errors", "are", "seen", "without", "an", "error", "-", "free", "period", "of", "at", "least", "timeout", ".", "From", "open", "the", "breaker", "half", "-", "closes", "after", "timeout", ".", "From", "half", "-", "open", "the", "breaker", "closes", "after", "successThreshold", "consecutive", "successes", "or", "opens", "on", "a", "single", "error", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/breaker/breaker.go#L37-L43
train
eapache/go-resiliency
breaker/breaker.go
Run
func (b *Breaker) Run(work func() error) error { state := atomic.LoadUint32(&b.state) if state == open { return ErrBreakerOpen } return b.doWork(state, work) }
go
func (b *Breaker) Run(work func() error) error { state := atomic.LoadUint32(&b.state) if state == open { return ErrBreakerOpen } return b.doWork(state, work) }
[ "func", "(", "b", "*", "Breaker", ")", "Run", "(", "work", "func", "(", ")", "error", ")", "error", "{", "state", ":=", "atomic", ".", "LoadUint32", "(", "&", "b", ".", "state", ")", "\n\n", "if", "state", "==", "open", "{", "return", "ErrBreakerOpen", "\n", "}", "\n\n", "return", "b", ".", "doWork", "(", "state", ",", "work", ")", "\n", "}" ]
// Run will either return ErrBreakerOpen immediately if the circuit-breaker is // already open, or it will run the given function and pass along its return // value. It is safe to call Run concurrently on the same Breaker.
[ "Run", "will", "either", "return", "ErrBreakerOpen", "immediately", "if", "the", "circuit", "-", "breaker", "is", "already", "open", "or", "it", "will", "run", "the", "given", "function", "and", "pass", "along", "its", "return", "value", ".", "It", "is", "safe", "to", "call", "Run", "concurrently", "on", "the", "same", "Breaker", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/breaker/breaker.go#L48-L56
train
eapache/go-resiliency
retrier/backoffs.go
ConstantBackoff
func ConstantBackoff(n int, amount time.Duration) []time.Duration { ret := make([]time.Duration, n) for i := range ret { ret[i] = amount } return ret }
go
func ConstantBackoff(n int, amount time.Duration) []time.Duration { ret := make([]time.Duration, n) for i := range ret { ret[i] = amount } return ret }
[ "func", "ConstantBackoff", "(", "n", "int", ",", "amount", "time", ".", "Duration", ")", "[", "]", "time", ".", "Duration", "{", "ret", ":=", "make", "(", "[", "]", "time", ".", "Duration", ",", "n", ")", "\n", "for", "i", ":=", "range", "ret", "{", "ret", "[", "i", "]", "=", "amount", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ConstantBackoff generates a simple back-off strategy of retrying 'n' times, and waiting 'amount' time after each one.
[ "ConstantBackoff", "generates", "a", "simple", "back", "-", "off", "strategy", "of", "retrying", "n", "times", "and", "waiting", "amount", "time", "after", "each", "one", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/retrier/backoffs.go#L6-L12
train
eapache/go-resiliency
retrier/backoffs.go
ExponentialBackoff
func ExponentialBackoff(n int, initialAmount time.Duration) []time.Duration { ret := make([]time.Duration, n) next := initialAmount for i := range ret { ret[i] = next next *= 2 } return ret }
go
func ExponentialBackoff(n int, initialAmount time.Duration) []time.Duration { ret := make([]time.Duration, n) next := initialAmount for i := range ret { ret[i] = next next *= 2 } return ret }
[ "func", "ExponentialBackoff", "(", "n", "int", ",", "initialAmount", "time", ".", "Duration", ")", "[", "]", "time", ".", "Duration", "{", "ret", ":=", "make", "(", "[", "]", "time", ".", "Duration", ",", "n", ")", "\n", "next", ":=", "initialAmount", "\n", "for", "i", ":=", "range", "ret", "{", "ret", "[", "i", "]", "=", "next", "\n", "next", "*=", "2", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ExponentialBackoff generates a simple back-off strategy of retrying 'n' times, and doubling the amount of // time waited after each one.
[ "ExponentialBackoff", "generates", "a", "simple", "back", "-", "off", "strategy", "of", "retrying", "n", "times", "and", "doubling", "the", "amount", "of", "time", "waited", "after", "each", "one", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/retrier/backoffs.go#L16-L24
train
eapache/go-resiliency
retrier/retrier.go
New
func New(backoff []time.Duration, class Classifier) *Retrier { if class == nil { class = DefaultClassifier{} } return &Retrier{ backoff: backoff, class: class, rand: rand.New(rand.NewSource(time.Now().UnixNano())), } }
go
func New(backoff []time.Duration, class Classifier) *Retrier { if class == nil { class = DefaultClassifier{} } return &Retrier{ backoff: backoff, class: class, rand: rand.New(rand.NewSource(time.Now().UnixNano())), } }
[ "func", "New", "(", "backoff", "[", "]", "time", ".", "Duration", ",", "class", "Classifier", ")", "*", "Retrier", "{", "if", "class", "==", "nil", "{", "class", "=", "DefaultClassifier", "{", "}", "\n", "}", "\n\n", "return", "&", "Retrier", "{", "backoff", ":", "backoff", ",", "class", ":", "class", ",", "rand", ":", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ")", ",", "}", "\n", "}" ]
// New constructs a Retrier with the given backoff pattern and classifier. The length of the backoff pattern // indicates how many times an action will be retried, and the value at each index indicates the amount of time // waited before each subsequent retry. The classifier is used to determine which errors should be retried and // which should cause the retrier to fail fast. The DefaultClassifier is used if nil is passed.
[ "New", "constructs", "a", "Retrier", "with", "the", "given", "backoff", "pattern", "and", "classifier", ".", "The", "length", "of", "the", "backoff", "pattern", "indicates", "how", "many", "times", "an", "action", "will", "be", "retried", "and", "the", "value", "at", "each", "index", "indicates", "the", "amount", "of", "time", "waited", "before", "each", "subsequent", "retry", ".", "The", "classifier", "is", "used", "to", "determine", "which", "errors", "should", "be", "retried", "and", "which", "should", "cause", "the", "retrier", "to", "fail", "fast", ".", "The", "DefaultClassifier", "is", "used", "if", "nil", "is", "passed", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/retrier/retrier.go#L25-L35
train
eapache/go-resiliency
retrier/retrier.go
Run
func (r *Retrier) Run(work func() error) error { return r.RunCtx(context.Background(), func(ctx context.Context) error { // never use ctx return work() }) }
go
func (r *Retrier) Run(work func() error) error { return r.RunCtx(context.Background(), func(ctx context.Context) error { // never use ctx return work() }) }
[ "func", "(", "r", "*", "Retrier", ")", "Run", "(", "work", "func", "(", ")", "error", ")", "error", "{", "return", "r", ".", "RunCtx", "(", "context", ".", "Background", "(", ")", ",", "func", "(", "ctx", "context", ".", "Context", ")", "error", "{", "// never use ctx", "return", "work", "(", ")", "\n", "}", ")", "\n", "}" ]
// Run executes the given work function by executing RunCtx without context.Context.
[ "Run", "executes", "the", "given", "work", "function", "by", "executing", "RunCtx", "without", "context", ".", "Context", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/retrier/retrier.go#L38-L43
train
eapache/go-resiliency
retrier/retrier.go
RunCtx
func (r *Retrier) RunCtx(ctx context.Context, work func(ctx context.Context) error) error { retries := 0 for { ret := work(ctx) switch r.class.Classify(ret) { case Succeed, Fail: return ret case Retry: if retries >= len(r.backoff) { return ret } timeout := time.After(r.calcSleep(retries)) if err := r.sleep(ctx, timeout); err != nil { return err } retries++ } } }
go
func (r *Retrier) RunCtx(ctx context.Context, work func(ctx context.Context) error) error { retries := 0 for { ret := work(ctx) switch r.class.Classify(ret) { case Succeed, Fail: return ret case Retry: if retries >= len(r.backoff) { return ret } timeout := time.After(r.calcSleep(retries)) if err := r.sleep(ctx, timeout); err != nil { return err } retries++ } } }
[ "func", "(", "r", "*", "Retrier", ")", "RunCtx", "(", "ctx", "context", ".", "Context", ",", "work", "func", "(", "ctx", "context", ".", "Context", ")", "error", ")", "error", "{", "retries", ":=", "0", "\n", "for", "{", "ret", ":=", "work", "(", "ctx", ")", "\n\n", "switch", "r", ".", "class", ".", "Classify", "(", "ret", ")", "{", "case", "Succeed", ",", "Fail", ":", "return", "ret", "\n", "case", "Retry", ":", "if", "retries", ">=", "len", "(", "r", ".", "backoff", ")", "{", "return", "ret", "\n", "}", "\n\n", "timeout", ":=", "time", ".", "After", "(", "r", ".", "calcSleep", "(", "retries", ")", ")", "\n", "if", "err", ":=", "r", ".", "sleep", "(", "ctx", ",", "timeout", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "retries", "++", "\n", "}", "\n", "}", "\n", "}" ]
// RunCtx executes the given work function, then classifies its return value based on the classifier used // to construct the Retrier. If the result is Succeed or Fail, the return value of the work function is // returned to the caller. If the result is Retry, then Run sleeps according to the its backoff policy // before retrying. If the total number of retries is exceeded then the return value of the work function // is returned to the caller regardless.
[ "RunCtx", "executes", "the", "given", "work", "function", "then", "classifies", "its", "return", "value", "based", "on", "the", "classifier", "used", "to", "construct", "the", "Retrier", ".", "If", "the", "result", "is", "Succeed", "or", "Fail", "the", "return", "value", "of", "the", "work", "function", "is", "returned", "to", "the", "caller", ".", "If", "the", "result", "is", "Retry", "then", "Run", "sleeps", "according", "to", "the", "its", "backoff", "policy", "before", "retrying", ".", "If", "the", "total", "number", "of", "retries", "is", "exceeded", "then", "the", "return", "value", "of", "the", "work", "function", "is", "returned", "to", "the", "caller", "regardless", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/retrier/retrier.go#L50-L71
train
eapache/go-resiliency
batcher/batcher.go
New
func New(timeout time.Duration, doWork func([]interface{}) error) *Batcher { return &Batcher{ timeout: timeout, doWork: doWork, } }
go
func New(timeout time.Duration, doWork func([]interface{}) error) *Batcher { return &Batcher{ timeout: timeout, doWork: doWork, } }
[ "func", "New", "(", "timeout", "time", ".", "Duration", ",", "doWork", "func", "(", "[", "]", "interface", "{", "}", ")", "error", ")", "*", "Batcher", "{", "return", "&", "Batcher", "{", "timeout", ":", "timeout", ",", "doWork", ":", "doWork", ",", "}", "\n", "}" ]
// New constructs a new batcher that will batch all calls to Run that occur within // `timeout` time before calling doWork just once for the entire batch. The doWork // function must be safe to run concurrently with itself as this may occur, especially // when the timeout is small.
[ "New", "constructs", "a", "new", "batcher", "that", "will", "batch", "all", "calls", "to", "Run", "that", "occur", "within", "timeout", "time", "before", "calling", "doWork", "just", "once", "for", "the", "entire", "batch", ".", "The", "doWork", "function", "must", "be", "safe", "to", "run", "concurrently", "with", "itself", "as", "this", "may", "occur", "especially", "when", "the", "timeout", "is", "small", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/batcher/batcher.go#L28-L33
train
eapache/go-resiliency
batcher/batcher.go
Run
func (b *Batcher) Run(param interface{}) error { if b.prefilter != nil { if err := b.prefilter(param); err != nil { return err } } if b.timeout == 0 { return b.doWork([]interface{}{param}) } w := &work{ param: param, future: make(chan error, 1), } b.submitWork(w) return <-w.future }
go
func (b *Batcher) Run(param interface{}) error { if b.prefilter != nil { if err := b.prefilter(param); err != nil { return err } } if b.timeout == 0 { return b.doWork([]interface{}{param}) } w := &work{ param: param, future: make(chan error, 1), } b.submitWork(w) return <-w.future }
[ "func", "(", "b", "*", "Batcher", ")", "Run", "(", "param", "interface", "{", "}", ")", "error", "{", "if", "b", ".", "prefilter", "!=", "nil", "{", "if", "err", ":=", "b", ".", "prefilter", "(", "param", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "b", ".", "timeout", "==", "0", "{", "return", "b", ".", "doWork", "(", "[", "]", "interface", "{", "}", "{", "param", "}", ")", "\n", "}", "\n\n", "w", ":=", "&", "work", "{", "param", ":", "param", ",", "future", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "}", "\n\n", "b", ".", "submitWork", "(", "w", ")", "\n\n", "return", "<-", "w", ".", "future", "\n", "}" ]
// Run runs the work function with the given parameter, possibly // including it in a batch with other calls to Run that occur within the // specified timeout. It is safe to call Run concurrently on the same batcher.
[ "Run", "runs", "the", "work", "function", "with", "the", "given", "parameter", "possibly", "including", "it", "in", "a", "batch", "with", "other", "calls", "to", "Run", "that", "occur", "within", "the", "specified", "timeout", ".", "It", "is", "safe", "to", "call", "Run", "concurrently", "on", "the", "same", "batcher", "." ]
842e16ec2c98ef0c59eebfe60d2d3500a793ba19
https://github.com/eapache/go-resiliency/blob/842e16ec2c98ef0c59eebfe60d2d3500a793ba19/batcher/batcher.go#L38-L57
train
pebbe/zmq4
examples/kvsimple/kvsimple.go
NewKvmsg
func NewKvmsg(sequence int64) (kvmsg *Kvmsg) { kvmsg = &Kvmsg{ present: make([]bool, kvmsg_FRAMES), frame: make([]string, kvmsg_FRAMES), } kvmsg.SetSequence(sequence) return }
go
func NewKvmsg(sequence int64) (kvmsg *Kvmsg) { kvmsg = &Kvmsg{ present: make([]bool, kvmsg_FRAMES), frame: make([]string, kvmsg_FRAMES), } kvmsg.SetSequence(sequence) return }
[ "func", "NewKvmsg", "(", "sequence", "int64", ")", "(", "kvmsg", "*", "Kvmsg", ")", "{", "kvmsg", "=", "&", "Kvmsg", "{", "present", ":", "make", "(", "[", "]", "bool", ",", "kvmsg_FRAMES", ")", ",", "frame", ":", "make", "(", "[", "]", "string", ",", "kvmsg_FRAMES", ")", ",", "}", "\n", "kvmsg", ".", "SetSequence", "(", "sequence", ")", "\n", "return", "\n", "}" ]
// Constructor, takes a sequence number for the new Kvmsg instance.
[ "Constructor", "takes", "a", "sequence", "number", "for", "the", "new", "Kvmsg", "instance", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvsimple/kvsimple.go#L31-L38
train
pebbe/zmq4
examples/kvsimple/kvsimple.go
Size
func (kvmsg *Kvmsg) Size() int { if kvmsg.present[frame_BODY] { return len(kvmsg.frame[frame_BODY]) } return 0 }
go
func (kvmsg *Kvmsg) Size() int { if kvmsg.present[frame_BODY] { return len(kvmsg.frame[frame_BODY]) } return 0 }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "Size", "(", ")", "int", "{", "if", "kvmsg", ".", "present", "[", "frame_BODY", "]", "{", "return", "len", "(", "kvmsg", ".", "frame", "[", "frame_BODY", "]", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
// The size method returns the body size of the last-read message, if any.
[ "The", "size", "method", "returns", "the", "body", "size", "of", "the", "last", "-", "read", "message", "if", "any", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvsimple/kvsimple.go#L128-L133
train
pebbe/zmq4
examples/kvsimple/kvsimple.go
Dump
func (kvmsg *Kvmsg) Dump() { size := kvmsg.Size() body, _ := kvmsg.GetBody() seq, _ := kvmsg.GetSequence() key, _ := kvmsg.GetKey() fmt.Fprintf(os.Stderr, "[seq:%v][key:%v][size:%v]", seq, key, size) for char_nbr := 0; char_nbr < size; char_nbr++ { fmt.Fprintf(os.Stderr, "%02X", body[char_nbr]) } fmt.Fprintln(os.Stderr) }
go
func (kvmsg *Kvmsg) Dump() { size := kvmsg.Size() body, _ := kvmsg.GetBody() seq, _ := kvmsg.GetSequence() key, _ := kvmsg.GetKey() fmt.Fprintf(os.Stderr, "[seq:%v][key:%v][size:%v]", seq, key, size) for char_nbr := 0; char_nbr < size; char_nbr++ { fmt.Fprintf(os.Stderr, "%02X", body[char_nbr]) } fmt.Fprintln(os.Stderr) }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "Dump", "(", ")", "{", "size", ":=", "kvmsg", ".", "Size", "(", ")", "\n", "body", ",", "_", ":=", "kvmsg", ".", "GetBody", "(", ")", "\n", "seq", ",", "_", ":=", "kvmsg", ".", "GetSequence", "(", ")", "\n", "key", ",", "_", ":=", "kvmsg", ".", "GetKey", "(", ")", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "seq", ",", "key", ",", "size", ")", "\n", "for", "char_nbr", ":=", "0", ";", "char_nbr", "<", "size", ";", "char_nbr", "++", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "body", "[", "char_nbr", "]", ")", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ")", "\n", "}" ]
// The dump method prints the key-value message to stderr, // for debugging and tracing.
[ "The", "dump", "method", "prints", "the", "key", "-", "value", "message", "to", "stderr", "for", "debugging", "and", "tracing", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvsimple/kvsimple.go#L145-L155
train
pebbe/zmq4
examples/ppqueue.go
s_worker_new
func s_worker_new(identity string) worker_t { return worker_t{ identity: identity, id_string: identity, expire: time.Now().Add(HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS), } }
go
func s_worker_new(identity string) worker_t { return worker_t{ identity: identity, id_string: identity, expire: time.Now().Add(HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS), } }
[ "func", "s_worker_new", "(", "identity", "string", ")", "worker_t", "{", "return", "worker_t", "{", "identity", ":", "identity", ",", "id_string", ":", "identity", ",", "expire", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "HEARTBEAT_INTERVAL", "*", "HEARTBEAT_LIVENESS", ")", ",", "}", "\n", "}" ]
// Construct new worker
[ "Construct", "new", "worker" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/ppqueue.go#L32-L38
train
pebbe/zmq4
examples/ppqueue.go
unwrap
func unwrap(msg []string) (head string, tail []string) { head = msg[0] if len(msg) > 1 && msg[1] == "" { tail = msg[2:] } else { tail = msg[1:] } return }
go
func unwrap(msg []string) (head string, tail []string) { head = msg[0] if len(msg) > 1 && msg[1] == "" { tail = msg[2:] } else { tail = msg[1:] } return }
[ "func", "unwrap", "(", "msg", "[", "]", "string", ")", "(", "head", "string", ",", "tail", "[", "]", "string", ")", "{", "head", "=", "msg", "[", "0", "]", "\n", "if", "len", "(", "msg", ")", ">", "1", "&&", "msg", "[", "1", "]", "==", "\"", "\"", "{", "tail", "=", "msg", "[", "2", ":", "]", "\n", "}", "else", "{", "tail", "=", "msg", "[", "1", ":", "]", "\n", "}", "\n", "return", "\n", "}" ]
// Pops frame off front of message and returns it as 'head' // If next frame is empty, pops that empty frame. // Return remaining frames of message as 'tail'
[ "Pops", "frame", "off", "front", "of", "message", "and", "returns", "it", "as", "head", "If", "next", "frame", "is", "empty", "pops", "that", "empty", "frame", ".", "Return", "remaining", "frames", "of", "message", "as", "tail" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/ppqueue.go#L158-L166
train
pebbe/zmq4
draft/zmq4.go
Version
func Version() (major, minor, patch int) { if initVersionError != nil { return 0, 0, 0 } var maj, min, pat C.int C.zmq_version(&maj, &min, &pat) return int(maj), int(min), int(pat) }
go
func Version() (major, minor, patch int) { if initVersionError != nil { return 0, 0, 0 } var maj, min, pat C.int C.zmq_version(&maj, &min, &pat) return int(maj), int(min), int(pat) }
[ "func", "Version", "(", ")", "(", "major", ",", "minor", ",", "patch", "int", ")", "{", "if", "initVersionError", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", "\n", "}", "\n", "var", "maj", ",", "min", ",", "pat", "C", ".", "int", "\n", "C", ".", "zmq_version", "(", "&", "maj", ",", "&", "min", ",", "&", "pat", ")", "\n", "return", "int", "(", "maj", ")", ",", "int", "(", "min", ")", ",", "int", "(", "pat", ")", "\n", "}" ]
//. Util // Report 0MQ library version.
[ ".", "Util", "Report", "0MQ", "library", "version", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L159-L166
train
pebbe/zmq4
draft/zmq4.go
Error
func Error(e int) string { return C.GoString(C.zmq_strerror(C.int(e))) }
go
func Error(e int) string { return C.GoString(C.zmq_strerror(C.int(e))) }
[ "func", "Error", "(", "e", "int", ")", "string", "{", "return", "C", ".", "GoString", "(", "C", ".", "zmq_strerror", "(", "C", ".", "int", "(", "e", ")", ")", ")", "\n", "}" ]
// Get 0MQ error message string.
[ "Get", "0MQ", "error", "message", "string", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L169-L171
train
pebbe/zmq4
draft/zmq4.go
GetIoThreads
func GetIoThreads() (int, error) { if initVersionError != nil { return 0, initVersionError } if initContextError != nil { return 0, initContextError } return defaultCtx.GetIoThreads() }
go
func GetIoThreads() (int, error) { if initVersionError != nil { return 0, initVersionError } if initContextError != nil { return 0, initContextError } return defaultCtx.GetIoThreads() }
[ "func", "GetIoThreads", "(", ")", "(", "int", ",", "error", ")", "{", "if", "initVersionError", "!=", "nil", "{", "return", "0", ",", "initVersionError", "\n", "}", "\n", "if", "initContextError", "!=", "nil", "{", "return", "0", ",", "initContextError", "\n", "}", "\n", "return", "defaultCtx", ".", "GetIoThreads", "(", ")", "\n", "}" ]
// Returns the size of the 0MQ thread pool in the default context.
[ "Returns", "the", "size", "of", "the", "0MQ", "thread", "pool", "in", "the", "default", "context", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L251-L259
train
pebbe/zmq4
draft/zmq4.go
GetMaxSockets
func GetMaxSockets() (int, error) { if initVersionError != nil { return 0, initVersionError } if initContextError != nil { return 0, initContextError } return defaultCtx.GetMaxSockets() }
go
func GetMaxSockets() (int, error) { if initVersionError != nil { return 0, initVersionError } if initContextError != nil { return 0, initContextError } return defaultCtx.GetMaxSockets() }
[ "func", "GetMaxSockets", "(", ")", "(", "int", ",", "error", ")", "{", "if", "initVersionError", "!=", "nil", "{", "return", "0", ",", "initVersionError", "\n", "}", "\n", "if", "initContextError", "!=", "nil", "{", "return", "0", ",", "initContextError", "\n", "}", "\n", "return", "defaultCtx", ".", "GetMaxSockets", "(", ")", "\n", "}" ]
// Returns the maximum number of sockets allowed in the default context.
[ "Returns", "the", "maximum", "number", "of", "sockets", "allowed", "in", "the", "default", "context", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L267-L275
train
pebbe/zmq4
draft/zmq4.go
GetIpv6
func GetIpv6() (bool, error) { if initVersionError != nil { return false, initVersionError } if initContextError != nil { return false, initContextError } return defaultCtx.GetIpv6() }
go
func GetIpv6() (bool, error) { if initVersionError != nil { return false, initVersionError } if initContextError != nil { return false, initContextError } return defaultCtx.GetIpv6() }
[ "func", "GetIpv6", "(", ")", "(", "bool", ",", "error", ")", "{", "if", "initVersionError", "!=", "nil", "{", "return", "false", ",", "initVersionError", "\n", "}", "\n", "if", "initContextError", "!=", "nil", "{", "return", "false", ",", "initContextError", "\n", "}", "\n", "return", "defaultCtx", ".", "GetIpv6", "(", ")", "\n", "}" ]
// Returns the IPv6 option in the default context.
[ "Returns", "the", "IPv6", "option", "in", "the", "default", "context", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L310-L318
train
pebbe/zmq4
draft/zmq4.go
GetIpv6
func (ctx *Context) GetIpv6() (bool, error) { i, e := getOption(ctx, C.ZMQ_IPV6) if i == 0 { return false, e } return true, e }
go
func (ctx *Context) GetIpv6() (bool, error) { i, e := getOption(ctx, C.ZMQ_IPV6) if i == 0 { return false, e } return true, e }
[ "func", "(", "ctx", "*", "Context", ")", "GetIpv6", "(", ")", "(", "bool", ",", "error", ")", "{", "i", ",", "e", ":=", "getOption", "(", "ctx", ",", "C", ".", "ZMQ_IPV6", ")", "\n", "if", "i", "==", "0", "{", "return", "false", ",", "e", "\n", "}", "\n", "return", "true", ",", "e", "\n", "}" ]
// Returns the IPv6 option.
[ "Returns", "the", "IPv6", "option", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L321-L327
train
pebbe/zmq4
draft/zmq4.go
Close
func (soc *Socket) Close() error { if soc.opened { soc.opened = false if i, err := C.zmq_close(soc.soc); int(i) != 0 { soc.err = errget(err) } soc.soc = unsafe.Pointer(nil) soc.ctx = nil } return soc.err }
go
func (soc *Socket) Close() error { if soc.opened { soc.opened = false if i, err := C.zmq_close(soc.soc); int(i) != 0 { soc.err = errget(err) } soc.soc = unsafe.Pointer(nil) soc.ctx = nil } return soc.err }
[ "func", "(", "soc", "*", "Socket", ")", "Close", "(", ")", "error", "{", "if", "soc", ".", "opened", "{", "soc", ".", "opened", "=", "false", "\n", "if", "i", ",", "err", ":=", "C", ".", "zmq_close", "(", "soc", ".", "soc", ")", ";", "int", "(", "i", ")", "!=", "0", "{", "soc", ".", "err", "=", "errget", "(", "err", ")", "\n", "}", "\n", "soc", ".", "soc", "=", "unsafe", ".", "Pointer", "(", "nil", ")", "\n", "soc", ".", "ctx", "=", "nil", "\n", "}", "\n", "return", "soc", ".", "err", "\n", "}" ]
// If not called explicitly, the socket will be closed on garbage collection
[ "If", "not", "called", "explicitly", "the", "socket", "will", "be", "closed", "on", "garbage", "collection" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L881-L891
train
pebbe/zmq4
draft/zmq4.go
Context
func (soc *Socket) Context() (*Context, error) { if !soc.opened { return nil, ErrorSocketClosed } return soc.ctx, nil }
go
func (soc *Socket) Context() (*Context, error) { if !soc.opened { return nil, ErrorSocketClosed } return soc.ctx, nil }
[ "func", "(", "soc", "*", "Socket", ")", "Context", "(", ")", "(", "*", "Context", ",", "error", ")", "{", "if", "!", "soc", ".", "opened", "{", "return", "nil", ",", "ErrorSocketClosed", "\n", "}", "\n", "return", "soc", ".", "ctx", ",", "nil", "\n", "}" ]
// Return the context associated with a socket
[ "Return", "the", "context", "associated", "with", "a", "socket" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/draft/zmq4.go#L894-L899
train
pebbe/zmq4
examples/clonesrv4.go
main
func main() { snapshot, _ := zmq.NewSocket(zmq.ROUTER) snapshot.Bind("tcp://*:5556") publisher, _ := zmq.NewSocket(zmq.PUB) publisher.Bind("tcp://*:5557") collector, _ := zmq.NewSocket(zmq.PULL) collector.Bind("tcp://*:5558") // The body of the main task collects updates from clients and // publishes them back out to clients: sequence := int64(0) kvmap := make(map[string]*kvsimple.Kvmsg) poller := zmq.NewPoller() poller.Add(collector, zmq.POLLIN) poller.Add(snapshot, zmq.POLLIN) LOOP: for { polled, err := poller.Poll(1000 * time.Millisecond) if err != nil { break } for _, item := range polled { switch socket := item.Socket; socket { case collector: // Apply state update sent from client kvmsg, err := kvsimple.RecvKvmsg(collector) if err != nil { break LOOP // Interrupted } sequence++ kvmsg.SetSequence(sequence) kvmsg.Send(publisher) kvmsg.Store(kvmap) fmt.Println("I: publishing update", sequence) case snapshot: // Execute state snapshot request msg, err := snapshot.RecvMessage(0) if err != nil { break LOOP } identity := msg[0] // Request is in second frame of message request := msg[1] if request != "ICANHAZ?" { fmt.Println("E: bad request, aborting") break LOOP } subtree := msg[2] // Send state snapshot to client // For each entry in kvmap, send kvmsg to client for _, kvmsg := range kvmap { if key, _ := kvmsg.GetKey(); strings.HasPrefix(key, subtree) { snapshot.Send(identity, zmq.SNDMORE) kvmsg.Send(snapshot) } } // Now send END message with sequence number fmt.Println("I: sending shapshot =", sequence) snapshot.Send(identity, zmq.SNDMORE) kvmsg := kvsimple.NewKvmsg(sequence) kvmsg.SetKey("KTHXBAI") kvmsg.SetBody(subtree) kvmsg.Send(snapshot) } } } fmt.Printf("Interrupted\n%d messages handled\n", sequence) }
go
func main() { snapshot, _ := zmq.NewSocket(zmq.ROUTER) snapshot.Bind("tcp://*:5556") publisher, _ := zmq.NewSocket(zmq.PUB) publisher.Bind("tcp://*:5557") collector, _ := zmq.NewSocket(zmq.PULL) collector.Bind("tcp://*:5558") // The body of the main task collects updates from clients and // publishes them back out to clients: sequence := int64(0) kvmap := make(map[string]*kvsimple.Kvmsg) poller := zmq.NewPoller() poller.Add(collector, zmq.POLLIN) poller.Add(snapshot, zmq.POLLIN) LOOP: for { polled, err := poller.Poll(1000 * time.Millisecond) if err != nil { break } for _, item := range polled { switch socket := item.Socket; socket { case collector: // Apply state update sent from client kvmsg, err := kvsimple.RecvKvmsg(collector) if err != nil { break LOOP // Interrupted } sequence++ kvmsg.SetSequence(sequence) kvmsg.Send(publisher) kvmsg.Store(kvmap) fmt.Println("I: publishing update", sequence) case snapshot: // Execute state snapshot request msg, err := snapshot.RecvMessage(0) if err != nil { break LOOP } identity := msg[0] // Request is in second frame of message request := msg[1] if request != "ICANHAZ?" { fmt.Println("E: bad request, aborting") break LOOP } subtree := msg[2] // Send state snapshot to client // For each entry in kvmap, send kvmsg to client for _, kvmsg := range kvmap { if key, _ := kvmsg.GetKey(); strings.HasPrefix(key, subtree) { snapshot.Send(identity, zmq.SNDMORE) kvmsg.Send(snapshot) } } // Now send END message with sequence number fmt.Println("I: sending shapshot =", sequence) snapshot.Send(identity, zmq.SNDMORE) kvmsg := kvsimple.NewKvmsg(sequence) kvmsg.SetKey("KTHXBAI") kvmsg.SetBody(subtree) kvmsg.Send(snapshot) } } } fmt.Printf("Interrupted\n%d messages handled\n", sequence) }
[ "func", "main", "(", ")", "{", "snapshot", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "ROUTER", ")", "\n", "snapshot", ".", "Bind", "(", "\"", "\"", ")", "\n", "publisher", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "PUB", ")", "\n", "publisher", ".", "Bind", "(", "\"", "\"", ")", "\n", "collector", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "PULL", ")", "\n", "collector", ".", "Bind", "(", "\"", "\"", ")", "\n\n", "// The body of the main task collects updates from clients and", "// publishes them back out to clients:", "sequence", ":=", "int64", "(", "0", ")", "\n", "kvmap", ":=", "make", "(", "map", "[", "string", "]", "*", "kvsimple", ".", "Kvmsg", ")", "\n\n", "poller", ":=", "zmq", ".", "NewPoller", "(", ")", "\n", "poller", ".", "Add", "(", "collector", ",", "zmq", ".", "POLLIN", ")", "\n", "poller", ".", "Add", "(", "snapshot", ",", "zmq", ".", "POLLIN", ")", "\n", "LOOP", ":", "for", "{", "polled", ",", "err", ":=", "poller", ".", "Poll", "(", "1000", "*", "time", ".", "Millisecond", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "for", "_", ",", "item", ":=", "range", "polled", "{", "switch", "socket", ":=", "item", ".", "Socket", ";", "socket", "{", "case", "collector", ":", "// Apply state update sent from client", "kvmsg", ",", "err", ":=", "kvsimple", ".", "RecvKvmsg", "(", "collector", ")", "\n", "if", "err", "!=", "nil", "{", "break", "LOOP", "// Interrupted", "\n", "}", "\n", "sequence", "++", "\n", "kvmsg", ".", "SetSequence", "(", "sequence", ")", "\n", "kvmsg", ".", "Send", "(", "publisher", ")", "\n", "kvmsg", ".", "Store", "(", "kvmap", ")", "\n", "fmt", ".", "Println", "(", "\"", "\"", ",", "sequence", ")", "\n", "case", "snapshot", ":", "// Execute state snapshot request", "msg", ",", "err", ":=", "snapshot", ".", "RecvMessage", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "break", "LOOP", "\n", "}", "\n", "identity", ":=", "msg", "[", "0", "]", "\n\n", "// Request is in second frame of message", "request", ":=", "msg", "[", "1", "]", "\n", "if", "request", "!=", "\"", "\"", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "break", "LOOP", "\n", "}", "\n", "subtree", ":=", "msg", "[", "2", "]", "\n", "// Send state snapshot to client", "// For each entry in kvmap, send kvmsg to client", "for", "_", ",", "kvmsg", ":=", "range", "kvmap", "{", "if", "key", ",", "_", ":=", "kvmsg", ".", "GetKey", "(", ")", ";", "strings", ".", "HasPrefix", "(", "key", ",", "subtree", ")", "{", "snapshot", ".", "Send", "(", "identity", ",", "zmq", ".", "SNDMORE", ")", "\n", "kvmsg", ".", "Send", "(", "snapshot", ")", "\n", "}", "\n", "}", "\n\n", "// Now send END message with sequence number", "fmt", ".", "Println", "(", "\"", "\"", ",", "sequence", ")", "\n", "snapshot", ".", "Send", "(", "identity", ",", "zmq", ".", "SNDMORE", ")", "\n", "kvmsg", ":=", "kvsimple", ".", "NewKvmsg", "(", "sequence", ")", "\n", "kvmsg", ".", "SetKey", "(", "\"", "\"", ")", "\n", "kvmsg", ".", "SetBody", "(", "subtree", ")", "\n", "kvmsg", ".", "Send", "(", "snapshot", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ",", "sequence", ")", "\n", "}" ]
// The main task is identical to clonesrv3 except for where it // handles subtrees.
[ "The", "main", "task", "is", "identical", "to", "clonesrv3", "except", "for", "where", "it", "handles", "subtrees", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/clonesrv4.go#L19-L91
train
pebbe/zmq4
examples/intface/intface.go
control_message
func (agent *agent_t) control_message() (err error) { // Get the whole message off the pipe in one go msg, e := agent.pipe.RecvMessage(0) if e != nil { return e } command := msg[0] // We don't actually implement any control commands yet // but if we did, this would be where we did it.. switch command { case "EXAMPLE": default: } return }
go
func (agent *agent_t) control_message() (err error) { // Get the whole message off the pipe in one go msg, e := agent.pipe.RecvMessage(0) if e != nil { return e } command := msg[0] // We don't actually implement any control commands yet // but if we did, this would be where we did it.. switch command { case "EXAMPLE": default: } return }
[ "func", "(", "agent", "*", "agent_t", ")", "control_message", "(", ")", "(", "err", "error", ")", "{", "// Get the whole message off the pipe in one go", "msg", ",", "e", ":=", "agent", ".", "pipe", ".", "RecvMessage", "(", "0", ")", "\n", "if", "e", "!=", "nil", "{", "return", "e", "\n", "}", "\n", "command", ":=", "msg", "[", "0", "]", "\n\n", "// We don't actually implement any control commands yet", "// but if we did, this would be where we did it..", "switch", "command", "{", "case", "\"", "\"", ":", "default", ":", "}", "\n\n", "return", "\n", "}" ]
// Here we handle the different control messages from the front-end.
[ "Here", "we", "handle", "the", "different", "control", "messages", "from", "the", "front", "-", "end", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/intface/intface.go#L145-L161
train
pebbe/zmq4
examples/ppworker.go
s_worker_socket
func s_worker_socket() (*zmq.Socket, *zmq.Poller) { worker, _ := zmq.NewSocket(zmq.DEALER) worker.Connect("tcp://localhost:5556") // Tell queue we're ready for work fmt.Println("I: worker ready") worker.Send(PPP_READY, 0) poller := zmq.NewPoller() poller.Add(worker, zmq.POLLIN) return worker, poller }
go
func s_worker_socket() (*zmq.Socket, *zmq.Poller) { worker, _ := zmq.NewSocket(zmq.DEALER) worker.Connect("tcp://localhost:5556") // Tell queue we're ready for work fmt.Println("I: worker ready") worker.Send(PPP_READY, 0) poller := zmq.NewPoller() poller.Add(worker, zmq.POLLIN) return worker, poller }
[ "func", "s_worker_socket", "(", ")", "(", "*", "zmq", ".", "Socket", ",", "*", "zmq", ".", "Poller", ")", "{", "worker", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "DEALER", ")", "\n", "worker", ".", "Connect", "(", "\"", "\"", ")", "\n\n", "// Tell queue we're ready for work", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "worker", ".", "Send", "(", "PPP_READY", ",", "0", ")", "\n\n", "poller", ":=", "zmq", ".", "NewPoller", "(", ")", "\n", "poller", ".", "Add", "(", "worker", ",", "zmq", ".", "POLLIN", ")", "\n\n", "return", "worker", ",", "poller", "\n", "}" ]
// Helper function that returns a new configured socket // connected to the Paranoid Pirate queue
[ "Helper", "function", "that", "returns", "a", "new", "configured", "socket", "connected", "to", "the", "Paranoid", "Pirate", "queue" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/ppworker.go#L29-L41
train
pebbe/zmq4
auth.go
AuthStop
func AuthStop() { if !auth_init { if auth_verbose { log.Println("AUTH: Not running, can't stop") } return } if auth_verbose { log.Println("AUTH: Stopping") } _, err := auth_quit.SendMessageDontwait("QUIT") if err != nil && auth_verbose { log.Println("AUTH: Stopping: SendMessageDontwait(\"QUIT\"):", err) } _, err = auth_quit.RecvMessage(0) if err != nil && auth_verbose { log.Println("AUTH: Stopping: RecvMessage:", err) } err = auth_quit.Close() if err != nil && auth_verbose { log.Println("AUTH: Stopping: Close:", err) } if auth_verbose { log.Println("AUTH: Stopped") } auth_init = false }
go
func AuthStop() { if !auth_init { if auth_verbose { log.Println("AUTH: Not running, can't stop") } return } if auth_verbose { log.Println("AUTH: Stopping") } _, err := auth_quit.SendMessageDontwait("QUIT") if err != nil && auth_verbose { log.Println("AUTH: Stopping: SendMessageDontwait(\"QUIT\"):", err) } _, err = auth_quit.RecvMessage(0) if err != nil && auth_verbose { log.Println("AUTH: Stopping: RecvMessage:", err) } err = auth_quit.Close() if err != nil && auth_verbose { log.Println("AUTH: Stopping: Close:", err) } if auth_verbose { log.Println("AUTH: Stopped") } auth_init = false }
[ "func", "AuthStop", "(", ")", "{", "if", "!", "auth_init", "{", "if", "auth_verbose", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "auth_verbose", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "err", ":=", "auth_quit", ".", "SendMessageDontwait", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "&&", "auth_verbose", "{", "log", ".", "Println", "(", "\"", "\\\"", "\\\"", "\"", ",", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "auth_quit", ".", "RecvMessage", "(", "0", ")", "\n", "if", "err", "!=", "nil", "&&", "auth_verbose", "{", "log", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "auth_quit", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "auth_verbose", "{", "log", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "auth_verbose", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n\n", "auth_init", "=", "false", "\n\n", "}" ]
// Stop authentication.
[ "Stop", "authentication", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L351-L379
train
pebbe/zmq4
auth.go
AuthPlainRemove
func AuthPlainRemove(domain string, usernames ...string) { if u, ok := auth_users[domain]; ok { for _, username := range usernames { delete(u, username) } } }
go
func AuthPlainRemove(domain string, usernames ...string) { if u, ok := auth_users[domain]; ok { for _, username := range usernames { delete(u, username) } } }
[ "func", "AuthPlainRemove", "(", "domain", "string", ",", "usernames", "...", "string", ")", "{", "if", "u", ",", "ok", ":=", "auth_users", "[", "domain", "]", ";", "ok", "{", "for", "_", ",", "username", ":=", "range", "usernames", "{", "delete", "(", "u", ",", "username", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Remove users from PLAIN authentication for a given domain.
[ "Remove", "users", "from", "PLAIN", "authentication", "for", "a", "given", "domain", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L478-L484
train
pebbe/zmq4
auth.go
AuthCurveRemove
func AuthCurveRemove(domain string, pubkeys ...string) { if p, ok := auth_pubkeys[domain]; ok { for _, pubkey := range pubkeys { delete(p, pubkey) } } }
go
func AuthCurveRemove(domain string, pubkeys ...string) { if p, ok := auth_pubkeys[domain]; ok { for _, pubkey := range pubkeys { delete(p, pubkey) } } }
[ "func", "AuthCurveRemove", "(", "domain", "string", ",", "pubkeys", "...", "string", ")", "{", "if", "p", ",", "ok", ":=", "auth_pubkeys", "[", "domain", "]", ";", "ok", "{", "for", "_", ",", "pubkey", ":=", "range", "pubkeys", "{", "delete", "(", "p", ",", "pubkey", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Remove user keys from CURVE authentication for a given domain.
[ "Remove", "user", "keys", "from", "CURVE", "authentication", "for", "a", "given", "domain", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L508-L514
train
pebbe/zmq4
auth.go
ServerAuthNull
func (server *Socket) ServerAuthNull(domain string) error { err := server.SetPlainServer(0) if err == nil { err = server.SetZapDomain(domain) } return err }
go
func (server *Socket) ServerAuthNull(domain string) error { err := server.SetPlainServer(0) if err == nil { err = server.SetZapDomain(domain) } return err }
[ "func", "(", "server", "*", "Socket", ")", "ServerAuthNull", "(", "domain", "string", ")", "error", "{", "err", ":=", "server", ".", "SetPlainServer", "(", "0", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "server", ".", "SetZapDomain", "(", "domain", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
//. Additional functions for configuring server or client socket with a single command // Set NULL server role.
[ ".", "Additional", "functions", "for", "configuring", "server", "or", "client", "socket", "with", "a", "single", "command", "Set", "NULL", "server", "role", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L579-L585
train
pebbe/zmq4
auth.go
ServerAuthCurve
func (server *Socket) ServerAuthCurve(domain, secret_key string) error { err := server.SetCurveServer(1) if err == nil { err = server.SetCurveSecretkey(secret_key) } if err == nil { err = server.SetZapDomain(domain) } return err }
go
func (server *Socket) ServerAuthCurve(domain, secret_key string) error { err := server.SetCurveServer(1) if err == nil { err = server.SetCurveSecretkey(secret_key) } if err == nil { err = server.SetZapDomain(domain) } return err }
[ "func", "(", "server", "*", "Socket", ")", "ServerAuthCurve", "(", "domain", ",", "secret_key", "string", ")", "error", "{", "err", ":=", "server", ".", "SetCurveServer", "(", "1", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "server", ".", "SetCurveSecretkey", "(", "secret_key", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "err", "=", "server", ".", "SetZapDomain", "(", "domain", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Set CURVE server role.
[ "Set", "CURVE", "server", "role", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L597-L606
train
pebbe/zmq4
auth.go
ClientAuthPlain
func (client *Socket) ClientAuthPlain(username, password string) error { err := client.SetPlainUsername(username) if err == nil { err = client.SetPlainPassword(password) } return err }
go
func (client *Socket) ClientAuthPlain(username, password string) error { err := client.SetPlainUsername(username) if err == nil { err = client.SetPlainPassword(password) } return err }
[ "func", "(", "client", "*", "Socket", ")", "ClientAuthPlain", "(", "username", ",", "password", "string", ")", "error", "{", "err", ":=", "client", ".", "SetPlainUsername", "(", "username", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "client", ".", "SetPlainPassword", "(", "password", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Set PLAIN client role.
[ "Set", "PLAIN", "client", "role", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L609-L615
train
pebbe/zmq4
auth.go
ClientAuthCurve
func (client *Socket) ClientAuthCurve(server_public_key, client_public_key, client_secret_key string) error { err := client.SetCurveServerkey(server_public_key) if err == nil { err = client.SetCurvePublickey(client_public_key) } if err == nil { client.SetCurveSecretkey(client_secret_key) } return err }
go
func (client *Socket) ClientAuthCurve(server_public_key, client_public_key, client_secret_key string) error { err := client.SetCurveServerkey(server_public_key) if err == nil { err = client.SetCurvePublickey(client_public_key) } if err == nil { client.SetCurveSecretkey(client_secret_key) } return err }
[ "func", "(", "client", "*", "Socket", ")", "ClientAuthCurve", "(", "server_public_key", ",", "client_public_key", ",", "client_secret_key", "string", ")", "error", "{", "err", ":=", "client", ".", "SetCurveServerkey", "(", "server_public_key", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "client", ".", "SetCurvePublickey", "(", "client_public_key", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "client", ".", "SetCurveSecretkey", "(", "client_secret_key", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Set CURVE client role.
[ "Set", "CURVE", "client", "role", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L618-L627
train
pebbe/zmq4
auth.go
AuthCurvePublic
func AuthCurvePublic(z85SecretKey string) (z85PublicKey string, err error) { if minor < 2 { return "", ErrorNotImplemented42 } secret := C.CString(z85SecretKey) defer C.free(unsafe.Pointer(secret)) public := C.CString(strings.Repeat(" ", 41)) defer C.free(unsafe.Pointer(public)) if i, err := C.zmq_curve_public(public, secret); int(i) != 0 { return "", errget(err) } z85PublicKey = C.GoString(public) return z85PublicKey, nil }
go
func AuthCurvePublic(z85SecretKey string) (z85PublicKey string, err error) { if minor < 2 { return "", ErrorNotImplemented42 } secret := C.CString(z85SecretKey) defer C.free(unsafe.Pointer(secret)) public := C.CString(strings.Repeat(" ", 41)) defer C.free(unsafe.Pointer(public)) if i, err := C.zmq_curve_public(public, secret); int(i) != 0 { return "", errget(err) } z85PublicKey = C.GoString(public) return z85PublicKey, nil }
[ "func", "AuthCurvePublic", "(", "z85SecretKey", "string", ")", "(", "z85PublicKey", "string", ",", "err", "error", ")", "{", "if", "minor", "<", "2", "{", "return", "\"", "\"", ",", "ErrorNotImplemented42", "\n", "}", "\n", "secret", ":=", "C", ".", "CString", "(", "z85SecretKey", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "secret", ")", ")", "\n", "public", ":=", "C", ".", "CString", "(", "strings", ".", "Repeat", "(", "\"", "\"", ",", "41", ")", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "public", ")", ")", "\n", "if", "i", ",", "err", ":=", "C", ".", "zmq_curve_public", "(", "public", ",", "secret", ")", ";", "int", "(", "i", ")", "!=", "0", "{", "return", "\"", "\"", ",", "errget", "(", "err", ")", "\n", "}", "\n", "z85PublicKey", "=", "C", ".", "GoString", "(", "public", ")", "\n", "return", "z85PublicKey", ",", "nil", "\n", "}" ]
// Helper function to derive z85 public key from secret key // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2
[ "Helper", "function", "to", "derive", "z85", "public", "key", "from", "secret", "key", "Returns", "ErrorNotImplemented42", "with", "ZeroMQ", "version", "<", "4", ".", "2" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/auth.go#L632-L645
train
pebbe/zmq4
examples/espresso.go
subscriber_thread
func subscriber_thread() { // Subscribe to "A" and "B" subscriber, _ := zmq.NewSocket(zmq.SUB) subscriber.Connect("tcp://localhost:6001") subscriber.SetSubscribe("A") subscriber.SetSubscribe("B") defer subscriber.Close() // cancel subscribe for count := 0; count < 5; count++ { _, err := subscriber.RecvMessage(0) if err != nil { break // Interrupted } } }
go
func subscriber_thread() { // Subscribe to "A" and "B" subscriber, _ := zmq.NewSocket(zmq.SUB) subscriber.Connect("tcp://localhost:6001") subscriber.SetSubscribe("A") subscriber.SetSubscribe("B") defer subscriber.Close() // cancel subscribe for count := 0; count < 5; count++ { _, err := subscriber.RecvMessage(0) if err != nil { break // Interrupted } } }
[ "func", "subscriber_thread", "(", ")", "{", "// Subscribe to \"A\" and \"B\"", "subscriber", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "SUB", ")", "\n", "subscriber", ".", "Connect", "(", "\"", "\"", ")", "\n", "subscriber", ".", "SetSubscribe", "(", "\"", "\"", ")", "\n", "subscriber", ".", "SetSubscribe", "(", "\"", "\"", ")", "\n", "defer", "subscriber", ".", "Close", "(", ")", "// cancel subscribe", "\n\n", "for", "count", ":=", "0", ";", "count", "<", "5", ";", "count", "++", "{", "_", ",", "err", ":=", "subscriber", ".", "RecvMessage", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "break", "// Interrupted", "\n", "}", "\n", "}", "\n", "}" ]
// The subscriber thread requests messages starting with // A and B, then reads and counts incoming messages.
[ "The", "subscriber", "thread", "requests", "messages", "starting", "with", "A", "and", "B", "then", "reads", "and", "counts", "incoming", "messages", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/espresso.go#L19-L33
train
pebbe/zmq4
examples/asyncsrv.go
server_task
func server_task() { // Frontend socket talks to clients over TCP frontend, _ := zmq.NewSocket(zmq.ROUTER) defer frontend.Close() frontend.Bind("tcp://*:5570") // Backend socket talks to workers over inproc backend, _ := zmq.NewSocket(zmq.DEALER) defer backend.Close() backend.Bind("inproc://backend") // Launch pool of worker threads, precise number is not critical for i := 0; i < 5; i++ { go server_worker() } // Connect backend to frontend via a proxy err := zmq.Proxy(frontend, backend, nil) log.Fatalln("Proxy interrupted:", err) }
go
func server_task() { // Frontend socket talks to clients over TCP frontend, _ := zmq.NewSocket(zmq.ROUTER) defer frontend.Close() frontend.Bind("tcp://*:5570") // Backend socket talks to workers over inproc backend, _ := zmq.NewSocket(zmq.DEALER) defer backend.Close() backend.Bind("inproc://backend") // Launch pool of worker threads, precise number is not critical for i := 0; i < 5; i++ { go server_worker() } // Connect backend to frontend via a proxy err := zmq.Proxy(frontend, backend, nil) log.Fatalln("Proxy interrupted:", err) }
[ "func", "server_task", "(", ")", "{", "// Frontend socket talks to clients over TCP", "frontend", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "ROUTER", ")", "\n", "defer", "frontend", ".", "Close", "(", ")", "\n", "frontend", ".", "Bind", "(", "\"", "\"", ")", "\n\n", "// Backend socket talks to workers over inproc", "backend", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "DEALER", ")", "\n", "defer", "backend", ".", "Close", "(", ")", "\n", "backend", ".", "Bind", "(", "\"", "\"", ")", "\n\n", "// Launch pool of worker threads, precise number is not critical", "for", "i", ":=", "0", ";", "i", "<", "5", ";", "i", "++", "{", "go", "server_worker", "(", ")", "\n", "}", "\n\n", "// Connect backend to frontend via a proxy", "err", ":=", "zmq", ".", "Proxy", "(", "frontend", ",", "backend", ",", "nil", ")", "\n", "log", ".", "Fatalln", "(", "\"", "\"", ",", "err", ")", "\n", "}" ]
// This is our server task. // It uses the multithreaded server model to deal requests out to a pool // of workers and route replies back to clients. One worker can handle // one request at a time but one client can talk to multiple workers at // once.
[ "This", "is", "our", "server", "task", ".", "It", "uses", "the", "multithreaded", "server", "model", "to", "deal", "requests", "out", "to", "a", "pool", "of", "workers", "and", "route", "replies", "back", "to", "clients", ".", "One", "worker", "can", "handle", "one", "request", "at", "a", "time", "but", "one", "client", "can", "talk", "to", "multiple", "workers", "at", "once", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/asyncsrv.go#L63-L83
train
pebbe/zmq4
examples/asyncsrv.go
main
func main() { rand.Seed(time.Now().UnixNano()) go client_task() go client_task() go client_task() go server_task() // Run for 5 seconds then quit time.Sleep(5 * time.Second) }
go
func main() { rand.Seed(time.Now().UnixNano()) go client_task() go client_task() go client_task() go server_task() // Run for 5 seconds then quit time.Sleep(5 * time.Second) }
[ "func", "main", "(", ")", "{", "rand", ".", "Seed", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n\n", "go", "client_task", "(", ")", "\n", "go", "client_task", "(", ")", "\n", "go", "client_task", "(", ")", "\n", "go", "server_task", "(", ")", "\n\n", "// Run for 5 seconds then quit", "time", ".", "Sleep", "(", "5", "*", "time", ".", "Second", ")", "\n", "}" ]
// The main thread simply starts several clients, and a server, and then // waits for the server to finish.
[ "The", "main", "thread", "simply", "starts", "several", "clients", "and", "a", "server", "and", "then", "waits", "for", "the", "server", "to", "finish", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/asyncsrv.go#L112-L122
train
pebbe/zmq4
examples/lbbroker2.go
client_task
func client_task() { client, _ := zmq.NewSocket(zmq.REQ) defer client.Close() client.Connect("ipc://frontend.ipc") // Send request, get reply for { client.SendMessage("HELLO") reply, _ := client.RecvMessage(0) if len(reply) == 0 { break } fmt.Println("Client:", strings.Join(reply, "\n\t")) time.Sleep(time.Second) } }
go
func client_task() { client, _ := zmq.NewSocket(zmq.REQ) defer client.Close() client.Connect("ipc://frontend.ipc") // Send request, get reply for { client.SendMessage("HELLO") reply, _ := client.RecvMessage(0) if len(reply) == 0 { break } fmt.Println("Client:", strings.Join(reply, "\n\t")) time.Sleep(time.Second) } }
[ "func", "client_task", "(", ")", "{", "client", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "REQ", ")", "\n", "defer", "client", ".", "Close", "(", ")", "\n", "client", ".", "Connect", "(", "\"", "\"", ")", "\n\n", "// Send request, get reply", "for", "{", "client", ".", "SendMessage", "(", "\"", "\"", ")", "\n", "reply", ",", "_", ":=", "client", ".", "RecvMessage", "(", "0", ")", "\n", "if", "len", "(", "reply", ")", "==", "0", "{", "break", "\n", "}", "\n", "fmt", ".", "Println", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "reply", ",", "\"", "\\n", "\\t", "\"", ")", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "}", "\n", "}" ]
// Basic request-reply client using REQ socket //
[ "Basic", "request", "-", "reply", "client", "using", "REQ", "socket" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/lbbroker2.go#L24-L39
train
pebbe/zmq4
polling.go
NewPoller
func NewPoller() *Poller { return &Poller{ items: make([]C.zmq_pollitem_t, 0), socks: make([]*Socket, 0), } }
go
func NewPoller() *Poller { return &Poller{ items: make([]C.zmq_pollitem_t, 0), socks: make([]*Socket, 0), } }
[ "func", "NewPoller", "(", ")", "*", "Poller", "{", "return", "&", "Poller", "{", "items", ":", "make", "(", "[", "]", "C", ".", "zmq_pollitem_t", ",", "0", ")", ",", "socks", ":", "make", "(", "[", "]", "*", "Socket", ",", "0", ")", ",", "}", "\n", "}" ]
// Create a new Poller
[ "Create", "a", "new", "Poller" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/polling.go#L25-L30
train
pebbe/zmq4
polling.go
Update
func (p *Poller) Update(id int, events State) (previous State, err error) { if id >= 0 && id < len(p.items) { previous = State(p.items[id].events) p.items[id].events = C.short(events) return previous, nil } return 0, ErrorNoSocket }
go
func (p *Poller) Update(id int, events State) (previous State, err error) { if id >= 0 && id < len(p.items) { previous = State(p.items[id].events) p.items[id].events = C.short(events) return previous, nil } return 0, ErrorNoSocket }
[ "func", "(", "p", "*", "Poller", ")", "Update", "(", "id", "int", ",", "events", "State", ")", "(", "previous", "State", ",", "err", "error", ")", "{", "if", "id", ">=", "0", "&&", "id", "<", "len", "(", "p", ".", "items", ")", "{", "previous", "=", "State", "(", "p", ".", "items", "[", "id", "]", ".", "events", ")", "\n", "p", ".", "items", "[", "id", "]", ".", "events", "=", "C", ".", "short", "(", "events", ")", "\n", "return", "previous", ",", "nil", "\n", "}", "\n", "return", "0", ",", "ErrorNoSocket", "\n", "}" ]
// Update the events mask of a socket in the poller // // Replaces the Poller's bitmask for the specified id with the events parameter passed // // Returns the previous value, or ErrorNoSocket if the id was out of range
[ "Update", "the", "events", "mask", "of", "a", "socket", "in", "the", "poller", "Replaces", "the", "Poller", "s", "bitmask", "for", "the", "specified", "id", "with", "the", "events", "parameter", "passed", "Returns", "the", "previous", "value", "or", "ErrorNoSocket", "if", "the", "id", "was", "out", "of", "range" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/polling.go#L53-L60
train
pebbe/zmq4
polling.go
UpdateBySocket
func (p *Poller) UpdateBySocket(soc *Socket, events State) (previous State, err error) { for id, s := range p.socks { if s == soc { previous = State(p.items[id].events) p.items[id].events = C.short(events) return previous, nil } } return 0, ErrorNoSocket }
go
func (p *Poller) UpdateBySocket(soc *Socket, events State) (previous State, err error) { for id, s := range p.socks { if s == soc { previous = State(p.items[id].events) p.items[id].events = C.short(events) return previous, nil } } return 0, ErrorNoSocket }
[ "func", "(", "p", "*", "Poller", ")", "UpdateBySocket", "(", "soc", "*", "Socket", ",", "events", "State", ")", "(", "previous", "State", ",", "err", "error", ")", "{", "for", "id", ",", "s", ":=", "range", "p", ".", "socks", "{", "if", "s", "==", "soc", "{", "previous", "=", "State", "(", "p", ".", "items", "[", "id", "]", ".", "events", ")", "\n", "p", ".", "items", "[", "id", "]", ".", "events", "=", "C", ".", "short", "(", "events", ")", "\n", "return", "previous", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "0", ",", "ErrorNoSocket", "\n", "}" ]
// Update the events mask of a socket in the poller // // Replaces the Poller's bitmask for the specified socket with the events parameter passed // // Returns the previous value, or ErrorNoSocket if the socket didn't match
[ "Update", "the", "events", "mask", "of", "a", "socket", "in", "the", "poller", "Replaces", "the", "Poller", "s", "bitmask", "for", "the", "specified", "socket", "with", "the", "events", "parameter", "passed", "Returns", "the", "previous", "value", "or", "ErrorNoSocket", "if", "the", "socket", "didn", "t", "match" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/polling.go#L67-L76
train
pebbe/zmq4
polling.go
Remove
func (p *Poller) Remove(id int) error { if id >= 0 && id < len(p.items) { if id == len(p.items)-1 { p.items = p.items[:id] p.socks = p.socks[:id] } else { p.items = append(p.items[:id], p.items[id+1:]...) p.socks = append(p.socks[:id], p.socks[id+1:]...) } return nil } return ErrorNoSocket }
go
func (p *Poller) Remove(id int) error { if id >= 0 && id < len(p.items) { if id == len(p.items)-1 { p.items = p.items[:id] p.socks = p.socks[:id] } else { p.items = append(p.items[:id], p.items[id+1:]...) p.socks = append(p.socks[:id], p.socks[id+1:]...) } return nil } return ErrorNoSocket }
[ "func", "(", "p", "*", "Poller", ")", "Remove", "(", "id", "int", ")", "error", "{", "if", "id", ">=", "0", "&&", "id", "<", "len", "(", "p", ".", "items", ")", "{", "if", "id", "==", "len", "(", "p", ".", "items", ")", "-", "1", "{", "p", ".", "items", "=", "p", ".", "items", "[", ":", "id", "]", "\n", "p", ".", "socks", "=", "p", ".", "socks", "[", ":", "id", "]", "\n", "}", "else", "{", "p", ".", "items", "=", "append", "(", "p", ".", "items", "[", ":", "id", "]", ",", "p", ".", "items", "[", "id", "+", "1", ":", "]", "...", ")", "\n", "p", ".", "socks", "=", "append", "(", "p", ".", "socks", "[", ":", "id", "]", ",", "p", ".", "socks", "[", "id", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "ErrorNoSocket", "\n", "}" ]
// Remove a socket from the poller // // Returns ErrorNoSocket if the id was out of range
[ "Remove", "a", "socket", "from", "the", "poller", "Returns", "ErrorNoSocket", "if", "the", "id", "was", "out", "of", "range" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/polling.go#L81-L93
train
pebbe/zmq4
polling.go
RemoveBySocket
func (p *Poller) RemoveBySocket(soc *Socket) error { for id, s := range p.socks { if s == soc { return p.Remove(id) } } return ErrorNoSocket }
go
func (p *Poller) RemoveBySocket(soc *Socket) error { for id, s := range p.socks { if s == soc { return p.Remove(id) } } return ErrorNoSocket }
[ "func", "(", "p", "*", "Poller", ")", "RemoveBySocket", "(", "soc", "*", "Socket", ")", "error", "{", "for", "id", ",", "s", ":=", "range", "p", ".", "socks", "{", "if", "s", "==", "soc", "{", "return", "p", ".", "Remove", "(", "id", ")", "\n", "}", "\n", "}", "\n", "return", "ErrorNoSocket", "\n", "}" ]
// Remove a socket from the poller // // Returns ErrorNoSocket if the socket didn't match
[ "Remove", "a", "socket", "from", "the", "poller", "Returns", "ErrorNoSocket", "if", "the", "socket", "didn", "t", "match" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/polling.go#L98-L105
train
pebbe/zmq4
polling.go
String
func (p *Poller) String() string { str := make([]string, 0) for i, poll := range p.items { str = append(str, fmt.Sprintf("%v%v", p.socks[i], State(poll.events))) } return fmt.Sprint("Poller", str) }
go
func (p *Poller) String() string { str := make([]string, 0) for i, poll := range p.items { str = append(str, fmt.Sprintf("%v%v", p.socks[i], State(poll.events))) } return fmt.Sprint("Poller", str) }
[ "func", "(", "p", "*", "Poller", ")", "String", "(", ")", "string", "{", "str", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "for", "i", ",", "poll", ":=", "range", "p", ".", "items", "{", "str", "=", "append", "(", "str", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "socks", "[", "i", "]", ",", "State", "(", "poll", ".", "events", ")", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprint", "(", "\"", "\"", ",", "str", ")", "\n", "}" ]
// Poller as string.
[ "Poller", "as", "string", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/polling.go#L181-L187
train
pebbe/zmq4
errors.go
Error
func (errno Errno) Error() string { if errno >= C.ZMQ_HAUSNUMERO { return C.GoString(C.zmq_strerror(C.int(errno))) } return syscall.Errno(errno).Error() }
go
func (errno Errno) Error() string { if errno >= C.ZMQ_HAUSNUMERO { return C.GoString(C.zmq_strerror(C.int(errno))) } return syscall.Errno(errno).Error() }
[ "func", "(", "errno", "Errno", ")", "Error", "(", ")", "string", "{", "if", "errno", ">=", "C", ".", "ZMQ_HAUSNUMERO", "{", "return", "C", ".", "GoString", "(", "C", ".", "zmq_strerror", "(", "C", ".", "int", "(", "errno", ")", ")", ")", "\n", "}", "\n", "return", "syscall", ".", "Errno", "(", "errno", ")", ".", "Error", "(", ")", "\n", "}" ]
// Return Errno as string.
[ "Return", "Errno", "as", "string", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/errors.go#L56-L61
train
pebbe/zmq4
examples/kvmsg/kvmsg.go
RecvKvmsg
func RecvKvmsg(socket *zmq.Socket) (kvmsg *Kvmsg, err error) { kvmsg = &Kvmsg{ present: make([]bool, kvmsg_FRAMES), frame: make([]string, kvmsg_FRAMES), } msg, err := socket.RecvMessage(0) if err != nil { return } //fmt.Printf("Recv from %s: %q\n", socket, msg) for i := 0; i < kvmsg_FRAMES && i < len(msg); i++ { kvmsg.frame[i] = msg[i] kvmsg.present[i] = true } kvmsg.decode_props() return }
go
func RecvKvmsg(socket *zmq.Socket) (kvmsg *Kvmsg, err error) { kvmsg = &Kvmsg{ present: make([]bool, kvmsg_FRAMES), frame: make([]string, kvmsg_FRAMES), } msg, err := socket.RecvMessage(0) if err != nil { return } //fmt.Printf("Recv from %s: %q\n", socket, msg) for i := 0; i < kvmsg_FRAMES && i < len(msg); i++ { kvmsg.frame[i] = msg[i] kvmsg.present[i] = true } kvmsg.decode_props() return }
[ "func", "RecvKvmsg", "(", "socket", "*", "zmq", ".", "Socket", ")", "(", "kvmsg", "*", "Kvmsg", ",", "err", "error", ")", "{", "kvmsg", "=", "&", "Kvmsg", "{", "present", ":", "make", "(", "[", "]", "bool", ",", "kvmsg_FRAMES", ")", ",", "frame", ":", "make", "(", "[", "]", "string", ",", "kvmsg_FRAMES", ")", ",", "}", "\n", "msg", ",", "err", ":=", "socket", ".", "RecvMessage", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "//fmt.Printf(\"Recv from %s: %q\\n\", socket, msg)", "for", "i", ":=", "0", ";", "i", "<", "kvmsg_FRAMES", "&&", "i", "<", "len", "(", "msg", ")", ";", "i", "++", "{", "kvmsg", ".", "frame", "[", "i", "]", "=", "msg", "[", "i", "]", "\n", "kvmsg", ".", "present", "[", "i", "]", "=", "true", "\n", "}", "\n", "kvmsg", ".", "decode_props", "(", ")", "\n", "return", "\n", "}" ]
// The RecvKvmsg function reads a key-value message from socket, and returns a new // Kvmsg instance.
[ "The", "RecvKvmsg", "function", "reads", "a", "key", "-", "value", "message", "from", "socket", "and", "returns", "a", "new", "Kvmsg", "instance", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvmsg/kvmsg.go#L68-L84
train
pebbe/zmq4
examples/kvmsg/kvmsg.go
Send
func (kvmsg *Kvmsg) Send(socket *zmq.Socket) (err error) { //fmt.Printf("Send to %s: %q\n", socket, kvmsg.frame) kvmsg.encode_props() _, err = socket.SendMessage(kvmsg.frame) return }
go
func (kvmsg *Kvmsg) Send(socket *zmq.Socket) (err error) { //fmt.Printf("Send to %s: %q\n", socket, kvmsg.frame) kvmsg.encode_props() _, err = socket.SendMessage(kvmsg.frame) return }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "Send", "(", "socket", "*", "zmq", ".", "Socket", ")", "(", "err", "error", ")", "{", "//fmt.Printf(\"Send to %s: %q\\n\", socket, kvmsg.frame)", "kvmsg", ".", "encode_props", "(", ")", "\n", "_", ",", "err", "=", "socket", ".", "SendMessage", "(", "kvmsg", ".", "frame", ")", "\n", "return", "\n", "}" ]
// Send key-value message to socket; any empty frames are sent as such.
[ "Send", "key", "-", "value", "message", "to", "socket", ";", "any", "empty", "frames", "are", "sent", "as", "such", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvmsg/kvmsg.go#L87-L92
train
pebbe/zmq4
examples/kvmsg/kvmsg.go
Dup
func (kvmsg *Kvmsg) Dup() (dup *Kvmsg) { dup = &Kvmsg{ present: make([]bool, kvmsg_FRAMES), frame: make([]string, kvmsg_FRAMES), props: make([]string, len(kvmsg.props)), } copy(dup.present, kvmsg.present) copy(dup.frame, kvmsg.frame) copy(dup.props, kvmsg.props) return }
go
func (kvmsg *Kvmsg) Dup() (dup *Kvmsg) { dup = &Kvmsg{ present: make([]bool, kvmsg_FRAMES), frame: make([]string, kvmsg_FRAMES), props: make([]string, len(kvmsg.props)), } copy(dup.present, kvmsg.present) copy(dup.frame, kvmsg.frame) copy(dup.props, kvmsg.props) return }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "Dup", "(", ")", "(", "dup", "*", "Kvmsg", ")", "{", "dup", "=", "&", "Kvmsg", "{", "present", ":", "make", "(", "[", "]", "bool", ",", "kvmsg_FRAMES", ")", ",", "frame", ":", "make", "(", "[", "]", "string", ",", "kvmsg_FRAMES", ")", ",", "props", ":", "make", "(", "[", "]", "string", ",", "len", "(", "kvmsg", ".", "props", ")", ")", ",", "}", "\n", "copy", "(", "dup", ".", "present", ",", "kvmsg", ".", "present", ")", "\n", "copy", "(", "dup", ".", "frame", ",", "kvmsg", ".", "frame", ")", "\n", "copy", "(", "dup", ".", "props", ",", "kvmsg", ".", "props", ")", "\n", "return", "\n", "}" ]
// The Dup method duplicates a kvmsg instance, returns the new instance.
[ "The", "Dup", "method", "duplicates", "a", "kvmsg", "instance", "returns", "the", "new", "instance", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvmsg/kvmsg.go#L95-L105
train
pebbe/zmq4
examples/kvmsg/kvmsg.go
SetUuid
func (kvmsg *Kvmsg) SetUuid() { kvmsg.frame[frame_UUID] = string(uuid.NewRandom()) // raw 16 bytes kvmsg.present[frame_UUID] = true }
go
func (kvmsg *Kvmsg) SetUuid() { kvmsg.frame[frame_UUID] = string(uuid.NewRandom()) // raw 16 bytes kvmsg.present[frame_UUID] = true }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "SetUuid", "(", ")", "{", "kvmsg", ".", "frame", "[", "frame_UUID", "]", "=", "string", "(", "uuid", ".", "NewRandom", "(", ")", ")", "// raw 16 bytes", "\n", "kvmsg", ".", "present", "[", "frame_UUID", "]", "=", "true", "\n\n", "}" ]
// Sets the UUID to a random generated value
[ "Sets", "the", "UUID", "to", "a", "random", "generated", "value" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvmsg/kvmsg.go#L187-L191
train
pebbe/zmq4
examples/kvmsg/kvmsg.go
GetProp
func (kvmsg *Kvmsg) GetProp(name string) (value string, err error) { if !kvmsg.present[frame_PROPS] { err = errors.New("No properties set") return } f := name + "=" for _, prop := range kvmsg.props { if strings.HasPrefix(prop, f) { value = prop[len(f):] return } } err = errors.New("Property not set") return }
go
func (kvmsg *Kvmsg) GetProp(name string) (value string, err error) { if !kvmsg.present[frame_PROPS] { err = errors.New("No properties set") return } f := name + "=" for _, prop := range kvmsg.props { if strings.HasPrefix(prop, f) { value = prop[len(f):] return } } err = errors.New("Property not set") return }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "GetProp", "(", "name", "string", ")", "(", "value", "string", ",", "err", "error", ")", "{", "if", "!", "kvmsg", ".", "present", "[", "frame_PROPS", "]", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "f", ":=", "name", "+", "\"", "\"", "\n", "for", "_", ",", "prop", ":=", "range", "kvmsg", ".", "props", "{", "if", "strings", ".", "HasPrefix", "(", "prop", ",", "f", ")", "{", "value", "=", "prop", "[", "len", "(", "f", ")", ":", "]", "\n", "return", "\n", "}", "\n", "}", "\n", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}" ]
// Get message property, return error if no such property is defined.
[ "Get", "message", "property", "return", "error", "if", "no", "such", "property", "is", "defined", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvmsg/kvmsg.go#L194-L208
train
pebbe/zmq4
examples/kvmsg/kvmsg.go
SetProp
func (kvmsg *Kvmsg) SetProp(name, value string) (err error) { if strings.Index(name, "=") >= 0 { err = errors.New("No '=' allowed in property name") return } p := name + "=" for i, prop := range kvmsg.props { if strings.HasPrefix(prop, p) { kvmsg.props = append(kvmsg.props[:i], kvmsg.props[i+1:]...) break } } kvmsg.props = append(kvmsg.props, name+"="+value) kvmsg.present[frame_PROPS] = true return }
go
func (kvmsg *Kvmsg) SetProp(name, value string) (err error) { if strings.Index(name, "=") >= 0 { err = errors.New("No '=' allowed in property name") return } p := name + "=" for i, prop := range kvmsg.props { if strings.HasPrefix(prop, p) { kvmsg.props = append(kvmsg.props[:i], kvmsg.props[i+1:]...) break } } kvmsg.props = append(kvmsg.props, name+"="+value) kvmsg.present[frame_PROPS] = true return }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "SetProp", "(", "name", ",", "value", "string", ")", "(", "err", "error", ")", "{", "if", "strings", ".", "Index", "(", "name", ",", "\"", "\"", ")", ">=", "0", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "p", ":=", "name", "+", "\"", "\"", "\n", "for", "i", ",", "prop", ":=", "range", "kvmsg", ".", "props", "{", "if", "strings", ".", "HasPrefix", "(", "prop", ",", "p", ")", "{", "kvmsg", ".", "props", "=", "append", "(", "kvmsg", ".", "props", "[", ":", "i", "]", ",", "kvmsg", ".", "props", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "kvmsg", ".", "props", "=", "append", "(", "kvmsg", ".", "props", ",", "name", "+", "\"", "\"", "+", "value", ")", "\n", "kvmsg", ".", "present", "[", "frame_PROPS", "]", "=", "true", "\n", "return", "\n", "}" ]
// Set message property. Property name cannot contain '='.
[ "Set", "message", "property", ".", "Property", "name", "cannot", "contain", "=", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvmsg/kvmsg.go#L211-L226
train
pebbe/zmq4
examples/kvmsg/kvmsg.go
Dump
func (kvmsg *Kvmsg) Dump() { size := kvmsg.Size() body, _ := kvmsg.GetBody() seq, _ := kvmsg.GetSequence() key, _ := kvmsg.GetKey() fmt.Fprintf(os.Stderr, "[seq:%v][key:%v][size:%v] ", seq, key, size) p := "[" for _, prop := range kvmsg.props { fmt.Fprint(os.Stderr, p, prop) p = ";" } if p == ";" { fmt.Fprint(os.Stderr, "]") } for char_nbr := 0; char_nbr < size; char_nbr++ { fmt.Fprintf(os.Stderr, "%02X", body[char_nbr]) } fmt.Fprintln(os.Stderr) }
go
func (kvmsg *Kvmsg) Dump() { size := kvmsg.Size() body, _ := kvmsg.GetBody() seq, _ := kvmsg.GetSequence() key, _ := kvmsg.GetKey() fmt.Fprintf(os.Stderr, "[seq:%v][key:%v][size:%v] ", seq, key, size) p := "[" for _, prop := range kvmsg.props { fmt.Fprint(os.Stderr, p, prop) p = ";" } if p == ";" { fmt.Fprint(os.Stderr, "]") } for char_nbr := 0; char_nbr < size; char_nbr++ { fmt.Fprintf(os.Stderr, "%02X", body[char_nbr]) } fmt.Fprintln(os.Stderr) }
[ "func", "(", "kvmsg", "*", "Kvmsg", ")", "Dump", "(", ")", "{", "size", ":=", "kvmsg", ".", "Size", "(", ")", "\n", "body", ",", "_", ":=", "kvmsg", ".", "GetBody", "(", ")", "\n", "seq", ",", "_", ":=", "kvmsg", ".", "GetSequence", "(", ")", "\n", "key", ",", "_", ":=", "kvmsg", ".", "GetKey", "(", ")", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "seq", ",", "key", ",", "size", ")", "\n", "p", ":=", "\"", "\"", "\n", "for", "_", ",", "prop", ":=", "range", "kvmsg", ".", "props", "{", "fmt", ".", "Fprint", "(", "os", ".", "Stderr", ",", "p", ",", "prop", ")", "\n", "p", "=", "\"", "\"", "\n", "}", "\n", "if", "p", "==", "\"", "\"", "{", "fmt", ".", "Fprint", "(", "os", ".", "Stderr", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "char_nbr", ":=", "0", ";", "char_nbr", "<", "size", ";", "char_nbr", "++", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "body", "[", "char_nbr", "]", ")", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ")", "\n", "}" ]
// The dump method extends the kvsimple implementation with support for // message properties.
[ "The", "dump", "method", "extends", "the", "kvsimple", "implementation", "with", "support", "for", "message", "properties", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/kvmsg/kvmsg.go#L242-L260
train
pebbe/zmq4
examples/lbbroker3.go
worker_task
func worker_task() { worker, _ := zmq.NewSocket(zmq.REQ) defer worker.Close() worker.Connect("ipc://backend.ipc") // Tell broker we're ready for work worker.SendMessage(WORKER_READY) // Process messages as they arrive for { msg, e := worker.RecvMessage(0) if e != nil { break // Interrupted } msg[len(msg)-1] = "OK" worker.SendMessage(msg) } }
go
func worker_task() { worker, _ := zmq.NewSocket(zmq.REQ) defer worker.Close() worker.Connect("ipc://backend.ipc") // Tell broker we're ready for work worker.SendMessage(WORKER_READY) // Process messages as they arrive for { msg, e := worker.RecvMessage(0) if e != nil { break // Interrupted } msg[len(msg)-1] = "OK" worker.SendMessage(msg) } }
[ "func", "worker_task", "(", ")", "{", "worker", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "REQ", ")", "\n", "defer", "worker", ".", "Close", "(", ")", "\n", "worker", ".", "Connect", "(", "\"", "\"", ")", "\n\n", "// Tell broker we're ready for work", "worker", ".", "SendMessage", "(", "WORKER_READY", ")", "\n\n", "// Process messages as they arrive", "for", "{", "msg", ",", "e", ":=", "worker", ".", "RecvMessage", "(", "0", ")", "\n", "if", "e", "!=", "nil", "{", "break", "// Interrupted", "\n", "}", "\n", "msg", "[", "len", "(", "msg", ")", "-", "1", "]", "=", "\"", "\"", "\n", "worker", ".", "SendMessage", "(", "msg", ")", "\n", "}", "\n", "}" ]
// Worker using REQ socket to do load-balancing //
[ "Worker", "using", "REQ", "socket", "to", "do", "load", "-", "balancing" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/lbbroker3.go#L43-L60
train
pebbe/zmq4
examples/lbbroker3.go
handle_backend
func handle_backend(lbbroker *lbbroker_t) error { // Use worker identity for load-balancing msg, err := lbbroker.backend.RecvMessage(0) if err != nil { return err } identity, msg := unwrap(msg) lbbroker.workers = append(lbbroker.workers, identity) // Enable reader on frontend if we went from 0 to 1 workers if len(lbbroker.workers) == 1 { lbbroker.reactor.AddSocket(lbbroker.frontend, zmq.POLLIN, func(e zmq.State) error { return handle_frontend(lbbroker) }) } // Forward message to client if it's not a READY if msg[0] != WORKER_READY { lbbroker.frontend.SendMessage(msg) } return nil }
go
func handle_backend(lbbroker *lbbroker_t) error { // Use worker identity for load-balancing msg, err := lbbroker.backend.RecvMessage(0) if err != nil { return err } identity, msg := unwrap(msg) lbbroker.workers = append(lbbroker.workers, identity) // Enable reader on frontend if we went from 0 to 1 workers if len(lbbroker.workers) == 1 { lbbroker.reactor.AddSocket(lbbroker.frontend, zmq.POLLIN, func(e zmq.State) error { return handle_frontend(lbbroker) }) } // Forward message to client if it's not a READY if msg[0] != WORKER_READY { lbbroker.frontend.SendMessage(msg) } return nil }
[ "func", "handle_backend", "(", "lbbroker", "*", "lbbroker_t", ")", "error", "{", "// Use worker identity for load-balancing", "msg", ",", "err", ":=", "lbbroker", ".", "backend", ".", "RecvMessage", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "identity", ",", "msg", ":=", "unwrap", "(", "msg", ")", "\n", "lbbroker", ".", "workers", "=", "append", "(", "lbbroker", ".", "workers", ",", "identity", ")", "\n\n", "// Enable reader on frontend if we went from 0 to 1 workers", "if", "len", "(", "lbbroker", ".", "workers", ")", "==", "1", "{", "lbbroker", ".", "reactor", ".", "AddSocket", "(", "lbbroker", ".", "frontend", ",", "zmq", ".", "POLLIN", ",", "func", "(", "e", "zmq", ".", "State", ")", "error", "{", "return", "handle_frontend", "(", "lbbroker", ")", "}", ")", "\n", "}", "\n\n", "// Forward message to client if it's not a READY", "if", "msg", "[", "0", "]", "!=", "WORKER_READY", "{", "lbbroker", ".", "frontend", ".", "SendMessage", "(", "msg", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Handle input from worker, on backend
[ "Handle", "input", "from", "worker", "on", "backend" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/lbbroker3.go#L93-L114
train
pebbe/zmq4
examples/mdbroker.go
Delete
func (worker *Worker) Delete(disconnect bool) { if disconnect { worker.Send(mdapi.MDPW_DISCONNECT, "", []string{}) } if worker.service != nil { worker.service.waiting = delWorker(worker.service.waiting, worker) } worker.broker.waiting = delWorker(worker.broker.waiting, worker) delete(worker.broker.workers, worker.id_string) }
go
func (worker *Worker) Delete(disconnect bool) { if disconnect { worker.Send(mdapi.MDPW_DISCONNECT, "", []string{}) } if worker.service != nil { worker.service.waiting = delWorker(worker.service.waiting, worker) } worker.broker.waiting = delWorker(worker.broker.waiting, worker) delete(worker.broker.workers, worker.id_string) }
[ "func", "(", "worker", "*", "Worker", ")", "Delete", "(", "disconnect", "bool", ")", "{", "if", "disconnect", "{", "worker", ".", "Send", "(", "mdapi", ".", "MDPW_DISCONNECT", ",", "\"", "\"", ",", "[", "]", "string", "{", "}", ")", "\n", "}", "\n\n", "if", "worker", ".", "service", "!=", "nil", "{", "worker", ".", "service", ".", "waiting", "=", "delWorker", "(", "worker", ".", "service", ".", "waiting", ",", "worker", ")", "\n", "}", "\n", "worker", ".", "broker", ".", "waiting", "=", "delWorker", "(", "worker", ".", "broker", ".", "waiting", ",", "worker", ")", "\n", "delete", "(", "worker", ".", "broker", ".", "workers", ",", "worker", ".", "id_string", ")", "\n", "}" ]
// The delete method deletes the current worker.
[ "The", "delete", "method", "deletes", "the", "current", "worker", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/mdbroker.go#L279-L289
train
pebbe/zmq4
examples/mdbroker.go
Waiting
func (worker *Worker) Waiting() { // Queue to broker and service waiting lists worker.broker.waiting = append(worker.broker.waiting, worker) worker.service.waiting = append(worker.service.waiting, worker) worker.expiry = time.Now().Add(HEARTBEAT_EXPIRY) worker.service.Dispatch([]string{}) }
go
func (worker *Worker) Waiting() { // Queue to broker and service waiting lists worker.broker.waiting = append(worker.broker.waiting, worker) worker.service.waiting = append(worker.service.waiting, worker) worker.expiry = time.Now().Add(HEARTBEAT_EXPIRY) worker.service.Dispatch([]string{}) }
[ "func", "(", "worker", "*", "Worker", ")", "Waiting", "(", ")", "{", "// Queue to broker and service waiting lists", "worker", ".", "broker", ".", "waiting", "=", "append", "(", "worker", ".", "broker", ".", "waiting", ",", "worker", ")", "\n", "worker", ".", "service", ".", "waiting", "=", "append", "(", "worker", ".", "service", ".", "waiting", ",", "worker", ")", "\n", "worker", ".", "expiry", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "HEARTBEAT_EXPIRY", ")", "\n", "worker", ".", "service", ".", "Dispatch", "(", "[", "]", "string", "{", "}", ")", "\n", "}" ]
// This worker is now waiting for work
[ "This", "worker", "is", "now", "waiting", "for", "work" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/mdbroker.go#L322-L328
train
pebbe/zmq4
examples/lbbroker.go
client_task
func client_task() { client, _ := zmq.NewSocket(zmq.REQ) defer client.Close() // set_id(client) // Set a printable identity client.Connect("ipc://frontend.ipc") // Send request, get reply client.Send("HELLO", 0) reply, _ := client.Recv(0) fmt.Println("Client:", reply) }
go
func client_task() { client, _ := zmq.NewSocket(zmq.REQ) defer client.Close() // set_id(client) // Set a printable identity client.Connect("ipc://frontend.ipc") // Send request, get reply client.Send("HELLO", 0) reply, _ := client.Recv(0) fmt.Println("Client:", reply) }
[ "func", "client_task", "(", ")", "{", "client", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "REQ", ")", "\n", "defer", "client", ".", "Close", "(", ")", "\n", "// set_id(client) // Set a printable identity", "client", ".", "Connect", "(", "\"", "\"", ")", "\n\n", "// Send request, get reply", "client", ".", "Send", "(", "\"", "\"", ",", "0", ")", "\n", "reply", ",", "_", ":=", "client", ".", "Recv", "(", "0", ")", "\n", "fmt", ".", "Println", "(", "\"", "\"", ",", "reply", ")", "\n", "}" ]
// Basic request-reply client using REQ socket // Since Go Send and Recv can handle 0MQ binary identities we // don't need printable text identity to allow routing.
[ "Basic", "request", "-", "reply", "client", "using", "REQ", "socket", "Since", "Go", "Send", "and", "Recv", "can", "handle", "0MQ", "binary", "identities", "we", "don", "t", "need", "printable", "text", "identity", "to", "allow", "routing", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/lbbroker.go#L25-L35
train
pebbe/zmq4
examples/lbbroker.go
worker_task
func worker_task() { worker, _ := zmq.NewSocket(zmq.REQ) defer worker.Close() // set_id(worker) worker.Connect("ipc://backend.ipc") // Tell broker we're ready for work worker.Send("READY", 0) for { // Read and save all frames until we get an empty frame // In this example there is only 1 but it could be more identity, _ := worker.Recv(0) empty, _ := worker.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } // Get request, send reply request, _ := worker.Recv(0) fmt.Println("Worker:", request) worker.Send(identity, zmq.SNDMORE) worker.Send("", zmq.SNDMORE) worker.Send("OK", 0) } }
go
func worker_task() { worker, _ := zmq.NewSocket(zmq.REQ) defer worker.Close() // set_id(worker) worker.Connect("ipc://backend.ipc") // Tell broker we're ready for work worker.Send("READY", 0) for { // Read and save all frames until we get an empty frame // In this example there is only 1 but it could be more identity, _ := worker.Recv(0) empty, _ := worker.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } // Get request, send reply request, _ := worker.Recv(0) fmt.Println("Worker:", request) worker.Send(identity, zmq.SNDMORE) worker.Send("", zmq.SNDMORE) worker.Send("OK", 0) } }
[ "func", "worker_task", "(", ")", "{", "worker", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "REQ", ")", "\n", "defer", "worker", ".", "Close", "(", ")", "\n", "// set_id(worker)", "worker", ".", "Connect", "(", "\"", "\"", ")", "\n\n", "// Tell broker we're ready for work", "worker", ".", "Send", "(", "\"", "\"", ",", "0", ")", "\n\n", "for", "{", "// Read and save all frames until we get an empty frame", "// In this example there is only 1 but it could be more", "identity", ",", "_", ":=", "worker", ".", "Recv", "(", "0", ")", "\n", "empty", ",", "_", ":=", "worker", ".", "Recv", "(", "0", ")", "\n", "if", "empty", "!=", "\"", "\"", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "empty", ")", ")", "\n", "}", "\n\n", "// Get request, send reply", "request", ",", "_", ":=", "worker", ".", "Recv", "(", "0", ")", "\n", "fmt", ".", "Println", "(", "\"", "\"", ",", "request", ")", "\n\n", "worker", ".", "Send", "(", "identity", ",", "zmq", ".", "SNDMORE", ")", "\n", "worker", ".", "Send", "(", "\"", "\"", ",", "zmq", ".", "SNDMORE", ")", "\n", "worker", ".", "Send", "(", "\"", "\"", ",", "0", ")", "\n", "}", "\n", "}" ]
// While this example runs in a single process, that is just to make // it easier to start and stop the example. // This is the worker task, using a REQ socket to do load-balancing. // Since Go Send and Recv can handle 0MQ binary identities we // don't need printable text identity to allow routing.
[ "While", "this", "example", "runs", "in", "a", "single", "process", "that", "is", "just", "to", "make", "it", "easier", "to", "start", "and", "stop", "the", "example", ".", "This", "is", "the", "worker", "task", "using", "a", "REQ", "socket", "to", "do", "load", "-", "balancing", ".", "Since", "Go", "Send", "and", "Recv", "can", "handle", "0MQ", "binary", "identities", "we", "don", "t", "need", "printable", "text", "identity", "to", "allow", "routing", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/lbbroker.go#L43-L69
train
pebbe/zmq4
examples/lbbroker.go
main
func main() { // Prepare our sockets frontend, _ := zmq.NewSocket(zmq.ROUTER) backend, _ := zmq.NewSocket(zmq.ROUTER) defer frontend.Close() defer backend.Close() frontend.Bind("ipc://frontend.ipc") backend.Bind("ipc://backend.ipc") client_nbr := 0 for ; client_nbr < NBR_CLIENTS; client_nbr++ { go client_task() } for worker_nbr := 0; worker_nbr < NBR_WORKERS; worker_nbr++ { go worker_task() } // Here is the main loop for the least-recently-used queue. It has two // sockets; a frontend for clients and a backend for workers. It polls // the backend in all cases, and polls the frontend only when there are // one or more workers ready. This is a neat way to use 0MQ's own queues // to hold messages we're not ready to process yet. When we get a client // reply, we pop the next available worker, and send the request to it, // including the originating client identity. When a worker replies, we // re-queue that worker, and we forward the reply to the original client, // using the reply envelope. // Queue of available workers worker_queue := make([]string, 0, 10) poller1 := zmq.NewPoller() poller1.Add(backend, zmq.POLLIN) poller2 := zmq.NewPoller() poller2.Add(backend, zmq.POLLIN) poller2.Add(frontend, zmq.POLLIN) for client_nbr > 0 { // Poll frontend only if we have available workers var sockets []zmq.Polled if len(worker_queue) > 0 { sockets, _ = poller2.Poll(-1) } else { sockets, _ = poller1.Poll(-1) } for _, socket := range sockets { switch socket.Socket { case backend: // Handle worker activity on backend // Queue worker identity for load-balancing worker_id, _ := backend.Recv(0) if !(len(worker_queue) < NBR_WORKERS) { panic("!(len(worker_queue) < NBR_WORKERS)") } worker_queue = append(worker_queue, worker_id) // Second frame is empty empty, _ := backend.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } // Third frame is READY or else a client reply identity client_id, _ := backend.Recv(0) // If client reply, send rest back to frontend if client_id != "READY" { empty, _ := backend.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } reply, _ := backend.Recv(0) frontend.Send(client_id, zmq.SNDMORE) frontend.Send("", zmq.SNDMORE) frontend.Send(reply, 0) client_nbr-- } case frontend: // Here is how we handle a client request: // Now get next client request, route to last-used worker // Client request is [identity][empty][request] client_id, _ := frontend.Recv(0) empty, _ := frontend.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } request, _ := frontend.Recv(0) backend.Send(worker_queue[0], zmq.SNDMORE) backend.Send("", zmq.SNDMORE) backend.Send(client_id, zmq.SNDMORE) backend.Send("", zmq.SNDMORE) backend.Send(request, 0) // Dequeue and drop the next worker identity worker_queue = worker_queue[1:] } } } time.Sleep(100 * time.Millisecond) }
go
func main() { // Prepare our sockets frontend, _ := zmq.NewSocket(zmq.ROUTER) backend, _ := zmq.NewSocket(zmq.ROUTER) defer frontend.Close() defer backend.Close() frontend.Bind("ipc://frontend.ipc") backend.Bind("ipc://backend.ipc") client_nbr := 0 for ; client_nbr < NBR_CLIENTS; client_nbr++ { go client_task() } for worker_nbr := 0; worker_nbr < NBR_WORKERS; worker_nbr++ { go worker_task() } // Here is the main loop for the least-recently-used queue. It has two // sockets; a frontend for clients and a backend for workers. It polls // the backend in all cases, and polls the frontend only when there are // one or more workers ready. This is a neat way to use 0MQ's own queues // to hold messages we're not ready to process yet. When we get a client // reply, we pop the next available worker, and send the request to it, // including the originating client identity. When a worker replies, we // re-queue that worker, and we forward the reply to the original client, // using the reply envelope. // Queue of available workers worker_queue := make([]string, 0, 10) poller1 := zmq.NewPoller() poller1.Add(backend, zmq.POLLIN) poller2 := zmq.NewPoller() poller2.Add(backend, zmq.POLLIN) poller2.Add(frontend, zmq.POLLIN) for client_nbr > 0 { // Poll frontend only if we have available workers var sockets []zmq.Polled if len(worker_queue) > 0 { sockets, _ = poller2.Poll(-1) } else { sockets, _ = poller1.Poll(-1) } for _, socket := range sockets { switch socket.Socket { case backend: // Handle worker activity on backend // Queue worker identity for load-balancing worker_id, _ := backend.Recv(0) if !(len(worker_queue) < NBR_WORKERS) { panic("!(len(worker_queue) < NBR_WORKERS)") } worker_queue = append(worker_queue, worker_id) // Second frame is empty empty, _ := backend.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } // Third frame is READY or else a client reply identity client_id, _ := backend.Recv(0) // If client reply, send rest back to frontend if client_id != "READY" { empty, _ := backend.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } reply, _ := backend.Recv(0) frontend.Send(client_id, zmq.SNDMORE) frontend.Send("", zmq.SNDMORE) frontend.Send(reply, 0) client_nbr-- } case frontend: // Here is how we handle a client request: // Now get next client request, route to last-used worker // Client request is [identity][empty][request] client_id, _ := frontend.Recv(0) empty, _ := frontend.Recv(0) if empty != "" { panic(fmt.Sprintf("empty is not \"\": %q", empty)) } request, _ := frontend.Recv(0) backend.Send(worker_queue[0], zmq.SNDMORE) backend.Send("", zmq.SNDMORE) backend.Send(client_id, zmq.SNDMORE) backend.Send("", zmq.SNDMORE) backend.Send(request, 0) // Dequeue and drop the next worker identity worker_queue = worker_queue[1:] } } } time.Sleep(100 * time.Millisecond) }
[ "func", "main", "(", ")", "{", "// Prepare our sockets", "frontend", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "ROUTER", ")", "\n", "backend", ",", "_", ":=", "zmq", ".", "NewSocket", "(", "zmq", ".", "ROUTER", ")", "\n", "defer", "frontend", ".", "Close", "(", ")", "\n", "defer", "backend", ".", "Close", "(", ")", "\n", "frontend", ".", "Bind", "(", "\"", "\"", ")", "\n", "backend", ".", "Bind", "(", "\"", "\"", ")", "\n\n", "client_nbr", ":=", "0", "\n", "for", ";", "client_nbr", "<", "NBR_CLIENTS", ";", "client_nbr", "++", "{", "go", "client_task", "(", ")", "\n", "}", "\n", "for", "worker_nbr", ":=", "0", ";", "worker_nbr", "<", "NBR_WORKERS", ";", "worker_nbr", "++", "{", "go", "worker_task", "(", ")", "\n", "}", "\n\n", "// Here is the main loop for the least-recently-used queue. It has two", "// sockets; a frontend for clients and a backend for workers. It polls", "// the backend in all cases, and polls the frontend only when there are", "// one or more workers ready. This is a neat way to use 0MQ's own queues", "// to hold messages we're not ready to process yet. When we get a client", "// reply, we pop the next available worker, and send the request to it,", "// including the originating client identity. When a worker replies, we", "// re-queue that worker, and we forward the reply to the original client,", "// using the reply envelope.", "// Queue of available workers", "worker_queue", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "10", ")", "\n\n", "poller1", ":=", "zmq", ".", "NewPoller", "(", ")", "\n", "poller1", ".", "Add", "(", "backend", ",", "zmq", ".", "POLLIN", ")", "\n", "poller2", ":=", "zmq", ".", "NewPoller", "(", ")", "\n", "poller2", ".", "Add", "(", "backend", ",", "zmq", ".", "POLLIN", ")", "\n", "poller2", ".", "Add", "(", "frontend", ",", "zmq", ".", "POLLIN", ")", "\n\n", "for", "client_nbr", ">", "0", "{", "// Poll frontend only if we have available workers", "var", "sockets", "[", "]", "zmq", ".", "Polled", "\n", "if", "len", "(", "worker_queue", ")", ">", "0", "{", "sockets", ",", "_", "=", "poller2", ".", "Poll", "(", "-", "1", ")", "\n", "}", "else", "{", "sockets", ",", "_", "=", "poller1", ".", "Poll", "(", "-", "1", ")", "\n", "}", "\n", "for", "_", ",", "socket", ":=", "range", "sockets", "{", "switch", "socket", ".", "Socket", "{", "case", "backend", ":", "// Handle worker activity on backend", "// Queue worker identity for load-balancing", "worker_id", ",", "_", ":=", "backend", ".", "Recv", "(", "0", ")", "\n", "if", "!", "(", "len", "(", "worker_queue", ")", "<", "NBR_WORKERS", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "worker_queue", "=", "append", "(", "worker_queue", ",", "worker_id", ")", "\n\n", "// Second frame is empty", "empty", ",", "_", ":=", "backend", ".", "Recv", "(", "0", ")", "\n", "if", "empty", "!=", "\"", "\"", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "empty", ")", ")", "\n", "}", "\n\n", "// Third frame is READY or else a client reply identity", "client_id", ",", "_", ":=", "backend", ".", "Recv", "(", "0", ")", "\n\n", "// If client reply, send rest back to frontend", "if", "client_id", "!=", "\"", "\"", "{", "empty", ",", "_", ":=", "backend", ".", "Recv", "(", "0", ")", "\n", "if", "empty", "!=", "\"", "\"", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "empty", ")", ")", "\n", "}", "\n", "reply", ",", "_", ":=", "backend", ".", "Recv", "(", "0", ")", "\n", "frontend", ".", "Send", "(", "client_id", ",", "zmq", ".", "SNDMORE", ")", "\n", "frontend", ".", "Send", "(", "\"", "\"", ",", "zmq", ".", "SNDMORE", ")", "\n", "frontend", ".", "Send", "(", "reply", ",", "0", ")", "\n", "client_nbr", "--", "\n", "}", "\n\n", "case", "frontend", ":", "// Here is how we handle a client request:", "// Now get next client request, route to last-used worker", "// Client request is [identity][empty][request]", "client_id", ",", "_", ":=", "frontend", ".", "Recv", "(", "0", ")", "\n", "empty", ",", "_", ":=", "frontend", ".", "Recv", "(", "0", ")", "\n", "if", "empty", "!=", "\"", "\"", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "empty", ")", ")", "\n", "}", "\n", "request", ",", "_", ":=", "frontend", ".", "Recv", "(", "0", ")", "\n\n", "backend", ".", "Send", "(", "worker_queue", "[", "0", "]", ",", "zmq", ".", "SNDMORE", ")", "\n", "backend", ".", "Send", "(", "\"", "\"", ",", "zmq", ".", "SNDMORE", ")", "\n", "backend", ".", "Send", "(", "client_id", ",", "zmq", ".", "SNDMORE", ")", "\n", "backend", ".", "Send", "(", "\"", "\"", ",", "zmq", ".", "SNDMORE", ")", "\n", "backend", ".", "Send", "(", "request", ",", "0", ")", "\n\n", "// Dequeue and drop the next worker identity", "worker_queue", "=", "worker_queue", "[", "1", ":", "]", "\n\n", "}", "\n", "}", "\n", "}", "\n\n", "time", ".", "Sleep", "(", "100", "*", "time", ".", "Millisecond", ")", "\n", "}" ]
// This is the main task. It starts the clients and workers, and then // routes requests between the two layers. Workers signal READY when // they start; after that we treat them as ready when they reply with // a response back to a client. The load-balancing data structure is // just a queue of next available workers.
[ "This", "is", "the", "main", "task", ".", "It", "starts", "the", "clients", "and", "workers", "and", "then", "routes", "requests", "between", "the", "two", "layers", ".", "Workers", "signal", "READY", "when", "they", "start", ";", "after", "that", "we", "treat", "them", "as", "ready", "when", "they", "reply", "with", "a", "response", "back", "to", "a", "client", ".", "The", "load", "-", "balancing", "data", "structure", "is", "just", "a", "queue", "of", "next", "available", "workers", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/lbbroker.go#L77-L181
train
pebbe/zmq4
examples/bstar/bstar.go
recv_state
func (bstar *Bstar) recv_state() (err error) { msg, err := bstar.statesub.RecvMessage(0) if err == nil { e, _ := strconv.Atoi(msg[0]) bstar.event = event_t(e) } return bstar.execute_fsm() }
go
func (bstar *Bstar) recv_state() (err error) { msg, err := bstar.statesub.RecvMessage(0) if err == nil { e, _ := strconv.Atoi(msg[0]) bstar.event = event_t(e) } return bstar.execute_fsm() }
[ "func", "(", "bstar", "*", "Bstar", ")", "recv_state", "(", ")", "(", "err", "error", ")", "{", "msg", ",", "err", ":=", "bstar", ".", "statesub", ".", "RecvMessage", "(", "0", ")", "\n", "if", "err", "==", "nil", "{", "e", ",", "_", ":=", "strconv", ".", "Atoi", "(", "msg", "[", "0", "]", ")", "\n", "bstar", ".", "event", "=", "event_t", "(", "e", ")", "\n", "}", "\n", "return", "bstar", ".", "execute_fsm", "(", ")", "\n", "}" ]
// Receive state from peer, execute finite state machine
[ "Receive", "state", "from", "peer", "execute", "finite", "state", "machine" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/bstar/bstar.go#L170-L177
train
pebbe/zmq4
examples/bstar/bstar.go
voter_ready
func (bstar *Bstar) voter_ready(socket *zmq.Socket) error { // If server can accept input now, call appl handler bstar.event = client_REQUEST err := bstar.execute_fsm() if err == nil { bstar.voter_fn(socket) } else { // Destroy waiting message, no-one to read it socket.RecvMessage(0) } return nil }
go
func (bstar *Bstar) voter_ready(socket *zmq.Socket) error { // If server can accept input now, call appl handler bstar.event = client_REQUEST err := bstar.execute_fsm() if err == nil { bstar.voter_fn(socket) } else { // Destroy waiting message, no-one to read it socket.RecvMessage(0) } return nil }
[ "func", "(", "bstar", "*", "Bstar", ")", "voter_ready", "(", "socket", "*", "zmq", ".", "Socket", ")", "error", "{", "// If server can accept input now, call appl handler", "bstar", ".", "event", "=", "client_REQUEST", "\n", "err", ":=", "bstar", ".", "execute_fsm", "(", ")", "\n", "if", "err", "==", "nil", "{", "bstar", ".", "voter_fn", "(", "socket", ")", "\n", "}", "else", "{", "// Destroy waiting message, no-one to read it", "socket", ".", "RecvMessage", "(", "0", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Application wants to speak to us, see if it's possible
[ "Application", "wants", "to", "speak", "to", "us", "see", "if", "it", "s", "possible" ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/examples/bstar/bstar.go#L180-L191
train
pebbe/zmq4
reactor.go
RemoveSocket
func (r *Reactor) RemoveSocket(soc *Socket) { if _, ok := r.sockets[soc]; ok { delete(r.sockets, soc) // rebuild poller r.p = NewPoller() for s, props := range r.sockets { r.p.Add(s, props.e) } } }
go
func (r *Reactor) RemoveSocket(soc *Socket) { if _, ok := r.sockets[soc]; ok { delete(r.sockets, soc) // rebuild poller r.p = NewPoller() for s, props := range r.sockets { r.p.Add(s, props.e) } } }
[ "func", "(", "r", "*", "Reactor", ")", "RemoveSocket", "(", "soc", "*", "Socket", ")", "{", "if", "_", ",", "ok", ":=", "r", ".", "sockets", "[", "soc", "]", ";", "ok", "{", "delete", "(", "r", ".", "sockets", ",", "soc", ")", "\n", "// rebuild poller", "r", ".", "p", "=", "NewPoller", "(", ")", "\n", "for", "s", ",", "props", ":=", "range", "r", ".", "sockets", "{", "r", ".", "p", ".", "Add", "(", "s", ",", "props", ".", "e", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Remove a socket handler from the reactor.
[ "Remove", "a", "socket", "handler", "from", "the", "reactor", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/reactor.go#L62-L71
train
pebbe/zmq4
reactor.go
AddChannel
func (r *Reactor) AddChannel(ch <-chan interface{}, limit int, handler func(interface{}) error) (id uint64) { r.idx++ id = r.idx r.channels[id] = &reactor_channel{ch: ch, f: handler, limit: limit} return }
go
func (r *Reactor) AddChannel(ch <-chan interface{}, limit int, handler func(interface{}) error) (id uint64) { r.idx++ id = r.idx r.channels[id] = &reactor_channel{ch: ch, f: handler, limit: limit} return }
[ "func", "(", "r", "*", "Reactor", ")", "AddChannel", "(", "ch", "<-", "chan", "interface", "{", "}", ",", "limit", "int", ",", "handler", "func", "(", "interface", "{", "}", ")", "error", ")", "(", "id", "uint64", ")", "{", "r", ".", "idx", "++", "\n", "id", "=", "r", ".", "idx", "\n", "r", ".", "channels", "[", "id", "]", "=", "&", "reactor_channel", "{", "ch", ":", "ch", ",", "f", ":", "handler", ",", "limit", ":", "limit", "}", "\n", "return", "\n", "}" ]
// Add channel handler to the reactor. // // Returns id of added handler, that can be used later to remove it. // // If limit is positive, at most this many items will be handled in each run through the main loop, // otherwise it will process as many items as possible. // // The handler function receives the value received from the channel.
[ "Add", "channel", "handler", "to", "the", "reactor", ".", "Returns", "id", "of", "added", "handler", "that", "can", "be", "used", "later", "to", "remove", "it", ".", "If", "limit", "is", "positive", "at", "most", "this", "many", "items", "will", "be", "handled", "in", "each", "run", "through", "the", "main", "loop", "otherwise", "it", "will", "process", "as", "many", "items", "as", "possible", ".", "The", "handler", "function", "receives", "the", "value", "received", "from", "the", "channel", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/reactor.go#L81-L86
train
pebbe/zmq4
reactor.go
RemoveChannel
func (r *Reactor) RemoveChannel(id uint64) { r.remove = append(r.remove, id) }
go
func (r *Reactor) RemoveChannel(id uint64) { r.remove = append(r.remove, id) }
[ "func", "(", "r", "*", "Reactor", ")", "RemoveChannel", "(", "id", "uint64", ")", "{", "r", ".", "remove", "=", "append", "(", "r", ".", "remove", ",", "id", ")", "\n", "}" ]
// Remove a channel from the reactor. // // Closed channels are removed automatically.
[ "Remove", "a", "channel", "from", "the", "reactor", ".", "Closed", "channels", "are", "removed", "automatically", "." ]
7a493a642e7acbd03045d4f5fe9516908a62f86f
https://github.com/pebbe/zmq4/blob/7a493a642e7acbd03045d4f5fe9516908a62f86f/reactor.go#L107-L109
train
kardianos/osext
osext.go
ExecutableFolder
func ExecutableFolder() (string, error) { p, err := Executable() if err != nil { return "", err } return filepath.Dir(p), nil }
go
func ExecutableFolder() (string, error) { p, err := Executable() if err != nil { return "", err } return filepath.Dir(p), nil }
[ "func", "ExecutableFolder", "(", ")", "(", "string", ",", "error", ")", "{", "p", ",", "err", ":=", "Executable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "filepath", ".", "Dir", "(", "p", ")", ",", "nil", "\n", "}" ]
// Returns same path as Executable, returns just the folder // path. Excludes the executable name and any trailing slash.
[ "Returns", "same", "path", "as", "Executable", "returns", "just", "the", "folder", "path", ".", "Excludes", "the", "executable", "name", "and", "any", "trailing", "slash", "." ]
2bc1f35cddc0cc527b4bc3dce8578fc2a6c11384
https://github.com/kardianos/osext/blob/2bc1f35cddc0cc527b4bc3dce8578fc2a6c11384/osext.go#L26-L33
train
cloudfoundry/bosh-cli
stemcell/mocks/mocks.go
NewMockCloudStemcell
func NewMockCloudStemcell(ctrl *gomock.Controller) *MockCloudStemcell { mock := &MockCloudStemcell{ctrl: ctrl} mock.recorder = &MockCloudStemcellMockRecorder{mock} return mock }
go
func NewMockCloudStemcell(ctrl *gomock.Controller) *MockCloudStemcell { mock := &MockCloudStemcell{ctrl: ctrl} mock.recorder = &MockCloudStemcellMockRecorder{mock} return mock }
[ "func", "NewMockCloudStemcell", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockCloudStemcell", "{", "mock", ":=", "&", "MockCloudStemcell", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockCloudStemcellMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockCloudStemcell creates a new mock instance
[ "NewMockCloudStemcell", "creates", "a", "new", "mock", "instance" ]
0ee5b2abedb27e521dc6e70719023e7b382cab79
https://github.com/cloudfoundry/bosh-cli/blob/0ee5b2abedb27e521dc6e70719023e7b382cab79/stemcell/mocks/mocks.go#L26-L30
train