id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
16,600
pkg/xattr
xattr.go
FSet
func FSet(f *os.File, name string, data []byte) error { if err := fsetxattr(f, name, data, 0); err != nil { return &Error{"xattr.FSet", f.Name(), name, err} } return nil }
go
func FSet(f *os.File, name string, data []byte) error { if err := fsetxattr(f, name, data, 0); err != nil { return &Error{"xattr.FSet", f.Name(), name, err} } return nil }
[ "func", "FSet", "(", "f", "*", "os", ".", "File", ",", "name", "string", ",", "data", "[", "]", "byte", ")", "error", "{", "if", "err", ":=", "fsetxattr", "(", "f", ",", "name", ",", "data", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "&", "Error", "{", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "name", ",", "err", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FSet is like Set but accepts a os.File instead of a file path.
[ "FSet", "is", "like", "Set", "but", "accepts", "a", "os", ".", "File", "instead", "of", "a", "file", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L122-L127
16,601
pkg/xattr
xattr.go
SetWithFlags
func SetWithFlags(path, name string, data []byte, flags int) error { if err := setxattr(path, name, data, flags); err != nil { return &Error{"xattr.SetWithFlags", path, name, err} } return nil }
go
func SetWithFlags(path, name string, data []byte, flags int) error { if err := setxattr(path, name, data, flags); err != nil { return &Error{"xattr.SetWithFlags", path, name, err} } return nil }
[ "func", "SetWithFlags", "(", "path", ",", "name", "string", ",", "data", "[", "]", "byte", ",", "flags", "int", ")", "error", "{", "if", "err", ":=", "setxattr", "(", "path", ",", "name", ",", "data", ",", "flags", ")", ";", "err", "!=", "nil", "{", "return", "&", "Error", "{", "\"", "\"", ",", "path", ",", "name", ",", "err", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetWithFlags associates name and data together as an attribute of path. // Forwards the flags parameter to the syscall layer.
[ "SetWithFlags", "associates", "name", "and", "data", "together", "as", "an", "attribute", "of", "path", ".", "Forwards", "the", "flags", "parameter", "to", "the", "syscall", "layer", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L131-L136
16,602
pkg/xattr
xattr.go
LSetWithFlags
func LSetWithFlags(path, name string, data []byte, flags int) error { if err := lsetxattr(path, name, data, flags); err != nil { return &Error{"xattr.LSetWithFlags", path, name, err} } return nil }
go
func LSetWithFlags(path, name string, data []byte, flags int) error { if err := lsetxattr(path, name, data, flags); err != nil { return &Error{"xattr.LSetWithFlags", path, name, err} } return nil }
[ "func", "LSetWithFlags", "(", "path", ",", "name", "string", ",", "data", "[", "]", "byte", ",", "flags", "int", ")", "error", "{", "if", "err", ":=", "lsetxattr", "(", "path", ",", "name", ",", "data", ",", "flags", ")", ";", "err", "!=", "nil", "{", "return", "&", "Error", "{", "\"", "\"", ",", "path", ",", "name", ",", "err", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LSetWithFlags is like SetWithFlags but does not follow a symlink at // the end of the path.
[ "LSetWithFlags", "is", "like", "SetWithFlags", "but", "does", "not", "follow", "a", "symlink", "at", "the", "end", "of", "the", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L140-L145
16,603
pkg/xattr
xattr.go
FSetWithFlags
func FSetWithFlags(f *os.File, name string, data []byte, flags int) error { if err := fsetxattr(f, name, data, flags); err != nil { return &Error{"xattr.FSetWithFlags", f.Name(), name, err} } return nil }
go
func FSetWithFlags(f *os.File, name string, data []byte, flags int) error { if err := fsetxattr(f, name, data, flags); err != nil { return &Error{"xattr.FSetWithFlags", f.Name(), name, err} } return nil }
[ "func", "FSetWithFlags", "(", "f", "*", "os", ".", "File", ",", "name", "string", ",", "data", "[", "]", "byte", ",", "flags", "int", ")", "error", "{", "if", "err", ":=", "fsetxattr", "(", "f", ",", "name", ",", "data", ",", "flags", ")", ";", "err", "!=", "nil", "{", "return", "&", "Error", "{", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "name", ",", "err", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FSetWithFlags is like SetWithFlags but accepts a os.File instead of a file path.
[ "FSetWithFlags", "is", "like", "SetWithFlags", "but", "accepts", "a", "os", ".", "File", "instead", "of", "a", "file", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L148-L153
16,604
pkg/xattr
xattr.go
Remove
func Remove(path, name string) error { if err := removexattr(path, name); err != nil { return &Error{"xattr.Remove", path, name, err} } return nil }
go
func Remove(path, name string) error { if err := removexattr(path, name); err != nil { return &Error{"xattr.Remove", path, name, err} } return nil }
[ "func", "Remove", "(", "path", ",", "name", "string", ")", "error", "{", "if", "err", ":=", "removexattr", "(", "path", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "&", "Error", "{", "\"", "\"", ",", "path", ",", "name", ",", "err", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Remove removes the attribute associated with the given path.
[ "Remove", "removes", "the", "attribute", "associated", "with", "the", "given", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L156-L161
16,605
pkg/xattr
xattr.go
LRemove
func LRemove(path, name string) error { if err := lremovexattr(path, name); err != nil { return &Error{"xattr.LRemove", path, name, err} } return nil }
go
func LRemove(path, name string) error { if err := lremovexattr(path, name); err != nil { return &Error{"xattr.LRemove", path, name, err} } return nil }
[ "func", "LRemove", "(", "path", ",", "name", "string", ")", "error", "{", "if", "err", ":=", "lremovexattr", "(", "path", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "&", "Error", "{", "\"", "\"", ",", "path", ",", "name", ",", "err", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LRemove is like Remove but does not follow a symlink at the end of the // path.
[ "LRemove", "is", "like", "Remove", "but", "does", "not", "follow", "a", "symlink", "at", "the", "end", "of", "the", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L165-L170
16,606
pkg/xattr
xattr.go
FRemove
func FRemove(f *os.File, name string) error { if err := fremovexattr(f, name); err != nil { return &Error{"xattr.FRemove", f.Name(), name, err} } return nil }
go
func FRemove(f *os.File, name string) error { if err := fremovexattr(f, name); err != nil { return &Error{"xattr.FRemove", f.Name(), name, err} } return nil }
[ "func", "FRemove", "(", "f", "*", "os", ".", "File", ",", "name", "string", ")", "error", "{", "if", "err", ":=", "fremovexattr", "(", "f", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "&", "Error", "{", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "name", ",", "err", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FRemove is like Remove but accepts a os.File instead of a file path.
[ "FRemove", "is", "like", "Remove", "but", "accepts", "a", "os", ".", "File", "instead", "of", "a", "file", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L173-L178
16,607
pkg/xattr
xattr.go
List
func List(path string) ([]string, error) { return list(path, func(data []byte) (int, error) { return listxattr(path, data) }) }
go
func List(path string) ([]string, error) { return list(path, func(data []byte) (int, error) { return listxattr(path, data) }) }
[ "func", "List", "(", "path", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "return", "list", "(", "path", ",", "func", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "listxattr", "(", "path", ",", "data", ")", "\n", "}", ")", "\n", "}" ]
// List retrieves a list of names of extended attributes associated // with the given path in the file system.
[ "List", "retrieves", "a", "list", "of", "names", "of", "extended", "attributes", "associated", "with", "the", "given", "path", "in", "the", "file", "system", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L182-L186
16,608
pkg/xattr
xattr.go
LList
func LList(path string) ([]string, error) { return list(path, func(data []byte) (int, error) { return llistxattr(path, data) }) }
go
func LList(path string) ([]string, error) { return list(path, func(data []byte) (int, error) { return llistxattr(path, data) }) }
[ "func", "LList", "(", "path", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "return", "list", "(", "path", ",", "func", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "llistxattr", "(", "path", ",", "data", ")", "\n", "}", ")", "\n", "}" ]
// LList is like List but does not follow a symlink at the end of the // path.
[ "LList", "is", "like", "List", "but", "does", "not", "follow", "a", "symlink", "at", "the", "end", "of", "the", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L190-L194
16,609
pkg/xattr
xattr.go
FList
func FList(f *os.File) ([]string, error) { return list(f.Name(), func(data []byte) (int, error) { return flistxattr(f, data) }) }
go
func FList(f *os.File) ([]string, error) { return list(f.Name(), func(data []byte) (int, error) { return flistxattr(f, data) }) }
[ "func", "FList", "(", "f", "*", "os", ".", "File", ")", "(", "[", "]", "string", ",", "error", ")", "{", "return", "list", "(", "f", ".", "Name", "(", ")", ",", "func", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "flistxattr", "(", "f", ",", "data", ")", "\n", "}", ")", "\n", "}" ]
// FList is like List but accepts a os.File instead of a file path.
[ "FList", "is", "like", "List", "but", "accepts", "a", "os", ".", "File", "instead", "of", "a", "file", "path", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L197-L201
16,610
pkg/xattr
xattr.go
list
func list(path string, listxattrFunc listxattrFunc) ([]string, error) { myname := "xattr.list" // find size. size, err := listxattrFunc(nil) if err != nil { return nil, &Error{myname, path, "", err} } if size > 0 { // `size + 1` because of ERANGE error when reading // from a SMB1 mount point (https://github.com/pkg/xattr/issues/16). buf := make([]byte, size+1) // Read into buffer of that size. read, err := listxattrFunc(buf) if err != nil { return nil, &Error{myname, path, "", err} } return stringsFromByteSlice(buf[:read]), nil } return []string{}, nil }
go
func list(path string, listxattrFunc listxattrFunc) ([]string, error) { myname := "xattr.list" // find size. size, err := listxattrFunc(nil) if err != nil { return nil, &Error{myname, path, "", err} } if size > 0 { // `size + 1` because of ERANGE error when reading // from a SMB1 mount point (https://github.com/pkg/xattr/issues/16). buf := make([]byte, size+1) // Read into buffer of that size. read, err := listxattrFunc(buf) if err != nil { return nil, &Error{myname, path, "", err} } return stringsFromByteSlice(buf[:read]), nil } return []string{}, nil }
[ "func", "list", "(", "path", "string", ",", "listxattrFunc", "listxattrFunc", ")", "(", "[", "]", "string", ",", "error", ")", "{", "myname", ":=", "\"", "\"", "\n", "// find size.", "size", ",", "err", ":=", "listxattrFunc", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "Error", "{", "myname", ",", "path", ",", "\"", "\"", ",", "err", "}", "\n", "}", "\n", "if", "size", ">", "0", "{", "// `size + 1` because of ERANGE error when reading", "// from a SMB1 mount point (https://github.com/pkg/xattr/issues/16).", "buf", ":=", "make", "(", "[", "]", "byte", ",", "size", "+", "1", ")", "\n", "// Read into buffer of that size.", "read", ",", "err", ":=", "listxattrFunc", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "Error", "{", "myname", ",", "path", ",", "\"", "\"", ",", "err", "}", "\n", "}", "\n", "return", "stringsFromByteSlice", "(", "buf", "[", ":", "read", "]", ")", ",", "nil", "\n", "}", "\n", "return", "[", "]", "string", "{", "}", ",", "nil", "\n", "}" ]
// list contains the buffer allocation logic used by both List and LList.
[ "list", "contains", "the", "buffer", "allocation", "logic", "used", "by", "both", "List", "and", "LList", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L206-L225
16,611
pkg/xattr
xattr.go
bytePtrFromSlice
func bytePtrFromSlice(data []byte) (ptr *byte, size int) { size = len(data) if size > 0 { ptr = &data[0] } return }
go
func bytePtrFromSlice(data []byte) (ptr *byte, size int) { size = len(data) if size > 0 { ptr = &data[0] } return }
[ "func", "bytePtrFromSlice", "(", "data", "[", "]", "byte", ")", "(", "ptr", "*", "byte", ",", "size", "int", ")", "{", "size", "=", "len", "(", "data", ")", "\n", "if", "size", ">", "0", "{", "ptr", "=", "&", "data", "[", "0", "]", "\n", "}", "\n", "return", "\n", "}" ]
// bytePtrFromSlice returns a pointer to array of bytes and a size.
[ "bytePtrFromSlice", "returns", "a", "pointer", "to", "array", "of", "bytes", "and", "a", "size", "." ]
f2ae4ae548121ce70f98b72822c65d86900849c3
https://github.com/pkg/xattr/blob/f2ae4ae548121ce70f98b72822c65d86900849c3/xattr.go#L228-L234
16,612
kobolog/gorb
util/net.go
AddrFamily
func AddrFamily(ip net.IP) int { if len(ip) == v4Length { return IPv4 } if len(ip) == v6Length && bytes.HasPrefix(ip, v4Prefix) { return IPv4 } return IPv6 }
go
func AddrFamily(ip net.IP) int { if len(ip) == v4Length { return IPv4 } if len(ip) == v6Length && bytes.HasPrefix(ip, v4Prefix) { return IPv4 } return IPv6 }
[ "func", "AddrFamily", "(", "ip", "net", ".", "IP", ")", "int", "{", "if", "len", "(", "ip", ")", "==", "v4Length", "{", "return", "IPv4", "\n", "}", "\n\n", "if", "len", "(", "ip", ")", "==", "v6Length", "&&", "bytes", ".", "HasPrefix", "(", "ip", ",", "v4Prefix", ")", "{", "return", "IPv4", "\n", "}", "\n\n", "return", "IPv6", "\n", "}" ]
// AddrFamily returns the address family of an IP address.
[ "AddrFamily", "returns", "the", "address", "family", "of", "an", "IP", "address", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/util/net.go#L45-L55
16,613
kobolog/gorb
util/net.go
InterfaceIPs
func InterfaceIPs(device string) (ips []net.IP, _ error) { var networks []net.Addr if iface, err := net.InterfaceByName(device); err != nil { return nil, err } else if networks, err = iface.Addrs(); err != nil { return nil, err } for _, network := range networks { if ipNet, castable := network.(*net.IPNet); castable { ips = append(ips, ipNet.IP) } } // Note that on non-IP interfaces it will be an empty slice // and no error indicator. Maybe that's not super-perfect. return ips, nil }
go
func InterfaceIPs(device string) (ips []net.IP, _ error) { var networks []net.Addr if iface, err := net.InterfaceByName(device); err != nil { return nil, err } else if networks, err = iface.Addrs(); err != nil { return nil, err } for _, network := range networks { if ipNet, castable := network.(*net.IPNet); castable { ips = append(ips, ipNet.IP) } } // Note that on non-IP interfaces it will be an empty slice // and no error indicator. Maybe that's not super-perfect. return ips, nil }
[ "func", "InterfaceIPs", "(", "device", "string", ")", "(", "ips", "[", "]", "net", ".", "IP", ",", "_", "error", ")", "{", "var", "networks", "[", "]", "net", ".", "Addr", "\n\n", "if", "iface", ",", "err", ":=", "net", ".", "InterfaceByName", "(", "device", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "networks", ",", "err", "=", "iface", ".", "Addrs", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "network", ":=", "range", "networks", "{", "if", "ipNet", ",", "castable", ":=", "network", ".", "(", "*", "net", ".", "IPNet", ")", ";", "castable", "{", "ips", "=", "append", "(", "ips", ",", "ipNet", ".", "IP", ")", "\n", "}", "\n", "}", "\n\n", "// Note that on non-IP interfaces it will be an empty slice", "// and no error indicator. Maybe that's not super-perfect.", "return", "ips", ",", "nil", "\n", "}" ]
// InterfaceIPs returns a slice of interface IP addresses.
[ "InterfaceIPs", "returns", "a", "slice", "of", "interface", "IP", "addresses", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/util/net.go#L58-L76
16,614
kobolog/gorb
core/options.go
Validate
func (o *ServiceOptions) Validate(defaultHost net.IP) error { if o.Port == 0 { return ErrMissingEndpoint } if len(o.Host) != 0 { if addr, err := net.ResolveIPAddr("ip", o.Host); err == nil { o.host = addr.IP } else { return err } } else if defaultHost != nil { o.host = defaultHost } else { return ErrMissingEndpoint } if len(o.Protocol) == 0 { o.Protocol = "tcp" } o.Protocol = strings.ToLower(o.Protocol) switch o.Protocol { case "tcp": o.protocol = syscall.IPPROTO_TCP case "udp": o.protocol = syscall.IPPROTO_UDP default: return ErrUnknownProtocol } if o.Flags != "" { for _, flag := range strings.Split(o.Flags, "|") { if _, ok := schedulerFlags[flag]; !ok { return ErrUnknownFlag } } } if len(o.Method) == 0 { // WRR since Pulse will dynamically reweight backends. o.Method = "wrr" } return nil }
go
func (o *ServiceOptions) Validate(defaultHost net.IP) error { if o.Port == 0 { return ErrMissingEndpoint } if len(o.Host) != 0 { if addr, err := net.ResolveIPAddr("ip", o.Host); err == nil { o.host = addr.IP } else { return err } } else if defaultHost != nil { o.host = defaultHost } else { return ErrMissingEndpoint } if len(o.Protocol) == 0 { o.Protocol = "tcp" } o.Protocol = strings.ToLower(o.Protocol) switch o.Protocol { case "tcp": o.protocol = syscall.IPPROTO_TCP case "udp": o.protocol = syscall.IPPROTO_UDP default: return ErrUnknownProtocol } if o.Flags != "" { for _, flag := range strings.Split(o.Flags, "|") { if _, ok := schedulerFlags[flag]; !ok { return ErrUnknownFlag } } } if len(o.Method) == 0 { // WRR since Pulse will dynamically reweight backends. o.Method = "wrr" } return nil }
[ "func", "(", "o", "*", "ServiceOptions", ")", "Validate", "(", "defaultHost", "net", ".", "IP", ")", "error", "{", "if", "o", ".", "Port", "==", "0", "{", "return", "ErrMissingEndpoint", "\n", "}", "\n\n", "if", "len", "(", "o", ".", "Host", ")", "!=", "0", "{", "if", "addr", ",", "err", ":=", "net", ".", "ResolveIPAddr", "(", "\"", "\"", ",", "o", ".", "Host", ")", ";", "err", "==", "nil", "{", "o", ".", "host", "=", "addr", ".", "IP", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "else", "if", "defaultHost", "!=", "nil", "{", "o", ".", "host", "=", "defaultHost", "\n", "}", "else", "{", "return", "ErrMissingEndpoint", "\n", "}", "\n\n", "if", "len", "(", "o", ".", "Protocol", ")", "==", "0", "{", "o", ".", "Protocol", "=", "\"", "\"", "\n", "}", "\n\n", "o", ".", "Protocol", "=", "strings", ".", "ToLower", "(", "o", ".", "Protocol", ")", "\n\n", "switch", "o", ".", "Protocol", "{", "case", "\"", "\"", ":", "o", ".", "protocol", "=", "syscall", ".", "IPPROTO_TCP", "\n", "case", "\"", "\"", ":", "o", ".", "protocol", "=", "syscall", ".", "IPPROTO_UDP", "\n", "default", ":", "return", "ErrUnknownProtocol", "\n", "}", "\n\n", "if", "o", ".", "Flags", "!=", "\"", "\"", "{", "for", "_", ",", "flag", ":=", "range", "strings", ".", "Split", "(", "o", ".", "Flags", ",", "\"", "\"", ")", "{", "if", "_", ",", "ok", ":=", "schedulerFlags", "[", "flag", "]", ";", "!", "ok", "{", "return", "ErrUnknownFlag", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "o", ".", "Method", ")", "==", "0", "{", "// WRR since Pulse will dynamically reweight backends.", "o", ".", "Method", "=", "\"", "\"", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate fills missing fields and validates virtual service configuration.
[ "Validate", "fills", "missing", "fields", "and", "validates", "virtual", "service", "configuration", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/core/options.go#L69-L115
16,615
kobolog/gorb
core/options.go
Validate
func (o *BackendOptions) Validate() error { if len(o.Host) == 0 || o.Port == 0 { return ErrMissingEndpoint } if addr, err := net.ResolveIPAddr("ip", o.Host); err == nil { o.host = addr.IP } else { return err } if o.Weight <= 0 { o.Weight = 100 } if len(o.Method) == 0 { o.Method = "nat" } o.Method = strings.ToLower(o.Method) switch o.Method { case "dr": o.methodID = gnl2go.IPVS_DIRECTROUTE case "nat": o.methodID = gnl2go.IPVS_MASQUERADING case "tunnel", "ipip": o.methodID = gnl2go.IPVS_TUNNELING default: return ErrUnknownMethod } if o.Pulse == nil { // It doesn't make much sense to have a backend with no Pulse. o.Pulse = &pulse.Options{} } return nil }
go
func (o *BackendOptions) Validate() error { if len(o.Host) == 0 || o.Port == 0 { return ErrMissingEndpoint } if addr, err := net.ResolveIPAddr("ip", o.Host); err == nil { o.host = addr.IP } else { return err } if o.Weight <= 0 { o.Weight = 100 } if len(o.Method) == 0 { o.Method = "nat" } o.Method = strings.ToLower(o.Method) switch o.Method { case "dr": o.methodID = gnl2go.IPVS_DIRECTROUTE case "nat": o.methodID = gnl2go.IPVS_MASQUERADING case "tunnel", "ipip": o.methodID = gnl2go.IPVS_TUNNELING default: return ErrUnknownMethod } if o.Pulse == nil { // It doesn't make much sense to have a backend with no Pulse. o.Pulse = &pulse.Options{} } return nil }
[ "func", "(", "o", "*", "BackendOptions", ")", "Validate", "(", ")", "error", "{", "if", "len", "(", "o", ".", "Host", ")", "==", "0", "||", "o", ".", "Port", "==", "0", "{", "return", "ErrMissingEndpoint", "\n", "}", "\n\n", "if", "addr", ",", "err", ":=", "net", ".", "ResolveIPAddr", "(", "\"", "\"", ",", "o", ".", "Host", ")", ";", "err", "==", "nil", "{", "o", ".", "host", "=", "addr", ".", "IP", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n\n", "if", "o", ".", "Weight", "<=", "0", "{", "o", ".", "Weight", "=", "100", "\n", "}", "\n\n", "if", "len", "(", "o", ".", "Method", ")", "==", "0", "{", "o", ".", "Method", "=", "\"", "\"", "\n", "}", "\n\n", "o", ".", "Method", "=", "strings", ".", "ToLower", "(", "o", ".", "Method", ")", "\n\n", "switch", "o", ".", "Method", "{", "case", "\"", "\"", ":", "o", ".", "methodID", "=", "gnl2go", ".", "IPVS_DIRECTROUTE", "\n", "case", "\"", "\"", ":", "o", ".", "methodID", "=", "gnl2go", ".", "IPVS_MASQUERADING", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "o", ".", "methodID", "=", "gnl2go", ".", "IPVS_TUNNELING", "\n", "default", ":", "return", "ErrUnknownMethod", "\n", "}", "\n\n", "if", "o", ".", "Pulse", "==", "nil", "{", "// It doesn't make much sense to have a backend with no Pulse.", "o", ".", "Pulse", "=", "&", "pulse", ".", "Options", "{", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate fills missing fields and validates backend configuration.
[ "Validate", "fills", "missing", "fields", "and", "validates", "backend", "configuration", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/core/options.go#L156-L194
16,616
kobolog/gorb
pulse/options.go
Validate
func (o *Options) Validate() error { if len(o.Type) == 0 { // TCP is a safe guess: the majority of services are TCP-based. o.Type = "tcp" } if len(o.Interval) == 0 { o.Interval = "1m" } o.Type = strings.ToLower(o.Type) if fn := get[o.Type]; fn == nil { return ErrUnknownPulseType } var err error if o.interval, err = util.ParseInterval(o.Interval); err != nil { return err } else if o.interval <= 0 { return ErrInvalidPulseInterval } return nil }
go
func (o *Options) Validate() error { if len(o.Type) == 0 { // TCP is a safe guess: the majority of services are TCP-based. o.Type = "tcp" } if len(o.Interval) == 0 { o.Interval = "1m" } o.Type = strings.ToLower(o.Type) if fn := get[o.Type]; fn == nil { return ErrUnknownPulseType } var err error if o.interval, err = util.ParseInterval(o.Interval); err != nil { return err } else if o.interval <= 0 { return ErrInvalidPulseInterval } return nil }
[ "func", "(", "o", "*", "Options", ")", "Validate", "(", ")", "error", "{", "if", "len", "(", "o", ".", "Type", ")", "==", "0", "{", "// TCP is a safe guess: the majority of services are TCP-based.", "o", ".", "Type", "=", "\"", "\"", "\n", "}", "\n\n", "if", "len", "(", "o", ".", "Interval", ")", "==", "0", "{", "o", ".", "Interval", "=", "\"", "\"", "\n", "}", "\n\n", "o", ".", "Type", "=", "strings", ".", "ToLower", "(", "o", ".", "Type", ")", "\n\n", "if", "fn", ":=", "get", "[", "o", ".", "Type", "]", ";", "fn", "==", "nil", "{", "return", "ErrUnknownPulseType", "\n", "}", "\n\n", "var", "err", "error", "\n\n", "if", "o", ".", "interval", ",", "err", "=", "util", ".", "ParseInterval", "(", "o", ".", "Interval", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "o", ".", "interval", "<=", "0", "{", "return", "ErrInvalidPulseInterval", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate fills missing fields and validates Pulse configuration.
[ "Validate", "fills", "missing", "fields", "and", "validates", "Pulse", "configuration", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/pulse/options.go#L47-L72
16,617
kobolog/gorb
pulse/metrics.go
NewMetrics
func NewMetrics() *Metrics { return &Metrics{Status: StatusUp, Health: 1, Uptime: 0, lastTs: time.Now()} }
go
func NewMetrics() *Metrics { return &Metrics{Status: StatusUp, Health: 1, Uptime: 0, lastTs: time.Now()} }
[ "func", "NewMetrics", "(", ")", "*", "Metrics", "{", "return", "&", "Metrics", "{", "Status", ":", "StatusUp", ",", "Health", ":", "1", ",", "Uptime", ":", "0", ",", "lastTs", ":", "time", ".", "Now", "(", ")", "}", "\n", "}" ]
// NewMetrics creates a new instance of metrics.
[ "NewMetrics", "creates", "a", "new", "instance", "of", "metrics", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/pulse/metrics.go#L39-L41
16,618
kobolog/gorb
pulse/metrics.go
Update
func (m *Metrics) Update(status StatusType) Metrics { m.Status = status m.Health = 0 m.record = append(m.record, status) if len(m.record) > 100 { m.record = m.record[1:] } for _, result := range m.record { m.Health += float64(result) } m.Health = 1.0 - m.Health/float64(len(m.record)) if ts := time.Now(); m.Status != StatusUp { m.Uptime, m.lastTs = 0, ts } else { m.Uptime, m.lastTs = m.Uptime+ts.Sub(m.lastTs)/time.Second, ts } return *m }
go
func (m *Metrics) Update(status StatusType) Metrics { m.Status = status m.Health = 0 m.record = append(m.record, status) if len(m.record) > 100 { m.record = m.record[1:] } for _, result := range m.record { m.Health += float64(result) } m.Health = 1.0 - m.Health/float64(len(m.record)) if ts := time.Now(); m.Status != StatusUp { m.Uptime, m.lastTs = 0, ts } else { m.Uptime, m.lastTs = m.Uptime+ts.Sub(m.lastTs)/time.Second, ts } return *m }
[ "func", "(", "m", "*", "Metrics", ")", "Update", "(", "status", "StatusType", ")", "Metrics", "{", "m", ".", "Status", "=", "status", "\n", "m", ".", "Health", "=", "0", "\n", "m", ".", "record", "=", "append", "(", "m", ".", "record", ",", "status", ")", "\n\n", "if", "len", "(", "m", ".", "record", ")", ">", "100", "{", "m", ".", "record", "=", "m", ".", "record", "[", "1", ":", "]", "\n", "}", "\n\n", "for", "_", ",", "result", ":=", "range", "m", ".", "record", "{", "m", ".", "Health", "+=", "float64", "(", "result", ")", "\n", "}", "\n\n", "m", ".", "Health", "=", "1.0", "-", "m", ".", "Health", "/", "float64", "(", "len", "(", "m", ".", "record", ")", ")", "\n\n", "if", "ts", ":=", "time", ".", "Now", "(", ")", ";", "m", ".", "Status", "!=", "StatusUp", "{", "m", ".", "Uptime", ",", "m", ".", "lastTs", "=", "0", ",", "ts", "\n", "}", "else", "{", "m", ".", "Uptime", ",", "m", ".", "lastTs", "=", "m", ".", "Uptime", "+", "ts", ".", "Sub", "(", "m", ".", "lastTs", ")", "/", "time", ".", "Second", ",", "ts", "\n", "}", "\n\n", "return", "*", "m", "\n", "}" ]
// Update updates metrics based on Pulse status message.
[ "Update", "updates", "metrics", "based", "on", "Pulse", "status", "message", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/pulse/metrics.go#L44-L66
16,619
kobolog/gorb
util/time.go
ParseInterval
func ParseInterval(s string) (time.Duration, error) { if m := reInterval.FindStringSubmatch(strings.TrimSpace(s)); len(m) != 0 { value, _ := strconv.ParseInt(m[1], 10, 32) duration := intervals[strings.ToLower(m[2])] return duration * time.Duration(value), nil } return 0, errInvalidIntervalFormat }
go
func ParseInterval(s string) (time.Duration, error) { if m := reInterval.FindStringSubmatch(strings.TrimSpace(s)); len(m) != 0 { value, _ := strconv.ParseInt(m[1], 10, 32) duration := intervals[strings.ToLower(m[2])] return duration * time.Duration(value), nil } return 0, errInvalidIntervalFormat }
[ "func", "ParseInterval", "(", "s", "string", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "m", ":=", "reInterval", ".", "FindStringSubmatch", "(", "strings", ".", "TrimSpace", "(", "s", ")", ")", ";", "len", "(", "m", ")", "!=", "0", "{", "value", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "m", "[", "1", "]", ",", "10", ",", "32", ")", "\n", "duration", ":=", "intervals", "[", "strings", ".", "ToLower", "(", "m", "[", "2", "]", ")", "]", "\n\n", "return", "duration", "*", "time", ".", "Duration", "(", "value", ")", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "errInvalidIntervalFormat", "\n", "}" ]
// ParseInterval parses an interval string and returns the corresponding duration.
[ "ParseInterval", "parses", "an", "interval", "string", "and", "returns", "the", "corresponding", "duration", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/util/time.go#L49-L58
16,620
kobolog/gorb
util/json.go
MustMarshal
func MustMarshal(object interface{}, options JSONOptions) []byte { output, err := json.Marshal(&object) if err != nil { panic(err) } switch { case options.Indent: buffer := bytes.Buffer{} // TODO(@kobolog): Expose indentation options via JSONOptions. json.Indent(&buffer, output, "", "\t") return buffer.Bytes() default: return output } }
go
func MustMarshal(object interface{}, options JSONOptions) []byte { output, err := json.Marshal(&object) if err != nil { panic(err) } switch { case options.Indent: buffer := bytes.Buffer{} // TODO(@kobolog): Expose indentation options via JSONOptions. json.Indent(&buffer, output, "", "\t") return buffer.Bytes() default: return output } }
[ "func", "MustMarshal", "(", "object", "interface", "{", "}", ",", "options", "JSONOptions", ")", "[", "]", "byte", "{", "output", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "object", ")", "\n\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "switch", "{", "case", "options", ".", "Indent", ":", "buffer", ":=", "bytes", ".", "Buffer", "{", "}", "\n\n", "// TODO(@kobolog): Expose indentation options via JSONOptions.", "json", ".", "Indent", "(", "&", "buffer", ",", "output", ",", "\"", "\"", ",", "\"", "\\t", "\"", ")", "\n\n", "return", "buffer", ".", "Bytes", "(", ")", "\n\n", "default", ":", "return", "output", "\n", "}", "\n", "}" ]
// MustMarshal will try to convert the given object to JSON or panic if there's an error.
[ "MustMarshal", "will", "try", "to", "convert", "the", "given", "object", "to", "JSON", "or", "panic", "if", "there", "s", "an", "error", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/util/json.go#L34-L53
16,621
kobolog/gorb
disco/disco.go
New
func New(opts *Options) (Driver, error) { switch opts.Type { case "consul": return newConsulDriver(opts.Args) default: return &noopDriver{}, nil } }
go
func New(opts *Options) (Driver, error) { switch opts.Type { case "consul": return newConsulDriver(opts.Args) default: return &noopDriver{}, nil } }
[ "func", "New", "(", "opts", "*", "Options", ")", "(", "Driver", ",", "error", ")", "{", "switch", "opts", ".", "Type", "{", "case", "\"", "\"", ":", "return", "newConsulDriver", "(", "opts", ".", "Args", ")", "\n", "default", ":", "return", "&", "noopDriver", "{", "}", ",", "nil", "\n", "}", "\n", "}" ]
// New creates a new Discovery from the provided options.
[ "New", "creates", "a", "new", "Discovery", "from", "the", "provided", "options", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/disco/disco.go#L40-L47
16,622
kobolog/gorb
pulse/pulse.go
New
func New(host string, port uint16, opts *Options) (*Pulse, error) { if err := opts.Validate(); err != nil { return nil, err } d, err := get[opts.Type](host, port, opts.Args) if err != nil { return nil, err } stopCh := make(chan struct{}) return &Pulse{d, opts.interval, stopCh, NewMetrics()}, nil }
go
func New(host string, port uint16, opts *Options) (*Pulse, error) { if err := opts.Validate(); err != nil { return nil, err } d, err := get[opts.Type](host, port, opts.Args) if err != nil { return nil, err } stopCh := make(chan struct{}) return &Pulse{d, opts.interval, stopCh, NewMetrics()}, nil }
[ "func", "New", "(", "host", "string", ",", "port", "uint16", ",", "opts", "*", "Options", ")", "(", "*", "Pulse", ",", "error", ")", "{", "if", "err", ":=", "opts", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "d", ",", "err", ":=", "get", "[", "opts", ".", "Type", "]", "(", "host", ",", "port", ",", "opts", ".", "Args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stopCh", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "return", "&", "Pulse", "{", "d", ",", "opts", ".", "interval", ",", "stopCh", ",", "NewMetrics", "(", ")", "}", ",", "nil", "\n", "}" ]
// New creates a new Pulse from the provided endpoint and options.
[ "New", "creates", "a", "new", "Pulse", "from", "the", "provided", "endpoint", "and", "options", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/pulse/pulse.go#L57-L70
16,623
kobolog/gorb
pulse/pulse.go
Loop
func (p *Pulse) Loop(id ID, pulseCh chan Update, consumerStopCh <-chan struct{}) { log.Infof("starting pulse for %s", id) // Randomize the first health-check to avoid thundering herd syndrome. interval := time.Duration(rng.Int63n(int64(p.interval))) for { select { case <-time.After(interval): select { // Recalculate metrics and statistics and send them to Context. case pulseCh <- Update{id, p.metrics.Update(p.driver.Check())}: case <-consumerStopCh: // prevent blocking if the consumer stops before us } case <-p.stopCh: log.Infof("stopping pulse for %s", id) pulseCh <- Update{id, p.metrics.Update(StatusRemoved)} return } // TODO(@kobolog): Add exponential back-offs, thresholds. interval = p.interval log.Debugf("current pulse for %s: %s", id, p.metrics.Status.String()) } }
go
func (p *Pulse) Loop(id ID, pulseCh chan Update, consumerStopCh <-chan struct{}) { log.Infof("starting pulse for %s", id) // Randomize the first health-check to avoid thundering herd syndrome. interval := time.Duration(rng.Int63n(int64(p.interval))) for { select { case <-time.After(interval): select { // Recalculate metrics and statistics and send them to Context. case pulseCh <- Update{id, p.metrics.Update(p.driver.Check())}: case <-consumerStopCh: // prevent blocking if the consumer stops before us } case <-p.stopCh: log.Infof("stopping pulse for %s", id) pulseCh <- Update{id, p.metrics.Update(StatusRemoved)} return } // TODO(@kobolog): Add exponential back-offs, thresholds. interval = p.interval log.Debugf("current pulse for %s: %s", id, p.metrics.Status.String()) } }
[ "func", "(", "p", "*", "Pulse", ")", "Loop", "(", "id", "ID", ",", "pulseCh", "chan", "Update", ",", "consumerStopCh", "<-", "chan", "struct", "{", "}", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "id", ")", "\n\n", "// Randomize the first health-check to avoid thundering herd syndrome.", "interval", ":=", "time", ".", "Duration", "(", "rng", ".", "Int63n", "(", "int64", "(", "p", ".", "interval", ")", ")", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "interval", ")", ":", "select", "{", "// Recalculate metrics and statistics and send them to Context.", "case", "pulseCh", "<-", "Update", "{", "id", ",", "p", ".", "metrics", ".", "Update", "(", "p", ".", "driver", ".", "Check", "(", ")", ")", "}", ":", "case", "<-", "consumerStopCh", ":", "// prevent blocking if the consumer stops before us", "}", "\n", "case", "<-", "p", ".", "stopCh", ":", "log", ".", "Infof", "(", "\"", "\"", ",", "id", ")", "\n", "pulseCh", "<-", "Update", "{", "id", ",", "p", ".", "metrics", ".", "Update", "(", "StatusRemoved", ")", "}", "\n", "return", "\n", "}", "\n\n", "// TODO(@kobolog): Add exponential back-offs, thresholds.", "interval", "=", "p", ".", "interval", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "id", ",", "p", ".", "metrics", ".", "Status", ".", "String", "(", ")", ")", "\n", "}", "\n", "}" ]
// Loop starts the Pulse.
[ "Loop", "starts", "the", "Pulse", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/pulse/pulse.go#L79-L105
16,624
kobolog/gorb
util/map.go
Get
func (do DynamicMap) Get(key string, d interface{}) interface{} { if v, exists := do[key]; !exists { return d } else if vt, dt := reflect.TypeOf(v), reflect.TypeOf(d); vt.ConvertibleTo(dt) { return v } else if isInt(v.(string)) { convertedValue, _ := strconv.Atoi(v.(string)) return convertedValue } else { return d } }
go
func (do DynamicMap) Get(key string, d interface{}) interface{} { if v, exists := do[key]; !exists { return d } else if vt, dt := reflect.TypeOf(v), reflect.TypeOf(d); vt.ConvertibleTo(dt) { return v } else if isInt(v.(string)) { convertedValue, _ := strconv.Atoi(v.(string)) return convertedValue } else { return d } }
[ "func", "(", "do", "DynamicMap", ")", "Get", "(", "key", "string", ",", "d", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "v", ",", "exists", ":=", "do", "[", "key", "]", ";", "!", "exists", "{", "return", "d", "\n", "}", "else", "if", "vt", ",", "dt", ":=", "reflect", ".", "TypeOf", "(", "v", ")", ",", "reflect", ".", "TypeOf", "(", "d", ")", ";", "vt", ".", "ConvertibleTo", "(", "dt", ")", "{", "return", "v", "\n", "}", "else", "if", "isInt", "(", "v", ".", "(", "string", ")", ")", "{", "convertedValue", ",", "_", ":=", "strconv", ".", "Atoi", "(", "v", ".", "(", "string", ")", ")", "\n", "return", "convertedValue", "\n", "}", "else", "{", "return", "d", "\n", "}", "\n", "}" ]
// Get returns a typed option or a default value if the option is not set.
[ "Get", "returns", "a", "typed", "option", "or", "a", "default", "value", "if", "the", "option", "is", "not", "set", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/util/map.go#L33-L44
16,625
kobolog/gorb
core/context.go
NewContext
func NewContext(options ContextOptions) (*Context, error) { log.Info("initializing IPVS context") ctx := &Context{ ipvs: &gnl2go.IpvsClient{}, services: make(map[string]*service), backends: make(map[string]*backend), pulseCh: make(chan pulse.Update), stopCh: make(chan struct{}), } if len(options.Disco) > 0 { log.Infof("creating Consul client with Agent URL: %s", options.Disco) var err error ctx.disco, err = disco.New(&disco.Options{ Type: "consul", Args: util.DynamicMap{"URL": options.Disco}}) if err != nil { return nil, err } } else { ctx.disco, _ = disco.New(&disco.Options{Type: "none"}) } if len(options.Endpoints) > 0 { // TODO(@kobolog): Bind virtual services on multiple endpoints. ctx.endpoint = options.Endpoints[0] if options.ListenPort != 0 { log.Info("Registered the REST service to Consul.") ctx.disco.Expose("gorb", ctx.endpoint.String(), options.ListenPort) } } if err := ctx.ipvs.Init(); err != nil { log.Errorf("unable to initialize IPVS context: %s", err) // Here and in other places: IPVS errors are abstracted to make GNL2GO // replaceable in the future, since it's not really maintained anymore. return nil, ErrIpvsSyscallFailed } if options.Flush && ctx.ipvs.Flush() != nil { log.Errorf("unable to clean up IPVS pools - ensure ip_vs is loaded") ctx.Close() return nil, ErrIpvsSyscallFailed } if options.VipInterface != "" { var err error if ctx.vipInterface, err = netlink.LinkByName(options.VipInterface); err != nil { ctx.Close() return nil, fmt.Errorf( "unable to find the interface '%s' for VIPs: %s", options.VipInterface, err) } log.Infof("VIPs will be added to interface '%s'", ctx.vipInterface.Attrs().Name) } // Fire off a pulse notifications sink goroutine. go ctx.run() return ctx, nil }
go
func NewContext(options ContextOptions) (*Context, error) { log.Info("initializing IPVS context") ctx := &Context{ ipvs: &gnl2go.IpvsClient{}, services: make(map[string]*service), backends: make(map[string]*backend), pulseCh: make(chan pulse.Update), stopCh: make(chan struct{}), } if len(options.Disco) > 0 { log.Infof("creating Consul client with Agent URL: %s", options.Disco) var err error ctx.disco, err = disco.New(&disco.Options{ Type: "consul", Args: util.DynamicMap{"URL": options.Disco}}) if err != nil { return nil, err } } else { ctx.disco, _ = disco.New(&disco.Options{Type: "none"}) } if len(options.Endpoints) > 0 { // TODO(@kobolog): Bind virtual services on multiple endpoints. ctx.endpoint = options.Endpoints[0] if options.ListenPort != 0 { log.Info("Registered the REST service to Consul.") ctx.disco.Expose("gorb", ctx.endpoint.String(), options.ListenPort) } } if err := ctx.ipvs.Init(); err != nil { log.Errorf("unable to initialize IPVS context: %s", err) // Here and in other places: IPVS errors are abstracted to make GNL2GO // replaceable in the future, since it's not really maintained anymore. return nil, ErrIpvsSyscallFailed } if options.Flush && ctx.ipvs.Flush() != nil { log.Errorf("unable to clean up IPVS pools - ensure ip_vs is loaded") ctx.Close() return nil, ErrIpvsSyscallFailed } if options.VipInterface != "" { var err error if ctx.vipInterface, err = netlink.LinkByName(options.VipInterface); err != nil { ctx.Close() return nil, fmt.Errorf( "unable to find the interface '%s' for VIPs: %s", options.VipInterface, err) } log.Infof("VIPs will be added to interface '%s'", ctx.vipInterface.Attrs().Name) } // Fire off a pulse notifications sink goroutine. go ctx.run() return ctx, nil }
[ "func", "NewContext", "(", "options", "ContextOptions", ")", "(", "*", "Context", ",", "error", ")", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n\n", "ctx", ":=", "&", "Context", "{", "ipvs", ":", "&", "gnl2go", ".", "IpvsClient", "{", "}", ",", "services", ":", "make", "(", "map", "[", "string", "]", "*", "service", ")", ",", "backends", ":", "make", "(", "map", "[", "string", "]", "*", "backend", ")", ",", "pulseCh", ":", "make", "(", "chan", "pulse", ".", "Update", ")", ",", "stopCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "if", "len", "(", "options", ".", "Disco", ")", ">", "0", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "options", ".", "Disco", ")", "\n\n", "var", "err", "error", "\n\n", "ctx", ".", "disco", ",", "err", "=", "disco", ".", "New", "(", "&", "disco", ".", "Options", "{", "Type", ":", "\"", "\"", ",", "Args", ":", "util", ".", "DynamicMap", "{", "\"", "\"", ":", "options", ".", "Disco", "}", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "ctx", ".", "disco", ",", "_", "=", "disco", ".", "New", "(", "&", "disco", ".", "Options", "{", "Type", ":", "\"", "\"", "}", ")", "\n", "}", "\n\n", "if", "len", "(", "options", ".", "Endpoints", ")", ">", "0", "{", "// TODO(@kobolog): Bind virtual services on multiple endpoints.", "ctx", ".", "endpoint", "=", "options", ".", "Endpoints", "[", "0", "]", "\n", "if", "options", ".", "ListenPort", "!=", "0", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "ctx", ".", "disco", ".", "Expose", "(", "\"", "\"", ",", "ctx", ".", "endpoint", ".", "String", "(", ")", ",", "options", ".", "ListenPort", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "ctx", ".", "ipvs", ".", "Init", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n\n", "// Here and in other places: IPVS errors are abstracted to make GNL2GO", "// replaceable in the future, since it's not really maintained anymore.", "return", "nil", ",", "ErrIpvsSyscallFailed", "\n", "}", "\n\n", "if", "options", ".", "Flush", "&&", "ctx", ".", "ipvs", ".", "Flush", "(", ")", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "ctx", ".", "Close", "(", ")", "\n", "return", "nil", ",", "ErrIpvsSyscallFailed", "\n", "}", "\n\n", "if", "options", ".", "VipInterface", "!=", "\"", "\"", "{", "var", "err", "error", "\n", "if", "ctx", ".", "vipInterface", ",", "err", "=", "netlink", ".", "LinkByName", "(", "options", ".", "VipInterface", ")", ";", "err", "!=", "nil", "{", "ctx", ".", "Close", "(", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "VipInterface", ",", "err", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "ctx", ".", "vipInterface", ".", "Attrs", "(", ")", ".", "Name", ")", "\n", "}", "\n\n", "// Fire off a pulse notifications sink goroutine.", "go", "ctx", ".", "run", "(", ")", "\n\n", "return", "ctx", ",", "nil", "\n", "}" ]
// NewContext creates a new Context and initializes IPVS.
[ "NewContext", "creates", "a", "new", "Context", "and", "initializes", "IPVS", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/core/context.go#L92-L157
16,626
kobolog/gorb
core/context.go
Close
func (ctx *Context) Close() { log.Info("shutting down IPVS context") // This will also shutdown the pulse notification sink goroutine. close(ctx.stopCh) for vsID := range ctx.services { ctx.RemoveService(vsID) } // This is not strictly required, as far as I know. ctx.ipvs.Exit() }
go
func (ctx *Context) Close() { log.Info("shutting down IPVS context") // This will also shutdown the pulse notification sink goroutine. close(ctx.stopCh) for vsID := range ctx.services { ctx.RemoveService(vsID) } // This is not strictly required, as far as I know. ctx.ipvs.Exit() }
[ "func", "(", "ctx", "*", "Context", ")", "Close", "(", ")", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n\n", "// This will also shutdown the pulse notification sink goroutine.", "close", "(", "ctx", ".", "stopCh", ")", "\n\n", "for", "vsID", ":=", "range", "ctx", ".", "services", "{", "ctx", ".", "RemoveService", "(", "vsID", ")", "\n", "}", "\n\n", "// This is not strictly required, as far as I know.", "ctx", ".", "ipvs", ".", "Exit", "(", ")", "\n", "}" ]
// Close shuts down IPVS and closes the Context.
[ "Close", "shuts", "down", "IPVS", "and", "closes", "the", "Context", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/core/context.go#L160-L172
16,627
kobolog/gorb
core/context.go
ListServices
func (ctx *Context) ListServices() ([]string, error) { ctx.mutex.RLock() defer ctx.mutex.RUnlock() r := make([]string, 0, len(ctx.services)) for vsID := range ctx.services { r = append(r, vsID) } return r, nil }
go
func (ctx *Context) ListServices() ([]string, error) { ctx.mutex.RLock() defer ctx.mutex.RUnlock() r := make([]string, 0, len(ctx.services)) for vsID := range ctx.services { r = append(r, vsID) } return r, nil }
[ "func", "(", "ctx", "*", "Context", ")", "ListServices", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "ctx", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "ctx", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "r", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "ctx", ".", "services", ")", ")", "\n\n", "for", "vsID", ":=", "range", "ctx", ".", "services", "{", "r", "=", "append", "(", "r", ",", "vsID", ")", "\n", "}", "\n\n", "return", "r", ",", "nil", "\n", "}" ]
// ListServices returns a list of all registered services.
[ "ListServices", "returns", "a", "list", "of", "all", "registered", "services", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/core/context.go#L486-L497
16,628
kobolog/gorb
core/context.go
GetService
func (ctx *Context) GetService(vsID string) (*ServiceInfo, error) { ctx.mutex.RLock() defer ctx.mutex.RUnlock() vs, exists := ctx.services[vsID] if !exists { return nil, ErrObjectNotFound } result := ServiceInfo{Options: vs.options} // This is O(n), can be optimized with reverse backend map. for rsID, backend := range ctx.backends { if backend.service != vs { continue } result.Backends = append(result.Backends, rsID) result.Health += backend.metrics.Health } if len(result.Backends) == 0 { // Service without backends is healthy, albeit useless. result.Health = 1.0 } else { result.Health /= float64(len(result.Backends)) } return &result, nil }
go
func (ctx *Context) GetService(vsID string) (*ServiceInfo, error) { ctx.mutex.RLock() defer ctx.mutex.RUnlock() vs, exists := ctx.services[vsID] if !exists { return nil, ErrObjectNotFound } result := ServiceInfo{Options: vs.options} // This is O(n), can be optimized with reverse backend map. for rsID, backend := range ctx.backends { if backend.service != vs { continue } result.Backends = append(result.Backends, rsID) result.Health += backend.metrics.Health } if len(result.Backends) == 0 { // Service without backends is healthy, albeit useless. result.Health = 1.0 } else { result.Health /= float64(len(result.Backends)) } return &result, nil }
[ "func", "(", "ctx", "*", "Context", ")", "GetService", "(", "vsID", "string", ")", "(", "*", "ServiceInfo", ",", "error", ")", "{", "ctx", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "ctx", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "vs", ",", "exists", ":=", "ctx", ".", "services", "[", "vsID", "]", "\n\n", "if", "!", "exists", "{", "return", "nil", ",", "ErrObjectNotFound", "\n", "}", "\n\n", "result", ":=", "ServiceInfo", "{", "Options", ":", "vs", ".", "options", "}", "\n\n", "// This is O(n), can be optimized with reverse backend map.", "for", "rsID", ",", "backend", ":=", "range", "ctx", ".", "backends", "{", "if", "backend", ".", "service", "!=", "vs", "{", "continue", "\n", "}", "\n\n", "result", ".", "Backends", "=", "append", "(", "result", ".", "Backends", ",", "rsID", ")", "\n", "result", ".", "Health", "+=", "backend", ".", "metrics", ".", "Health", "\n", "}", "\n\n", "if", "len", "(", "result", ".", "Backends", ")", "==", "0", "{", "// Service without backends is healthy, albeit useless.", "result", ".", "Health", "=", "1.0", "\n", "}", "else", "{", "result", ".", "Health", "/=", "float64", "(", "len", "(", "result", ".", "Backends", ")", ")", "\n", "}", "\n\n", "return", "&", "result", ",", "nil", "\n", "}" ]
// GetService returns information about a virtual service.
[ "GetService", "returns", "information", "about", "a", "virtual", "service", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/core/context.go#L508-L538
16,629
kobolog/gorb
core/context.go
GetBackend
func (ctx *Context) GetBackend(vsID, rsID string) (*BackendInfo, error) { ctx.mutex.RLock() defer ctx.mutex.RUnlock() rs, exists := ctx.backends[rsID] if !exists { return nil, ErrObjectNotFound } return &BackendInfo{rs.options, rs.metrics}, nil }
go
func (ctx *Context) GetBackend(vsID, rsID string) (*BackendInfo, error) { ctx.mutex.RLock() defer ctx.mutex.RUnlock() rs, exists := ctx.backends[rsID] if !exists { return nil, ErrObjectNotFound } return &BackendInfo{rs.options, rs.metrics}, nil }
[ "func", "(", "ctx", "*", "Context", ")", "GetBackend", "(", "vsID", ",", "rsID", "string", ")", "(", "*", "BackendInfo", ",", "error", ")", "{", "ctx", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "ctx", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "rs", ",", "exists", ":=", "ctx", ".", "backends", "[", "rsID", "]", "\n\n", "if", "!", "exists", "{", "return", "nil", ",", "ErrObjectNotFound", "\n", "}", "\n\n", "return", "&", "BackendInfo", "{", "rs", ".", "options", ",", "rs", ".", "metrics", "}", ",", "nil", "\n", "}" ]
// GetBackend returns information about a backend.
[ "GetBackend", "returns", "information", "about", "a", "backend", "." ]
8240420c08e2486a34a043eff26df7d387791743
https://github.com/kobolog/gorb/blob/8240420c08e2486a34a043eff26df7d387791743/core/context.go#L547-L558
16,630
vanng822/go-solr
solr/parser.go
ParseFacets
func (parser *ExtensiveResultParser) ParseFacets(response *SolrResponse, sr *SolrResult) { if fc, ok := response.Response["facet_counts"].(map[string]interface{}); ok { sr.FacetCounts = fc if f, ok := fc["facet_fields"].(map[string]interface{}); ok { sr.Facets = f } } }
go
func (parser *ExtensiveResultParser) ParseFacets(response *SolrResponse, sr *SolrResult) { if fc, ok := response.Response["facet_counts"].(map[string]interface{}); ok { sr.FacetCounts = fc if f, ok := fc["facet_fields"].(map[string]interface{}); ok { sr.Facets = f } } }
[ "func", "(", "parser", "*", "ExtensiveResultParser", ")", "ParseFacets", "(", "response", "*", "SolrResponse", ",", "sr", "*", "SolrResult", ")", "{", "if", "fc", ",", "ok", ":=", "response", ".", "Response", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "sr", ".", "FacetCounts", "=", "fc", "\n", "if", "f", ",", "ok", ":=", "fc", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "sr", ".", "Facets", "=", "f", "\n", "}", "\n", "}", "\n", "}" ]
// ParseJsonFacets will assign facets and build sr.jsonfacets if there is a facet_counts
[ "ParseJsonFacets", "will", "assign", "facets", "and", "build", "sr", ".", "jsonfacets", "if", "there", "is", "a", "facet_counts" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/parser.go#L88-L95
16,631
vanng822/go-solr
solr/parser.go
ParseJsonFacets
func (parser *ExtensiveResultParser) ParseJsonFacets(response *SolrResponse, sr *SolrResult) { if jf, ok := response.Response["facets"].(map[string]interface{}); ok { sr.JsonFacets = jf } }
go
func (parser *ExtensiveResultParser) ParseJsonFacets(response *SolrResponse, sr *SolrResult) { if jf, ok := response.Response["facets"].(map[string]interface{}); ok { sr.JsonFacets = jf } }
[ "func", "(", "parser", "*", "ExtensiveResultParser", ")", "ParseJsonFacets", "(", "response", "*", "SolrResponse", ",", "sr", "*", "SolrResult", ")", "{", "if", "jf", ",", "ok", ":=", "response", ".", "Response", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "sr", ".", "JsonFacets", "=", "jf", "\n", "}", "\n", "}" ]
// ParseJsonFacets will assign facets and build sr.jsonfacets if there is a facets
[ "ParseJsonFacets", "will", "assign", "facets", "and", "build", "sr", ".", "jsonfacets", "if", "there", "is", "a", "facets" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/parser.go#L98-L102
16,632
vanng822/go-solr
solr/parser.go
ParseFacetCounts
func (parser *StandardResultParser) ParseFacetCounts(response *SolrResponse, sr *SolrResult) { if facetCounts, ok := response.Response["facet_counts"].(map[string]interface{}); ok { sr.FacetCounts = facetCounts } }
go
func (parser *StandardResultParser) ParseFacetCounts(response *SolrResponse, sr *SolrResult) { if facetCounts, ok := response.Response["facet_counts"].(map[string]interface{}); ok { sr.FacetCounts = facetCounts } }
[ "func", "(", "parser", "*", "StandardResultParser", ")", "ParseFacetCounts", "(", "response", "*", "SolrResponse", ",", "sr", "*", "SolrResult", ")", "{", "if", "facetCounts", ",", "ok", ":=", "response", ".", "Response", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "sr", ".", "FacetCounts", "=", "facetCounts", "\n", "}", "\n", "}" ]
// ParseFacetCounts will assign facet_counts to sr if there is one. // No modification done here
[ "ParseFacetCounts", "will", "assign", "facet_counts", "to", "sr", "if", "there", "is", "one", ".", "No", "modification", "done", "here" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/parser.go#L198-L202
16,633
vanng822/go-solr
solr/parser.go
ParseHighlighting
func (parser *StandardResultParser) ParseHighlighting(response *SolrResponse, sr *SolrResult) { if highlighting, ok := response.Response["highlighting"].(map[string]interface{}); ok { sr.Highlighting = highlighting } }
go
func (parser *StandardResultParser) ParseHighlighting(response *SolrResponse, sr *SolrResult) { if highlighting, ok := response.Response["highlighting"].(map[string]interface{}); ok { sr.Highlighting = highlighting } }
[ "func", "(", "parser", "*", "StandardResultParser", ")", "ParseHighlighting", "(", "response", "*", "SolrResponse", ",", "sr", "*", "SolrResult", ")", "{", "if", "highlighting", ",", "ok", ":=", "response", ".", "Response", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "sr", ".", "Highlighting", "=", "highlighting", "\n", "}", "\n", "}" ]
// ParseHighlighting will assign highlighting to sr if there is one. // No modification done here
[ "ParseHighlighting", "will", "assign", "highlighting", "to", "sr", "if", "there", "is", "one", ".", "No", "modification", "done", "here" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/parser.go#L206-L210
16,634
vanng822/go-solr
solr/parser.go
ParseStats
func (parser *StandardResultParser) ParseStats(response *SolrResponse, sr *SolrResult) { if stats, ok := response.Response["stats"].(map[string]interface{}); ok { sr.Stats = stats } }
go
func (parser *StandardResultParser) ParseStats(response *SolrResponse, sr *SolrResult) { if stats, ok := response.Response["stats"].(map[string]interface{}); ok { sr.Stats = stats } }
[ "func", "(", "parser", "*", "StandardResultParser", ")", "ParseStats", "(", "response", "*", "SolrResponse", ",", "sr", "*", "SolrResult", ")", "{", "if", "stats", ",", "ok", ":=", "response", ".", "Response", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "sr", ".", "Stats", "=", "stats", "\n", "}", "\n", "}" ]
// Parse stats if there is in response
[ "Parse", "stats", "if", "there", "is", "in", "response" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/parser.go#L213-L217
16,635
vanng822/go-solr
solr/core_admin.go
SetBasicAuth
func (ca *CoreAdmin) SetBasicAuth(username, password string) { ca.username = username ca.password = password }
go
func (ca *CoreAdmin) SetBasicAuth(username, password string) { ca.username = username ca.password = password }
[ "func", "(", "ca", "*", "CoreAdmin", ")", "SetBasicAuth", "(", "username", ",", "password", "string", ")", "{", "ca", ".", "username", "=", "username", "\n", "ca", ".", "password", "=", "password", "\n", "}" ]
// Set basic auth in case solr require login
[ "Set", "basic", "auth", "in", "case", "solr", "require", "login" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/core_admin.go#L28-L31
16,636
vanng822/go-solr
solr/connection.go
HTTPPost
func HTTPPost(path string, data *[]byte, headers [][]string, username, password string) ([]byte, error) { var ( req *http.Request err error ) client := &http.Client{Transport: &transport} if data == nil { req, err = http.NewRequest("POST", path, nil) } else { req, err = http.NewRequest("POST", path, bytes.NewReader(*data)) } if err != nil { return nil, err } if username != "" && password != "" { req.SetBasicAuth(username, password) } if len(headers) > 0 { for i := range headers { req.Header.Add(headers[i][0], headers[i][1]) } } return makeRequest(client, req) }
go
func HTTPPost(path string, data *[]byte, headers [][]string, username, password string) ([]byte, error) { var ( req *http.Request err error ) client := &http.Client{Transport: &transport} if data == nil { req, err = http.NewRequest("POST", path, nil) } else { req, err = http.NewRequest("POST", path, bytes.NewReader(*data)) } if err != nil { return nil, err } if username != "" && password != "" { req.SetBasicAuth(username, password) } if len(headers) > 0 { for i := range headers { req.Header.Add(headers[i][0], headers[i][1]) } } return makeRequest(client, req) }
[ "func", "HTTPPost", "(", "path", "string", ",", "data", "*", "[", "]", "byte", ",", "headers", "[", "]", "[", "]", "string", ",", "username", ",", "password", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "(", "req", "*", "http", ".", "Request", "\n", "err", "error", "\n", ")", "\n\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "transport", "}", "\n", "if", "data", "==", "nil", "{", "req", ",", "err", "=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "path", ",", "nil", ")", "\n", "}", "else", "{", "req", ",", "err", "=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "path", ",", "bytes", ".", "NewReader", "(", "*", "data", ")", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "username", "!=", "\"", "\"", "&&", "password", "!=", "\"", "\"", "{", "req", ".", "SetBasicAuth", "(", "username", ",", "password", ")", "\n", "}", "\n\n", "if", "len", "(", "headers", ")", ">", "0", "{", "for", "i", ":=", "range", "headers", "{", "req", ".", "Header", ".", "Add", "(", "headers", "[", "i", "]", "[", "0", "]", ",", "headers", "[", "i", "]", "[", "1", "]", ")", "\n", "}", "\n", "}", "\n", "return", "makeRequest", "(", "client", ",", "req", ")", "\n", "}" ]
// HTTPPost make a POST request to path which also includes domain, headers are optional
[ "HTTPPost", "make", "a", "POST", "request", "to", "path", "which", "also", "includes", "domain", "headers", "are", "optional" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/connection.go#L24-L51
16,637
vanng822/go-solr
solr/connection.go
HTTPGet
func HTTPGet(url string, headers [][]string, username, password string) ([]byte, error) { client := &http.Client{Transport: &transport} req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if username != "" && password != "" { req.SetBasicAuth(username, password) } if len(headers) > 0 { for i := range headers { req.Header.Add(headers[i][0], headers[i][1]) } } return makeRequest(client, req) }
go
func HTTPGet(url string, headers [][]string, username, password string) ([]byte, error) { client := &http.Client{Transport: &transport} req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if username != "" && password != "" { req.SetBasicAuth(username, password) } if len(headers) > 0 { for i := range headers { req.Header.Add(headers[i][0], headers[i][1]) } } return makeRequest(client, req) }
[ "func", "HTTPGet", "(", "url", "string", ",", "headers", "[", "]", "[", "]", "string", ",", "username", ",", "password", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "transport", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "nil", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "username", "!=", "\"", "\"", "&&", "password", "!=", "\"", "\"", "{", "req", ".", "SetBasicAuth", "(", "username", ",", "password", ")", "\n", "}", "\n\n", "if", "len", "(", "headers", ")", ">", "0", "{", "for", "i", ":=", "range", "headers", "{", "req", ".", "Header", ".", "Add", "(", "headers", "[", "i", "]", "[", "0", "]", ",", "headers", "[", "i", "]", "[", "1", "]", ")", "\n", "}", "\n", "}", "\n", "return", "makeRequest", "(", "client", ",", "req", ")", "\n", "}" ]
// HTTPGet make a GET request to url, headers are optional
[ "HTTPGet", "make", "a", "GET", "request", "to", "url", "headers", "are", "optional" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/connection.go#L54-L72
16,638
vanng822/go-solr
solr/connection.go
NewConnection
func NewConnection(solrUrl, core string) (*Connection, error) { u, err := url.ParseRequestURI(strings.TrimRight(solrUrl, "/")) if err != nil { return nil, err } return &Connection{url: u, core: core}, nil }
go
func NewConnection(solrUrl, core string) (*Connection, error) { u, err := url.ParseRequestURI(strings.TrimRight(solrUrl, "/")) if err != nil { return nil, err } return &Connection{url: u, core: core}, nil }
[ "func", "NewConnection", "(", "solrUrl", ",", "core", "string", ")", "(", "*", "Connection", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "strings", ".", "TrimRight", "(", "solrUrl", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Connection", "{", "url", ":", "u", ",", "core", ":", "core", "}", ",", "nil", "\n", "}" ]
// NewConnection will parse solrUrl and return a connection object, solrUrl must be a absolute url or path
[ "NewConnection", "will", "parse", "solrUrl", "and", "return", "a", "connection", "object", "solrUrl", "must", "be", "a", "absolute", "url", "or", "path" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/connection.go#L129-L135
16,639
vanng822/go-solr
solr/connection.go
Update
func (c *Connection) Update(data interface{}, params *url.Values) (*SolrUpdateResponse, error) { b, err := json2bytes(data) if err != nil { return nil, err } if params == nil { params = &url.Values{} } params.Set("wt", "json") r, err := HTTPPost(fmt.Sprintf("%s/%s/update/?%s", c.url.String(), c.core, params.Encode()), b, [][]string{{"Content-Type", "application/json"}}, c.username, c.password) if err != nil { return nil, err } resp, err := bytes2json(&r) if err != nil { return nil, err } // check error in resp if !successStatus(resp) || hasError(resp) { return &SolrUpdateResponse{Success: false, Result: resp}, nil } return &SolrUpdateResponse{Success: true, Result: resp}, nil }
go
func (c *Connection) Update(data interface{}, params *url.Values) (*SolrUpdateResponse, error) { b, err := json2bytes(data) if err != nil { return nil, err } if params == nil { params = &url.Values{} } params.Set("wt", "json") r, err := HTTPPost(fmt.Sprintf("%s/%s/update/?%s", c.url.String(), c.core, params.Encode()), b, [][]string{{"Content-Type", "application/json"}}, c.username, c.password) if err != nil { return nil, err } resp, err := bytes2json(&r) if err != nil { return nil, err } // check error in resp if !successStatus(resp) || hasError(resp) { return &SolrUpdateResponse{Success: false, Result: resp}, nil } return &SolrUpdateResponse{Success: true, Result: resp}, nil }
[ "func", "(", "c", "*", "Connection", ")", "Update", "(", "data", "interface", "{", "}", ",", "params", "*", "url", ".", "Values", ")", "(", "*", "SolrUpdateResponse", ",", "error", ")", "{", "b", ",", "err", ":=", "json2bytes", "(", "data", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "params", "==", "nil", "{", "params", "=", "&", "url", ".", "Values", "{", "}", "\n", "}", "\n\n", "params", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "r", ",", "err", ":=", "HTTPPost", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "url", ".", "String", "(", ")", ",", "c", ".", "core", ",", "params", ".", "Encode", "(", ")", ")", ",", "b", ",", "[", "]", "[", "]", "string", "{", "{", "\"", "\"", ",", "\"", "\"", "}", "}", ",", "c", ".", "username", ",", "c", ".", "password", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "bytes2json", "(", "&", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// check error in resp", "if", "!", "successStatus", "(", "resp", ")", "||", "hasError", "(", "resp", ")", "{", "return", "&", "SolrUpdateResponse", "{", "Success", ":", "false", ",", "Result", ":", "resp", "}", ",", "nil", "\n", "}", "\n\n", "return", "&", "SolrUpdateResponse", "{", "Success", ":", "true", ",", "Result", ":", "resp", "}", ",", "nil", "\n", "}" ]
// Update take optional params which can use to specify addition parameters such as commit=true
[ "Update", "take", "optional", "params", "which", "can", "use", "to", "specify", "addition", "parameters", "such", "as", "commit", "=", "true" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/connection.go#L172-L201
16,640
vanng822/go-solr
solr/search.go
NewSearch
func NewSearch(c *Connection, q *Query) *Search { s := new(Search) if q != nil { s.SetQuery(q) } if c != nil { s.conn = c } return s }
go
func NewSearch(c *Connection, q *Query) *Search { s := new(Search) if q != nil { s.SetQuery(q) } if c != nil { s.conn = c } return s }
[ "func", "NewSearch", "(", "c", "*", "Connection", ",", "q", "*", "Query", ")", "*", "Search", "{", "s", ":=", "new", "(", "Search", ")", "\n", "if", "q", "!=", "nil", "{", "s", ".", "SetQuery", "(", "q", ")", "\n", "}", "\n\n", "if", "c", "!=", "nil", "{", "s", ".", "conn", "=", "c", "\n", "}", "\n", "return", "s", "\n", "}" ]
// NewSearch takes c and q as optional
[ "NewSearch", "takes", "c", "and", "q", "as", "optional" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/search.go#L15-L25
16,641
vanng822/go-solr
solr/search.go
QueryParams
func (s *Search) QueryParams() *url.Values { if s.query == nil { s.query = NewQuery() } if s.Debug != "" { s.query.params.Set("debug", s.Debug) s.query.params.Set("indent", "true") } return s.query.params }
go
func (s *Search) QueryParams() *url.Values { if s.query == nil { s.query = NewQuery() } if s.Debug != "" { s.query.params.Set("debug", s.Debug) s.query.params.Set("indent", "true") } return s.query.params }
[ "func", "(", "s", "*", "Search", ")", "QueryParams", "(", ")", "*", "url", ".", "Values", "{", "if", "s", ".", "query", "==", "nil", "{", "s", ".", "query", "=", "NewQuery", "(", ")", "\n", "}", "\n\n", "if", "s", ".", "Debug", "!=", "\"", "\"", "{", "s", ".", "query", ".", "params", ".", "Set", "(", "\"", "\"", ",", "s", ".", "Debug", ")", "\n", "s", ".", "query", ".", "params", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "s", ".", "query", ".", "params", "\n", "}" ]
// Return query params including debug and indent if Debug is set
[ "Return", "query", "params", "including", "debug", "and", "indent", "if", "Debug", "is", "set" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/search.go#L33-L45
16,642
vanng822/go-solr
solr/search.go
Result
func (s *Search) Result(parser ResultParser) (*SolrResult, error) { resp, err := s.Resource("select", s.QueryParams()) if err != nil { return nil, err } if parser == nil { parser = new(StandardResultParser) } return parser.Parse(resp) }
go
func (s *Search) Result(parser ResultParser) (*SolrResult, error) { resp, err := s.Resource("select", s.QueryParams()) if err != nil { return nil, err } if parser == nil { parser = new(StandardResultParser) } return parser.Parse(resp) }
[ "func", "(", "s", "*", "Search", ")", "Result", "(", "parser", "ResultParser", ")", "(", "*", "SolrResult", ",", "error", ")", "{", "resp", ",", "err", ":=", "s", ".", "Resource", "(", "\"", "\"", ",", "s", ".", "QueryParams", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "parser", "==", "nil", "{", "parser", "=", "new", "(", "StandardResultParser", ")", "\n", "}", "\n", "return", "parser", ".", "Parse", "(", "resp", ")", "\n", "}" ]
// Result will create a StandardResultParser if no parser specified. // parser must be an implementation of ResultParser interface
[ "Result", "will", "create", "a", "StandardResultParser", "if", "no", "parser", "specified", ".", "parser", "must", "be", "an", "implementation", "of", "ResultParser", "interface" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/search.go#L64-L73
16,643
vanng822/go-solr
solr/schema.go
NewSchema
func NewSchema(solrUrl, core string) (*Schema, error) { u, err := url.ParseRequestURI(strings.TrimRight(solrUrl, "/")) if err != nil { return nil, err } return &Schema{url: u, core: core}, nil }
go
func NewSchema(solrUrl, core string) (*Schema, error) { u, err := url.ParseRequestURI(strings.TrimRight(solrUrl, "/")) if err != nil { return nil, err } return &Schema{url: u, core: core}, nil }
[ "func", "NewSchema", "(", "solrUrl", ",", "core", "string", ")", "(", "*", "Schema", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "strings", ".", "TrimRight", "(", "solrUrl", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Schema", "{", "url", ":", "u", ",", "core", ":", "core", "}", ",", "nil", "\n", "}" ]
// NewSchema will parse solrUrl and return a schema object, solrUrl must be a absolute url or path
[ "NewSchema", "will", "parse", "solrUrl", "and", "return", "a", "schema", "object", "solrUrl", "must", "be", "a", "absolute", "url", "or", "path" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/schema.go#L17-L24
16,644
vanng822/go-solr
solr/query.go
Start
func (q *Query) Start(start int) { q.params.Set("start", fmt.Sprintf("%d", start)) }
go
func (q *Query) Start(start int) { q.params.Set("start", fmt.Sprintf("%d", start)) }
[ "func", "(", "q", "*", "Query", ")", "Start", "(", "start", "int", ")", "{", "q", ".", "params", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "start", ")", ")", "\n", "}" ]
// Start sets start value which is the offset of result
[ "Start", "sets", "start", "value", "which", "is", "the", "offset", "of", "result" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/query.go#L127-L129
16,645
vanng822/go-solr
solr/query.go
Rows
func (q *Query) Rows(rows int) { q.params.Set("rows", fmt.Sprintf("%d", rows)) }
go
func (q *Query) Rows(rows int) { q.params.Set("rows", fmt.Sprintf("%d", rows)) }
[ "func", "(", "q", "*", "Query", ")", "Rows", "(", "rows", "int", ")", "{", "q", ".", "params", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rows", ")", ")", "\n", "}" ]
// Rows sets value for rows which means set the limit for how many rows to return
[ "Rows", "sets", "value", "for", "rows", "which", "means", "set", "the", "limit", "for", "how", "many", "rows", "to", "return" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/query.go#L132-L134
16,646
vanng822/go-solr
solr/solr.go
Has
func (d Document) Has(k string) bool { _, ok := d[k] return ok }
go
func (d Document) Has(k string) bool { _, ok := d[k] return ok }
[ "func", "(", "d", "Document", ")", "Has", "(", "k", "string", ")", "bool", "{", "_", ",", "ok", ":=", "d", "[", "k", "]", "\n", "return", "ok", "\n", "}" ]
// Has check if a key exist in document
[ "Has", "check", "if", "a", "key", "exist", "in", "document" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L17-L20
16,647
vanng822/go-solr
solr/solr.go
Get
func (d Document) Get(k string) interface{} { v, _ := d[k] return v }
go
func (d Document) Get(k string) interface{} { v, _ := d[k] return v }
[ "func", "(", "d", "Document", ")", "Get", "(", "k", "string", ")", "interface", "{", "}", "{", "v", ",", "_", ":=", "d", "[", "k", "]", "\n", "return", "v", "\n", "}" ]
// Get returns value of a key
[ "Get", "returns", "value", "of", "a", "key" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L23-L26
16,648
vanng822/go-solr
solr/solr.go
NewSolrInterface
func NewSolrInterface(solrUrl, core string) (*SolrInterface, error) { c, err := NewConnection(solrUrl, core) if err != nil { return nil, err } return &SolrInterface{conn: c}, nil }
go
func NewSolrInterface(solrUrl, core string) (*SolrInterface, error) { c, err := NewConnection(solrUrl, core) if err != nil { return nil, err } return &SolrInterface{conn: c}, nil }
[ "func", "NewSolrInterface", "(", "solrUrl", ",", "core", "string", ")", "(", "*", "SolrInterface", ",", "error", ")", "{", "c", ",", "err", ":=", "NewConnection", "(", "solrUrl", ",", "core", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "SolrInterface", "{", "conn", ":", "c", "}", ",", "nil", "\n", "}" ]
// Return a new instance of SolrInterface
[ "Return", "a", "new", "instance", "of", "SolrInterface" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L107-L113
16,649
vanng822/go-solr
solr/solr.go
Search
func (si *SolrInterface) Search(q *Query) *Search { return NewSearch(si.conn, q) }
go
func (si *SolrInterface) Search(q *Query) *Search { return NewSearch(si.conn, q) }
[ "func", "(", "si", "*", "SolrInterface", ")", "Search", "(", "q", "*", "Query", ")", "*", "Search", "{", "return", "NewSearch", "(", "si", ".", "conn", ",", "q", ")", "\n", "}" ]
// Return a new instace of Search, q is optional and one can set it later
[ "Return", "a", "new", "instace", "of", "Search", "q", "is", "optional", "and", "one", "can", "set", "it", "later" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L128-L130
16,650
vanng822/go-solr
solr/solr.go
makeAddChunks
func makeAddChunks(docs []Document, chunk_size int) []map[string]interface{} { if chunk_size < 1 { chunk_size = 100 } docs_len := len(docs) num_chunk := int(math.Ceil(float64(docs_len) / float64(chunk_size))) doc_counter := 0 chunks := make([]map[string]interface{}, num_chunk) for i := 0; i < num_chunk; i++ { add := make([]Document, 0, chunk_size) for j := 0; j < chunk_size; j++ { if doc_counter >= docs_len { break } add = append(add, docs[doc_counter]) doc_counter++ } chunks[i] = M{"add": add} } return chunks }
go
func makeAddChunks(docs []Document, chunk_size int) []map[string]interface{} { if chunk_size < 1 { chunk_size = 100 } docs_len := len(docs) num_chunk := int(math.Ceil(float64(docs_len) / float64(chunk_size))) doc_counter := 0 chunks := make([]map[string]interface{}, num_chunk) for i := 0; i < num_chunk; i++ { add := make([]Document, 0, chunk_size) for j := 0; j < chunk_size; j++ { if doc_counter >= docs_len { break } add = append(add, docs[doc_counter]) doc_counter++ } chunks[i] = M{"add": add} } return chunks }
[ "func", "makeAddChunks", "(", "docs", "[", "]", "Document", ",", "chunk_size", "int", ")", "[", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "if", "chunk_size", "<", "1", "{", "chunk_size", "=", "100", "\n", "}", "\n", "docs_len", ":=", "len", "(", "docs", ")", "\n", "num_chunk", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "docs_len", ")", "/", "float64", "(", "chunk_size", ")", ")", ")", "\n", "doc_counter", ":=", "0", "\n", "chunks", ":=", "make", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "num_chunk", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "num_chunk", ";", "i", "++", "{", "add", ":=", "make", "(", "[", "]", "Document", ",", "0", ",", "chunk_size", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "chunk_size", ";", "j", "++", "{", "if", "doc_counter", ">=", "docs_len", "{", "break", "\n", "}", "\n", "add", "=", "append", "(", "add", ",", "docs", "[", "doc_counter", "]", ")", "\n", "doc_counter", "++", "\n", "}", "\n", "chunks", "[", "i", "]", "=", "M", "{", "\"", "\"", ":", "add", "}", "\n", "}", "\n", "return", "chunks", "\n", "}" ]
// makeAddChunks splits the documents into chunks. If chunk_size is less than one it will be default to 100
[ "makeAddChunks", "splits", "the", "documents", "into", "chunks", ".", "If", "chunk_size", "is", "less", "than", "one", "it", "will", "be", "default", "to", "100" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L133-L153
16,651
vanng822/go-solr
solr/solr.go
Add
func (si *SolrInterface) Add(docs []Document, chunk_size int, params *url.Values) (*SolrUpdateResponse, error) { result := &SolrUpdateResponse{Success: true} responses := M{} chunks := makeAddChunks(docs, chunk_size) for i := 0; i < len(chunks); i++ { res, err := si.Update(chunks[i], params) if err != nil { return nil, err } result.Success = result.Success && res.Success responses[fmt.Sprintf("chunk_%d", i+1)] = M{ "result": res.Result, "success": res.Success, "total": len(chunks[i]["add"].([]Document))} } result.Result = responses return result, nil }
go
func (si *SolrInterface) Add(docs []Document, chunk_size int, params *url.Values) (*SolrUpdateResponse, error) { result := &SolrUpdateResponse{Success: true} responses := M{} chunks := makeAddChunks(docs, chunk_size) for i := 0; i < len(chunks); i++ { res, err := si.Update(chunks[i], params) if err != nil { return nil, err } result.Success = result.Success && res.Success responses[fmt.Sprintf("chunk_%d", i+1)] = M{ "result": res.Result, "success": res.Success, "total": len(chunks[i]["add"].([]Document))} } result.Result = responses return result, nil }
[ "func", "(", "si", "*", "SolrInterface", ")", "Add", "(", "docs", "[", "]", "Document", ",", "chunk_size", "int", ",", "params", "*", "url", ".", "Values", ")", "(", "*", "SolrUpdateResponse", ",", "error", ")", "{", "result", ":=", "&", "SolrUpdateResponse", "{", "Success", ":", "true", "}", "\n", "responses", ":=", "M", "{", "}", "\n", "chunks", ":=", "makeAddChunks", "(", "docs", ",", "chunk_size", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "chunks", ")", ";", "i", "++", "{", "res", ",", "err", ":=", "si", ".", "Update", "(", "chunks", "[", "i", "]", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "result", ".", "Success", "=", "result", ".", "Success", "&&", "res", ".", "Success", "\n", "responses", "[", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", "+", "1", ")", "]", "=", "M", "{", "\"", "\"", ":", "res", ".", "Result", ",", "\"", "\"", ":", "res", ".", "Success", ",", "\"", "\"", ":", "len", "(", "chunks", "[", "i", "]", "[", "\"", "\"", "]", ".", "(", "[", "]", "Document", ")", ")", "}", "\n", "}", "\n", "result", ".", "Result", "=", "responses", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Add will insert documents in batch of chunk_size. success is false as long as one chunk failed. // The result in SolrUpdateResponse is summery of response from all chunks // with key chunk_%d
[ "Add", "will", "insert", "documents", "in", "batch", "of", "chunk_size", ".", "success", "is", "false", "as", "long", "as", "one", "chunk", "failed", ".", "The", "result", "in", "SolrUpdateResponse", "is", "summery", "of", "response", "from", "all", "chunks", "with", "key", "chunk_%d" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L158-L176
16,652
vanng822/go-solr
solr/solr.go
DeleteAll
func (si *SolrInterface) DeleteAll() (*SolrUpdateResponse, error) { params := &url.Values{} params.Add("commit", "true") return si.Delete(M{"query": "*:*"}, params) }
go
func (si *SolrInterface) DeleteAll() (*SolrUpdateResponse, error) { params := &url.Values{} params.Add("commit", "true") return si.Delete(M{"query": "*:*"}, params) }
[ "func", "(", "si", "*", "SolrInterface", ")", "DeleteAll", "(", ")", "(", "*", "SolrUpdateResponse", ",", "error", ")", "{", "params", ":=", "&", "url", ".", "Values", "{", "}", "\n", "params", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "si", ".", "Delete", "(", "M", "{", "\"", "\"", ":", "\"", "\"", "}", ",", "params", ")", "\n", "}" ]
// DeleteAll will remove all documents and commit
[ "DeleteAll", "will", "remove", "all", "documents", "and", "commit" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L188-L192
16,653
vanng822/go-solr
solr/solr.go
Commit
func (si *SolrInterface) Commit() (*SolrUpdateResponse, error) { params := &url.Values{} params.Add("commit", "true") return si.Update(M{}, params) }
go
func (si *SolrInterface) Commit() (*SolrUpdateResponse, error) { params := &url.Values{} params.Add("commit", "true") return si.Update(M{}, params) }
[ "func", "(", "si", "*", "SolrInterface", ")", "Commit", "(", ")", "(", "*", "SolrUpdateResponse", ",", "error", ")", "{", "params", ":=", "&", "url", ".", "Values", "{", "}", "\n", "params", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "si", ".", "Update", "(", "M", "{", "}", ",", "params", ")", "\n", "}" ]
// Commit the changes since the last commit
[ "Commit", "the", "changes", "since", "the", "last", "commit" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L203-L207
16,654
vanng822/go-solr
solr/solr.go
CoreAdmin
func (si *SolrInterface) CoreAdmin() (*CoreAdmin, error) { ca, err := NewCoreAdmin(si.conn.url.String()) if err != nil { return nil, err } ca.SetBasicAuth(si.conn.username, si.conn.password) return ca, nil }
go
func (si *SolrInterface) CoreAdmin() (*CoreAdmin, error) { ca, err := NewCoreAdmin(si.conn.url.String()) if err != nil { return nil, err } ca.SetBasicAuth(si.conn.username, si.conn.password) return ca, nil }
[ "func", "(", "si", "*", "SolrInterface", ")", "CoreAdmin", "(", ")", "(", "*", "CoreAdmin", ",", "error", ")", "{", "ca", ",", "err", ":=", "NewCoreAdmin", "(", "si", ".", "conn", ".", "url", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ca", ".", "SetBasicAuth", "(", "si", ".", "conn", ".", "username", ",", "si", ".", "conn", ".", "password", ")", "\n", "return", "ca", ",", "nil", "\n", "}" ]
// Return new instance of CoreAdmin with provided solrUrl and basic auth
[ "Return", "new", "instance", "of", "CoreAdmin", "with", "provided", "solrUrl", "and", "basic", "auth" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L225-L232
16,655
vanng822/go-solr
solr/solr.go
Schema
func (si *SolrInterface) Schema() (*Schema, error) { s, err := NewSchema(si.conn.url.String(), si.conn.core) if err != nil { return nil, err } s.SetBasicAuth(si.conn.username, si.conn.password) return s, nil }
go
func (si *SolrInterface) Schema() (*Schema, error) { s, err := NewSchema(si.conn.url.String(), si.conn.core) if err != nil { return nil, err } s.SetBasicAuth(si.conn.username, si.conn.password) return s, nil }
[ "func", "(", "si", "*", "SolrInterface", ")", "Schema", "(", ")", "(", "*", "Schema", ",", "error", ")", "{", "s", ",", "err", ":=", "NewSchema", "(", "si", ".", "conn", ".", "url", ".", "String", "(", ")", ",", "si", ".", "conn", ".", "core", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "s", ".", "SetBasicAuth", "(", "si", ".", "conn", ".", "username", ",", "si", ".", "conn", ".", "password", ")", "\n", "return", "s", ",", "nil", "\n", "}" ]
// Return new instance of Schema with provided solrUrl and basic auth
[ "Return", "new", "instance", "of", "Schema", "with", "provided", "solrUrl", "and", "basic", "auth" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L235-L242
16,656
vanng822/go-solr
solr/solr.go
Ping
func (si *SolrInterface) Ping() (status string, qtime int, err error) { r, err := HTTPGet(fmt.Sprintf("%s/%s/admin/ping?wt=json", si.conn.url.String(), si.conn.core), nil, si.conn.username, si.conn.password) if err != nil { return "", -1, err } resp, err := bytes2json(&r) if err != nil { return "", -1, err } status, ok := resp["status"].(string) if ok == false { return "", -1, fmt.Errorf("Unexpected response returned") } if QTime, ok := resp["responseHeader"].(map[string]interface{})["QTime"].(float64); ok { qtime = int(QTime) } else { qtime = -1 } return status, qtime, nil }
go
func (si *SolrInterface) Ping() (status string, qtime int, err error) { r, err := HTTPGet(fmt.Sprintf("%s/%s/admin/ping?wt=json", si.conn.url.String(), si.conn.core), nil, si.conn.username, si.conn.password) if err != nil { return "", -1, err } resp, err := bytes2json(&r) if err != nil { return "", -1, err } status, ok := resp["status"].(string) if ok == false { return "", -1, fmt.Errorf("Unexpected response returned") } if QTime, ok := resp["responseHeader"].(map[string]interface{})["QTime"].(float64); ok { qtime = int(QTime) } else { qtime = -1 } return status, qtime, nil }
[ "func", "(", "si", "*", "SolrInterface", ")", "Ping", "(", ")", "(", "status", "string", ",", "qtime", "int", ",", "err", "error", ")", "{", "r", ",", "err", ":=", "HTTPGet", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "si", ".", "conn", ".", "url", ".", "String", "(", ")", ",", "si", ".", "conn", ".", "core", ")", ",", "nil", ",", "si", ".", "conn", ".", "username", ",", "si", ".", "conn", ".", "password", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "-", "1", ",", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "bytes2json", "(", "&", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "-", "1", ",", "err", "\n", "}", "\n", "status", ",", "ok", ":=", "resp", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "if", "ok", "==", "false", "{", "return", "\"", "\"", ",", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "QTime", ",", "ok", ":=", "resp", "[", "\"", "\"", "]", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "[", "\"", "\"", "]", ".", "(", "float64", ")", ";", "ok", "{", "qtime", "=", "int", "(", "QTime", ")", "\n", "}", "else", "{", "qtime", "=", "-", "1", "\n", "}", "\n", "return", "status", ",", "qtime", ",", "nil", "\n", "}" ]
// Return 'status' and QTime from solr, if everything is fine status should have value 'OK' // QTime will have value -1 if can not determine
[ "Return", "status", "and", "QTime", "from", "solr", "if", "everything", "is", "fine", "status", "should", "have", "value", "OK", "QTime", "will", "have", "value", "-", "1", "if", "can", "not", "determine" ]
e3dd1d051d54b735110ab6ed8a6c6f948c8d789f
https://github.com/vanng822/go-solr/blob/e3dd1d051d54b735110ab6ed8a6c6f948c8d789f/solr/solr.go#L246-L266
16,657
mfonda/simhash
simhash.go
Vectorize
func Vectorize(features []Feature) Vector { var v Vector for _, feature := range features { sum := feature.Sum() weight := feature.Weight() for i := uint8(0); i < 64; i++ { bit := ((sum >> i) & 1) if bit == 1 { v[i] += weight } else { v[i] -= weight } } } return v }
go
func Vectorize(features []Feature) Vector { var v Vector for _, feature := range features { sum := feature.Sum() weight := feature.Weight() for i := uint8(0); i < 64; i++ { bit := ((sum >> i) & 1) if bit == 1 { v[i] += weight } else { v[i] -= weight } } } return v }
[ "func", "Vectorize", "(", "features", "[", "]", "Feature", ")", "Vector", "{", "var", "v", "Vector", "\n", "for", "_", ",", "feature", ":=", "range", "features", "{", "sum", ":=", "feature", ".", "Sum", "(", ")", "\n", "weight", ":=", "feature", ".", "Weight", "(", ")", "\n", "for", "i", ":=", "uint8", "(", "0", ")", ";", "i", "<", "64", ";", "i", "++", "{", "bit", ":=", "(", "(", "sum", ">>", "i", ")", "&", "1", ")", "\n", "if", "bit", "==", "1", "{", "v", "[", "i", "]", "+=", "weight", "\n", "}", "else", "{", "v", "[", "i", "]", "-=", "weight", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "v", "\n", "}" ]
// Vectorize generates 64 dimension vectors given a set of features. // Vectors are initialized to zero. The i-th element of the vector is then // incremented by weight of the i-th feature if the i-th bit of the feature // is set, and decremented by the weight of the i-th feature otherwise.
[ "Vectorize", "generates", "64", "dimension", "vectors", "given", "a", "set", "of", "features", ".", "Vectors", "are", "initialized", "to", "zero", ".", "The", "i", "-", "th", "element", "of", "the", "vector", "is", "then", "incremented", "by", "weight", "of", "the", "i", "-", "th", "feature", "if", "the", "i", "-", "th", "bit", "of", "the", "feature", "is", "set", "and", "decremented", "by", "the", "weight", "of", "the", "i", "-", "th", "feature", "otherwise", "." ]
79f94a1100d6da8bee6f6c253efc860a137a3186
https://github.com/mfonda/simhash/blob/79f94a1100d6da8bee6f6c253efc860a137a3186/simhash.go#L40-L55
16,658
mfonda/simhash
simhash.go
NewFeature
func NewFeature(f []byte) feature { h := fnv.New64() h.Write(f) return feature{h.Sum64(), 1} }
go
func NewFeature(f []byte) feature { h := fnv.New64() h.Write(f) return feature{h.Sum64(), 1} }
[ "func", "NewFeature", "(", "f", "[", "]", "byte", ")", "feature", "{", "h", ":=", "fnv", ".", "New64", "(", ")", "\n", "h", ".", "Write", "(", "f", ")", "\n", "return", "feature", "{", "h", ".", "Sum64", "(", ")", ",", "1", "}", "\n", "}" ]
// Returns a new feature representing the given byte slice, using a weight of 1
[ "Returns", "a", "new", "feature", "representing", "the", "given", "byte", "slice", "using", "a", "weight", "of", "1" ]
79f94a1100d6da8bee6f6c253efc860a137a3186
https://github.com/mfonda/simhash/blob/79f94a1100d6da8bee6f6c253efc860a137a3186/simhash.go#L112-L116
16,659
mfonda/simhash
simhash.go
NewFeatureWithWeight
func NewFeatureWithWeight(f []byte, weight int) feature { fw := NewFeature(f) fw.weight = weight return fw }
go
func NewFeatureWithWeight(f []byte, weight int) feature { fw := NewFeature(f) fw.weight = weight return fw }
[ "func", "NewFeatureWithWeight", "(", "f", "[", "]", "byte", ",", "weight", "int", ")", "feature", "{", "fw", ":=", "NewFeature", "(", "f", ")", "\n", "fw", ".", "weight", "=", "weight", "\n", "return", "fw", "\n", "}" ]
// Returns a new feature representing the given byte slice with the given weight
[ "Returns", "a", "new", "feature", "representing", "the", "given", "byte", "slice", "with", "the", "given", "weight" ]
79f94a1100d6da8bee6f6c253efc860a137a3186
https://github.com/mfonda/simhash/blob/79f94a1100d6da8bee6f6c253efc860a137a3186/simhash.go#L119-L123
16,660
hnakamur/go-scp
sink.go
ReceiveFile
func (s *SCP) ReceiveFile(srcFile, destFile string) error { srcFile = realPath(filepath.Clean(srcFile)) destFile = filepath.Clean(destFile) fiDest, err := os.Stat(destFile) if err != nil && !os.IsNotExist(err) { return fmt.Errorf("failed to get information of destnation file: err=%s", err) } if err == nil && fiDest.IsDir() { destFile = filepath.Join(destFile, filepath.Base(srcFile)) } return runSinkSession(s.client, srcFile, false, "", false, true, func(s *sinkSession) error { h, err := s.ReadHeaderOrReply() if err != nil { return fmt.Errorf("failed to read scp message header: err=%s", err) } timeHeader, ok := h.(timeMsgHeader) if !ok { return fmt.Errorf("expected time message header, got %+v", h) } h, err = s.ReadHeaderOrReply() if err != nil { return fmt.Errorf("failed to read scp message header: err=%s", err) } fileHeader, ok := h.(fileMsgHeader) if !ok { return fmt.Errorf("expected file message header, got %+v", h) } return copyFileBodyFromRemote(s, destFile, timeHeader, fileHeader) }) }
go
func (s *SCP) ReceiveFile(srcFile, destFile string) error { srcFile = realPath(filepath.Clean(srcFile)) destFile = filepath.Clean(destFile) fiDest, err := os.Stat(destFile) if err != nil && !os.IsNotExist(err) { return fmt.Errorf("failed to get information of destnation file: err=%s", err) } if err == nil && fiDest.IsDir() { destFile = filepath.Join(destFile, filepath.Base(srcFile)) } return runSinkSession(s.client, srcFile, false, "", false, true, func(s *sinkSession) error { h, err := s.ReadHeaderOrReply() if err != nil { return fmt.Errorf("failed to read scp message header: err=%s", err) } timeHeader, ok := h.(timeMsgHeader) if !ok { return fmt.Errorf("expected time message header, got %+v", h) } h, err = s.ReadHeaderOrReply() if err != nil { return fmt.Errorf("failed to read scp message header: err=%s", err) } fileHeader, ok := h.(fileMsgHeader) if !ok { return fmt.Errorf("expected file message header, got %+v", h) } return copyFileBodyFromRemote(s, destFile, timeHeader, fileHeader) }) }
[ "func", "(", "s", "*", "SCP", ")", "ReceiveFile", "(", "srcFile", ",", "destFile", "string", ")", "error", "{", "srcFile", "=", "realPath", "(", "filepath", ".", "Clean", "(", "srcFile", ")", ")", "\n", "destFile", "=", "filepath", ".", "Clean", "(", "destFile", ")", "\n", "fiDest", ",", "err", ":=", "os", ".", "Stat", "(", "destFile", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", "==", "nil", "&&", "fiDest", ".", "IsDir", "(", ")", "{", "destFile", "=", "filepath", ".", "Join", "(", "destFile", ",", "filepath", ".", "Base", "(", "srcFile", ")", ")", "\n", "}", "\n\n", "return", "runSinkSession", "(", "s", ".", "client", ",", "srcFile", ",", "false", ",", "\"", "\"", ",", "false", ",", "true", ",", "func", "(", "s", "*", "sinkSession", ")", "error", "{", "h", ",", "err", ":=", "s", ".", "ReadHeaderOrReply", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "timeHeader", ",", "ok", ":=", "h", ".", "(", "timeMsgHeader", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "h", ")", "\n", "}", "\n\n", "h", ",", "err", "=", "s", ".", "ReadHeaderOrReply", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "fileHeader", ",", "ok", ":=", "h", ".", "(", "fileMsgHeader", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "h", ")", "\n", "}", "\n\n", "return", "copyFileBodyFromRemote", "(", "s", ",", "destFile", ",", "timeHeader", ",", "fileHeader", ")", "\n", "}", ")", "\n", "}" ]
// ReceiveFile copies a single remote file to the local machine with // the specified name. The time and permission will be set to the same value // of the source file.
[ "ReceiveFile", "copies", "a", "single", "remote", "file", "to", "the", "local", "machine", "with", "the", "specified", "name", ".", "The", "time", "and", "permission", "will", "be", "set", "to", "the", "same", "value", "of", "the", "source", "file", "." ]
badb3bf1aae27e4e97b6494af96eed04a145a8a6
https://github.com/hnakamur/go-scp/blob/badb3bf1aae27e4e97b6494af96eed04a145a8a6/sink.go#L54-L86
16,661
hnakamur/go-scp
source.go
SendFile
func (s *SCP) SendFile(srcFile, destFile string) error { srcFile = filepath.Clean(srcFile) destFile = realPath(filepath.Clean(destFile)) return runSourceSession(s.client, destFile, false, "", false, true, func(s *sourceSession) error { osFileInfo, err := os.Stat(srcFile) if err != nil { return fmt.Errorf("failed to stat source file: err=%s", err) } fi := newFileInfoFromOS(osFileInfo, "") file, err := os.Open(srcFile) if err != nil { return fmt.Errorf("failed to open source file: err=%s", err) } // NOTE: file will be closed by WriteFile. err = s.WriteFile(fi, file) if err != nil { return fmt.Errorf("failed to copy file: err=%s", err) } return nil }) }
go
func (s *SCP) SendFile(srcFile, destFile string) error { srcFile = filepath.Clean(srcFile) destFile = realPath(filepath.Clean(destFile)) return runSourceSession(s.client, destFile, false, "", false, true, func(s *sourceSession) error { osFileInfo, err := os.Stat(srcFile) if err != nil { return fmt.Errorf("failed to stat source file: err=%s", err) } fi := newFileInfoFromOS(osFileInfo, "") file, err := os.Open(srcFile) if err != nil { return fmt.Errorf("failed to open source file: err=%s", err) } // NOTE: file will be closed by WriteFile. err = s.WriteFile(fi, file) if err != nil { return fmt.Errorf("failed to copy file: err=%s", err) } return nil }) }
[ "func", "(", "s", "*", "SCP", ")", "SendFile", "(", "srcFile", ",", "destFile", "string", ")", "error", "{", "srcFile", "=", "filepath", ".", "Clean", "(", "srcFile", ")", "\n", "destFile", "=", "realPath", "(", "filepath", ".", "Clean", "(", "destFile", ")", ")", "\n\n", "return", "runSourceSession", "(", "s", ".", "client", ",", "destFile", ",", "false", ",", "\"", "\"", ",", "false", ",", "true", ",", "func", "(", "s", "*", "sourceSession", ")", "error", "{", "osFileInfo", ",", "err", ":=", "os", ".", "Stat", "(", "srcFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "fi", ":=", "newFileInfoFromOS", "(", "osFileInfo", ",", "\"", "\"", ")", "\n\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "srcFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// NOTE: file will be closed by WriteFile.", "err", "=", "s", ".", "WriteFile", "(", "fi", ",", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// SendFile copies a single local file to the remote server. // The time and permission will be set with the value of the source file.
[ "SendFile", "copies", "a", "single", "local", "file", "to", "the", "remote", "server", ".", "The", "time", "and", "permission", "will", "be", "set", "with", "the", "value", "of", "the", "source", "file", "." ]
badb3bf1aae27e4e97b6494af96eed04a145a8a6
https://github.com/hnakamur/go-scp/blob/badb3bf1aae27e4e97b6494af96eed04a145a8a6/source.go#L33-L55
16,662
hnakamur/go-scp
source.go
SendDir
func (s *SCP) SendDir(srcDir, destDir string, acceptFn AcceptFunc) error { srcDir = filepath.Clean(srcDir) destDir = realPath(filepath.Clean(destDir)) if acceptFn == nil { acceptFn = acceptAny } return runSourceSession(s.client, destDir, false, "", true, true, func(s *sourceSession) error { prevDirSkipped := false endDirectories := func(prevDir, dir string) error { rel, err := filepath.Rel(prevDir, dir) if err != nil { return err } for _, comp := range strings.Split(rel, string([]rune{filepath.Separator})) { if comp == ".." { if prevDirSkipped { prevDirSkipped = false } else { err := s.EndDirectory() if err != nil { return err } } } } return nil } prevDir := srcDir myWalkFn := func(path string, info os.FileInfo, err error) error { // We must check err is not nil first. // See https://golang.org/pkg/path/filepath/#WalkFunc if err != nil { return err } isDir := info.IsDir() var dir string if isDir { dir = path } else { dir = filepath.Dir(path) } defer func() { prevDir = dir }() err = endDirectories(prevDir, dir) if err != nil { return err } scpFileInfo := newFileInfoFromOS(info, "") accepted, err := acceptFn(filepath.Dir(path), scpFileInfo) if err != nil { return err } if isDir { if !accepted { prevDirSkipped = true return filepath.SkipDir } err := s.StartDirectory(scpFileInfo) if err != nil { return err } } else { if accepted { fi := newFileInfoFromOS(info, "") file, err := os.Open(path) if err != nil { return err } err = s.WriteFile(fi, file) if err != nil { return err } } } return nil } err := filepath.Walk(srcDir, myWalkFn) if err != nil { return err } return endDirectories(prevDir, srcDir) }) }
go
func (s *SCP) SendDir(srcDir, destDir string, acceptFn AcceptFunc) error { srcDir = filepath.Clean(srcDir) destDir = realPath(filepath.Clean(destDir)) if acceptFn == nil { acceptFn = acceptAny } return runSourceSession(s.client, destDir, false, "", true, true, func(s *sourceSession) error { prevDirSkipped := false endDirectories := func(prevDir, dir string) error { rel, err := filepath.Rel(prevDir, dir) if err != nil { return err } for _, comp := range strings.Split(rel, string([]rune{filepath.Separator})) { if comp == ".." { if prevDirSkipped { prevDirSkipped = false } else { err := s.EndDirectory() if err != nil { return err } } } } return nil } prevDir := srcDir myWalkFn := func(path string, info os.FileInfo, err error) error { // We must check err is not nil first. // See https://golang.org/pkg/path/filepath/#WalkFunc if err != nil { return err } isDir := info.IsDir() var dir string if isDir { dir = path } else { dir = filepath.Dir(path) } defer func() { prevDir = dir }() err = endDirectories(prevDir, dir) if err != nil { return err } scpFileInfo := newFileInfoFromOS(info, "") accepted, err := acceptFn(filepath.Dir(path), scpFileInfo) if err != nil { return err } if isDir { if !accepted { prevDirSkipped = true return filepath.SkipDir } err := s.StartDirectory(scpFileInfo) if err != nil { return err } } else { if accepted { fi := newFileInfoFromOS(info, "") file, err := os.Open(path) if err != nil { return err } err = s.WriteFile(fi, file) if err != nil { return err } } } return nil } err := filepath.Walk(srcDir, myWalkFn) if err != nil { return err } return endDirectories(prevDir, srcDir) }) }
[ "func", "(", "s", "*", "SCP", ")", "SendDir", "(", "srcDir", ",", "destDir", "string", ",", "acceptFn", "AcceptFunc", ")", "error", "{", "srcDir", "=", "filepath", ".", "Clean", "(", "srcDir", ")", "\n", "destDir", "=", "realPath", "(", "filepath", ".", "Clean", "(", "destDir", ")", ")", "\n", "if", "acceptFn", "==", "nil", "{", "acceptFn", "=", "acceptAny", "\n", "}", "\n\n", "return", "runSourceSession", "(", "s", ".", "client", ",", "destDir", ",", "false", ",", "\"", "\"", ",", "true", ",", "true", ",", "func", "(", "s", "*", "sourceSession", ")", "error", "{", "prevDirSkipped", ":=", "false", "\n\n", "endDirectories", ":=", "func", "(", "prevDir", ",", "dir", "string", ")", "error", "{", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "prevDir", ",", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "comp", ":=", "range", "strings", ".", "Split", "(", "rel", ",", "string", "(", "[", "]", "rune", "{", "filepath", ".", "Separator", "}", ")", ")", "{", "if", "comp", "==", "\"", "\"", "{", "if", "prevDirSkipped", "{", "prevDirSkipped", "=", "false", "\n", "}", "else", "{", "err", ":=", "s", ".", "EndDirectory", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "prevDir", ":=", "srcDir", "\n", "myWalkFn", ":=", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "// We must check err is not nil first.", "// See https://golang.org/pkg/path/filepath/#WalkFunc", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "isDir", ":=", "info", ".", "IsDir", "(", ")", "\n", "var", "dir", "string", "\n", "if", "isDir", "{", "dir", "=", "path", "\n", "}", "else", "{", "dir", "=", "filepath", ".", "Dir", "(", "path", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "prevDir", "=", "dir", "\n", "}", "(", ")", "\n\n", "err", "=", "endDirectories", "(", "prevDir", ",", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "scpFileInfo", ":=", "newFileInfoFromOS", "(", "info", ",", "\"", "\"", ")", "\n", "accepted", ",", "err", ":=", "acceptFn", "(", "filepath", ".", "Dir", "(", "path", ")", ",", "scpFileInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "isDir", "{", "if", "!", "accepted", "{", "prevDirSkipped", "=", "true", "\n", "return", "filepath", ".", "SkipDir", "\n", "}", "\n\n", "err", ":=", "s", ".", "StartDirectory", "(", "scpFileInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "if", "accepted", "{", "fi", ":=", "newFileInfoFromOS", "(", "info", ",", "\"", "\"", ")", "\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "s", ".", "WriteFile", "(", "fi", ",", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "err", ":=", "filepath", ".", "Walk", "(", "srcDir", ",", "myWalkFn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "endDirectories", "(", "prevDir", ",", "srcDir", ")", "\n", "}", ")", "\n", "}" ]
// SendDir copies files and directories under the local srcDir to // to the remote destDir. You can filter the files and directories to be copied with acceptFn. // However this filtering is done at the receiver side, so all file bodies are transferred // over the network even if some files are filtered out. If you need more efficiency, // it is better to use another method like the tar command. // If acceptFn is nil, all files and directories will be copied. // The time and permission will be set to the same value of the source file or directory.
[ "SendDir", "copies", "files", "and", "directories", "under", "the", "local", "srcDir", "to", "to", "the", "remote", "destDir", ".", "You", "can", "filter", "the", "files", "and", "directories", "to", "be", "copied", "with", "acceptFn", ".", "However", "this", "filtering", "is", "done", "at", "the", "receiver", "side", "so", "all", "file", "bodies", "are", "transferred", "over", "the", "network", "even", "if", "some", "files", "are", "filtered", "out", ".", "If", "you", "need", "more", "efficiency", "it", "is", "better", "to", "use", "another", "method", "like", "the", "tar", "command", ".", "If", "acceptFn", "is", "nil", "all", "files", "and", "directories", "will", "be", "copied", ".", "The", "time", "and", "permission", "will", "be", "set", "to", "the", "same", "value", "of", "the", "source", "file", "or", "directory", "." ]
badb3bf1aae27e4e97b6494af96eed04a145a8a6
https://github.com/hnakamur/go-scp/blob/badb3bf1aae27e4e97b6494af96eed04a145a8a6/source.go#L74-L166
16,663
jinzhu/inflection
inflections.go
AddPlural
func AddPlural(find, replace string) { pluralInflections = append(pluralInflections, Regular{find, replace}) compile() }
go
func AddPlural(find, replace string) { pluralInflections = append(pluralInflections, Regular{find, replace}) compile() }
[ "func", "AddPlural", "(", "find", ",", "replace", "string", ")", "{", "pluralInflections", "=", "append", "(", "pluralInflections", ",", "Regular", "{", "find", ",", "replace", "}", ")", "\n", "compile", "(", ")", "\n", "}" ]
// AddPlural adds a plural inflection
[ "AddPlural", "adds", "a", "plural", "inflection" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L180-L183
16,664
jinzhu/inflection
inflections.go
AddSingular
func AddSingular(find, replace string) { singularInflections = append(singularInflections, Regular{find, replace}) compile() }
go
func AddSingular(find, replace string) { singularInflections = append(singularInflections, Regular{find, replace}) compile() }
[ "func", "AddSingular", "(", "find", ",", "replace", "string", ")", "{", "singularInflections", "=", "append", "(", "singularInflections", ",", "Regular", "{", "find", ",", "replace", "}", ")", "\n", "compile", "(", ")", "\n", "}" ]
// AddSingular adds a singular inflection
[ "AddSingular", "adds", "a", "singular", "inflection" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L186-L189
16,665
jinzhu/inflection
inflections.go
AddIrregular
func AddIrregular(singular, plural string) { irregularInflections = append(irregularInflections, Irregular{singular, plural}) compile() }
go
func AddIrregular(singular, plural string) { irregularInflections = append(irregularInflections, Irregular{singular, plural}) compile() }
[ "func", "AddIrregular", "(", "singular", ",", "plural", "string", ")", "{", "irregularInflections", "=", "append", "(", "irregularInflections", ",", "Irregular", "{", "singular", ",", "plural", "}", ")", "\n", "compile", "(", ")", "\n", "}" ]
// AddIrregular adds an irregular inflection
[ "AddIrregular", "adds", "an", "irregular", "inflection" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L192-L195
16,666
jinzhu/inflection
inflections.go
GetPlural
func GetPlural() RegularSlice { plurals := make(RegularSlice, len(pluralInflections)) copy(plurals, pluralInflections) return plurals }
go
func GetPlural() RegularSlice { plurals := make(RegularSlice, len(pluralInflections)) copy(plurals, pluralInflections) return plurals }
[ "func", "GetPlural", "(", ")", "RegularSlice", "{", "plurals", ":=", "make", "(", "RegularSlice", ",", "len", "(", "pluralInflections", ")", ")", "\n", "copy", "(", "plurals", ",", "pluralInflections", ")", "\n", "return", "plurals", "\n", "}" ]
// GetPlural retrieves the plural inflection values
[ "GetPlural", "retrieves", "the", "plural", "inflection", "values" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L204-L208
16,667
jinzhu/inflection
inflections.go
GetSingular
func GetSingular() RegularSlice { singulars := make(RegularSlice, len(singularInflections)) copy(singulars, singularInflections) return singulars }
go
func GetSingular() RegularSlice { singulars := make(RegularSlice, len(singularInflections)) copy(singulars, singularInflections) return singulars }
[ "func", "GetSingular", "(", ")", "RegularSlice", "{", "singulars", ":=", "make", "(", "RegularSlice", ",", "len", "(", "singularInflections", ")", ")", "\n", "copy", "(", "singulars", ",", "singularInflections", ")", "\n", "return", "singulars", "\n", "}" ]
// GetSingular retrieves the singular inflection values
[ "GetSingular", "retrieves", "the", "singular", "inflection", "values" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L211-L215
16,668
jinzhu/inflection
inflections.go
GetIrregular
func GetIrregular() IrregularSlice { irregular := make(IrregularSlice, len(irregularInflections)) copy(irregular, irregularInflections) return irregular }
go
func GetIrregular() IrregularSlice { irregular := make(IrregularSlice, len(irregularInflections)) copy(irregular, irregularInflections) return irregular }
[ "func", "GetIrregular", "(", ")", "IrregularSlice", "{", "irregular", ":=", "make", "(", "IrregularSlice", ",", "len", "(", "irregularInflections", ")", ")", "\n", "copy", "(", "irregular", ",", "irregularInflections", ")", "\n", "return", "irregular", "\n", "}" ]
// GetIrregular retrieves the irregular inflection values
[ "GetIrregular", "retrieves", "the", "irregular", "inflection", "values" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L218-L222
16,669
jinzhu/inflection
inflections.go
GetUncountable
func GetUncountable() []string { uncountables := make([]string, len(uncountableInflections)) copy(uncountables, uncountableInflections) return uncountables }
go
func GetUncountable() []string { uncountables := make([]string, len(uncountableInflections)) copy(uncountables, uncountableInflections) return uncountables }
[ "func", "GetUncountable", "(", ")", "[", "]", "string", "{", "uncountables", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "uncountableInflections", ")", ")", "\n", "copy", "(", "uncountables", ",", "uncountableInflections", ")", "\n", "return", "uncountables", "\n", "}" ]
// GetUncountable retrieves the uncountable inflection values
[ "GetUncountable", "retrieves", "the", "uncountable", "inflection", "values" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L225-L229
16,670
jinzhu/inflection
inflections.go
Plural
func Plural(str string) string { for _, inflection := range compiledPluralMaps { if inflection.regexp.MatchString(str) { return inflection.regexp.ReplaceAllString(str, inflection.replace) } } return str }
go
func Plural(str string) string { for _, inflection := range compiledPluralMaps { if inflection.regexp.MatchString(str) { return inflection.regexp.ReplaceAllString(str, inflection.replace) } } return str }
[ "func", "Plural", "(", "str", "string", ")", "string", "{", "for", "_", ",", "inflection", ":=", "range", "compiledPluralMaps", "{", "if", "inflection", ".", "regexp", ".", "MatchString", "(", "str", ")", "{", "return", "inflection", ".", "regexp", ".", "ReplaceAllString", "(", "str", ",", "inflection", ".", "replace", ")", "\n", "}", "\n", "}", "\n", "return", "str", "\n", "}" ]
// Plural converts a word to its plural form
[ "Plural", "converts", "a", "word", "to", "its", "plural", "form" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L256-L263
16,671
jinzhu/inflection
inflections.go
Singular
func Singular(str string) string { for _, inflection := range compiledSingularMaps { if inflection.regexp.MatchString(str) { return inflection.regexp.ReplaceAllString(str, inflection.replace) } } return str }
go
func Singular(str string) string { for _, inflection := range compiledSingularMaps { if inflection.regexp.MatchString(str) { return inflection.regexp.ReplaceAllString(str, inflection.replace) } } return str }
[ "func", "Singular", "(", "str", "string", ")", "string", "{", "for", "_", ",", "inflection", ":=", "range", "compiledSingularMaps", "{", "if", "inflection", ".", "regexp", ".", "MatchString", "(", "str", ")", "{", "return", "inflection", ".", "regexp", ".", "ReplaceAllString", "(", "str", ",", "inflection", ".", "replace", ")", "\n", "}", "\n", "}", "\n", "return", "str", "\n", "}" ]
// Singular converts a word to its singular form
[ "Singular", "converts", "a", "word", "to", "its", "singular", "form" ]
04140366298a54a039076d798123ffa108fff46c
https://github.com/jinzhu/inflection/blob/04140366298a54a039076d798123ffa108fff46c/inflections.go#L266-L273
16,672
drone/drone-go
plugin/webhook/handler.go
Handler
func Handler(plugin Plugin, secret string, logs logger.Logger) http.Handler { handler := &handler{ secret: secret, plugin: plugin, logger: logs, } if handler.logger == nil { handler.logger = logger.Discard() } return handler }
go
func Handler(plugin Plugin, secret string, logs logger.Logger) http.Handler { handler := &handler{ secret: secret, plugin: plugin, logger: logs, } if handler.logger == nil { handler.logger = logger.Discard() } return handler }
[ "func", "Handler", "(", "plugin", "Plugin", ",", "secret", "string", ",", "logs", "logger", ".", "Logger", ")", "http", ".", "Handler", "{", "handler", ":=", "&", "handler", "{", "secret", ":", "secret", ",", "plugin", ":", "plugin", ",", "logger", ":", "logs", ",", "}", "\n", "if", "handler", ".", "logger", "==", "nil", "{", "handler", ".", "logger", "=", "logger", ".", "Discard", "(", ")", "\n", "}", "\n", "return", "handler", "\n", "}" ]
// Handler returns a http.Handler that accepts JSON-encoded // HTTP requests for a webhook, invokes the underlying webhook // plugin, and writes the JSON-encoded data to the HTTP response. // // The handler verifies the authenticity of the HTTP request // using the http-signature, and returns a 400 Bad Request if // the signature is missing or invalid. // // The handler can optionally encrypt the response body using // aesgcm if the HTTP request includes the Accept-Encoding header // set to aesgcm.
[ "Handler", "returns", "a", "http", ".", "Handler", "that", "accepts", "JSON", "-", "encoded", "HTTP", "requests", "for", "a", "webhook", "invokes", "the", "underlying", "webhook", "plugin", "and", "writes", "the", "JSON", "-", "encoded", "data", "to", "the", "HTTP", "response", ".", "The", "handler", "verifies", "the", "authenticity", "of", "the", "HTTP", "request", "using", "the", "http", "-", "signature", "and", "returns", "a", "400", "Bad", "Request", "if", "the", "signature", "is", "missing", "or", "invalid", ".", "The", "handler", "can", "optionally", "encrypt", "the", "response", "body", "using", "aesgcm", "if", "the", "HTTP", "request", "includes", "the", "Accept", "-", "Encoding", "header", "set", "to", "aesgcm", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/plugin/webhook/handler.go#L38-L48
16,673
drone/drone-go
plugin/internal/client/client.go
New
func New(endpoint, secret string, skipverify bool) *Client { client := &Client{ Accept: "application/json", Encoding: "identity", Endpoint: endpoint, Secret: secret, } if skipverify { client.Client = &http.Client{ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, }, } } return client }
go
func New(endpoint, secret string, skipverify bool) *Client { client := &Client{ Accept: "application/json", Encoding: "identity", Endpoint: endpoint, Secret: secret, } if skipverify { client.Client = &http.Client{ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, }, } } return client }
[ "func", "New", "(", "endpoint", ",", "secret", "string", ",", "skipverify", "bool", ")", "*", "Client", "{", "client", ":=", "&", "Client", "{", "Accept", ":", "\"", "\"", ",", "Encoding", ":", "\"", "\"", ",", "Endpoint", ":", "endpoint", ",", "Secret", ":", "secret", ",", "}", "\n", "if", "skipverify", "{", "client", ".", "Client", "=", "&", "http", ".", "Client", "{", "CheckRedirect", ":", "func", "(", "*", "http", ".", "Request", ",", "[", "]", "*", "http", ".", "Request", ")", "error", "{", "return", "http", ".", "ErrUseLastResponse", "\n", "}", ",", "Transport", ":", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", ",", "}", ",", "}", ",", "}", "\n", "}", "\n", "return", "client", "\n", "}" ]
// New returns a new http.Client with signature verification.
[ "New", "returns", "a", "new", "http", ".", "Client", "with", "signature", "verification", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/plugin/internal/client/client.go#L58-L79
16,674
drone/drone-go
plugin/internal/client/client.go
Do
func (s *Client) Do(in, out interface{}) error { ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() data, err := json.Marshal(in) if err != nil { return err } buf := bytes.NewBuffer(data) req, err := http.NewRequest("POST", s.Endpoint, buf) if err != nil { return err } req = req.WithContext(ctx) req.Header.Add("Accept", s.Accept) req.Header.Add("Accept-Encoding", s.Encoding) req.Header.Add("Content-Type", "application/json") req.Header.Add("Digest", "SHA-256="+digest(data)) req.Header.Add("Date", time.Now().UTC().Format(http.TimeFormat)) err = signer.SignRequest("hmac-key", s.Secret, req) if err != nil { return err } res, err := s.client().Do(req) if err != nil { return err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return err } if res.StatusCode > 299 { // if the response body includes an error message // we should return the error string. if len(body) != 0 { return errors.New( string(body), ) } // if the response body is empty we should return // the default status code text. return errors.New( http.StatusText(res.StatusCode), ) } // if the response body return no content we exit // immediately. We do not read or unmarshal the response // and we do not return an error. if res.StatusCode == 204 { return nil } // the response body may be optionally encrypted // using the aesgcm algorithm. If encrypted, // decrypt using the shared secret. if res.Header.Get("Content-Encoding") == "aesgcm" { secret, err := aesgcm.Key(s.Secret) if err != nil { return err } plaintext, err := aesgcm.Decrypt(body, secret) if err != nil { return err } body = []byte(plaintext) } if out == nil { return nil } return json.Unmarshal(body, out) }
go
func (s *Client) Do(in, out interface{}) error { ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() data, err := json.Marshal(in) if err != nil { return err } buf := bytes.NewBuffer(data) req, err := http.NewRequest("POST", s.Endpoint, buf) if err != nil { return err } req = req.WithContext(ctx) req.Header.Add("Accept", s.Accept) req.Header.Add("Accept-Encoding", s.Encoding) req.Header.Add("Content-Type", "application/json") req.Header.Add("Digest", "SHA-256="+digest(data)) req.Header.Add("Date", time.Now().UTC().Format(http.TimeFormat)) err = signer.SignRequest("hmac-key", s.Secret, req) if err != nil { return err } res, err := s.client().Do(req) if err != nil { return err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return err } if res.StatusCode > 299 { // if the response body includes an error message // we should return the error string. if len(body) != 0 { return errors.New( string(body), ) } // if the response body is empty we should return // the default status code text. return errors.New( http.StatusText(res.StatusCode), ) } // if the response body return no content we exit // immediately. We do not read or unmarshal the response // and we do not return an error. if res.StatusCode == 204 { return nil } // the response body may be optionally encrypted // using the aesgcm algorithm. If encrypted, // decrypt using the shared secret. if res.Header.Get("Content-Encoding") == "aesgcm" { secret, err := aesgcm.Key(s.Secret) if err != nil { return err } plaintext, err := aesgcm.Decrypt(body, secret) if err != nil { return err } body = []byte(plaintext) } if out == nil { return nil } return json.Unmarshal(body, out) }
[ "func", "(", "s", "*", "Client", ")", "Do", "(", "in", ",", "out", "interface", "{", "}", ")", "error", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "time", ".", "Minute", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "s", ".", "Endpoint", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "req", "=", "req", ".", "WithContext", "(", "ctx", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "s", ".", "Accept", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "s", ".", "Encoding", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", "+", "digest", "(", "data", ")", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Format", "(", "http", ".", "TimeFormat", ")", ")", "\n", "err", "=", "signer", ".", "SignRequest", "(", "\"", "\"", ",", "s", ".", "Secret", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "s", ".", "client", "(", ")", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "res", ".", "StatusCode", ">", "299", "{", "// if the response body includes an error message", "// we should return the error string.", "if", "len", "(", "body", ")", "!=", "0", "{", "return", "errors", ".", "New", "(", "string", "(", "body", ")", ",", ")", "\n", "}", "\n", "// if the response body is empty we should return", "// the default status code text.", "return", "errors", ".", "New", "(", "http", ".", "StatusText", "(", "res", ".", "StatusCode", ")", ",", ")", "\n", "}", "\n\n", "// if the response body return no content we exit", "// immediately. We do not read or unmarshal the response", "// and we do not return an error.", "if", "res", ".", "StatusCode", "==", "204", "{", "return", "nil", "\n", "}", "\n\n", "// the response body may be optionally encrypted", "// using the aesgcm algorithm. If encrypted,", "// decrypt using the shared secret.", "if", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "secret", ",", "err", ":=", "aesgcm", ".", "Key", "(", "s", ".", "Secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "plaintext", ",", "err", ":=", "aesgcm", ".", "Decrypt", "(", "body", ",", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "body", "=", "[", "]", "byte", "(", "plaintext", ")", "\n", "}", "\n\n", "if", "out", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "json", ".", "Unmarshal", "(", "body", ",", "out", ")", "\n", "}" ]
// Do makes an http.Request to the target endpoint.
[ "Do", "makes", "an", "http", ".", "Request", "to", "the", "target", "endpoint", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/plugin/internal/client/client.go#L93-L172
16,675
drone/drone-go
drone/client.go
New
func New(uri string) Client { return &client{http.DefaultClient, strings.TrimSuffix(uri, "/")} }
go
func New(uri string) Client { return &client{http.DefaultClient, strings.TrimSuffix(uri, "/")} }
[ "func", "New", "(", "uri", "string", ")", "Client", "{", "return", "&", "client", "{", "http", ".", "DefaultClient", ",", "strings", ".", "TrimSuffix", "(", "uri", ",", "\"", "\"", ")", "}", "\n", "}" ]
// New returns a client at the specified url.
[ "New", "returns", "a", "client", "at", "the", "specified", "url", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L88-L90
16,676
drone/drone-go
drone/client.go
Self
func (c *client) Self() (*User, error) { out := new(User) uri := fmt.Sprintf(pathSelf, c.addr) err := c.get(uri, out) return out, err }
go
func (c *client) Self() (*User, error) { out := new(User) uri := fmt.Sprintf(pathSelf, c.addr) err := c.get(uri, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "Self", "(", ")", "(", "*", "User", ",", "error", ")", "{", "out", ":=", "new", "(", "User", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathSelf", ",", "c", ".", "addr", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// Self returns the currently authenticated user.
[ "Self", "returns", "the", "currently", "authenticated", "user", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L108-L113
16,677
drone/drone-go
drone/client.go
User
func (c *client) User(login string) (*User, error) { out := new(User) uri := fmt.Sprintf(pathUser, c.addr, login) err := c.get(uri, out) return out, err }
go
func (c *client) User(login string) (*User, error) { out := new(User) uri := fmt.Sprintf(pathUser, c.addr, login) err := c.get(uri, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "User", "(", "login", "string", ")", "(", "*", "User", ",", "error", ")", "{", "out", ":=", "new", "(", "User", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathUser", ",", "c", ".", "addr", ",", "login", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// User returns a user by login.
[ "User", "returns", "a", "user", "by", "login", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L116-L121
16,678
drone/drone-go
drone/client.go
UserList
func (c *client) UserList() ([]*User, error) { var out []*User uri := fmt.Sprintf(pathUsers, c.addr) err := c.get(uri, &out) return out, err }
go
func (c *client) UserList() ([]*User, error) { var out []*User uri := fmt.Sprintf(pathUsers, c.addr) err := c.get(uri, &out) return out, err }
[ "func", "(", "c", "*", "client", ")", "UserList", "(", ")", "(", "[", "]", "*", "User", ",", "error", ")", "{", "var", "out", "[", "]", "*", "User", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathUsers", ",", "c", ".", "addr", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "&", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// UserList returns a list of all registered users.
[ "UserList", "returns", "a", "list", "of", "all", "registered", "users", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L124-L129
16,679
drone/drone-go
drone/client.go
UserCreate
func (c *client) UserCreate(in *User) (*User, error) { out := new(User) uri := fmt.Sprintf(pathUsers, c.addr) err := c.post(uri, in, out) return out, err }
go
func (c *client) UserCreate(in *User) (*User, error) { out := new(User) uri := fmt.Sprintf(pathUsers, c.addr) err := c.post(uri, in, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "UserCreate", "(", "in", "*", "User", ")", "(", "*", "User", ",", "error", ")", "{", "out", ":=", "new", "(", "User", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathUsers", ",", "c", ".", "addr", ")", "\n", "err", ":=", "c", ".", "post", "(", "uri", ",", "in", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// UserCreate creates a new user account.
[ "UserCreate", "creates", "a", "new", "user", "account", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L132-L137
16,680
drone/drone-go
drone/client.go
UserUpdate
func (c *client) UserUpdate(login string, in *UserPatch) (*User, error) { out := new(User) uri := fmt.Sprintf(pathUser, c.addr, login) err := c.patch(uri, in, out) return out, err }
go
func (c *client) UserUpdate(login string, in *UserPatch) (*User, error) { out := new(User) uri := fmt.Sprintf(pathUser, c.addr, login) err := c.patch(uri, in, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "UserUpdate", "(", "login", "string", ",", "in", "*", "UserPatch", ")", "(", "*", "User", ",", "error", ")", "{", "out", ":=", "new", "(", "User", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathUser", ",", "c", ".", "addr", ",", "login", ")", "\n", "err", ":=", "c", ".", "patch", "(", "uri", ",", "in", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// UserUpdate updates a user account.
[ "UserUpdate", "updates", "a", "user", "account", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L140-L145
16,681
drone/drone-go
drone/client.go
UserDelete
func (c *client) UserDelete(login string) error { uri := fmt.Sprintf(pathUser, c.addr, login) err := c.delete(uri) return err }
go
func (c *client) UserDelete(login string) error { uri := fmt.Sprintf(pathUser, c.addr, login) err := c.delete(uri) return err }
[ "func", "(", "c", "*", "client", ")", "UserDelete", "(", "login", "string", ")", "error", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathUser", ",", "c", ".", "addr", ",", "login", ")", "\n", "err", ":=", "c", ".", "delete", "(", "uri", ")", "\n", "return", "err", "\n", "}" ]
// UserDelete deletes a user account.
[ "UserDelete", "deletes", "a", "user", "account", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L148-L152
16,682
drone/drone-go
drone/client.go
Repo
func (c *client) Repo(owner string, name string) (*Repo, error) { out := new(Repo) uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.get(uri, out) return out, err }
go
func (c *client) Repo(owner string, name string) (*Repo, error) { out := new(Repo) uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.get(uri, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "Repo", "(", "owner", "string", ",", "name", "string", ")", "(", "*", "Repo", ",", "error", ")", "{", "out", ":=", "new", "(", "Repo", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRepo", ",", "c", ".", "addr", ",", "owner", ",", "name", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// Repo returns a repository by name.
[ "Repo", "returns", "a", "repository", "by", "name", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L155-L160
16,683
drone/drone-go
drone/client.go
RepoList
func (c *client) RepoList() ([]*Repo, error) { var out []*Repo uri := fmt.Sprintf(pathRepos, c.addr) err := c.get(uri, &out) return out, err }
go
func (c *client) RepoList() ([]*Repo, error) { var out []*Repo uri := fmt.Sprintf(pathRepos, c.addr) err := c.get(uri, &out) return out, err }
[ "func", "(", "c", "*", "client", ")", "RepoList", "(", ")", "(", "[", "]", "*", "Repo", ",", "error", ")", "{", "var", "out", "[", "]", "*", "Repo", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRepos", ",", "c", ".", "addr", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "&", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// RepoList returns a list of all repositories to which // the user has explicit access in the host system.
[ "RepoList", "returns", "a", "list", "of", "all", "repositories", "to", "which", "the", "user", "has", "explicit", "access", "in", "the", "host", "system", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L164-L169
16,684
drone/drone-go
drone/client.go
RepoListSync
func (c *client) RepoListSync() ([]*Repo, error) { var out []*Repo uri := fmt.Sprintf(pathRepos, c.addr) err := c.post(uri, nil, &out) return out, err }
go
func (c *client) RepoListSync() ([]*Repo, error) { var out []*Repo uri := fmt.Sprintf(pathRepos, c.addr) err := c.post(uri, nil, &out) return out, err }
[ "func", "(", "c", "*", "client", ")", "RepoListSync", "(", ")", "(", "[", "]", "*", "Repo", ",", "error", ")", "{", "var", "out", "[", "]", "*", "Repo", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRepos", ",", "c", ".", "addr", ")", "\n", "err", ":=", "c", ".", "post", "(", "uri", ",", "nil", ",", "&", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// RepoListSync returns a list of all repositories to which // the user has explicit access in the host system.
[ "RepoListSync", "returns", "a", "list", "of", "all", "repositories", "to", "which", "the", "user", "has", "explicit", "access", "in", "the", "host", "system", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L173-L178
16,685
drone/drone-go
drone/client.go
RepoEnable
func (c *client) RepoEnable(owner, name string) (*Repo, error) { out := new(Repo) uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.post(uri, nil, out) return out, err }
go
func (c *client) RepoEnable(owner, name string) (*Repo, error) { out := new(Repo) uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.post(uri, nil, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "RepoEnable", "(", "owner", ",", "name", "string", ")", "(", "*", "Repo", ",", "error", ")", "{", "out", ":=", "new", "(", "Repo", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRepo", ",", "c", ".", "addr", ",", "owner", ",", "name", ")", "\n", "err", ":=", "c", ".", "post", "(", "uri", ",", "nil", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// RepoEnable activates a repository.
[ "RepoEnable", "activates", "a", "repository", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L181-L186
16,686
drone/drone-go
drone/client.go
RepoDisable
func (c *client) RepoDisable(owner, name string) error { uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.delete(uri) return err }
go
func (c *client) RepoDisable(owner, name string) error { uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.delete(uri) return err }
[ "func", "(", "c", "*", "client", ")", "RepoDisable", "(", "owner", ",", "name", "string", ")", "error", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRepo", ",", "c", ".", "addr", ",", "owner", ",", "name", ")", "\n", "err", ":=", "c", ".", "delete", "(", "uri", ")", "\n", "return", "err", "\n", "}" ]
// RepoDisable disables a repository.
[ "RepoDisable", "disables", "a", "repository", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L189-L193
16,687
drone/drone-go
drone/client.go
RepoUpdate
func (c *client) RepoUpdate(owner, name string, in *RepoPatch) (*Repo, error) { out := new(Repo) uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.patch(uri, in, out) return out, err }
go
func (c *client) RepoUpdate(owner, name string, in *RepoPatch) (*Repo, error) { out := new(Repo) uri := fmt.Sprintf(pathRepo, c.addr, owner, name) err := c.patch(uri, in, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "RepoUpdate", "(", "owner", ",", "name", "string", ",", "in", "*", "RepoPatch", ")", "(", "*", "Repo", ",", "error", ")", "{", "out", ":=", "new", "(", "Repo", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRepo", ",", "c", ".", "addr", ",", "owner", ",", "name", ")", "\n", "err", ":=", "c", ".", "patch", "(", "uri", ",", "in", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// RepoUpdate updates a repository.
[ "RepoUpdate", "updates", "a", "repository", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L203-L208
16,688
drone/drone-go
drone/client.go
RepoRepair
func (c *client) RepoRepair(owner, name string) error { uri := fmt.Sprintf(pathRepair, c.addr, owner, name) return c.post(uri, nil, nil) }
go
func (c *client) RepoRepair(owner, name string) error { uri := fmt.Sprintf(pathRepair, c.addr, owner, name) return c.post(uri, nil, nil) }
[ "func", "(", "c", "*", "client", ")", "RepoRepair", "(", "owner", ",", "name", "string", ")", "error", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRepair", ",", "c", ".", "addr", ",", "owner", ",", "name", ")", "\n", "return", "c", ".", "post", "(", "uri", ",", "nil", ",", "nil", ")", "\n", "}" ]
// RepoRepair repais the repository hooks.
[ "RepoRepair", "repais", "the", "repository", "hooks", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L219-L222
16,689
drone/drone-go
drone/client.go
Build
func (c *client) Build(owner, name string, num int) (*Build, error) { out := new(Build) uri := fmt.Sprintf(pathBuild, c.addr, owner, name, num) err := c.get(uri, out) return out, err }
go
func (c *client) Build(owner, name string, num int) (*Build, error) { out := new(Build) uri := fmt.Sprintf(pathBuild, c.addr, owner, name, num) err := c.get(uri, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "Build", "(", "owner", ",", "name", "string", ",", "num", "int", ")", "(", "*", "Build", ",", "error", ")", "{", "out", ":=", "new", "(", "Build", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathBuild", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "num", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// Build returns a repository build by number.
[ "Build", "returns", "a", "repository", "build", "by", "number", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L225-L230
16,690
drone/drone-go
drone/client.go
BuildLast
func (c *client) BuildLast(owner, name, branch string) (*Build, error) { out := new(Build) uri := fmt.Sprintf(pathBuild, c.addr, owner, name, "latest") if len(branch) != 0 { uri += "?branch=" + branch } err := c.get(uri, out) return out, err }
go
func (c *client) BuildLast(owner, name, branch string) (*Build, error) { out := new(Build) uri := fmt.Sprintf(pathBuild, c.addr, owner, name, "latest") if len(branch) != 0 { uri += "?branch=" + branch } err := c.get(uri, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "BuildLast", "(", "owner", ",", "name", ",", "branch", "string", ")", "(", "*", "Build", ",", "error", ")", "{", "out", ":=", "new", "(", "Build", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathBuild", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "\"", "\"", ")", "\n", "if", "len", "(", "branch", ")", "!=", "0", "{", "uri", "+=", "\"", "\"", "+", "branch", "\n", "}", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// Build returns the latest repository build by branch.
[ "Build", "returns", "the", "latest", "repository", "build", "by", "branch", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L233-L241
16,691
drone/drone-go
drone/client.go
BuildList
func (c *client) BuildList(owner, name string, opts ListOptions) ([]*Build, error) { var out []*Build uri := fmt.Sprintf(pathBuilds, c.addr, owner, name, encodeListOptions(opts)) err := c.get(uri, &out) return out, err }
go
func (c *client) BuildList(owner, name string, opts ListOptions) ([]*Build, error) { var out []*Build uri := fmt.Sprintf(pathBuilds, c.addr, owner, name, encodeListOptions(opts)) err := c.get(uri, &out) return out, err }
[ "func", "(", "c", "*", "client", ")", "BuildList", "(", "owner", ",", "name", "string", ",", "opts", "ListOptions", ")", "(", "[", "]", "*", "Build", ",", "error", ")", "{", "var", "out", "[", "]", "*", "Build", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathBuilds", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "encodeListOptions", "(", "opts", ")", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "&", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// BuildList returns a list of recent builds for the // the specified repository.
[ "BuildList", "returns", "a", "list", "of", "recent", "builds", "for", "the", "the", "specified", "repository", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L245-L250
16,692
drone/drone-go
drone/client.go
BuildRestart
func (c *client) BuildRestart(owner, name string, build int, params map[string]string) (*Build, error) { out := new(Build) val := mapValues(params) uri := fmt.Sprintf(pathBuild, c.addr, owner, name, build) if len(params) > 0 { uri = uri + "?" + val.Encode() } err := c.post(uri, nil, out) return out, err }
go
func (c *client) BuildRestart(owner, name string, build int, params map[string]string) (*Build, error) { out := new(Build) val := mapValues(params) uri := fmt.Sprintf(pathBuild, c.addr, owner, name, build) if len(params) > 0 { uri = uri + "?" + val.Encode() } err := c.post(uri, nil, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "BuildRestart", "(", "owner", ",", "name", "string", ",", "build", "int", ",", "params", "map", "[", "string", "]", "string", ")", "(", "*", "Build", ",", "error", ")", "{", "out", ":=", "new", "(", "Build", ")", "\n", "val", ":=", "mapValues", "(", "params", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathBuild", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "build", ")", "\n", "if", "len", "(", "params", ")", ">", "0", "{", "uri", "=", "uri", "+", "\"", "\"", "+", "val", ".", "Encode", "(", ")", "\n", "}", "\n", "err", ":=", "c", ".", "post", "(", "uri", ",", "nil", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// BuildRestart re-starts a stopped build.
[ "BuildRestart", "re", "-", "starts", "a", "stopped", "build", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L253-L262
16,693
drone/drone-go
drone/client.go
BuildCancel
func (c *client) BuildCancel(owner, name string, build int) error { uri := fmt.Sprintf(pathBuild, c.addr, owner, name, build) err := c.delete(uri) return err }
go
func (c *client) BuildCancel(owner, name string, build int) error { uri := fmt.Sprintf(pathBuild, c.addr, owner, name, build) err := c.delete(uri) return err }
[ "func", "(", "c", "*", "client", ")", "BuildCancel", "(", "owner", ",", "name", "string", ",", "build", "int", ")", "error", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathBuild", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "build", ")", "\n", "err", ":=", "c", ".", "delete", "(", "uri", ")", "\n", "return", "err", "\n", "}" ]
// BuildCancel cancels the running job.
[ "BuildCancel", "cancels", "the", "running", "job", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L265-L269
16,694
drone/drone-go
drone/client.go
BuildPurge
func (c *client) BuildPurge(owner, name string, before int) error { param := fmt.Sprintf("before=%d", before) uri := fmt.Sprintf(pathBuilds, c.addr, owner, name, param) err := c.delete(uri) return err }
go
func (c *client) BuildPurge(owner, name string, before int) error { param := fmt.Sprintf("before=%d", before) uri := fmt.Sprintf(pathBuilds, c.addr, owner, name, param) err := c.delete(uri) return err }
[ "func", "(", "c", "*", "client", ")", "BuildPurge", "(", "owner", ",", "name", "string", ",", "before", "int", ")", "error", "{", "param", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "before", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathBuilds", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "param", ")", "\n", "err", ":=", "c", ".", "delete", "(", "uri", ")", "\n", "return", "err", "\n", "}" ]
// BuildPurge purges the build history.
[ "BuildPurge", "purges", "the", "build", "history", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L272-L277
16,695
drone/drone-go
drone/client.go
Rollback
func (c *client) Rollback(namespace, name string, build int, target string, params map[string]string) (*Build, error) { out := new(Build) val := mapValues(params) val.Set("target", target) uri := fmt.Sprintf(pathRollback, c.addr, namespace, name, build, val.Encode()) err := c.post(uri, nil, out) return out, err }
go
func (c *client) Rollback(namespace, name string, build int, target string, params map[string]string) (*Build, error) { out := new(Build) val := mapValues(params) val.Set("target", target) uri := fmt.Sprintf(pathRollback, c.addr, namespace, name, build, val.Encode()) err := c.post(uri, nil, out) return out, err }
[ "func", "(", "c", "*", "client", ")", "Rollback", "(", "namespace", ",", "name", "string", ",", "build", "int", ",", "target", "string", ",", "params", "map", "[", "string", "]", "string", ")", "(", "*", "Build", ",", "error", ")", "{", "out", ":=", "new", "(", "Build", ")", "\n", "val", ":=", "mapValues", "(", "params", ")", "\n", "val", ".", "Set", "(", "\"", "\"", ",", "target", ")", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathRollback", ",", "c", ".", "addr", ",", "namespace", ",", "name", ",", "build", ",", "val", ".", "Encode", "(", ")", ")", "\n", "err", ":=", "c", ".", "post", "(", "uri", ",", "nil", ",", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// Roolback reverts the target environment to an previous build.
[ "Roolback", "reverts", "the", "target", "environment", "to", "an", "previous", "build", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L290-L297
16,696
drone/drone-go
drone/client.go
Approve
func (c *client) Approve(namespace, name string, build, stage int) error { uri := fmt.Sprintf(pathApprove, c.addr, namespace, name, build, stage) err := c.post(uri, nil, nil) return err }
go
func (c *client) Approve(namespace, name string, build, stage int) error { uri := fmt.Sprintf(pathApprove, c.addr, namespace, name, build, stage) err := c.post(uri, nil, nil) return err }
[ "func", "(", "c", "*", "client", ")", "Approve", "(", "namespace", ",", "name", "string", ",", "build", ",", "stage", "int", ")", "error", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathApprove", ",", "c", ".", "addr", ",", "namespace", ",", "name", ",", "build", ",", "stage", ")", "\n", "err", ":=", "c", ".", "post", "(", "uri", ",", "nil", ",", "nil", ")", "\n", "return", "err", "\n", "}" ]
// Approve approves a blocked build stage.
[ "Approve", "approves", "a", "blocked", "build", "stage", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L300-L304
16,697
drone/drone-go
drone/client.go
Logs
func (c *client) Logs(owner, name string, build, stage, step int) ([]*Line, error) { var out []*Line uri := fmt.Sprintf(pathLog, c.addr, owner, name, build, stage, step) err := c.get(uri, &out) return out, err }
go
func (c *client) Logs(owner, name string, build, stage, step int) ([]*Line, error) { var out []*Line uri := fmt.Sprintf(pathLog, c.addr, owner, name, build, stage, step) err := c.get(uri, &out) return out, err }
[ "func", "(", "c", "*", "client", ")", "Logs", "(", "owner", ",", "name", "string", ",", "build", ",", "stage", ",", "step", "int", ")", "(", "[", "]", "*", "Line", ",", "error", ")", "{", "var", "out", "[", "]", "*", "Line", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathLog", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "build", ",", "stage", ",", "step", ")", "\n", "err", ":=", "c", ".", "get", "(", "uri", ",", "&", "out", ")", "\n", "return", "out", ",", "err", "\n", "}" ]
// BuildLogs returns the build logs for the specified job.
[ "BuildLogs", "returns", "the", "build", "logs", "for", "the", "specified", "job", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L314-L319
16,698
drone/drone-go
drone/client.go
LogsPurge
func (c *client) LogsPurge(owner, name string, build, stage, step int) error { uri := fmt.Sprintf(pathLog, c.addr, owner, name, build, stage, step) err := c.delete(uri) return err }
go
func (c *client) LogsPurge(owner, name string, build, stage, step int) error { uri := fmt.Sprintf(pathLog, c.addr, owner, name, build, stage, step) err := c.delete(uri) return err }
[ "func", "(", "c", "*", "client", ")", "LogsPurge", "(", "owner", ",", "name", "string", ",", "build", ",", "stage", ",", "step", "int", ")", "error", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathLog", ",", "c", ".", "addr", ",", "owner", ",", "name", ",", "build", ",", "stage", ",", "step", ")", "\n", "err", ":=", "c", ".", "delete", "(", "uri", ")", "\n", "return", "err", "\n", "}" ]
// LogsPurge purges the build logs for the specified build.
[ "LogsPurge", "purges", "the", "build", "logs", "for", "the", "specified", "build", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L322-L326
16,699
drone/drone-go
drone/client.go
Sign
func (c *client) Sign(owner, name, file string) (string, error) { in := struct { Data string `json:"data"` }{Data: file} out := struct { Data string `json:"data"` }{} uri := fmt.Sprintf(pathSign, c.addr, owner, name) err := c.post(uri, &in, &out) return out.Data, err }
go
func (c *client) Sign(owner, name, file string) (string, error) { in := struct { Data string `json:"data"` }{Data: file} out := struct { Data string `json:"data"` }{} uri := fmt.Sprintf(pathSign, c.addr, owner, name) err := c.post(uri, &in, &out) return out.Data, err }
[ "func", "(", "c", "*", "client", ")", "Sign", "(", "owner", ",", "name", ",", "file", "string", ")", "(", "string", ",", "error", ")", "{", "in", ":=", "struct", "{", "Data", "string", "`json:\"data\"`", "\n", "}", "{", "Data", ":", "file", "}", "\n", "out", ":=", "struct", "{", "Data", "string", "`json:\"data\"`", "\n", "}", "{", "}", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "pathSign", ",", "c", ".", "addr", ",", "owner", ",", "name", ")", "\n", "err", ":=", "c", ".", "post", "(", "uri", ",", "&", "in", ",", "&", "out", ")", "\n", "return", "out", ".", "Data", ",", "err", "\n", "}" ]
// Sign signs the yaml file.
[ "Sign", "signs", "the", "yaml", "file", "." ]
618e4496482ebbcc8e0a32499e0a550b1a9c7b98
https://github.com/drone/drone-go/blob/618e4496482ebbcc8e0a32499e0a550b1a9c7b98/drone/client.go#L329-L339