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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
koding/kite | kontrol/kontrol.go | registerSelf | func (k *Kontrol) registerSelf() {
value := &kontrolprotocol.RegisterValue{
URL: k.Kite.Config.KontrolURL,
}
// change if the user wants something different
if k.RegisterURL != "" {
value.URL = k.RegisterURL
}
keyPair, err := k.KeyPair()
if err != nil {
if err != errNoSelfKeyPair {
k.log.Error("%s", e... | go | func (k *Kontrol) registerSelf() {
value := &kontrolprotocol.RegisterValue{
URL: k.Kite.Config.KontrolURL,
}
// change if the user wants something different
if k.RegisterURL != "" {
value.URL = k.RegisterURL
}
keyPair, err := k.KeyPair()
if err != nil {
if err != errNoSelfKeyPair {
k.log.Error("%s", e... | [
"func",
"(",
"k",
"*",
"Kontrol",
")",
"registerSelf",
"(",
")",
"{",
"value",
":=",
"&",
"kontrolprotocol",
".",
"RegisterValue",
"{",
"URL",
":",
"k",
".",
"Kite",
".",
"Config",
".",
"KontrolURL",
",",
"}",
"\n\n",
"// change if the user wants something d... | // registerSelf adds Kontrol itself to the storage as a kite. | [
"registerSelf",
"adds",
"Kontrol",
"itself",
"to",
"the",
"storage",
"as",
"a",
"kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kontrol.go#L390-L451 | train |
koding/kite | kontrol/kontrol.go | KeyPair | func (k *Kontrol) KeyPair() (pair *KeyPair, err error) {
if k.selfKeyPair != nil {
return k.selfKeyPair, nil
}
kiteKey := k.Kite.KiteKey()
if kiteKey == "" || len(k.lastPublic) == 0 {
return nil, errNoSelfKeyPair
}
keyIndex := -1
me := new(multiError)
for i := range k.lastPublic {
ri := len(k.lastPub... | go | func (k *Kontrol) KeyPair() (pair *KeyPair, err error) {
if k.selfKeyPair != nil {
return k.selfKeyPair, nil
}
kiteKey := k.Kite.KiteKey()
if kiteKey == "" || len(k.lastPublic) == 0 {
return nil, errNoSelfKeyPair
}
keyIndex := -1
me := new(multiError)
for i := range k.lastPublic {
ri := len(k.lastPub... | [
"func",
"(",
"k",
"*",
"Kontrol",
")",
"KeyPair",
"(",
")",
"(",
"pair",
"*",
"KeyPair",
",",
"err",
"error",
")",
"{",
"if",
"k",
".",
"selfKeyPair",
"!=",
"nil",
"{",
"return",
"k",
".",
"selfKeyPair",
",",
"nil",
"\n",
"}",
"\n\n",
"kiteKey",
... | // KeyPair looks up a key pair that was used to sign Kontrol's kite key.
//
// The value is cached on first call of the function. | [
"KeyPair",
"looks",
"up",
"a",
"key",
"pair",
"that",
"was",
"used",
"to",
"sign",
"Kontrol",
"s",
"kite",
"key",
".",
"The",
"value",
"is",
"cached",
"on",
"first",
"call",
"of",
"the",
"function",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kontrol.go#L456-L502 | train |
koding/kite | kontrol/kontrol.go | cacheToken | func (k *Kontrol) cacheToken(key, signed string) {
if ct, ok := k.tokenCache[key]; ok {
ct.timer.Stop()
}
k.tokenCache[key] = cachedToken{
signed: signed,
timer: time.AfterFunc(k.tokenTTL()-k.tokenLeeway(), func() {
k.tokenCacheMu.Lock()
delete(k.tokenCache, key)
k.tokenCacheMu.Unlock()
}),
}
} | go | func (k *Kontrol) cacheToken(key, signed string) {
if ct, ok := k.tokenCache[key]; ok {
ct.timer.Stop()
}
k.tokenCache[key] = cachedToken{
signed: signed,
timer: time.AfterFunc(k.tokenTTL()-k.tokenLeeway(), func() {
k.tokenCacheMu.Lock()
delete(k.tokenCache, key)
k.tokenCacheMu.Unlock()
}),
}
} | [
"func",
"(",
"k",
"*",
"Kontrol",
")",
"cacheToken",
"(",
"key",
",",
"signed",
"string",
")",
"{",
"if",
"ct",
",",
"ok",
":=",
"k",
".",
"tokenCache",
"[",
"key",
"]",
";",
"ok",
"{",
"ct",
".",
"timer",
".",
"Stop",
"(",
")",
"\n",
"}",
"\... | // cacheToken cached the signed token under the given key.
//
// It also ensures the token is invalidated after its expiration time.
//
// If the token was already exists in the cache, it will be
// overwritten with a new value. | [
"cacheToken",
"cached",
"the",
"signed",
"token",
"under",
"the",
"given",
"key",
".",
"It",
"also",
"ensures",
"the",
"token",
"is",
"invalidated",
"after",
"its",
"expiration",
"time",
".",
"If",
"the",
"token",
"was",
"already",
"exists",
"in",
"the",
"... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/kontrol.go#L543-L556 | train |
koding/kite | dnode/partial.go | UnmarshalJSON | func (p *Partial) UnmarshalJSON(data []byte) error {
if p == nil {
return errors.New("json.Partial: UnmarshalJSON on nil pointer")
}
p.Raw = make([]byte, len(data))
copy(p.Raw, data)
return nil
} | go | func (p *Partial) UnmarshalJSON(data []byte) error {
if p == nil {
return errors.New("json.Partial: UnmarshalJSON on nil pointer")
}
p.Raw = make([]byte, len(data))
copy(p.Raw, data)
return nil
} | [
"func",
"(",
"p",
"*",
"Partial",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"p",
".",
"Raw",
"=",
"make",
"(",
... | // UnmarshalJSON puts the data into Partial.Raw. | [
"UnmarshalJSON",
"puts",
"the",
"data",
"into",
"Partial",
".",
"Raw",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L22-L30 | train |
koding/kite | dnode/partial.go | SliceOfLength | func (p *Partial) SliceOfLength(length int) (a []*Partial, err error) {
err = p.Unmarshal(&a)
if err != nil {
return
}
if len(a) != length {
err = errors.New("Invalid array length")
}
return
} | go | func (p *Partial) SliceOfLength(length int) (a []*Partial, err error) {
err = p.Unmarshal(&a)
if err != nil {
return
}
if len(a) != length {
err = errors.New("Invalid array length")
}
return
} | [
"func",
"(",
"p",
"*",
"Partial",
")",
"SliceOfLength",
"(",
"length",
"int",
")",
"(",
"a",
"[",
"]",
"*",
"Partial",
",",
"err",
"error",
")",
"{",
"err",
"=",
"p",
".",
"Unmarshal",
"(",
"&",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // SliceOfLength is a helper method to unmarshal a JSON Array with specified length. | [
"SliceOfLength",
"is",
"a",
"helper",
"method",
"to",
"unmarshal",
"a",
"JSON",
"Array",
"with",
"specified",
"length",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L70-L81 | train |
koding/kite | dnode/partial.go | Map | func (p *Partial) Map() (m map[string]*Partial, err error) {
err = p.Unmarshal(&m)
return
} | go | func (p *Partial) Map() (m map[string]*Partial, err error) {
err = p.Unmarshal(&m)
return
} | [
"func",
"(",
"p",
"*",
"Partial",
")",
"Map",
"(",
")",
"(",
"m",
"map",
"[",
"string",
"]",
"*",
"Partial",
",",
"err",
"error",
")",
"{",
"err",
"=",
"p",
".",
"Unmarshal",
"(",
"&",
"m",
")",
"\n",
"return",
"\n",
"}"
] | // Map is a helper method to unmarshal to a JSON Object. | [
"Map",
"is",
"a",
"helper",
"method",
"to",
"unmarshal",
"to",
"a",
"JSON",
"Object",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L84-L87 | train |
koding/kite | dnode/partial.go | String | func (p *Partial) String() (s string, err error) {
err = p.Unmarshal(&s)
return
} | go | func (p *Partial) String() (s string, err error) {
err = p.Unmarshal(&s)
return
} | [
"func",
"(",
"p",
"*",
"Partial",
")",
"String",
"(",
")",
"(",
"s",
"string",
",",
"err",
"error",
")",
"{",
"err",
"=",
"p",
".",
"Unmarshal",
"(",
"&",
"s",
")",
"\n",
"return",
"\n",
"}"
] | // String is a helper to unmarshal a JSON String. | [
"String",
"is",
"a",
"helper",
"to",
"unmarshal",
"a",
"JSON",
"String",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L90-L93 | train |
koding/kite | dnode/partial.go | Float64 | func (p *Partial) Float64() (f float64, err error) {
err = p.Unmarshal(&f)
return
} | go | func (p *Partial) Float64() (f float64, err error) {
err = p.Unmarshal(&f)
return
} | [
"func",
"(",
"p",
"*",
"Partial",
")",
"Float64",
"(",
")",
"(",
"f",
"float64",
",",
"err",
"error",
")",
"{",
"err",
"=",
"p",
".",
"Unmarshal",
"(",
"&",
"f",
")",
"\n",
"return",
"\n",
"}"
] | // Float64 is a helper to unmarshal a JSON Number. | [
"Float64",
"is",
"a",
"helper",
"to",
"unmarshal",
"a",
"JSON",
"Number",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L96-L99 | train |
koding/kite | dnode/partial.go | Bool | func (p *Partial) Bool() (b bool, err error) {
err = p.Unmarshal(&b)
return
} | go | func (p *Partial) Bool() (b bool, err error) {
err = p.Unmarshal(&b)
return
} | [
"func",
"(",
"p",
"*",
"Partial",
")",
"Bool",
"(",
")",
"(",
"b",
"bool",
",",
"err",
"error",
")",
"{",
"err",
"=",
"p",
".",
"Unmarshal",
"(",
"&",
"b",
")",
"\n",
"return",
"\n",
"}"
] | // Bool is a helper to unmarshal a JSON Boolean. | [
"Bool",
"is",
"a",
"helper",
"to",
"unmarshal",
"a",
"JSON",
"Boolean",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L102-L105 | train |
koding/kite | dnode/partial.go | Function | func (p *Partial) Function() (f Function, err error) {
err = p.Unmarshal(&f)
return
} | go | func (p *Partial) Function() (f Function, err error) {
err = p.Unmarshal(&f)
return
} | [
"func",
"(",
"p",
"*",
"Partial",
")",
"Function",
"(",
")",
"(",
"f",
"Function",
",",
"err",
"error",
")",
"{",
"err",
"=",
"p",
".",
"Unmarshal",
"(",
"&",
"f",
")",
"\n",
"return",
"\n",
"}"
] | // Function is a helper to unmarshal a callback function. | [
"Function",
"is",
"a",
"helper",
"to",
"unmarshal",
"a",
"callback",
"function",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/partial.go#L108-L111 | train |
koding/kite | kontrol/etcd.go | validateKiteKey | func validateKiteKey(k *protocol.Kite) error {
fields := k.Query().Fields()
// Validate fields.
for k, v := range fields {
if v == "" {
return fmt.Errorf("Empty Kite field: %s", k)
}
if strings.ContainsRune(v, '/') {
return fmt.Errorf("Field \"%s\" must not contain '/'", k)
}
}
return nil
} | go | func validateKiteKey(k *protocol.Kite) error {
fields := k.Query().Fields()
// Validate fields.
for k, v := range fields {
if v == "" {
return fmt.Errorf("Empty Kite field: %s", k)
}
if strings.ContainsRune(v, '/') {
return fmt.Errorf("Field \"%s\" must not contain '/'", k)
}
}
return nil
} | [
"func",
"validateKiteKey",
"(",
"k",
"*",
"protocol",
".",
"Kite",
")",
"error",
"{",
"fields",
":=",
"k",
".",
"Query",
"(",
")",
".",
"Fields",
"(",
")",
"\n\n",
"// Validate fields.",
"for",
"k",
",",
"v",
":=",
"range",
"fields",
"{",
"if",
"v",
... | // validateKiteKey returns a string representing the kite uniquely
// that is suitable to use as a key for etcd. | [
"validateKiteKey",
"returns",
"a",
"string",
"representing",
"the",
"kite",
"uniquely",
"that",
"is",
"suitable",
"to",
"use",
"as",
"a",
"key",
"for",
"etcd",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/etcd.go#L300-L314 | train |
koding/kite | kontrol/etcd.go | onlyIDQuery | func onlyIDQuery(q *protocol.KontrolQuery) bool {
fields := q.Fields()
// check if any other key exist, if yes return a false
for _, k := range keyOrder {
v := fields[k]
if k != "id" && v != "" {
return false
}
}
// now all other keys are empty, check finally for our ID
if fields["id"] != "" {
return... | go | func onlyIDQuery(q *protocol.KontrolQuery) bool {
fields := q.Fields()
// check if any other key exist, if yes return a false
for _, k := range keyOrder {
v := fields[k]
if k != "id" && v != "" {
return false
}
}
// now all other keys are empty, check finally for our ID
if fields["id"] != "" {
return... | [
"func",
"onlyIDQuery",
"(",
"q",
"*",
"protocol",
".",
"KontrolQuery",
")",
"bool",
"{",
"fields",
":=",
"q",
".",
"Fields",
"(",
")",
"\n\n",
"// check if any other key exist, if yes return a false",
"for",
"_",
",",
"k",
":=",
"range",
"keyOrder",
"{",
"v",
... | // onlyIDQuery returns true if the query contains only a non-empty ID and all
// others keys are empty | [
"onlyIDQuery",
"returns",
"true",
"if",
"the",
"query",
"contains",
"only",
"a",
"non",
"-",
"empty",
"ID",
"and",
"all",
"others",
"keys",
"are",
"empty"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/etcd.go#L318-L336 | train |
koding/kite | kontrol/etcd.go | GetQueryKey | func GetQueryKey(q *protocol.KontrolQuery) (string, error) {
fields := q.Fields()
if q.Username == "" {
return "", errors.New("Empty username field")
}
// Validate query and build key.
path := "/"
empty := false // encountered with empty field?
empytField := "" // for error log
// http://golang.org/doc/... | go | func GetQueryKey(q *protocol.KontrolQuery) (string, error) {
fields := q.Fields()
if q.Username == "" {
return "", errors.New("Empty username field")
}
// Validate query and build key.
path := "/"
empty := false // encountered with empty field?
empytField := "" // for error log
// http://golang.org/doc/... | [
"func",
"GetQueryKey",
"(",
"q",
"*",
"protocol",
".",
"KontrolQuery",
")",
"(",
"string",
",",
"error",
")",
"{",
"fields",
":=",
"q",
".",
"Fields",
"(",
")",
"\n\n",
"if",
"q",
".",
"Username",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
... | // getQueryKey returns the etcd key for the query. | [
"getQueryKey",
"returns",
"the",
"etcd",
"key",
"for",
"the",
"query",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/etcd.go#L339-L372 | train |
koding/kite | kite.go | New | func New(name, version string) *Kite {
return NewWithConfig(name, version, config.New())
} | go | func New(name, version string) *Kite {
return NewWithConfig(name, version, config.New())
} | [
"func",
"New",
"(",
"name",
",",
"version",
"string",
")",
"*",
"Kite",
"{",
"return",
"NewWithConfig",
"(",
"name",
",",
"version",
",",
"config",
".",
"New",
"(",
")",
")",
"\n",
"}"
] | // New creates, initializes and then returns a new Kite instance.
//
// Version must be in 3-digit semantic form.
//
// Name is important that it's also used to be searched by others. | [
"New",
"creates",
"initializes",
"and",
"then",
"returns",
"a",
"new",
"Kite",
"instance",
".",
"Version",
"must",
"be",
"in",
"3",
"-",
"digit",
"semantic",
"form",
".",
"Name",
"is",
"important",
"that",
"it",
"s",
"also",
"used",
"to",
"be",
"searched... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L163-L165 | train |
koding/kite | kite.go | NewWithConfig | func NewWithConfig(name, version string, cfg *config.Config) *Kite {
if name == "" {
panic("kite: name cannot be empty")
}
if digits := strings.Split(version, "."); len(digits) != 3 {
panic("kite: version must be 3-digits semantic version")
}
kiteID := uuid.Must(uuid.NewV4())
l, setlevel := newLogger(name)... | go | func NewWithConfig(name, version string, cfg *config.Config) *Kite {
if name == "" {
panic("kite: name cannot be empty")
}
if digits := strings.Split(version, "."); len(digits) != 3 {
panic("kite: version must be 3-digits semantic version")
}
kiteID := uuid.Must(uuid.NewV4())
l, setlevel := newLogger(name)... | [
"func",
"NewWithConfig",
"(",
"name",
",",
"version",
"string",
",",
"cfg",
"*",
"config",
".",
"Config",
")",
"*",
"Kite",
"{",
"if",
"name",
"==",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"digits",
":=",
"strings",... | // NewWithConfig builds a new kite value for the given configuration. | [
"NewWithConfig",
"builds",
"a",
"new",
"kite",
"value",
"for",
"the",
"given",
"configuration",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L168-L229 | train |
koding/kite | kite.go | Kite | func (k *Kite) Kite() *protocol.Kite {
return &protocol.Kite{
Username: k.Config.Username,
Environment: k.Config.Environment,
Name: k.name,
Version: k.version,
Region: k.Config.Region,
Hostname: hostname,
ID: k.Id,
}
} | go | func (k *Kite) Kite() *protocol.Kite {
return &protocol.Kite{
Username: k.Config.Username,
Environment: k.Config.Environment,
Name: k.name,
Version: k.version,
Region: k.Config.Region,
Hostname: hostname,
ID: k.Id,
}
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"Kite",
"(",
")",
"*",
"protocol",
".",
"Kite",
"{",
"return",
"&",
"protocol",
".",
"Kite",
"{",
"Username",
":",
"k",
".",
"Config",
".",
"Username",
",",
"Environment",
":",
"k",
".",
"Config",
".",
"Environme... | // Kite returns the definition of the kite. | [
"Kite",
"returns",
"the",
"definition",
"of",
"the",
"kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L232-L242 | train |
koding/kite | kite.go | KiteKey | func (k *Kite) KiteKey() string {
k.configMu.RLock()
defer k.configMu.RUnlock()
return k.Config.KiteKey
} | go | func (k *Kite) KiteKey() string {
k.configMu.RLock()
defer k.configMu.RUnlock()
return k.Config.KiteKey
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"KiteKey",
"(",
")",
"string",
"{",
"k",
".",
"configMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"k",
".",
"configMu",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"k",
".",
"Config",
".",
"KiteKey",
"\n",
"}"
] | // KiteKey gives a kite key used to authenticate to kontrol and other kites. | [
"KiteKey",
"gives",
"a",
"kite",
"key",
"used",
"to",
"authenticate",
"to",
"kontrol",
"and",
"other",
"kites",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L245-L250 | train |
koding/kite | kite.go | KontrolKey | func (k *Kite) KontrolKey() *rsa.PublicKey {
k.configMu.RLock()
defer k.configMu.RUnlock()
return k.kontrolKey
} | go | func (k *Kite) KontrolKey() *rsa.PublicKey {
k.configMu.RLock()
defer k.configMu.RUnlock()
return k.kontrolKey
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"KontrolKey",
"(",
")",
"*",
"rsa",
".",
"PublicKey",
"{",
"k",
".",
"configMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"k",
".",
"configMu",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"k",
".",
"kontrolKey",
... | // KontrolKey gives a Kontrol's public key.
//
// The value is taken form kite key's kontrolKey claim. | [
"KontrolKey",
"gives",
"a",
"Kontrol",
"s",
"public",
"key",
".",
"The",
"value",
"is",
"taken",
"form",
"kite",
"key",
"s",
"kontrolKey",
"claim",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L255-L260 | train |
koding/kite | kite.go | HandleHTTP | func (k *Kite) HandleHTTP(pattern string, handler http.Handler) {
k.muxer.Handle(pattern, handler)
} | go | func (k *Kite) HandleHTTP(pattern string, handler http.Handler) {
k.muxer.Handle(pattern, handler)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"HandleHTTP",
"(",
"pattern",
"string",
",",
"handler",
"http",
".",
"Handler",
")",
"{",
"k",
".",
"muxer",
".",
"Handle",
"(",
"pattern",
",",
"handler",
")",
"\n",
"}"
] | // HandleHTTP registers the HTTP handler for the given pattern into the
// underlying HTTP muxer. | [
"HandleHTTP",
"registers",
"the",
"HTTP",
"handler",
"for",
"the",
"given",
"pattern",
"into",
"the",
"underlying",
"HTTP",
"muxer",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L264-L266 | train |
koding/kite | kite.go | HandleHTTPFunc | func (k *Kite) HandleHTTPFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
k.muxer.HandleFunc(pattern, handler)
} | go | func (k *Kite) HandleHTTPFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
k.muxer.HandleFunc(pattern, handler)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"HandleHTTPFunc",
"(",
"pattern",
"string",
",",
"handler",
"func",
"(",
"http",
".",
"ResponseWriter",
",",
"*",
"http",
".",
"Request",
")",
")",
"{",
"k",
".",
"muxer",
".",
"HandleFunc",
"(",
"pattern",
",",
"h... | // HandleHTTPFunc registers the HTTP handler for the given pattern into the
// underlying HTTP muxer. | [
"HandleHTTPFunc",
"registers",
"the",
"HTTP",
"handler",
"for",
"the",
"given",
"pattern",
"into",
"the",
"underlying",
"HTTP",
"muxer",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L270-L272 | train |
koding/kite | kite.go | ServeHTTP | func (k *Kite) ServeHTTP(w http.ResponseWriter, req *http.Request) {
k.muxer.ServeHTTP(w, req)
} | go | func (k *Kite) ServeHTTP(w http.ResponseWriter, req *http.Request) {
k.muxer.ServeHTTP(w, req)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"k",
".",
"muxer",
".",
"ServeHTTP",
"(",
"w",
",",
"req",
")",
"\n",
"}"
] | // ServeHTTP helps Kite to satisfy the http.Handler interface. So kite can be
// used as a standard http server. | [
"ServeHTTP",
"helps",
"Kite",
"to",
"satisfy",
"the",
"http",
".",
"Handler",
"interface",
".",
"So",
"kite",
"can",
"be",
"used",
"as",
"a",
"standard",
"http",
"server",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L276-L278 | train |
koding/kite | kite.go | OnConnect | func (k *Kite) OnConnect(handler func(*Client)) {
k.handlersMu.Lock()
k.onConnectHandlers = append(k.onConnectHandlers, handler)
k.handlersMu.Unlock()
} | go | func (k *Kite) OnConnect(handler func(*Client)) {
k.handlersMu.Lock()
k.onConnectHandlers = append(k.onConnectHandlers, handler)
k.handlersMu.Unlock()
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"OnConnect",
"(",
"handler",
"func",
"(",
"*",
"Client",
")",
")",
"{",
"k",
".",
"handlersMu",
".",
"Lock",
"(",
")",
"\n",
"k",
".",
"onConnectHandlers",
"=",
"append",
"(",
"k",
".",
"onConnectHandlers",
",",
... | // OnConnect registers a callbacks which is called when a Kite connects
// to the k Kite. | [
"OnConnect",
"registers",
"a",
"callbacks",
"which",
"is",
"called",
"when",
"a",
"Kite",
"connects",
"to",
"the",
"k",
"Kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L304-L308 | train |
koding/kite | kite.go | OnFirstRequest | func (k *Kite) OnFirstRequest(handler func(*Client)) {
k.handlersMu.Lock()
k.onFirstRequestHandlers = append(k.onFirstRequestHandlers, handler)
k.handlersMu.Unlock()
} | go | func (k *Kite) OnFirstRequest(handler func(*Client)) {
k.handlersMu.Lock()
k.onFirstRequestHandlers = append(k.onFirstRequestHandlers, handler)
k.handlersMu.Unlock()
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"OnFirstRequest",
"(",
"handler",
"func",
"(",
"*",
"Client",
")",
")",
"{",
"k",
".",
"handlersMu",
".",
"Lock",
"(",
")",
"\n",
"k",
".",
"onFirstRequestHandlers",
"=",
"append",
"(",
"k",
".",
"onFirstRequestHandl... | // OnFirstRequest registers a function to run when we receive first request
// from other Kite. | [
"OnFirstRequest",
"registers",
"a",
"function",
"to",
"run",
"when",
"we",
"receive",
"first",
"request",
"from",
"other",
"Kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L312-L316 | train |
koding/kite | kite.go | OnDisconnect | func (k *Kite) OnDisconnect(handler func(*Client)) {
k.handlersMu.Lock()
k.onDisconnectHandlers = append(k.onDisconnectHandlers, handler)
k.handlersMu.Unlock()
} | go | func (k *Kite) OnDisconnect(handler func(*Client)) {
k.handlersMu.Lock()
k.onDisconnectHandlers = append(k.onDisconnectHandlers, handler)
k.handlersMu.Unlock()
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"OnDisconnect",
"(",
"handler",
"func",
"(",
"*",
"Client",
")",
")",
"{",
"k",
".",
"handlersMu",
".",
"Lock",
"(",
")",
"\n",
"k",
".",
"onDisconnectHandlers",
"=",
"append",
"(",
"k",
".",
"onDisconnectHandlers",
... | // OnDisconnect registers a function to run when a connected Kite is disconnected. | [
"OnDisconnect",
"registers",
"a",
"function",
"to",
"run",
"when",
"a",
"connected",
"Kite",
"is",
"disconnected",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L319-L323 | train |
koding/kite | kite.go | OnRegister | func (k *Kite) OnRegister(handler func(*protocol.RegisterResult)) {
k.handlersMu.Lock()
k.onRegisterHandlers = append(k.onRegisterHandlers, handler)
k.handlersMu.Unlock()
} | go | func (k *Kite) OnRegister(handler func(*protocol.RegisterResult)) {
k.handlersMu.Lock()
k.onRegisterHandlers = append(k.onRegisterHandlers, handler)
k.handlersMu.Unlock()
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"OnRegister",
"(",
"handler",
"func",
"(",
"*",
"protocol",
".",
"RegisterResult",
")",
")",
"{",
"k",
".",
"handlersMu",
".",
"Lock",
"(",
")",
"\n",
"k",
".",
"onRegisterHandlers",
"=",
"append",
"(",
"k",
".",
... | // OnRegister registers a callback which is called when a Kite registers
// to a Kontrol. | [
"OnRegister",
"registers",
"a",
"callback",
"which",
"is",
"called",
"when",
"a",
"Kite",
"registers",
"to",
"a",
"Kontrol",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L327-L331 | train |
koding/kite | kite.go | RSAKey | func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) {
k.verifyOnce.Do(k.verifyInit)
kontrolKey := k.KontrolKey()
if kontrolKey == nil {
panic("kontrol key is not set in config")
}
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, errors.New("invalid signing method")
}
claims, o... | go | func (k *Kite) RSAKey(token *jwt.Token) (interface{}, error) {
k.verifyOnce.Do(k.verifyInit)
kontrolKey := k.KontrolKey()
if kontrolKey == nil {
panic("kontrol key is not set in config")
}
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, errors.New("invalid signing method")
}
claims, o... | [
"func",
"(",
"k",
"*",
"Kite",
")",
"RSAKey",
"(",
"token",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"k",
".",
"verifyOnce",
".",
"Do",
"(",
"k",
".",
"verifyInit",
")",
"\n\n",
"kontrolKey",
":=",
"k",
... | // RSAKey returns the corresponding public key for the issuer of the token.
// It is called by jwt-go package when validating the signature in the token. | [
"RSAKey",
"returns",
"the",
"corresponding",
"public",
"key",
"for",
"the",
"issuer",
"of",
"the",
"token",
".",
"It",
"is",
"called",
"by",
"jwt",
"-",
"go",
"package",
"when",
"validating",
"the",
"signature",
"in",
"the",
"token",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L422-L445 | train |
koding/kite | kite.go | Error | func (err *ErrClose) Error() string {
if len(err.Errs) == 1 {
return err.Errs[0].Error()
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "The following kites failed to close:\n\n")
for i, e := range err.Errs {
if e == nil {
continue
}
fmt.Fprintf(&buf, "\t[%d] %s\n", i, e)
}
return buf.String()
} | go | func (err *ErrClose) Error() string {
if len(err.Errs) == 1 {
return err.Errs[0].Error()
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "The following kites failed to close:\n\n")
for i, e := range err.Errs {
if e == nil {
continue
}
fmt.Fprintf(&buf, "\t[%d] %s\n", i, e)
}
return buf.String()
} | [
"func",
"(",
"err",
"*",
"ErrClose",
")",
"Error",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"err",
".",
"Errs",
")",
"==",
"1",
"{",
"return",
"err",
".",
"Errs",
"[",
"0",
"]",
".",
"Error",
"(",
")",
"\n",
"}",
"\n\n",
"var",
"buf",
"byte... | // Error implements the built-in error interface. | [
"Error",
"implements",
"the",
"built",
"-",
"in",
"error",
"interface",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kite.go#L456-L474 | train |
koding/kite | kontrol/postgres.go | RunCleaner | func (p *Postgres) RunCleaner(interval, expire time.Duration) {
cleanFunc := func() {
affectedRows, err := p.CleanExpiredRows(expire)
if err != nil {
p.Log.Warning("postgres: cleaning old rows failed: %s", err)
} else if affectedRows != 0 {
p.Log.Debug("postgres: cleaned up %d rows", affectedRows)
}
}
... | go | func (p *Postgres) RunCleaner(interval, expire time.Duration) {
cleanFunc := func() {
affectedRows, err := p.CleanExpiredRows(expire)
if err != nil {
p.Log.Warning("postgres: cleaning old rows failed: %s", err)
} else if affectedRows != 0 {
p.Log.Debug("postgres: cleaned up %d rows", affectedRows)
}
}
... | [
"func",
"(",
"p",
"*",
"Postgres",
")",
"RunCleaner",
"(",
"interval",
",",
"expire",
"time",
".",
"Duration",
")",
"{",
"cleanFunc",
":=",
"func",
"(",
")",
"{",
"affectedRows",
",",
"err",
":=",
"p",
".",
"CleanExpiredRows",
"(",
"expire",
")",
"\n",... | // RunCleaner deletes every "interval" duration rows which are older than
// "expire" duration based on the "updated_at" field. For more info check
// CleanExpireRows which is used to delete old rows. | [
"RunCleaner",
"deletes",
"every",
"interval",
"duration",
"rows",
"which",
"are",
"older",
"than",
"expire",
"duration",
"based",
"on",
"the",
"updated_at",
"field",
".",
"For",
"more",
"info",
"check",
"CleanExpireRows",
"which",
"is",
"used",
"to",
"delete",
... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L93-L106 | train |
koding/kite | kontrol/postgres.go | CleanExpiredRows | func (p *Postgres) CleanExpiredRows(expire time.Duration) (int64, error) {
// See: http://stackoverflow.com/questions/14465727/how-to-insert-things-like-now-interval-2-minutes-into-php-pdo-query
// basically by passing an integer to INTERVAL is not possible, we need to
// cast it. However there is a more simpler way... | go | func (p *Postgres) CleanExpiredRows(expire time.Duration) (int64, error) {
// See: http://stackoverflow.com/questions/14465727/how-to-insert-things-like-now-interval-2-minutes-into-php-pdo-query
// basically by passing an integer to INTERVAL is not possible, we need to
// cast it. However there is a more simpler way... | [
"func",
"(",
"p",
"*",
"Postgres",
")",
"CleanExpiredRows",
"(",
"expire",
"time",
".",
"Duration",
")",
"(",
"int64",
",",
"error",
")",
"{",
"// See: http://stackoverflow.com/questions/14465727/how-to-insert-things-like-now-interval-2-minutes-into-php-pdo-query",
"// basica... | // CleanExpiredRows deletes rows that are at least "expire" duration old. So if
// say an expire duration of 10 second is given, it will delete all rows that
// were updated 10 seconds ago | [
"CleanExpiredRows",
"deletes",
"rows",
"that",
"are",
"at",
"least",
"expire",
"duration",
"old",
".",
"So",
"if",
"say",
"an",
"expire",
"duration",
"of",
"10",
"second",
"is",
"given",
"it",
"will",
"delete",
"all",
"rows",
"that",
"were",
"updated",
"10... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L111-L125 | train |
koding/kite | kontrol/postgres.go | selectQuery | func selectQuery(query *protocol.KontrolQuery) (string, []interface{}, error) {
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
kites := psql.Select("*").From("kite.kite")
fields := query.Fields()
andQuery := sq.And{}
// we stop for the first empty value
for _, key := range keyOrder {
v := fields[key... | go | func selectQuery(query *protocol.KontrolQuery) (string, []interface{}, error) {
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
kites := psql.Select("*").From("kite.kite")
fields := query.Fields()
andQuery := sq.And{}
// we stop for the first empty value
for _, key := range keyOrder {
v := fields[key... | [
"func",
"selectQuery",
"(",
"query",
"*",
"protocol",
".",
"KontrolQuery",
")",
"(",
"string",
",",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"psql",
":=",
"sq",
".",
"StatementBuilder",
".",
"PlaceholderFormat",
"(",
"sq",
".",
"Dollar",
... | // selectQuery returns a SQL query for the given query | [
"selectQuery",
"returns",
"a",
"SQL",
"query",
"for",
"the",
"given",
"query"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L334-L361 | train |
koding/kite | kontrol/postgres.go | insertKiteQuery | func insertKiteQuery(kiteProt *protocol.Kite, url, keyId string) (string, []interface{}, error) {
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
kiteValues := kiteProt.Values()
values := make([]interface{}, len(kiteValues))
for i, kiteVal := range kiteValues {
values[i] = kiteVal
}
values = append(... | go | func insertKiteQuery(kiteProt *protocol.Kite, url, keyId string) (string, []interface{}, error) {
psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
kiteValues := kiteProt.Values()
values := make([]interface{}, len(kiteValues))
for i, kiteVal := range kiteValues {
values[i] = kiteVal
}
values = append(... | [
"func",
"insertKiteQuery",
"(",
"kiteProt",
"*",
"protocol",
".",
"Kite",
",",
"url",
",",
"keyId",
"string",
")",
"(",
"string",
",",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"psql",
":=",
"sq",
".",
"StatementBuilder",
".",
"Placehold... | // inseryKiteQuery inserts the given kite, url and key to the kite.kite table | [
"inseryKiteQuery",
"inserts",
"the",
"given",
"kite",
"url",
"and",
"key",
"to",
"the",
"kite",
".",
"kite",
"table"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kontrol/postgres.go#L364-L388 | train |
koding/kite | logger_unix.go | SetupSignalHandler | func (k *Kite) SetupSignalHandler() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGUSR2)
go func() {
for s := range c {
k.Log.Info("Got signal: %s", s)
if debugMode {
// toogle back to old settings.
k.Log.Info("Disabling debug mode")
if k.SetLogLevel == nil {
k.Log.Error("SetLo... | go | func (k *Kite) SetupSignalHandler() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGUSR2)
go func() {
for s := range c {
k.Log.Info("Got signal: %s", s)
if debugMode {
// toogle back to old settings.
k.Log.Info("Disabling debug mode")
if k.SetLogLevel == nil {
k.Log.Error("SetLo... | [
"func",
"(",
"k",
"*",
"Kite",
")",
"SetupSignalHandler",
"(",
")",
"{",
"c",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n\n",
"signal",
".",
"Notify",
"(",
"c",
",",
"syscall",
".",
"SIGUSR2",
")",
"\n",
"go",
"func",
"(",
... | // SetupSignalHandler listens to signals and toggles the log level to DEBUG
// mode when it received a SIGUSR2 signal. Another SIGUSR2 toggles the log
// level back to the old level. | [
"SetupSignalHandler",
"listens",
"to",
"signals",
"and",
"toggles",
"the",
"log",
"level",
"to",
"DEBUG",
"mode",
"when",
"it",
"received",
"a",
"SIGUSR2",
"signal",
".",
"Another",
"SIGUSR2",
"toggles",
"the",
"log",
"level",
"back",
"to",
"the",
"old",
"le... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/logger_unix.go#L14-L44 | train |
koding/kite | sockjsclient/xhr.go | DialXHR | func DialXHR(uri string, cfg *config.Config) (*XHRSession, error) {
// following /server_id/session_id should always be the same for every session
serverID := threeDigits()
sessionID := utils.RandomString(20)
sessionURL := uri + "/" + serverID + "/" + sessionID
// start the initial session handshake
sessionResp,... | go | func DialXHR(uri string, cfg *config.Config) (*XHRSession, error) {
// following /server_id/session_id should always be the same for every session
serverID := threeDigits()
sessionID := utils.RandomString(20)
sessionURL := uri + "/" + serverID + "/" + sessionID
// start the initial session handshake
sessionResp,... | [
"func",
"DialXHR",
"(",
"uri",
"string",
",",
"cfg",
"*",
"config",
".",
"Config",
")",
"(",
"*",
"XHRSession",
",",
"error",
")",
"{",
"// following /server_id/session_id should always be the same for every session",
"serverID",
":=",
"threeDigits",
"(",
")",
"\n",... | // DialXHR establishes a SockJS session over a XHR connection.
//
// Requires cfg.XHR to be a valid client. | [
"DialXHR",
"establishes",
"a",
"SockJS",
"session",
"over",
"a",
"XHR",
"connection",
".",
"Requires",
"cfg",
".",
"XHR",
"to",
"be",
"a",
"valid",
"client",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/sockjsclient/xhr.go#L49-L84 | train |
koding/kite | handlers.go | ServeKite | func (w *webRTCHandler) ServeKite(r *Request) (interface{}, error) {
var args protocol.WebRTCSignalMessage
if err := r.Args.One().Unmarshal(&args); err != nil {
return nil, fmt.Errorf("invalid query: %s", err)
}
args.Src = r.Client.ID
w.registerSrc(r.Client)
dst, err := w.getDst(args.Dst)
if err != nil {
... | go | func (w *webRTCHandler) ServeKite(r *Request) (interface{}, error) {
var args protocol.WebRTCSignalMessage
if err := r.Args.One().Unmarshal(&args); err != nil {
return nil, fmt.Errorf("invalid query: %s", err)
}
args.Src = r.Client.ID
w.registerSrc(r.Client)
dst, err := w.getDst(args.Dst)
if err != nil {
... | [
"func",
"(",
"w",
"*",
"webRTCHandler",
")",
"ServeKite",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"args",
"protocol",
".",
"WebRTCSignalMessage",
"\n\n",
"if",
"err",
":=",
"r",
".",
"Args",
".",
"One... | // ServeKite implements Hander interface. | [
"ServeKite",
"implements",
"Hander",
"interface",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L64-L81 | train |
koding/kite | handlers.go | handleLog | func (k *Kite) handleLog(r *Request) (interface{}, error) {
msg, err := r.Args.One().String()
if err != nil {
return nil, err
}
k.Log.Info("%s: %s", r.Client.Name, msg)
return nil, nil
} | go | func (k *Kite) handleLog(r *Request) (interface{}, error) {
msg, err := r.Args.One().String()
if err != nil {
return nil, err
}
k.Log.Info("%s: %s", r.Client.Name, msg)
return nil, nil
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"handleLog",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"msg",
",",
"err",
":=",
"r",
".",
"Args",
".",
"One",
"(",
")",
".",
"String",
"(",
")",
"\n",
"if",
"err",
... | // handleLog prints a log message to stderr. | [
"handleLog",
"prints",
"a",
"log",
"message",
"to",
"stderr",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L107-L116 | train |
koding/kite | handlers.go | handlePrint | func handlePrint(r *Request) (interface{}, error) {
return fmt.Print(r.Args.One().MustString())
} | go | func handlePrint(r *Request) (interface{}, error) {
return fmt.Print(r.Args.One().MustString())
} | [
"func",
"handlePrint",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"fmt",
".",
"Print",
"(",
"r",
".",
"Args",
".",
"One",
"(",
")",
".",
"MustString",
"(",
")",
")",
"\n",
"}"
] | // handlePrint prints a message to stdout. | [
"handlePrint",
"prints",
"a",
"message",
"to",
"stdout",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L124-L126 | train |
koding/kite | handlers.go | handlePrompt | func handlePrompt(r *Request) (interface{}, error) {
fmt.Print(r.Args.One().MustString())
var s string
_, err := fmt.Scanln(&s)
return s, err
} | go | func handlePrompt(r *Request) (interface{}, error) {
fmt.Print(r.Args.One().MustString())
var s string
_, err := fmt.Scanln(&s)
return s, err
} | [
"func",
"handlePrompt",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"fmt",
".",
"Print",
"(",
"r",
".",
"Args",
".",
"One",
"(",
")",
".",
"MustString",
"(",
")",
")",
"\n",
"var",
"s",
"string",
"\n",
"_"... | // handlePrompt asks user a single line input. | [
"handlePrompt",
"asks",
"user",
"a",
"single",
"line",
"input",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L129-L134 | train |
koding/kite | handlers.go | handleGetPass | func handleGetPass(r *Request) (interface{}, error) {
fmt.Print(r.Args.One().MustString())
data, err := terminal.ReadPassword(int(os.Stdin.Fd())) // stdin
fmt.Println()
if err != nil {
return nil, err
}
return string(data), nil
} | go | func handleGetPass(r *Request) (interface{}, error) {
fmt.Print(r.Args.One().MustString())
data, err := terminal.ReadPassword(int(os.Stdin.Fd())) // stdin
fmt.Println()
if err != nil {
return nil, err
}
return string(data), nil
} | [
"func",
"handleGetPass",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"fmt",
".",
"Print",
"(",
"r",
".",
"Args",
".",
"One",
"(",
")",
".",
"MustString",
"(",
")",
")",
"\n",
"data",
",",
"err",
":=",
"ter... | // handleGetPass reads a line of input from a terminal without local echo. | [
"handleGetPass",
"reads",
"a",
"line",
"of",
"input",
"from",
"a",
"terminal",
"without",
"local",
"echo",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L137-L145 | train |
koding/kite | handlers.go | handleNotifyDarwin | func handleNotifyDarwin(r *Request) (interface{}, error) {
args := r.Args.MustSliceOfLength(3)
cmd := exec.Command("osascript", "-e", fmt.Sprintf("display notification \"%s\" with title \"%s\" subtitle \"%s\"",
args[1].MustString(), args[2].MustString(), args[0].MustString()))
return nil, cmd.Start()
} | go | func handleNotifyDarwin(r *Request) (interface{}, error) {
args := r.Args.MustSliceOfLength(3)
cmd := exec.Command("osascript", "-e", fmt.Sprintf("display notification \"%s\" with title \"%s\" subtitle \"%s\"",
args[1].MustString(), args[2].MustString(), args[0].MustString()))
return nil, cmd.Start()
} | [
"func",
"handleNotifyDarwin",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"args",
":=",
"r",
".",
"Args",
".",
"MustSliceOfLength",
"(",
"3",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",... | // handleNotifyDarwin displays a desktop notification on OS X. | [
"handleNotifyDarwin",
"displays",
"a",
"desktop",
"notification",
"on",
"OS",
"X",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L148-L153 | train |
koding/kite | handlers.go | handleTunnel | func handleTunnel(r *Request) (interface{}, error) {
var args struct {
URL string
}
r.Args.One().MustUnmarshal(&args)
parsed, err := url.Parse(args.URL)
if err != nil {
return nil, err
}
requestHeader := http.Header{}
requestHeader.Add("Origin", "http://"+parsed.Host)
remoteConn, _, err := websocket.Def... | go | func handleTunnel(r *Request) (interface{}, error) {
var args struct {
URL string
}
r.Args.One().MustUnmarshal(&args)
parsed, err := url.Parse(args.URL)
if err != nil {
return nil, err
}
requestHeader := http.Header{}
requestHeader.Add("Origin", "http://"+parsed.Host)
remoteConn, _, err := websocket.Def... | [
"func",
"handleTunnel",
"(",
"r",
"*",
"Request",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"args",
"struct",
"{",
"URL",
"string",
"\n",
"}",
"\n",
"r",
".",
"Args",
".",
"One",
"(",
")",
".",
"MustUnmarshal",
"(",
"&",
"ar... | // handleTunnel opens two websockets, one to proxy kite and one to itself,
// then it copies the message between them. | [
"handleTunnel",
"opens",
"two",
"websockets",
"one",
"to",
"proxy",
"kite",
"and",
"one",
"to",
"itself",
"then",
"it",
"copies",
"the",
"message",
"between",
"them",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/handlers.go#L157-L180 | train |
koding/kite | tokenrenewer.go | parse | func (t *TokenRenewer) parse(tokenString string) error {
claims := &kitekey.KiteClaims{}
_, err := jwt.ParseWithClaims(tokenString, claims, t.localKite.RSAKey)
if err != nil {
valErr, ok := err.(*jwt.ValidationError)
if !ok {
return err
}
// do noy return for ValidationErrorSignatureValid. This is becau... | go | func (t *TokenRenewer) parse(tokenString string) error {
claims := &kitekey.KiteClaims{}
_, err := jwt.ParseWithClaims(tokenString, claims, t.localKite.RSAKey)
if err != nil {
valErr, ok := err.(*jwt.ValidationError)
if !ok {
return err
}
// do noy return for ValidationErrorSignatureValid. This is becau... | [
"func",
"(",
"t",
"*",
"TokenRenewer",
")",
"parse",
"(",
"tokenString",
"string",
")",
"error",
"{",
"claims",
":=",
"&",
"kitekey",
".",
"KiteClaims",
"{",
"}",
"\n\n",
"_",
",",
"err",
":=",
"jwt",
".",
"ParseWithClaims",
"(",
"tokenString",
",",
"c... | // parse the token string and set | [
"parse",
"the",
"token",
"string",
"and",
"set"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/tokenrenewer.go#L41-L61 | train |
koding/kite | tokenrenewer.go | renewDuration | func (t *TokenRenewer) renewDuration() time.Duration {
return t.validUntil.Add(-renewBefore).Sub(time.Now().UTC())
} | go | func (t *TokenRenewer) renewDuration() time.Duration {
return t.validUntil.Add(-renewBefore).Sub(time.Now().UTC())
} | [
"func",
"(",
"t",
"*",
"TokenRenewer",
")",
"renewDuration",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"t",
".",
"validUntil",
".",
"Add",
"(",
"-",
"renewBefore",
")",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
... | // The duration from now to the time token needs to be renewed.
// Needs to be calculated after renewing the token. | [
"The",
"duration",
"from",
"now",
"to",
"the",
"time",
"token",
"needs",
"to",
"be",
"renewed",
".",
"Needs",
"to",
"be",
"calculated",
"after",
"renewing",
"the",
"token",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/tokenrenewer.go#L111-L113 | train |
koding/kite | tokenrenewer.go | renewToken | func (t *TokenRenewer) renewToken() error {
renew := &protocol.Kite{
ID: t.client.Kite.ID,
}
token, err := t.localKite.GetToken(renew)
if err != nil {
return err
}
if err = t.parse(token); err != nil {
return err
}
t.client.authMu.Lock()
t.client.Auth.Key = token
t.client.authMu.Unlock()
t.client.c... | go | func (t *TokenRenewer) renewToken() error {
renew := &protocol.Kite{
ID: t.client.Kite.ID,
}
token, err := t.localKite.GetToken(renew)
if err != nil {
return err
}
if err = t.parse(token); err != nil {
return err
}
t.client.authMu.Lock()
t.client.Auth.Key = token
t.client.authMu.Unlock()
t.client.c... | [
"func",
"(",
"t",
"*",
"TokenRenewer",
")",
"renewToken",
"(",
")",
"error",
"{",
"renew",
":=",
"&",
"protocol",
".",
"Kite",
"{",
"ID",
":",
"t",
".",
"client",
".",
"Kite",
".",
"ID",
",",
"}",
"\n\n",
"token",
",",
"err",
":=",
"t",
".",
"l... | // renewToken gets a new token from a kontrolClient, parses it and sets it as the token. | [
"renewToken",
"gets",
"a",
"new",
"token",
"from",
"a",
"kontrolClient",
"parses",
"it",
"and",
"sets",
"it",
"as",
"the",
"token",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/tokenrenewer.go#L144-L165 | train |
koding/kite | config/config.go | NewFromKiteKey | func NewFromKiteKey(file string) (*Config, error) {
key, err := kitekey.ParseFile(file)
if err != nil {
return nil, err
}
var c Config
if err := c.ReadToken(key); err != nil {
return nil, err
}
return &c, nil
} | go | func NewFromKiteKey(file string) (*Config, error) {
key, err := kitekey.ParseFile(file)
if err != nil {
return nil, err
}
var c Config
if err := c.ReadToken(key); err != nil {
return nil, err
}
return &c, nil
} | [
"func",
"NewFromKiteKey",
"(",
"file",
"string",
")",
"(",
"*",
"Config",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"kitekey",
".",
"ParseFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
... | // NewFromKiteKey parses the given kite key file and gives a new Config value. | [
"NewFromKiteKey",
"parses",
"the",
"given",
"kite",
"key",
"file",
"and",
"gives",
"a",
"new",
"Config",
"value",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L154-L166 | train |
koding/kite | config/config.go | ReadKiteKey | func (c *Config) ReadKiteKey() error {
key, err := kitekey.Parse()
if err != nil {
return err
}
return c.ReadToken(key)
} | go | func (c *Config) ReadKiteKey() error {
key, err := kitekey.Parse()
if err != nil {
return err
}
return c.ReadToken(key)
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"ReadKiteKey",
"(",
")",
"error",
"{",
"key",
",",
"err",
":=",
"kitekey",
".",
"Parse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"ReadToken",
"("... | // ReadKiteKey parsed the user's kite key and returns a new Config. | [
"ReadKiteKey",
"parsed",
"the",
"user",
"s",
"kite",
"key",
"and",
"returns",
"a",
"new",
"Config",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L244-L251 | train |
koding/kite | config/config.go | ReadToken | func (c *Config) ReadToken(key *jwt.Token) error {
c.KiteKey = key.Raw
claims, ok := key.Claims.(*kitekey.KiteClaims)
if !ok {
return errors.New("no claims found")
}
c.Username = claims.Subject
c.KontrolUser = claims.Issuer
c.Id = claims.Id // jti is used for jwt's but let's also use it for kite ID
c.Kontro... | go | func (c *Config) ReadToken(key *jwt.Token) error {
c.KiteKey = key.Raw
claims, ok := key.Claims.(*kitekey.KiteClaims)
if !ok {
return errors.New("no claims found")
}
c.Username = claims.Subject
c.KontrolUser = claims.Issuer
c.Id = claims.Id // jti is used for jwt's but let's also use it for kite ID
c.Kontro... | [
"func",
"(",
"c",
"*",
"Config",
")",
"ReadToken",
"(",
"key",
"*",
"jwt",
".",
"Token",
")",
"error",
"{",
"c",
".",
"KiteKey",
"=",
"key",
".",
"Raw",
"\n\n",
"claims",
",",
"ok",
":=",
"key",
".",
"Claims",
".",
"(",
"*",
"kitekey",
".",
"Ki... | // ReadToken reads Kite Claims from JWT token and uses them to initialize Config. | [
"ReadToken",
"reads",
"Kite",
"Claims",
"from",
"JWT",
"token",
"and",
"uses",
"them",
"to",
"initialize",
"Config",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L254-L269 | train |
koding/kite | config/config.go | Copy | func (c *Config) Copy() *Config {
copy := *c
if c.XHR != nil {
xhr := *copy.XHR
copy.XHR = &xhr
}
if c.Client != nil {
client := *copy.Client
copy.Client = &client
}
if c.Websocket != nil {
ws := *copy.Websocket
copy.Websocket = &ws
}
return ©
} | go | func (c *Config) Copy() *Config {
copy := *c
if c.XHR != nil {
xhr := *copy.XHR
copy.XHR = &xhr
}
if c.Client != nil {
client := *copy.Client
copy.Client = &client
}
if c.Websocket != nil {
ws := *copy.Websocket
copy.Websocket = &ws
}
return ©
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"Copy",
"(",
")",
"*",
"Config",
"{",
"copy",
":=",
"*",
"c",
"\n\n",
"if",
"c",
".",
"XHR",
"!=",
"nil",
"{",
"xhr",
":=",
"*",
"copy",
".",
"XHR",
"\n",
"copy",
".",
"XHR",
"=",
"&",
"xhr",
"\n",
"}",... | // Copy returns a new copy of the config object. | [
"Copy",
"returns",
"a",
"new",
"copy",
"of",
"the",
"config",
"object",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/config/config.go#L272-L291 | train |
koding/kite | request.go | runMethod | func (c *Client) runMethod(method *Method, args *dnode.Partial) {
var (
callFunc func(interface{}, *Error)
request *Request
)
// Recover dnode argument errors and send them back. The caller can use
// functions like MustString(), MustSlice()... without the fear of panic.
defer func() {
if r := recover(); r... | go | func (c *Client) runMethod(method *Method, args *dnode.Partial) {
var (
callFunc func(interface{}, *Error)
request *Request
)
// Recover dnode argument errors and send them back. The caller can use
// functions like MustString(), MustSlice()... without the fear of panic.
defer func() {
if r := recover(); r... | [
"func",
"(",
"c",
"*",
"Client",
")",
"runMethod",
"(",
"method",
"*",
"Method",
",",
"args",
"*",
"dnode",
".",
"Partial",
")",
"{",
"var",
"(",
"callFunc",
"func",
"(",
"interface",
"{",
"}",
",",
"*",
"Error",
")",
"\n",
"request",
"*",
"Request... | // runMethod is called when a method is received from remote Kite. | [
"runMethod",
"is",
"called",
"when",
"a",
"method",
"is",
"received",
"from",
"remote",
"Kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L62-L119 | train |
koding/kite | request.go | runCallback | func (c *Client) runCallback(callback func(*dnode.Partial), args *dnode.Partial) {
// Do not panic no matter what.
defer func() {
if err := recover(); err != nil {
c.LocalKite.Log.Warning("Error in calling the callback function : %v", err)
}
}()
// Call the callback function.
callback(args)
} | go | func (c *Client) runCallback(callback func(*dnode.Partial), args *dnode.Partial) {
// Do not panic no matter what.
defer func() {
if err := recover(); err != nil {
c.LocalKite.Log.Warning("Error in calling the callback function : %v", err)
}
}()
// Call the callback function.
callback(args)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"runCallback",
"(",
"callback",
"func",
"(",
"*",
"dnode",
".",
"Partial",
")",
",",
"args",
"*",
"dnode",
".",
"Partial",
")",
"{",
"// Do not panic no matter what.",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"... | // runCallback is called when a callback method call is received from remote Kite. | [
"runCallback",
"is",
"called",
"when",
"a",
"callback",
"method",
"call",
"is",
"received",
"from",
"remote",
"Kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L122-L132 | train |
koding/kite | request.go | authenticate | func (r *Request) authenticate() *Error {
// Trust the Kite if we have initiated the connection. Following casts
// means, session is opened by the client.
if _, ok := r.Client.session.(*sockjsclient.WebsocketSession); ok {
return nil
}
if _, ok := r.Client.session.(*sockjsclient.XHRSession); ok {
return nil... | go | func (r *Request) authenticate() *Error {
// Trust the Kite if we have initiated the connection. Following casts
// means, session is opened by the client.
if _, ok := r.Client.session.(*sockjsclient.WebsocketSession); ok {
return nil
}
if _, ok := r.Client.session.(*sockjsclient.XHRSession); ok {
return nil... | [
"func",
"(",
"r",
"*",
"Request",
")",
"authenticate",
"(",
")",
"*",
"Error",
"{",
"// Trust the Kite if we have initiated the connection. Following casts",
"// means, session is opened by the client.",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"Client",
".",
"session",
... | // authenticate tries to authenticate the user by selecting appropriate
// authenticator function. | [
"authenticate",
"tries",
"to",
"authenticate",
"the",
"user",
"by",
"selecting",
"appropriate",
"authenticator",
"function",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L182-L222 | train |
koding/kite | request.go | AuthenticateFromToken | func (k *Kite) AuthenticateFromToken(r *Request) error {
k.verifyOnce.Do(k.verifyInit)
token, err := jwt.ParseWithClaims(r.Auth.Key, &kitekey.KiteClaims{}, r.LocalKite.RSAKey)
if e, ok := err.(*jwt.ValidationError); ok {
// Translate public key mismatch errors to token-is-expired one.
// This is to signal remo... | go | func (k *Kite) AuthenticateFromToken(r *Request) error {
k.verifyOnce.Do(k.verifyInit)
token, err := jwt.ParseWithClaims(r.Auth.Key, &kitekey.KiteClaims{}, r.LocalKite.RSAKey)
if e, ok := err.(*jwt.ValidationError); ok {
// Translate public key mismatch errors to token-is-expired one.
// This is to signal remo... | [
"func",
"(",
"k",
"*",
"Kite",
")",
"AuthenticateFromToken",
"(",
"r",
"*",
"Request",
")",
"error",
"{",
"k",
".",
"verifyOnce",
".",
"Do",
"(",
"k",
".",
"verifyInit",
")",
"\n\n",
"token",
",",
"err",
":=",
"jwt",
".",
"ParseWithClaims",
"(",
"r",... | // AuthenticateFromToken is the default Authenticator for Kite. | [
"AuthenticateFromToken",
"is",
"the",
"default",
"Authenticator",
"for",
"Kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L225-L272 | train |
koding/kite | request.go | AuthenticateFromKiteKey | func (k *Kite) AuthenticateFromKiteKey(r *Request) error {
claims := &kitekey.KiteClaims{}
token, err := jwt.ParseWithClaims(r.Auth.Key, claims, k.verify)
if err != nil {
return err
}
if !token.Valid {
return errors.New("Invalid signature in kite key")
}
if claims.Subject == "" {
return errors.New("toke... | go | func (k *Kite) AuthenticateFromKiteKey(r *Request) error {
claims := &kitekey.KiteClaims{}
token, err := jwt.ParseWithClaims(r.Auth.Key, claims, k.verify)
if err != nil {
return err
}
if !token.Valid {
return errors.New("Invalid signature in kite key")
}
if claims.Subject == "" {
return errors.New("toke... | [
"func",
"(",
"k",
"*",
"Kite",
")",
"AuthenticateFromKiteKey",
"(",
"r",
"*",
"Request",
")",
"error",
"{",
"claims",
":=",
"&",
"kitekey",
".",
"KiteClaims",
"{",
"}",
"\n\n",
"token",
",",
"err",
":=",
"jwt",
".",
"ParseWithClaims",
"(",
"r",
".",
... | // AuthenticateFromKiteKey authenticates user from kite key. | [
"AuthenticateFromKiteKey",
"authenticates",
"user",
"from",
"kite",
"key",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/request.go#L275-L294 | train |
koding/kite | registerurl.go | publicIP | func publicIP() (net.IP, error) {
resp, err := http.Get(publicEcho)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// The ip address is 16 chars long, we read more
// to account for excessive whitespace.
p, err := ioutil.ReadAll(io.LimitReader(resp.Body, 24))
if err != nil {
return nil, err
}
... | go | func publicIP() (net.IP, error) {
resp, err := http.Get(publicEcho)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// The ip address is 16 chars long, we read more
// to account for excessive whitespace.
p, err := ioutil.ReadAll(io.LimitReader(resp.Body, 24))
if err != nil {
return nil, err
}
... | [
"func",
"publicIP",
"(",
")",
"(",
"net",
".",
"IP",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"publicEcho",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp... | // publicIP returns an IP that is supposed to be Public. | [
"publicIP",
"returns",
"an",
"IP",
"that",
"is",
"supposed",
"to",
"be",
"Public",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/registerurl.go#L80-L100 | train |
koding/kite | kitectl/command/install.go | extractTar | func extractTar(r io.Reader, dir string) error {
first := true // true if we are on the first entry of tarball
tr := tar.NewReader(r)
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
return err
}
// Check if the same kite version is installed before
... | go | func extractTar(r io.Reader, dir string) error {
first := true // true if we are on the first entry of tarball
tr := tar.NewReader(r)
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
return err
}
// Check if the same kite version is installed before
... | [
"func",
"extractTar",
"(",
"r",
"io",
".",
"Reader",
",",
"dir",
"string",
")",
"error",
"{",
"first",
":=",
"true",
"// true if we are on the first entry of tarball",
"\n",
"tr",
":=",
"tar",
".",
"NewReader",
"(",
"r",
")",
"\n",
"for",
"{",
"hdr",
",",
... | // extractTar reads from the io.Reader and writes the files into the directory. | [
"extractTar",
"reads",
"from",
"the",
"io",
".",
"Reader",
"and",
"writes",
"the",
"files",
"into",
"the",
"directory",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kitectl/command/install.go#L189-L238 | train |
koding/kite | kitectl/command/install.go | validatePackage | func validatePackage(tempKitePath, repoName string) (bundlePath string, err error) {
dirs, err := ioutil.ReadDir(tempKitePath)
if err != nil {
return "", err
}
if len(dirs) != 1 {
return "", errors.New("Invalid package: Package must contain only one directory.")
}
bundlePath = filepath.Join(tempKitePath, di... | go | func validatePackage(tempKitePath, repoName string) (bundlePath string, err error) {
dirs, err := ioutil.ReadDir(tempKitePath)
if err != nil {
return "", err
}
if len(dirs) != 1 {
return "", errors.New("Invalid package: Package must contain only one directory.")
}
bundlePath = filepath.Join(tempKitePath, di... | [
"func",
"validatePackage",
"(",
"tempKitePath",
",",
"repoName",
"string",
")",
"(",
"bundlePath",
"string",
",",
"err",
"error",
")",
"{",
"dirs",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"tempKitePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // validatePackage does some checks on kite bundle and returns the bundle path. | [
"validatePackage",
"does",
"some",
"checks",
"on",
"kite",
"bundle",
"and",
"returns",
"the",
"bundle",
"path",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/kitectl/command/install.go#L241-L262 | train |
koding/kite | dnode/scrubber.go | RemoveCallback | func (s *Scrubber) RemoveCallback(id uint64) {
s.Lock()
delete(s.callbacks, id)
s.Unlock()
} | go | func (s *Scrubber) RemoveCallback(id uint64) {
s.Lock()
delete(s.callbacks, id)
s.Unlock()
} | [
"func",
"(",
"s",
"*",
"Scrubber",
")",
"RemoveCallback",
"(",
"id",
"uint64",
")",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"callbacks",
",",
"id",
")",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // RemoveCallback removes the callback with id from callbacks.
// Can be used to remove unused callbacks to free memory. | [
"RemoveCallback",
"removes",
"the",
"callback",
"with",
"id",
"from",
"callbacks",
".",
"Can",
"be",
"used",
"to",
"remove",
"unused",
"callbacks",
"to",
"free",
"memory",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/dnode/scrubber.go#L24-L28 | train |
koding/kite | method.go | addHandle | func (k *Kite) addHandle(method string, handler Handler) *Method {
authenticate := true
if k.Config.DisableAuthentication {
authenticate = false
}
m := &Method{
name: method,
handler: handler,
authenticate: authenticate,
handling: k.MethodHandling,
}
k.handlers[method] = m
return m
} | go | func (k *Kite) addHandle(method string, handler Handler) *Method {
authenticate := true
if k.Config.DisableAuthentication {
authenticate = false
}
m := &Method{
name: method,
handler: handler,
authenticate: authenticate,
handling: k.MethodHandling,
}
k.handlers[method] = m
return m
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"addHandle",
"(",
"method",
"string",
",",
"handler",
"Handler",
")",
"*",
"Method",
"{",
"authenticate",
":=",
"true",
"\n",
"if",
"k",
".",
"Config",
".",
"DisableAuthentication",
"{",
"authenticate",
"=",
"false",
"... | // addHandle is an internal method to add a handler | [
"addHandle",
"is",
"an",
"internal",
"method",
"to",
"add",
"a",
"handler"
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L78-L93 | train |
koding/kite | method.go | PreHandle | func (m *Method) PreHandle(handler Handler) *Method {
m.preHandlers = append(m.preHandlers, handler)
return m
} | go | func (m *Method) PreHandle(handler Handler) *Method {
m.preHandlers = append(m.preHandlers, handler)
return m
} | [
"func",
"(",
"m",
"*",
"Method",
")",
"PreHandle",
"(",
"handler",
"Handler",
")",
"*",
"Method",
"{",
"m",
".",
"preHandlers",
"=",
"append",
"(",
"m",
".",
"preHandlers",
",",
"handler",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // PreHandler adds a new kite handler which is executed before the method. | [
"PreHandler",
"adds",
"a",
"new",
"kite",
"handler",
"which",
"is",
"executed",
"before",
"the",
"method",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L126-L129 | train |
koding/kite | method.go | PostHandle | func (m *Method) PostHandle(handler Handler) *Method {
m.postHandlers = append(m.postHandlers, handler)
return m
} | go | func (m *Method) PostHandle(handler Handler) *Method {
m.postHandlers = append(m.postHandlers, handler)
return m
} | [
"func",
"(",
"m",
"*",
"Method",
")",
"PostHandle",
"(",
"handler",
"Handler",
")",
"*",
"Method",
"{",
"m",
".",
"postHandlers",
"=",
"append",
"(",
"m",
".",
"postHandlers",
",",
"handler",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // PostHandle adds a new kite handler which is executed after the method. | [
"PostHandle",
"adds",
"a",
"new",
"kite",
"handler",
"which",
"is",
"executed",
"after",
"the",
"method",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L138-L141 | train |
koding/kite | method.go | FinalFunc | func (m *Method) FinalFunc(f FinalFunc) *Method {
m.finalFuncs = append(m.finalFuncs, f)
return m
} | go | func (m *Method) FinalFunc(f FinalFunc) *Method {
m.finalFuncs = append(m.finalFuncs, f)
return m
} | [
"func",
"(",
"m",
"*",
"Method",
")",
"FinalFunc",
"(",
"f",
"FinalFunc",
")",
"*",
"Method",
"{",
"m",
".",
"finalFuncs",
"=",
"append",
"(",
"m",
".",
"finalFuncs",
",",
"f",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // FinalFunc registers a function that is always called as a last one
// after pre-, handler and post- functions for the given method.
//
// It receives a result and an error from last handler that
// got executed prior to calling final func. | [
"FinalFunc",
"registers",
"a",
"function",
"that",
"is",
"always",
"called",
"as",
"a",
"last",
"one",
"after",
"pre",
"-",
"handler",
"and",
"post",
"-",
"functions",
"for",
"the",
"given",
"method",
".",
"It",
"receives",
"a",
"result",
"and",
"an",
"e... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L154-L157 | train |
koding/kite | method.go | Handle | func (k *Kite) Handle(method string, handler Handler) *Method {
return k.addHandle(method, handler)
} | go | func (k *Kite) Handle(method string, handler Handler) *Method {
return k.addHandle(method, handler)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"Handle",
"(",
"method",
"string",
",",
"handler",
"Handler",
")",
"*",
"Method",
"{",
"return",
"k",
".",
"addHandle",
"(",
"method",
",",
"handler",
")",
"\n",
"}"
] | // Handle registers the handler for the given method. The handler is called
// when a method call is received from a Kite. | [
"Handle",
"registers",
"the",
"handler",
"for",
"the",
"given",
"method",
".",
"The",
"handler",
"is",
"called",
"when",
"a",
"method",
"call",
"is",
"received",
"from",
"a",
"Kite",
"."
] | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L161-L163 | train |
koding/kite | method.go | PreHandle | func (k *Kite) PreHandle(handler Handler) {
k.preHandlers = append(k.preHandlers, handler)
} | go | func (k *Kite) PreHandle(handler Handler) {
k.preHandlers = append(k.preHandlers, handler)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"PreHandle",
"(",
"handler",
"Handler",
")",
"{",
"k",
".",
"preHandlers",
"=",
"append",
"(",
"k",
".",
"preHandlers",
",",
"handler",
")",
"\n",
"}"
] | // PreHandle registers an handler which is executed before a kite.Handler
// method is executed. Calling PreHandle multiple times registers multiple
// handlers. A non-error return triggers the execution of the next handler. The
// execution order is FIFO. | [
"PreHandle",
"registers",
"an",
"handler",
"which",
"is",
"executed",
"before",
"a",
"kite",
".",
"Handler",
"method",
"is",
"executed",
".",
"Calling",
"PreHandle",
"multiple",
"times",
"registers",
"multiple",
"handlers",
".",
"A",
"non",
"-",
"error",
"retu... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L176-L178 | train |
koding/kite | method.go | PostHandle | func (k *Kite) PostHandle(handler Handler) {
k.postHandlers = append(k.postHandlers, handler)
} | go | func (k *Kite) PostHandle(handler Handler) {
k.postHandlers = append(k.postHandlers, handler)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"PostHandle",
"(",
"handler",
"Handler",
")",
"{",
"k",
".",
"postHandlers",
"=",
"append",
"(",
"k",
".",
"postHandlers",
",",
"handler",
")",
"\n",
"}"
] | // PostHandle registers an handler which is executed after a kite.Handler
// method is executed. Calling PostHandler multiple times registers multiple
// handlers. A non-error return triggers the execution of the next handler. The
// execution order is FIFO. | [
"PostHandle",
"registers",
"an",
"handler",
"which",
"is",
"executed",
"after",
"a",
"kite",
".",
"Handler",
"method",
"is",
"executed",
".",
"Calling",
"PostHandler",
"multiple",
"times",
"registers",
"multiple",
"handlers",
".",
"A",
"non",
"-",
"error",
"re... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L189-L191 | train |
koding/kite | method.go | FinalFunc | func (k *Kite) FinalFunc(f FinalFunc) {
k.finalFuncs = append(k.finalFuncs, f)
} | go | func (k *Kite) FinalFunc(f FinalFunc) {
k.finalFuncs = append(k.finalFuncs, f)
} | [
"func",
"(",
"k",
"*",
"Kite",
")",
"FinalFunc",
"(",
"f",
"FinalFunc",
")",
"{",
"k",
".",
"finalFuncs",
"=",
"append",
"(",
"k",
".",
"finalFuncs",
",",
"f",
")",
"\n",
"}"
] | // FinalFunc registers a function that is always called as a last one
// after pre-, handler and post- functions.
//
// It receives a result and an error from last handler that
// got executed prior to calling final func. | [
"FinalFunc",
"registers",
"a",
"function",
"that",
"is",
"always",
"called",
"as",
"a",
"last",
"one",
"after",
"pre",
"-",
"handler",
"and",
"post",
"-",
"functions",
".",
"It",
"receives",
"a",
"result",
"and",
"an",
"error",
"from",
"last",
"handler",
... | baa1a54919e3035417f7571dd46005e91afe8abe | https://github.com/koding/kite/blob/baa1a54919e3035417f7571dd46005e91afe8abe/method.go#L203-L205 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/path.go | Matches | func (p Path) Matches(other string) bool {
if CaseSensitivePath {
return strings.HasPrefix(string(p), other)
}
return strings.HasPrefix(strings.ToLower(string(p)), strings.ToLower(other))
} | go | func (p Path) Matches(other string) bool {
if CaseSensitivePath {
return strings.HasPrefix(string(p), other)
}
return strings.HasPrefix(strings.ToLower(string(p)), strings.ToLower(other))
} | [
"func",
"(",
"p",
"Path",
")",
"Matches",
"(",
"other",
"string",
")",
"bool",
"{",
"if",
"CaseSensitivePath",
"{",
"return",
"strings",
".",
"HasPrefix",
"(",
"string",
"(",
"p",
")",
",",
"other",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Ha... | // Matches checks to see if other matches p.
//
// Path matching will probably not always be a direct
// comparison; this method assures that paths can be
// easily and consistently matched. | [
"Matches",
"checks",
"to",
"see",
"if",
"other",
"matches",
"p",
".",
"Path",
"matching",
"will",
"probably",
"not",
"always",
"be",
"a",
"direct",
"comparison",
";",
"this",
"method",
"assures",
"that",
"paths",
"can",
"be",
"easily",
"and",
"consistently",... | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/path.go#L16-L21 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/gzip/gzip.go | Write | func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
if !w.statusCodeWritten {
w.WriteHeader(http.StatusOK)
}
n, err := w.Writer.Write(b)
return n, err
} | go | func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
if !w.statusCodeWritten {
w.WriteHeader(http.StatusOK)
}
n, err := w.Writer.Write(b)
return n, err
} | [
"func",
"(",
"w",
"*",
"gzipResponseWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"w",
".",
"Header",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"w",
".",
"Header",
... | // Write wraps the underlying Write method to do compression. | [
"Write",
"wraps",
"the",
"underlying",
"Write",
"method",
"to",
"do",
"compression",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/gzip/gzip.go#L126-L135 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/staticfiles/fileserver.go | IsHidden | func (fs FileServer) IsHidden(d os.FileInfo) bool {
// If the file is supposed to be hidden, return a 404
for _, hiddenPath := range fs.Hide {
// Check if the served file is exactly the hidden file.
if hFile, err := fs.Root.Open(hiddenPath); err == nil {
fs, _ := hFile.Stat()
hFile.Close()
if os.SameFile... | go | func (fs FileServer) IsHidden(d os.FileInfo) bool {
// If the file is supposed to be hidden, return a 404
for _, hiddenPath := range fs.Hide {
// Check if the served file is exactly the hidden file.
if hFile, err := fs.Root.Open(hiddenPath); err == nil {
fs, _ := hFile.Stat()
hFile.Close()
if os.SameFile... | [
"func",
"(",
"fs",
"FileServer",
")",
"IsHidden",
"(",
"d",
"os",
".",
"FileInfo",
")",
"bool",
"{",
"// If the file is supposed to be hidden, return a 404",
"for",
"_",
",",
"hiddenPath",
":=",
"range",
"fs",
".",
"Hide",
"{",
"// Check if the served file is exactl... | // IsHidden checks if file with FileInfo d is on hide list. | [
"IsHidden",
"checks",
"if",
"file",
"with",
"FileInfo",
"d",
"is",
"on",
"hide",
"list",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/staticfiles/fileserver.go#L184-L197 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/staticfiles/fileserver.go | Redirect | func Redirect(w http.ResponseWriter, r *http.Request, newPath string, statusCode int) {
if q := r.URL.RawQuery; q != "" {
newPath += "?" + q
}
http.Redirect(w, r, newPath, statusCode)
} | go | func Redirect(w http.ResponseWriter, r *http.Request, newPath string, statusCode int) {
if q := r.URL.RawQuery; q != "" {
newPath += "?" + q
}
http.Redirect(w, r, newPath, statusCode)
} | [
"func",
"Redirect",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"newPath",
"string",
",",
"statusCode",
"int",
")",
"{",
"if",
"q",
":=",
"r",
".",
"URL",
".",
"RawQuery",
";",
"q",
"!=",
"\"",
"\"",
"{",
... | // Redirect sends an HTTP redirect to the client but will preserve
// the query string for the new path. Based on http.localRedirect
// from the Go standard library. | [
"Redirect",
"sends",
"an",
"HTTP",
"redirect",
"to",
"the",
"client",
"but",
"will",
"preserve",
"the",
"query",
"string",
"for",
"the",
"new",
"path",
".",
"Based",
"on",
"http",
".",
"localRedirect",
"from",
"the",
"Go",
"standard",
"library",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/staticfiles/fileserver.go#L202-L207 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/handler.go | TapperFromContext | func TapperFromContext(ctx context.Context) (t Tapper) {
t, _ = ctx.(Tapper)
return
} | go | func TapperFromContext(ctx context.Context) (t Tapper) {
t, _ = ctx.(Tapper)
return
} | [
"func",
"TapperFromContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"t",
"Tapper",
")",
"{",
"t",
",",
"_",
"=",
"ctx",
".",
"(",
"Tapper",
")",
"\n",
"return",
"\n",
"}"
] | // TapperFromContext will return a Tapper if the dnstap plugin is enabled. | [
"TapperFromContext",
"will",
"return",
"a",
"Tapper",
"if",
"the",
"dnstap",
"plugin",
"is",
"enabled",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/handler.go#L48-L51 | train |
inverse-inc/packetfence | go/coredns/plugin/dnstap/handler.go | TapBuilder | func (h Dnstap) TapBuilder() msg.Builder {
return msg.Builder{Full: h.Pack}
} | go | func (h Dnstap) TapBuilder() msg.Builder {
return msg.Builder{Full: h.Pack}
} | [
"func",
"(",
"h",
"Dnstap",
")",
"TapBuilder",
"(",
")",
"msg",
".",
"Builder",
"{",
"return",
"msg",
".",
"Builder",
"{",
"Full",
":",
"h",
".",
"Pack",
"}",
"\n",
"}"
] | // TapBuilder implements Tapper. | [
"TapBuilder",
"implements",
"Tapper",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/handler.go#L69-L71 | train |
inverse-inc/packetfence | go/dhcp/pool/pool.go | GetIssues | func (dp *DHCPPool) GetIssues(macs []string) ([]string, map[uint64]string) {
dp.lock.Lock()
defer dp.lock.Unlock()
var found bool
found = false
var inPoolNotInCache []string
var duplicateInPool map[uint64]string
duplicateInPool = make(map[uint64]string)
var count int
var saveindex uint64
for i := uint64(0); ... | go | func (dp *DHCPPool) GetIssues(macs []string) ([]string, map[uint64]string) {
dp.lock.Lock()
defer dp.lock.Unlock()
var found bool
found = false
var inPoolNotInCache []string
var duplicateInPool map[uint64]string
duplicateInPool = make(map[uint64]string)
var count int
var saveindex uint64
for i := uint64(0); ... | [
"func",
"(",
"dp",
"*",
"DHCPPool",
")",
"GetIssues",
"(",
"macs",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"map",
"[",
"uint64",
"]",
"string",
")",
"{",
"dp",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dp",
".",
"lock",... | // Compare what we have in the cache with what we have in the pool | [
"Compare",
"what",
"we",
"have",
"in",
"the",
"cache",
"with",
"what",
"we",
"have",
"in",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L34-L81 | train |
inverse-inc/packetfence | go/dhcp/pool/pool.go | ReserveIPIndex | func (dp *DHCPPool) ReserveIPIndex(index uint64, mac string) (error, string) {
dp.lock.Lock()
defer dp.lock.Unlock()
if index >= dp.capacity {
return errors.New("Trying to reserve an IP that is outside the capacity of this pool"), FreeMac
}
if _, free := dp.free[index]; free {
delete(dp.free, index)
dp.mac... | go | func (dp *DHCPPool) ReserveIPIndex(index uint64, mac string) (error, string) {
dp.lock.Lock()
defer dp.lock.Unlock()
if index >= dp.capacity {
return errors.New("Trying to reserve an IP that is outside the capacity of this pool"), FreeMac
}
if _, free := dp.free[index]; free {
delete(dp.free, index)
dp.mac... | [
"func",
"(",
"dp",
"*",
"DHCPPool",
")",
"ReserveIPIndex",
"(",
"index",
"uint64",
",",
"mac",
"string",
")",
"(",
"error",
",",
"string",
")",
"{",
"dp",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dp",
".",
"lock",
".",
"Unlock",
"(",
"... | // Reserves an IP in the pool, returns an error if the IP has already been reserved | [
"Reserves",
"an",
"IP",
"in",
"the",
"pool",
"returns",
"an",
"error",
"if",
"the",
"IP",
"has",
"already",
"been",
"reserved"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L84-L99 | train |
inverse-inc/packetfence | go/dhcp/pool/pool.go | FreeIPIndex | func (dp *DHCPPool) FreeIPIndex(index uint64) error {
dp.lock.Lock()
defer dp.lock.Unlock()
if !dp.IndexInPool(index) {
return errors.New("Trying to free an IP that is outside the capacity of this pool")
}
if _, free := dp.free[index]; free {
return errors.New("IP is already free")
} else {
dp.free[index]... | go | func (dp *DHCPPool) FreeIPIndex(index uint64) error {
dp.lock.Lock()
defer dp.lock.Unlock()
if !dp.IndexInPool(index) {
return errors.New("Trying to free an IP that is outside the capacity of this pool")
}
if _, free := dp.free[index]; free {
return errors.New("IP is already free")
} else {
dp.free[index]... | [
"func",
"(",
"dp",
"*",
"DHCPPool",
")",
"FreeIPIndex",
"(",
"index",
"uint64",
")",
"error",
"{",
"dp",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dp",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"dp",
".",
"IndexInPool",
"... | // Frees an IP in the pool, returns an error if the IP is already free | [
"Frees",
"an",
"IP",
"in",
"the",
"pool",
"returns",
"an",
"error",
"if",
"the",
"IP",
"is",
"already",
"free"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L102-L117 | train |
inverse-inc/packetfence | go/dhcp/pool/pool.go | GetFreeIPIndex | func (dp *DHCPPool) GetFreeIPIndex(mac string) (uint64, string, error) {
dp.lock.Lock()
defer dp.lock.Unlock()
if len(dp.free) == 0 {
return 0, FreeMac, errors.New("DHCP pool is full")
}
index := rand.Intn(len(dp.free))
var available uint64
for available = range dp.free {
if index == 0 {
break
}
ind... | go | func (dp *DHCPPool) GetFreeIPIndex(mac string) (uint64, string, error) {
dp.lock.Lock()
defer dp.lock.Unlock()
if len(dp.free) == 0 {
return 0, FreeMac, errors.New("DHCP pool is full")
}
index := rand.Intn(len(dp.free))
var available uint64
for available = range dp.free {
if index == 0 {
break
}
ind... | [
"func",
"(",
"dp",
"*",
"DHCPPool",
")",
"GetFreeIPIndex",
"(",
"mac",
"string",
")",
"(",
"uint64",
",",
"string",
",",
"error",
")",
"{",
"dp",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dp",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n... | // Returns a random free IP address, an error if the pool is full | [
"Returns",
"a",
"random",
"free",
"IP",
"address",
"an",
"error",
"if",
"the",
"pool",
"is",
"full"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L152-L173 | train |
inverse-inc/packetfence | go/dhcp/pool/pool.go | FreeIPsRemaining | func (dp *DHCPPool) FreeIPsRemaining() uint64 {
dp.lock.Lock()
defer dp.lock.Unlock()
return uint64(len(dp.free))
} | go | func (dp *DHCPPool) FreeIPsRemaining() uint64 {
dp.lock.Lock()
defer dp.lock.Unlock()
return uint64(len(dp.free))
} | [
"func",
"(",
"dp",
"*",
"DHCPPool",
")",
"FreeIPsRemaining",
"(",
")",
"uint64",
"{",
"dp",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dp",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"uint64",
"(",
"len",
"(",
"dp",
".",
"free... | // Returns the amount of free IPs in the pool | [
"Returns",
"the",
"amount",
"of",
"free",
"IPs",
"in",
"the",
"pool"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/pool/pool.go#L181-L185 | train |
inverse-inc/packetfence | go/firewallsso/watchguard.go | Stop | func (fw *WatchGuard) Stop(ctx context.Context, info map[string]string) (bool, error) {
p := fw.stopRadiusPacket(ctx, info)
client := fw.getRadiusClient(ctx)
var err error
client.Dialer.LocalAddr, err = net.ResolveUDPAddr("udp", fw.getSourceIp(ctx).String()+":0")
sharedutils.CheckError(err)
// Use the backgroun... | go | func (fw *WatchGuard) Stop(ctx context.Context, info map[string]string) (bool, error) {
p := fw.stopRadiusPacket(ctx, info)
client := fw.getRadiusClient(ctx)
var err error
client.Dialer.LocalAddr, err = net.ResolveUDPAddr("udp", fw.getSourceIp(ctx).String()+":0")
sharedutils.CheckError(err)
// Use the backgroun... | [
"func",
"(",
"fw",
"*",
"WatchGuard",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"p",
":=",
"fw",
".",
"stopRadiusPacket",
"(",
"ctx",
",",
"info",... | // Send an SSO stop to the WatchGuard firewall
// Returns an error unless there is a valid reply from the firewall | [
"Send",
"an",
"SSO",
"stop",
"to",
"the",
"WatchGuard",
"firewall",
"Returns",
"an",
"error",
"unless",
"there",
"is",
"a",
"valid",
"reply",
"from",
"the",
"firewall"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/watchguard.go#L58-L76 | train |
inverse-inc/packetfence | go/firewallsso/watchguard.go | stopRadiusPacket | func (fw *WatchGuard) stopRadiusPacket(ctx context.Context, info map[string]string) *radius.Packet {
r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password))
rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"])
rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Stop)
rfc2865.UserName_AddStri... | go | func (fw *WatchGuard) stopRadiusPacket(ctx context.Context, info map[string]string) *radius.Packet {
r := radius.New(radius.CodeAccountingRequest, []byte(fw.Password))
rfc2866.AcctSessionID_AddString(r, "acct_pf-"+info["mac"])
rfc2866.AcctStatusType_Add(r, rfc2866.AcctStatusType_Value_Stop)
rfc2865.UserName_AddStri... | [
"func",
"(",
"fw",
"*",
"WatchGuard",
")",
"stopRadiusPacket",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"radius",
".",
"Packet",
"{",
"r",
":=",
"radius",
".",
"New",
"(",
"radius",
".",
"Code... | // Build the RADIUS packet for an SSO stop | [
"Build",
"the",
"RADIUS",
"packet",
"for",
"an",
"SSO",
"stop"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/watchguard.go#L79-L90 | train |
inverse-inc/packetfence | go/caddy/requestlimit/requestlimit.go | setup | func setup(c *caddy.Controller) error {
var max int
for c.Next() {
val := c.Val()
switch val {
case "requestlimit":
if !c.NextArg() {
fmt.Println("Missing limit argument for requestlimit")
return c.ArgErr()
} else {
val := c.Val()
if val != "" {
max64, err := strconv.ParseInt(c.Val()... | go | func setup(c *caddy.Controller) error {
var max int
for c.Next() {
val := c.Val()
switch val {
case "requestlimit":
if !c.NextArg() {
fmt.Println("Missing limit argument for requestlimit")
return c.ArgErr()
} else {
val := c.Val()
if val != "" {
max64, err := strconv.ParseInt(c.Val()... | [
"func",
"setup",
"(",
"c",
"*",
"caddy",
".",
"Controller",
")",
"error",
"{",
"var",
"max",
"int",
"\n\n",
"for",
"c",
".",
"Next",
"(",
")",
"{",
"val",
":=",
"c",
".",
"Val",
"(",
")",
"\n",
"switch",
"val",
"{",
"case",
"\"",
"\"",
":",
"... | // Setup the rate limiter with the configuration in the Caddyfile | [
"Setup",
"the",
"rate",
"limiter",
"with",
"the",
"configuration",
"in",
"the",
"Caddyfile"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/requestlimit/requestlimit.go#L21-L55 | train |
inverse-inc/packetfence | go/caddy/requestlimit/requestlimit.go | ServeHTTP | func (h RequestLimitHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// Limit the concurrent requests that can run through the sem channel
h.sem <- 1
defer func() {
<-h.sem
}()
return h.Next.ServeHTTP(w, r)
} | go | func (h RequestLimitHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// Limit the concurrent requests that can run through the sem channel
h.sem <- 1
defer func() {
<-h.sem
}()
return h.Next.ServeHTTP(w, r)
} | [
"func",
"(",
"h",
"RequestLimitHandler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"int",
",",
"error",
")",
"{",
"// Limit the concurrent requests that can run through the sem channel",
"h",
".",
... | // Middleware that will rate limit the amount of concurrent requests the webserver can do at once
// Controlled via the sem channel which has a capacity defined by the limit that is in the Caddyfile | [
"Middleware",
"that",
"will",
"rate",
"limit",
"the",
"amount",
"of",
"concurrent",
"requests",
"the",
"webserver",
"can",
"do",
"at",
"once",
"Controlled",
"via",
"the",
"sem",
"channel",
"which",
"has",
"a",
"capacity",
"defined",
"by",
"the",
"limit",
"th... | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/requestlimit/requestlimit.go#L64-L72 | train |
inverse-inc/packetfence | go/logging/logging.go | NewContext | func NewContext(ctx context.Context) context.Context {
u, _ := uuid.NewV4()
uStr := u.String()
ctx = context.WithValue(ctx, requestUuidKey, uStr)
ctx = context.WithValue(ctx, processPidKey, strconv.Itoa(os.Getpid()))
ctx = context.WithValue(ctx, additionnalLogElementsKey, make(map[interface{}]interface{}))
return... | go | func NewContext(ctx context.Context) context.Context {
u, _ := uuid.NewV4()
uStr := u.String()
ctx = context.WithValue(ctx, requestUuidKey, uStr)
ctx = context.WithValue(ctx, processPidKey, strconv.Itoa(os.Getpid()))
ctx = context.WithValue(ctx, additionnalLogElementsKey, make(map[interface{}]interface{}))
return... | [
"func",
"NewContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"u",
",",
"_",
":=",
"uuid",
".",
"NewV4",
"(",
")",
"\n",
"uStr",
":=",
"u",
".",
"String",
"(",
")",
"\n",
"ctx",
"=",
"context",
".",
"WithValue",
... | // Grab a context that includes a UUID of the request for logging purposes | [
"Grab",
"a",
"context",
"that",
"includes",
"a",
"UUID",
"of",
"the",
"request",
"for",
"logging",
"purposes"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/logging/logging.go#L38-L45 | train |
inverse-inc/packetfence | go/caddy/forwardproxy/forwardproxy.go | dualStream | func dualStream(w1 io.Writer, r1 io.Reader, w2 io.Writer, r2 io.Reader) error {
errChan := make(chan error)
stream := func(w io.Writer, r io.Reader) {
buf := bufferPool.Get().([]byte)
buf = buf[0:cap(buf)]
_, _err := flushingIoCopy(w, r, buf)
errChan <- _err
}
go stream(w1, r1)
go stream(w2, r2)
err1 :=... | go | func dualStream(w1 io.Writer, r1 io.Reader, w2 io.Writer, r2 io.Reader) error {
errChan := make(chan error)
stream := func(w io.Writer, r io.Reader) {
buf := bufferPool.Get().([]byte)
buf = buf[0:cap(buf)]
_, _err := flushingIoCopy(w, r, buf)
errChan <- _err
}
go stream(w1, r1)
go stream(w2, r2)
err1 :=... | [
"func",
"dualStream",
"(",
"w1",
"io",
".",
"Writer",
",",
"r1",
"io",
".",
"Reader",
",",
"w2",
"io",
".",
"Writer",
",",
"r2",
"io",
".",
"Reader",
")",
"error",
"{",
"errChan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n\n",
"stream",
":=",
"... | // Copies data r1->w1 and r2->w2, flushes as needed, and returns when both streams are done. | [
"Copies",
"data",
"r1",
"-",
">",
"w1",
"and",
"r2",
"-",
">",
"w2",
"flushes",
"as",
"needed",
"and",
"returns",
"when",
"both",
"streams",
"are",
"done",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L75-L93 | train |
inverse-inc/packetfence | go/caddy/forwardproxy/forwardproxy.go | serveHijack | func serveHijack(w http.ResponseWriter, targetConn net.Conn) (int, error) {
hijacker, ok := w.(http.Hijacker)
if !ok {
return http.StatusInternalServerError, errors.New("ResponseWriter does not implement Hijacker")
}
clientConn, bufReader, err := hijacker.Hijack()
if err != nil {
return http.StatusInternalServ... | go | func serveHijack(w http.ResponseWriter, targetConn net.Conn) (int, error) {
hijacker, ok := w.(http.Hijacker)
if !ok {
return http.StatusInternalServerError, errors.New("ResponseWriter does not implement Hijacker")
}
clientConn, bufReader, err := hijacker.Hijack()
if err != nil {
return http.StatusInternalServ... | [
"func",
"serveHijack",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"targetConn",
"net",
".",
"Conn",
")",
"(",
"int",
",",
"error",
")",
"{",
"hijacker",
",",
"ok",
":=",
"w",
".",
"(",
"http",
".",
"Hijacker",
")",
"\n",
"if",
"!",
"ok",
"{",
... | // Hijacks the connection from ResponseWriter, writes the response and proxies data between targetConn
// and hijacked connection. | [
"Hijacks",
"the",
"connection",
"from",
"ResponseWriter",
"writes",
"the",
"response",
"and",
"proxies",
"data",
"between",
"targetConn",
"and",
"hijacked",
"connection",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L97-L134 | train |
inverse-inc/packetfence | go/caddy/forwardproxy/forwardproxy.go | checkCredentials | func (fp *ForwardProxy) checkCredentials(r *http.Request) error {
pa := strings.Split(r.Header.Get("Proxy-Authorization"), " ")
if len(pa) != 2 {
return errors.New("Proxy-Authorization is required! Expected format: <type> <credentials>")
}
if strings.ToLower(pa[0]) != "basic" {
return errors.New("Auth type is n... | go | func (fp *ForwardProxy) checkCredentials(r *http.Request) error {
pa := strings.Split(r.Header.Get("Proxy-Authorization"), " ")
if len(pa) != 2 {
return errors.New("Proxy-Authorization is required! Expected format: <type> <credentials>")
}
if strings.ToLower(pa[0]) != "basic" {
return errors.New("Auth type is n... | [
"func",
"(",
"fp",
"*",
"ForwardProxy",
")",
"checkCredentials",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"pa",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",... | // Returns nil error on successful credentials check. | [
"Returns",
"nil",
"error",
"on",
"successful",
"credentials",
"check",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L137-L154 | train |
inverse-inc/packetfence | go/caddy/forwardproxy/forwardproxy.go | isSubdomain | func isSubdomain(s, domain string) bool {
if s == domain {
return true
}
if strings.HasSuffix(s, "."+domain) {
return true
}
return false
} | go | func isSubdomain(s, domain string) bool {
if s == domain {
return true
}
if strings.HasSuffix(s, "."+domain) {
return true
}
return false
} | [
"func",
"isSubdomain",
"(",
"s",
",",
"domain",
"string",
")",
"bool",
"{",
"if",
"s",
"==",
"domain",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"s",
",",
"\"",
"\"",
"+",
"domain",
")",
"{",
"return",
"true",
... | // returns true if `s` is `domain` or subdomain of `domain`. Inputs are expected to be sanitized. | [
"returns",
"true",
"if",
"s",
"is",
"domain",
"or",
"subdomain",
"of",
"domain",
".",
"Inputs",
"are",
"expected",
"to",
"be",
"sanitized",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L157-L165 | train |
inverse-inc/packetfence | go/caddy/forwardproxy/forwardproxy.go | forwardResponse | func forwardResponse(w http.ResponseWriter, response *http.Response) error {
w.Header().Del("Server") // remove Server: Caddy, append via instead
w.Header().Add("Via", strconv.Itoa(response.ProtoMajor)+"."+strconv.Itoa(response.ProtoMinor)+" caddy")
for header, values := range response.Header {
for _, val := rang... | go | func forwardResponse(w http.ResponseWriter, response *http.Response) error {
w.Header().Del("Server") // remove Server: Caddy, append via instead
w.Header().Add("Via", strconv.Itoa(response.ProtoMajor)+"."+strconv.Itoa(response.ProtoMinor)+" caddy")
for header, values := range response.Header {
for _, val := rang... | [
"func",
"forwardResponse",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"response",
"*",
"http",
".",
"Response",
")",
"error",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Del",
"(",
"\"",
"\"",
")",
"// remove Server: Caddy, append via instead",
"\n",
"w",
... | // Removes hop-by-hop headers, and writes response into ResponseWriter. | [
"Removes",
"hop",
"-",
"by",
"-",
"hop",
"headers",
"and",
"writes",
"response",
"into",
"ResponseWriter",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L304-L320 | train |
inverse-inc/packetfence | go/caddy/forwardproxy/forwardproxy.go | generateForwardRequest | func (fp *ForwardProxy) generateForwardRequest(inReq *http.Request) (*http.Request, error) {
// Scheme has to be appended to avoid `unsupported protocol scheme ""` error.
// `http://` is used, since this initial request itself is always HTTP, regardless of what client and server
// may speak afterwards.
if len(inRe... | go | func (fp *ForwardProxy) generateForwardRequest(inReq *http.Request) (*http.Request, error) {
// Scheme has to be appended to avoid `unsupported protocol scheme ""` error.
// `http://` is used, since this initial request itself is always HTTP, regardless of what client and server
// may speak afterwards.
if len(inRe... | [
"func",
"(",
"fp",
"*",
"ForwardProxy",
")",
"generateForwardRequest",
"(",
"inReq",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"// Scheme has to be appended to avoid `unsupported protocol scheme \"\"` error.",
"// `htt... | // Based on http Request from client, generates new request to be forwarded to target server.
// Some fields are shallow-copied, thus genOutReq will mutate original request.
// If error is not nil - http.StatusBadRequest is to be sent to client. | [
"Based",
"on",
"http",
"Request",
"from",
"client",
"generates",
"new",
"request",
"to",
"be",
"forwarded",
"to",
"target",
"server",
".",
"Some",
"fields",
"are",
"shallow",
"-",
"copied",
"thus",
"genOutReq",
"will",
"mutate",
"original",
"request",
".",
"... | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/forwardproxy/forwardproxy.go#L325-L357 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/proxy/proxy.go | createUpstreamRequest | func createUpstreamRequest(r *http.Request) *http.Request {
outreq := new(http.Request)
*outreq = *r // includes shallow copies of maps, but okay
// We should set body to nil explicitly if request body is empty.
// For server requests the Request Body is always non-nil.
if r.ContentLength == 0 {
outreq.Body = ni... | go | func createUpstreamRequest(r *http.Request) *http.Request {
outreq := new(http.Request)
*outreq = *r // includes shallow copies of maps, but okay
// We should set body to nil explicitly if request body is empty.
// For server requests the Request Body is always non-nil.
if r.ContentLength == 0 {
outreq.Body = ni... | [
"func",
"createUpstreamRequest",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"*",
"http",
".",
"Request",
"{",
"outreq",
":=",
"new",
"(",
"http",
".",
"Request",
")",
"\n",
"*",
"outreq",
"=",
"*",
"r",
"// includes shallow copies of maps, but okay",
"\n",
... | // createUpstremRequest shallow-copies r into a new request
// that can be sent upstream.
//
// Derived from reverseproxy.go in the standard Go httputil package. | [
"createUpstremRequest",
"shallow",
"-",
"copies",
"r",
"into",
"a",
"new",
"request",
"that",
"can",
"be",
"sent",
"upstream",
".",
"Derived",
"from",
"reverseproxy",
".",
"go",
"in",
"the",
"standard",
"Go",
"httputil",
"package",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/proxy/proxy.go#L270-L328 | train |
inverse-inc/packetfence | go/caddy/caddy/plugins.go | StartupHooks | func StartupHooks(serverType string) error {
for stype, stypePlugins := range plugins {
if stype != "" && stype != serverType {
continue
}
for name := range stypePlugins {
if stypePlugins[name].StartupHook == nil {
continue
}
err := stypePlugins[name].StartupHook()
if err != nil {
return... | go | func StartupHooks(serverType string) error {
for stype, stypePlugins := range plugins {
if stype != "" && stype != serverType {
continue
}
for name := range stypePlugins {
if stypePlugins[name].StartupHook == nil {
continue
}
err := stypePlugins[name].StartupHook()
if err != nil {
return... | [
"func",
"StartupHooks",
"(",
"serverType",
"string",
")",
"error",
"{",
"for",
"stype",
",",
"stypePlugins",
":=",
"range",
"plugins",
"{",
"if",
"stype",
"!=",
"\"",
"\"",
"&&",
"stype",
"!=",
"serverType",
"{",
"continue",
"\n",
"}",
"\n\n",
"for",
"na... | // StartupHooks executes the startup hooks defined when the
// plugins were registered and returns the first error
// it encounters. | [
"StartupHooks",
"executes",
"the",
"startup",
"hooks",
"defined",
"when",
"the",
"plugins",
"were",
"registered",
"and",
"returns",
"the",
"first",
"error",
"it",
"encounters",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/plugins.go#L75-L94 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/browse/browse.go | BreadcrumbMap | func (l Listing) BreadcrumbMap() map[string]string {
result := map[string]string{}
if len(l.Path) == 0 {
return result
}
// skip trailing slash
lpath := l.Path
if lpath[len(lpath)-1] == '/' {
lpath = lpath[:len(lpath)-1]
}
parts := strings.Split(lpath, "/")
for i, part := range parts {
if i == 0 && pa... | go | func (l Listing) BreadcrumbMap() map[string]string {
result := map[string]string{}
if len(l.Path) == 0 {
return result
}
// skip trailing slash
lpath := l.Path
if lpath[len(lpath)-1] == '/' {
lpath = lpath[:len(lpath)-1]
}
parts := strings.Split(lpath, "/")
for i, part := range parts {
if i == 0 && pa... | [
"func",
"(",
"l",
"Listing",
")",
"BreadcrumbMap",
"(",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"result",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n\n",
"if",
"len",
"(",
"l",
".",
"Path",
")",
"==",
"0",
"{",
"return",
"resu... | // BreadcrumbMap returns l.Path where every element is a map
// of URLs and path segment names. | [
"BreadcrumbMap",
"returns",
"l",
".",
"Path",
"where",
"every",
"element",
"is",
"a",
"map",
"of",
"URLs",
"and",
"path",
"segment",
"names",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/browse/browse.go#L82-L106 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/browse/browse.go | applySort | func (l Listing) applySort() {
// Check '.Order' to know how to sort
if l.Order == "desc" {
switch l.Sort {
case sortByName:
sort.Sort(sort.Reverse(byName(l)))
case sortBySize:
sort.Sort(sort.Reverse(bySize(l)))
case sortByTime:
sort.Sort(sort.Reverse(byTime(l)))
default:
// If not one of the ab... | go | func (l Listing) applySort() {
// Check '.Order' to know how to sort
if l.Order == "desc" {
switch l.Sort {
case sortByName:
sort.Sort(sort.Reverse(byName(l)))
case sortBySize:
sort.Sort(sort.Reverse(bySize(l)))
case sortByTime:
sort.Sort(sort.Reverse(byTime(l)))
default:
// If not one of the ab... | [
"func",
"(",
"l",
"Listing",
")",
"applySort",
"(",
")",
"{",
"// Check '.Order' to know how to sort",
"if",
"l",
".",
"Order",
"==",
"\"",
"\"",
"{",
"switch",
"l",
".",
"Sort",
"{",
"case",
"sortByName",
":",
"sort",
".",
"Sort",
"(",
"sort",
".",
"R... | // Add sorting method to "Listing"
// it will apply what's in ".Sort" and ".Order" | [
"Add",
"sorting",
"method",
"to",
"Listing",
"it",
"will",
"apply",
"what",
"s",
"in",
".",
"Sort",
"and",
".",
"Order"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/browse/browse.go#L166-L193 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/browse/browse.go | ServeHTTP | func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// See if there's a browse configuration to match the path
var bc *Config
for i := range b.Configs {
if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) {
bc = &b.Configs[i]
break
}
}
if bc == nil {
return b.Nex... | go | func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// See if there's a browse configuration to match the path
var bc *Config
for i := range b.Configs {
if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) {
bc = &b.Configs[i]
break
}
}
if bc == nil {
return b.Nex... | [
"func",
"(",
"b",
"Browse",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"int",
",",
"error",
")",
"{",
"// See if there's a browse configuration to match the path",
"var",
"bc",
"*",
"Config",
"... | // ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
// If so, control is handed over to ServeListing. | [
"ServeHTTP",
"determines",
"if",
"the",
"request",
"is",
"for",
"this",
"plugin",
"and",
"if",
"all",
"prerequisites",
"are",
"met",
".",
"If",
"so",
"control",
"is",
"handed",
"over",
"to",
"ServeListing",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/browse/browse.go#L247-L307 | train |
inverse-inc/packetfence | go/caddy/caddy/sigtrap.go | executeShutdownCallbacks | func executeShutdownCallbacks(signame string) (exitCode int) {
shutdownCallbacksOnce.Do(func() {
errs := allShutdownCallbacks()
if len(errs) > 0 {
for _, err := range errs {
log.Printf("[ERROR] %s shutdown: %v", signame, err)
}
exitCode = 1
}
})
return
} | go | func executeShutdownCallbacks(signame string) (exitCode int) {
shutdownCallbacksOnce.Do(func() {
errs := allShutdownCallbacks()
if len(errs) > 0 {
for _, err := range errs {
log.Printf("[ERROR] %s shutdown: %v", signame, err)
}
exitCode = 1
}
})
return
} | [
"func",
"executeShutdownCallbacks",
"(",
"signame",
"string",
")",
"(",
"exitCode",
"int",
")",
"{",
"shutdownCallbacksOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"errs",
":=",
"allShutdownCallbacks",
"(",
")",
"\n",
"if",
"len",
"(",
"errs",
")",
">",
... | // executeShutdownCallbacks executes the shutdown callbacks as initiated
// by signame. It logs any errors and returns the recommended exit status.
// This function is idempotent; subsequent invocations always return 0. | [
"executeShutdownCallbacks",
"executes",
"the",
"shutdown",
"callbacks",
"as",
"initiated",
"by",
"signame",
".",
"It",
"logs",
"any",
"errors",
"and",
"returns",
"the",
"recommended",
"exit",
"status",
".",
"This",
"function",
"is",
"idempotent",
";",
"subsequent"... | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/sigtrap.go#L53-L64 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/plugin.go | standardizeAddress | func standardizeAddress(str string) (Address, error) {
input := str
// Split input into components (prepend with // to assert host by default)
if !strings.Contains(str, "//") && !strings.HasPrefix(str, "/") {
str = "//" + str
}
u, err := url.Parse(str)
if err != nil {
return Address{}, err
}
// separate h... | go | func standardizeAddress(str string) (Address, error) {
input := str
// Split input into components (prepend with // to assert host by default)
if !strings.Contains(str, "//") && !strings.HasPrefix(str, "/") {
str = "//" + str
}
u, err := url.Parse(str)
if err != nil {
return Address{}, err
}
// separate h... | [
"func",
"standardizeAddress",
"(",
"str",
"string",
")",
"(",
"Address",
",",
"error",
")",
"{",
"input",
":=",
"str",
"\n\n",
"// Split input into components (prepend with // to assert host by default)",
"if",
"!",
"strings",
".",
"Contains",
"(",
"str",
",",
"\"",... | // standardizeAddress parses an address string into a structured format with separate
// scheme, host, port, and path portions, as well as the original input string. | [
"standardizeAddress",
"parses",
"an",
"address",
"string",
"into",
"a",
"structured",
"format",
"with",
"separate",
"scheme",
"host",
"port",
"and",
"path",
"portions",
"as",
"well",
"as",
"the",
"original",
"input",
"string",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/plugin.go#L306-L356 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/logger.go | Close | func (l *Logger) Close() error {
// Will close local/remote syslog connections too :)
if closer, ok := l.writer.(io.WriteCloser); ok {
l.fileMu.Lock()
err := closer.Close()
l.fileMu.Unlock()
return err
}
return nil
} | go | func (l *Logger) Close() error {
// Will close local/remote syslog connections too :)
if closer, ok := l.writer.(io.WriteCloser); ok {
l.fileMu.Lock()
err := closer.Close()
l.fileMu.Unlock()
return err
}
return nil
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Close",
"(",
")",
"error",
"{",
"// Will close local/remote syslog connections too :)",
"if",
"closer",
",",
"ok",
":=",
"l",
".",
"writer",
".",
"(",
"io",
".",
"WriteCloser",
")",
";",
"ok",
"{",
"l",
".",
"fileMu... | // Close closes open log files or connections to syslog. | [
"Close",
"closes",
"open",
"log",
"files",
"or",
"connections",
"to",
"syslog",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/logger.go#L138-L148 | train |
inverse-inc/packetfence | go/coredns/core/dnsserver/address.go | Transport | func Transport(s string) string {
switch {
case strings.HasPrefix(s, TransportTLS+"://"):
return TransportTLS
case strings.HasPrefix(s, TransportDNS+"://"):
return TransportDNS
case strings.HasPrefix(s, TransportGRPC+"://"):
return TransportGRPC
}
return TransportDNS
} | go | func Transport(s string) string {
switch {
case strings.HasPrefix(s, TransportTLS+"://"):
return TransportTLS
case strings.HasPrefix(s, TransportDNS+"://"):
return TransportDNS
case strings.HasPrefix(s, TransportGRPC+"://"):
return TransportGRPC
}
return TransportDNS
} | [
"func",
"Transport",
"(",
"s",
"string",
")",
"string",
"{",
"switch",
"{",
"case",
"strings",
".",
"HasPrefix",
"(",
"s",
",",
"TransportTLS",
"+",
"\"",
"\"",
")",
":",
"return",
"TransportTLS",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"s",
",... | // Transport returns the protocol of the string s | [
"Transport",
"returns",
"the",
"protocol",
"of",
"the",
"string",
"s"
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/address.go#L23-L33 | train |
inverse-inc/packetfence | go/coredns/core/dnsserver/address.go | normalizeZone | func normalizeZone(str string) (zoneAddr, error) {
var err error
// Default to DNS if there isn't a transport protocol prefix.
trans := TransportDNS
switch {
case strings.HasPrefix(str, TransportTLS+"://"):
trans = TransportTLS
str = str[len(TransportTLS+"://"):]
case strings.HasPrefix(str, TransportDNS+":/... | go | func normalizeZone(str string) (zoneAddr, error) {
var err error
// Default to DNS if there isn't a transport protocol prefix.
trans := TransportDNS
switch {
case strings.HasPrefix(str, TransportTLS+"://"):
trans = TransportTLS
str = str[len(TransportTLS+"://"):]
case strings.HasPrefix(str, TransportDNS+":/... | [
"func",
"normalizeZone",
"(",
"str",
"string",
")",
"(",
"zoneAddr",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n\n",
"// Default to DNS if there isn't a transport protocol prefix.",
"trans",
":=",
"TransportDNS",
"\n\n",
"switch",
"{",
"case",
"strings",
".",... | // normalizeZone parses an zone string into a structured format with separate
// host, and port portions, as well as the original input string. | [
"normalizeZone",
"parses",
"an",
"zone",
"string",
"into",
"a",
"structured",
"format",
"with",
"separate",
"host",
"and",
"port",
"portions",
"as",
"well",
"as",
"the",
"original",
"input",
"string",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/address.go#L37-L73 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/proxy/reverseproxy.go | cloneTLSClientConfig | func cloneTLSClientConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return &tls.Config{
Rand: cfg.Rand,
Time: cfg.Time,
Certificates: cfg.Certificates,
NameToCertificate: cfg.NameToCertificate,
GetCertifica... | go | func cloneTLSClientConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return &tls.Config{
Rand: cfg.Rand,
Time: cfg.Time,
Certificates: cfg.Certificates,
NameToCertificate: cfg.NameToCertificate,
GetCertifica... | [
"func",
"cloneTLSClientConfig",
"(",
"cfg",
"*",
"tls",
".",
"Config",
")",
"*",
"tls",
".",
"Config",
"{",
"if",
"cfg",
"==",
"nil",
"{",
"return",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"tls",
".",
"Config",
"{",
"... | // cloneTLSClientConfig is like cloneTLSConfig but omits
// the fields SessionTicketsDisabled and SessionTicketKey.
// This makes it safe to call cloneTLSClientConfig on a config
// in active use by a server. | [
"cloneTLSClientConfig",
"is",
"like",
"cloneTLSConfig",
"but",
"omits",
"the",
"fields",
"SessionTicketsDisabled",
"and",
"SessionTicketKey",
".",
"This",
"makes",
"it",
"safe",
"to",
"call",
"cloneTLSClientConfig",
"on",
"a",
"config",
"in",
"active",
"use",
"by",
... | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/proxy/reverseproxy.go#L555-L580 | train |
inverse-inc/packetfence | go/coredns/plugin/auto/walk.go | matches | func matches(re *regexp.Regexp, filename, template string) (match bool, origin string) {
base := path.Base(filename)
matches := re.FindStringSubmatchIndex(base)
if matches == nil {
return false, ""
}
by := re.ExpandString(nil, template, base, matches)
if by == nil {
return false, ""
}
origin = dns.Fqdn(s... | go | func matches(re *regexp.Regexp, filename, template string) (match bool, origin string) {
base := path.Base(filename)
matches := re.FindStringSubmatchIndex(base)
if matches == nil {
return false, ""
}
by := re.ExpandString(nil, template, base, matches)
if by == nil {
return false, ""
}
origin = dns.Fqdn(s... | [
"func",
"matches",
"(",
"re",
"*",
"regexp",
".",
"Regexp",
",",
"filename",
",",
"template",
"string",
")",
"(",
"match",
"bool",
",",
"origin",
"string",
")",
"{",
"base",
":=",
"path",
".",
"Base",
"(",
"filename",
")",
"\n\n",
"matches",
":=",
"r... | // matches matches re to filename, if is is a match, the subexpression will be used to expand
// template to an origin. When match is true that origin is returned. Origin is fully qualified. | [
"matches",
"matches",
"re",
"to",
"filename",
"if",
"is",
"is",
"a",
"match",
"the",
"subexpression",
"will",
"be",
"used",
"to",
"expand",
"template",
"to",
"an",
"origin",
".",
"When",
"match",
"is",
"true",
"that",
"origin",
"is",
"returned",
".",
"Or... | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/auto/walk.go#L93-L109 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/graceful.go | Accept | func (gl *gracefulListener) Accept() (c net.Conn, err error) {
c, err = gl.Listener.Accept()
if err != nil {
return
}
c = gracefulConn{Conn: c, connWg: gl.connWg}
gl.connWg.Add(1)
return
} | go | func (gl *gracefulListener) Accept() (c net.Conn, err error) {
c, err = gl.Listener.Accept()
if err != nil {
return
}
c = gracefulConn{Conn: c, connWg: gl.connWg}
gl.connWg.Add(1)
return
} | [
"func",
"(",
"gl",
"*",
"gracefulListener",
")",
"Accept",
"(",
")",
"(",
"c",
"net",
".",
"Conn",
",",
"err",
"error",
")",
"{",
"c",
",",
"err",
"=",
"gl",
".",
"Listener",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return... | // Accept accepts a connection. | [
"Accept",
"accepts",
"a",
"connection",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/graceful.go#L39-L47 | train |
inverse-inc/packetfence | go/caddy/caddy/caddyhttp/httpserver/graceful.go | Close | func (gl *gracefulListener) Close() error {
gl.Lock()
if gl.stopped {
gl.Unlock()
return syscall.EINVAL
}
gl.Unlock()
gl.stop <- nil
return <-gl.stop
} | go | func (gl *gracefulListener) Close() error {
gl.Lock()
if gl.stopped {
gl.Unlock()
return syscall.EINVAL
}
gl.Unlock()
gl.stop <- nil
return <-gl.stop
} | [
"func",
"(",
"gl",
"*",
"gracefulListener",
")",
"Close",
"(",
")",
"error",
"{",
"gl",
".",
"Lock",
"(",
")",
"\n",
"if",
"gl",
".",
"stopped",
"{",
"gl",
".",
"Unlock",
"(",
")",
"\n",
"return",
"syscall",
".",
"EINVAL",
"\n",
"}",
"\n",
"gl",
... | // Close immediately closes the listener. | [
"Close",
"immediately",
"closes",
"the",
"listener",
"."
] | f29912bde7974931d699aba60aa8fde1c5d9a826 | https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/httpserver/graceful.go#L50-L59 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.