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
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
153,200
ccding/go-stun
stun/log.go
Debugf
func (l *Logger) Debugf(format string, v ...interface{}) { if l.debug { l.Printf(format, v...) } }
go
func (l *Logger) Debugf(format string, v ...interface{}) { if l.debug { l.Printf(format, v...) } }
[ "func", "(", "l", "*", "Logger", ")", "Debugf", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "if", "l", ".", "debug", "{", "l", ".", "Printf", "(", "format", ",", "v", "...", ")", "\n", "}", "\n", "}" ]
// Debugf outputs the log in the format of log.Printf.
[ "Debugf", "outputs", "the", "log", "in", "the", "format", "of", "log", ".", "Printf", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/log.go#L55-L59
153,201
ccding/go-stun
stun/log.go
Infof
func (l *Logger) Infof(format string, v ...interface{}) { if l.info { l.Printf(format, v...) } }
go
func (l *Logger) Infof(format string, v ...interface{}) { if l.info { l.Printf(format, v...) } }
[ "func", "(", "l", "*", "Logger", ")", "Infof", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "if", "l", ".", "info", "{", "l", ".", "Printf", "(", "format", ",", "v", "...", ")", "\n", "}", "\n", "}" ]
// Infof outputs the log in the format of log.Printf.
[ "Infof", "outputs", "the", "log", "in", "the", "format", "of", "log", ".", "Printf", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/log.go#L76-L80
153,202
ccding/go-stun
stun/response.go
String
func (r *response) String() string { if r == nil { return "Nil" } return fmt.Sprintf("{packet nil: %v, local: %v, remote: %v, changed: %v, other: %v, identical: %v}", r.packet == nil, r.mappedAddr, r.serverAddr, r.changedAddr, r.otherAddr, r.identical) }
go
func (r *response) String() string { if r == nil { return "Nil" } return fmt.Sprintf("{packet nil: %v, local: %v, remote: %v, changed: %v, other: %v, identical: %v}", r.packet == nil, r.mappedAddr, r.serverAddr, r.changedAddr, r.otherAddr, r.identical) }
[ "func", "(", "r", "*", "response", ")", "String", "(", ")", "string", "{", "if", "r", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "packet", "==", "nil", ",", "r", ".", "mappedAddr", ",", "r", ".", "serverAddr", ",", "r", ".", "changedAddr", ",", "r", ".", "otherAddr", ",", "r", ".", "identical", ")", "\n", "}" ]
// String is only used for verbose mode output.
[ "String", "is", "only", "used", "for", "verbose", "mode", "output", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/response.go#L67-L78
153,203
ccding/go-stun
stun/client.go
NewClient
func NewClient() *Client { c := new(Client) c.SetSoftwareName(DefaultSoftwareName) c.logger = NewLogger() return c }
go
func NewClient() *Client { c := new(Client) c.SetSoftwareName(DefaultSoftwareName) c.logger = NewLogger() return c }
[ "func", "NewClient", "(", ")", "*", "Client", "{", "c", ":=", "new", "(", "Client", ")", "\n", "c", ".", "SetSoftwareName", "(", "DefaultSoftwareName", ")", "\n", "c", ".", "logger", "=", "NewLogger", "(", ")", "\n", "return", "c", "\n", "}" ]
// NewClient returns a client without network connection. The network // connection will be build when calling Discover function.
[ "NewClient", "returns", "a", "client", "without", "network", "connection", ".", "The", "network", "connection", "will", "be", "build", "when", "calling", "Discover", "function", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L36-L41
153,204
ccding/go-stun
stun/client.go
SetServerHost
func (c *Client) SetServerHost(host string, port int) { c.serverAddr = net.JoinHostPort(host, strconv.Itoa(port)) }
go
func (c *Client) SetServerHost(host string, port int) { c.serverAddr = net.JoinHostPort(host, strconv.Itoa(port)) }
[ "func", "(", "c", "*", "Client", ")", "SetServerHost", "(", "host", "string", ",", "port", "int", ")", "{", "c", ".", "serverAddr", "=", "net", ".", "JoinHostPort", "(", "host", ",", "strconv", ".", "Itoa", "(", "port", ")", ")", "\n", "}" ]
// SetServerHost allows user to set the STUN hostname and port.
[ "SetServerHost", "allows", "user", "to", "set", "the", "STUN", "hostname", "and", "port", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L66-L68
153,205
ccding/go-stun
stun/client.go
Discover
func (c *Client) Discover() (NATType, *Host, error) { if c.serverAddr == "" { c.SetServerAddr(DefaultServerAddr) } serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr) if err != nil { return NATError, nil, err } // Use the connection passed to the client if it is not nil, otherwise // create a connection and close it at the end. conn := c.conn if conn == nil { conn, err = net.ListenUDP("udp", nil) if err != nil { return NATError, nil, err } defer conn.Close() } return c.discover(conn, serverUDPAddr) }
go
func (c *Client) Discover() (NATType, *Host, error) { if c.serverAddr == "" { c.SetServerAddr(DefaultServerAddr) } serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr) if err != nil { return NATError, nil, err } // Use the connection passed to the client if it is not nil, otherwise // create a connection and close it at the end. conn := c.conn if conn == nil { conn, err = net.ListenUDP("udp", nil) if err != nil { return NATError, nil, err } defer conn.Close() } return c.discover(conn, serverUDPAddr) }
[ "func", "(", "c", "*", "Client", ")", "Discover", "(", ")", "(", "NATType", ",", "*", "Host", ",", "error", ")", "{", "if", "c", ".", "serverAddr", "==", "\"", "\"", "{", "c", ".", "SetServerAddr", "(", "DefaultServerAddr", ")", "\n", "}", "\n", "serverUDPAddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "c", ".", "serverAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NATError", ",", "nil", ",", "err", "\n", "}", "\n", "// Use the connection passed to the client if it is not nil, otherwise", "// create a connection and close it at the end.", "conn", ":=", "c", ".", "conn", "\n", "if", "conn", "==", "nil", "{", "conn", ",", "err", "=", "net", ".", "ListenUDP", "(", "\"", "\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NATError", ",", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "return", "c", ".", "discover", "(", "conn", ",", "serverUDPAddr", ")", "\n", "}" ]
// Discover contacts the STUN server and gets the response of NAT type, host // for UDP punching.
[ "Discover", "contacts", "the", "STUN", "server", "and", "gets", "the", "response", "of", "NAT", "type", "host", "for", "UDP", "punching", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L83-L102
153,206
ccding/go-stun
stun/client.go
Keepalive
func (c *Client) Keepalive() (*Host, error) { if c.conn == nil { return nil, errors.New("no connection available") } if c.serverAddr == "" { c.SetServerAddr(DefaultServerAddr) } serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr) if err != nil { return nil, err } resp, err := c.test1(c.conn, serverUDPAddr) if err != nil { return nil, err } if resp == nil || resp.packet == nil { return nil, errors.New("failed to contact") } return resp.mappedAddr, nil }
go
func (c *Client) Keepalive() (*Host, error) { if c.conn == nil { return nil, errors.New("no connection available") } if c.serverAddr == "" { c.SetServerAddr(DefaultServerAddr) } serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr) if err != nil { return nil, err } resp, err := c.test1(c.conn, serverUDPAddr) if err != nil { return nil, err } if resp == nil || resp.packet == nil { return nil, errors.New("failed to contact") } return resp.mappedAddr, nil }
[ "func", "(", "c", "*", "Client", ")", "Keepalive", "(", ")", "(", "*", "Host", ",", "error", ")", "{", "if", "c", ".", "conn", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "serverAddr", "==", "\"", "\"", "{", "c", ".", "SetServerAddr", "(", "DefaultServerAddr", ")", "\n", "}", "\n", "serverUDPAddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "c", ".", "serverAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "c", ".", "test1", "(", "c", ".", "conn", ",", "serverUDPAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", "==", "nil", "||", "resp", ".", "packet", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "resp", ".", "mappedAddr", ",", "nil", "\n", "}" ]
// Keepalive sends and receives a bind request, which ensures the mapping stays open // Only applicable when client was created with a connection.
[ "Keepalive", "sends", "and", "receives", "a", "bind", "request", "which", "ensures", "the", "mapping", "stays", "open", "Only", "applicable", "when", "client", "was", "created", "with", "a", "connection", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/client.go#L106-L126
153,207
ccding/go-stun
stun/utils.go
padding
func padding(bytes []byte) []byte { length := uint16(len(bytes)) return append(bytes, make([]byte, align(length)-length)...) }
go
func padding(bytes []byte) []byte { length := uint16(len(bytes)) return append(bytes, make([]byte, align(length)-length)...) }
[ "func", "padding", "(", "bytes", "[", "]", "byte", ")", "[", "]", "byte", "{", "length", ":=", "uint16", "(", "len", "(", "bytes", ")", ")", "\n", "return", "append", "(", "bytes", ",", "make", "(", "[", "]", "byte", ",", "align", "(", "length", ")", "-", "length", ")", "...", ")", "\n", "}" ]
// Padding the length of the byte slice to multiple of 4.
[ "Padding", "the", "length", "of", "the", "byte", "slice", "to", "multiple", "of", "4", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/utils.go#L24-L27
153,208
ccding/go-stun
stun/utils.go
isLocalAddress
func isLocalAddress(local, localRemote string) bool { // Resolve the IP returned by the STUN server first. localRemoteAddr, err := net.ResolveUDPAddr("udp", localRemote) if err != nil { return false } // Try comparing with the local address on the socket first, but only if // it's actually specified. addr, err := net.ResolveUDPAddr("udp", local) if err == nil && addr.IP != nil && !addr.IP.IsUnspecified() { return addr.IP.Equal(localRemoteAddr.IP) } // Fallback to checking IPs of all interfaces addrs, err := net.InterfaceAddrs() if err != nil { return false } for _, addr := range addrs { ip, _, err := net.ParseCIDR(addr.String()) if err != nil { continue } if ip.Equal(localRemoteAddr.IP) { return true } } return false }
go
func isLocalAddress(local, localRemote string) bool { // Resolve the IP returned by the STUN server first. localRemoteAddr, err := net.ResolveUDPAddr("udp", localRemote) if err != nil { return false } // Try comparing with the local address on the socket first, but only if // it's actually specified. addr, err := net.ResolveUDPAddr("udp", local) if err == nil && addr.IP != nil && !addr.IP.IsUnspecified() { return addr.IP.Equal(localRemoteAddr.IP) } // Fallback to checking IPs of all interfaces addrs, err := net.InterfaceAddrs() if err != nil { return false } for _, addr := range addrs { ip, _, err := net.ParseCIDR(addr.String()) if err != nil { continue } if ip.Equal(localRemoteAddr.IP) { return true } } return false }
[ "func", "isLocalAddress", "(", "local", ",", "localRemote", "string", ")", "bool", "{", "// Resolve the IP returned by the STUN server first.", "localRemoteAddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "localRemote", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "// Try comparing with the local address on the socket first, but only if", "// it's actually specified.", "addr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "local", ")", "\n", "if", "err", "==", "nil", "&&", "addr", ".", "IP", "!=", "nil", "&&", "!", "addr", ".", "IP", ".", "IsUnspecified", "(", ")", "{", "return", "addr", ".", "IP", ".", "Equal", "(", "localRemoteAddr", ".", "IP", ")", "\n", "}", "\n", "// Fallback to checking IPs of all interfaces", "addrs", ",", "err", ":=", "net", ".", "InterfaceAddrs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "ip", ",", "_", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "addr", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "if", "ip", ".", "Equal", "(", "localRemoteAddr", ".", "IP", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isLocalAddress check if localRemote is a local address.
[ "isLocalAddress", "check", "if", "localRemote", "is", "a", "local", "address", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/utils.go#L36-L63
153,209
ccding/go-stun
stun/host.go
TransportAddr
func (h *Host) TransportAddr() string { return net.JoinHostPort(h.ip, strconv.Itoa(int(h.port))) }
go
func (h *Host) TransportAddr() string { return net.JoinHostPort(h.ip, strconv.Itoa(int(h.port))) }
[ "func", "(", "h", "*", "Host", ")", "TransportAddr", "(", ")", "string", "{", "return", "net", ".", "JoinHostPort", "(", "h", ".", "ip", ",", "strconv", ".", "Itoa", "(", "int", "(", "h", ".", "port", ")", ")", ")", "\n", "}" ]
// TransportAddr returns the transport layer address of the host.
[ "TransportAddr", "returns", "the", "transport", "layer", "address", "of", "the", "host", "." ]
be486d185f3dfcb2dbf8429332da50a0da7f95a6
https://github.com/ccding/go-stun/blob/be486d185f3dfcb2dbf8429332da50a0da7f95a6/stun/host.go#L63-L65
153,210
zalando/go-keyring
keyring_windows.go
Set
func (k windowsKeychain) Set(service, username, password string) error { cred := wincred.NewGenericCredential(k.credName(service, username)) cred.UserName = username cred.CredentialBlob = []byte(password) return cred.Write() }
go
func (k windowsKeychain) Set(service, username, password string) error { cred := wincred.NewGenericCredential(k.credName(service, username)) cred.UserName = username cred.CredentialBlob = []byte(password) return cred.Write() }
[ "func", "(", "k", "windowsKeychain", ")", "Set", "(", "service", ",", "username", ",", "password", "string", ")", "error", "{", "cred", ":=", "wincred", ".", "NewGenericCredential", "(", "k", ".", "credName", "(", "service", ",", "username", ")", ")", "\n", "cred", ".", "UserName", "=", "username", "\n", "cred", ".", "CredentialBlob", "=", "[", "]", "byte", "(", "password", ")", "\n", "return", "cred", ".", "Write", "(", ")", "\n", "}" ]
// Set stores stores user and pass in the keyring under the defined service // name.
[ "Set", "stores", "stores", "user", "and", "pass", "in", "the", "keyring", "under", "the", "defined", "service", "name", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring_windows.go#L24-L29
153,211
zalando/go-keyring
secret_service/secret_service.go
NewSecret
func NewSecret(session dbus.ObjectPath, secret string) Secret { return Secret{ Session: session, Parameters: []byte{}, Value: []byte(secret), ContentType: "text/plain; charset=utf8", } }
go
func NewSecret(session dbus.ObjectPath, secret string) Secret { return Secret{ Session: session, Parameters: []byte{}, Value: []byte(secret), ContentType: "text/plain; charset=utf8", } }
[ "func", "NewSecret", "(", "session", "dbus", ".", "ObjectPath", ",", "secret", "string", ")", "Secret", "{", "return", "Secret", "{", "Session", ":", "session", ",", "Parameters", ":", "[", "]", "byte", "{", "}", ",", "Value", ":", "[", "]", "byte", "(", "secret", ")", ",", "ContentType", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewSecret initializes a new Secret.
[ "NewSecret", "initializes", "a", "new", "Secret", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L33-L40
153,212
zalando/go-keyring
secret_service/secret_service.go
NewSecretService
func NewSecretService() (*SecretService, error) { conn, err := dbus.SessionBus() if err != nil { return nil, err } return &SecretService{ conn, conn.Object(serviceName, servicePath), }, nil }
go
func NewSecretService() (*SecretService, error) { conn, err := dbus.SessionBus() if err != nil { return nil, err } return &SecretService{ conn, conn.Object(serviceName, servicePath), }, nil }
[ "func", "NewSecretService", "(", ")", "(", "*", "SecretService", ",", "error", ")", "{", "conn", ",", "err", ":=", "dbus", ".", "SessionBus", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "SecretService", "{", "conn", ",", "conn", ".", "Object", "(", "serviceName", ",", "servicePath", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewSecretService inializes a new SecretService object.
[ "NewSecretService", "inializes", "a", "new", "SecretService", "object", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L49-L59
153,213
zalando/go-keyring
secret_service/secret_service.go
OpenSession
func (s *SecretService) OpenSession() (dbus.BusObject, error) { var disregard dbus.Variant var sessionPath dbus.ObjectPath err := s.object.Call(serviceInterface+".OpenSession", 0, "plain", dbus.MakeVariant("")).Store(&disregard, &sessionPath) if err != nil { return nil, err } return s.Object(serviceName, sessionPath), nil }
go
func (s *SecretService) OpenSession() (dbus.BusObject, error) { var disregard dbus.Variant var sessionPath dbus.ObjectPath err := s.object.Call(serviceInterface+".OpenSession", 0, "plain", dbus.MakeVariant("")).Store(&disregard, &sessionPath) if err != nil { return nil, err } return s.Object(serviceName, sessionPath), nil }
[ "func", "(", "s", "*", "SecretService", ")", "OpenSession", "(", ")", "(", "dbus", ".", "BusObject", ",", "error", ")", "{", "var", "disregard", "dbus", ".", "Variant", "\n", "var", "sessionPath", "dbus", ".", "ObjectPath", "\n", "err", ":=", "s", ".", "object", ".", "Call", "(", "serviceInterface", "+", "\"", "\"", ",", "0", ",", "\"", "\"", ",", "dbus", ".", "MakeVariant", "(", "\"", "\"", ")", ")", ".", "Store", "(", "&", "disregard", ",", "&", "sessionPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "s", ".", "Object", "(", "serviceName", ",", "sessionPath", ")", ",", "nil", "\n", "}" ]
// OpenSession opens a secret service session.
[ "OpenSession", "opens", "a", "secret", "service", "session", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L62-L71
153,214
zalando/go-keyring
secret_service/secret_service.go
GetCollection
func (s *SecretService) GetCollection(name string) dbus.BusObject { return s.Object(serviceName, dbus.ObjectPath(collectionBasePath+name)) }
go
func (s *SecretService) GetCollection(name string) dbus.BusObject { return s.Object(serviceName, dbus.ObjectPath(collectionBasePath+name)) }
[ "func", "(", "s", "*", "SecretService", ")", "GetCollection", "(", "name", "string", ")", "dbus", ".", "BusObject", "{", "return", "s", ".", "Object", "(", "serviceName", ",", "dbus", ".", "ObjectPath", "(", "collectionBasePath", "+", "name", ")", ")", "\n", "}" ]
// GetCollection returns a collection from a name.
[ "GetCollection", "returns", "a", "collection", "from", "a", "name", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L91-L93
153,215
zalando/go-keyring
secret_service/secret_service.go
GetLoginCollection
func (s *SecretService) GetLoginCollection() dbus.BusObject { path := dbus.ObjectPath(collectionBasePath + "login") if err := s.CheckCollectionPath(path); err != nil { path = dbus.ObjectPath(loginCollectionAlias) } return s.Object(serviceName, path) }
go
func (s *SecretService) GetLoginCollection() dbus.BusObject { path := dbus.ObjectPath(collectionBasePath + "login") if err := s.CheckCollectionPath(path); err != nil { path = dbus.ObjectPath(loginCollectionAlias) } return s.Object(serviceName, path) }
[ "func", "(", "s", "*", "SecretService", ")", "GetLoginCollection", "(", ")", "dbus", ".", "BusObject", "{", "path", ":=", "dbus", ".", "ObjectPath", "(", "collectionBasePath", "+", "\"", "\"", ")", "\n", "if", "err", ":=", "s", ".", "CheckCollectionPath", "(", "path", ")", ";", "err", "!=", "nil", "{", "path", "=", "dbus", ".", "ObjectPath", "(", "loginCollectionAlias", ")", "\n", "}", "\n", "return", "s", ".", "Object", "(", "serviceName", ",", "path", ")", "\n", "}" ]
// GetLoginCollection decides and returns the dbus collection to be used for login.
[ "GetLoginCollection", "decides", "and", "returns", "the", "dbus", "collection", "to", "be", "used", "for", "login", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L96-L102
153,216
zalando/go-keyring
secret_service/secret_service.go
Unlock
func (s *SecretService) Unlock(collection dbus.ObjectPath) error { var unlocked []dbus.ObjectPath var prompt dbus.ObjectPath err := s.object.Call(serviceInterface+".Unlock", 0, []dbus.ObjectPath{collection}).Store(&unlocked, &prompt) if err != nil { return err } _, v, err := s.handlePrompt(prompt) if err != nil { return err } collections := v.Value() switch c := collections.(type) { case []dbus.ObjectPath: unlocked = append(unlocked, c...) } if len(unlocked) != 1 || unlocked[0] != collection { return fmt.Errorf("failed to unlock correct collection '%v'", collection) } return nil }
go
func (s *SecretService) Unlock(collection dbus.ObjectPath) error { var unlocked []dbus.ObjectPath var prompt dbus.ObjectPath err := s.object.Call(serviceInterface+".Unlock", 0, []dbus.ObjectPath{collection}).Store(&unlocked, &prompt) if err != nil { return err } _, v, err := s.handlePrompt(prompt) if err != nil { return err } collections := v.Value() switch c := collections.(type) { case []dbus.ObjectPath: unlocked = append(unlocked, c...) } if len(unlocked) != 1 || unlocked[0] != collection { return fmt.Errorf("failed to unlock correct collection '%v'", collection) } return nil }
[ "func", "(", "s", "*", "SecretService", ")", "Unlock", "(", "collection", "dbus", ".", "ObjectPath", ")", "error", "{", "var", "unlocked", "[", "]", "dbus", ".", "ObjectPath", "\n", "var", "prompt", "dbus", ".", "ObjectPath", "\n", "err", ":=", "s", ".", "object", ".", "Call", "(", "serviceInterface", "+", "\"", "\"", ",", "0", ",", "[", "]", "dbus", ".", "ObjectPath", "{", "collection", "}", ")", ".", "Store", "(", "&", "unlocked", ",", "&", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "v", ",", "err", ":=", "s", ".", "handlePrompt", "(", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "collections", ":=", "v", ".", "Value", "(", ")", "\n", "switch", "c", ":=", "collections", ".", "(", "type", ")", "{", "case", "[", "]", "dbus", ".", "ObjectPath", ":", "unlocked", "=", "append", "(", "unlocked", ",", "c", "...", ")", "\n", "}", "\n\n", "if", "len", "(", "unlocked", ")", "!=", "1", "||", "unlocked", "[", "0", "]", "!=", "collection", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "collection", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Unlock unlocks a collection.
[ "Unlock", "unlocks", "a", "collection", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L105-L129
153,217
zalando/go-keyring
secret_service/secret_service.go
Close
func (s *SecretService) Close(session dbus.BusObject) error { return session.Call(sessionInterface+".Close", 0).Err }
go
func (s *SecretService) Close(session dbus.BusObject) error { return session.Call(sessionInterface+".Close", 0).Err }
[ "func", "(", "s", "*", "SecretService", ")", "Close", "(", "session", "dbus", ".", "BusObject", ")", "error", "{", "return", "session", ".", "Call", "(", "sessionInterface", "+", "\"", "\"", ",", "0", ")", ".", "Err", "\n", "}" ]
// Close closes a secret service dbus session.
[ "Close", "closes", "a", "secret", "service", "dbus", "session", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L132-L134
153,218
zalando/go-keyring
secret_service/secret_service.go
CreateCollection
func (s *SecretService) CreateCollection(label string) (dbus.BusObject, error) { properties := map[string]dbus.Variant{ collectionInterface + ".Label": dbus.MakeVariant(label), } var collection, prompt dbus.ObjectPath err := s.object.Call(serviceInterface+".CreateCollection", 0, properties, ""). Store(&collection, &prompt) if err != nil { return nil, err } _, v, err := s.handlePrompt(prompt) if err != nil { return nil, err } if v.String() != "" { collection = dbus.ObjectPath(v.String()) } return s.Object(serviceName, collection), nil }
go
func (s *SecretService) CreateCollection(label string) (dbus.BusObject, error) { properties := map[string]dbus.Variant{ collectionInterface + ".Label": dbus.MakeVariant(label), } var collection, prompt dbus.ObjectPath err := s.object.Call(serviceInterface+".CreateCollection", 0, properties, ""). Store(&collection, &prompt) if err != nil { return nil, err } _, v, err := s.handlePrompt(prompt) if err != nil { return nil, err } if v.String() != "" { collection = dbus.ObjectPath(v.String()) } return s.Object(serviceName, collection), nil }
[ "func", "(", "s", "*", "SecretService", ")", "CreateCollection", "(", "label", "string", ")", "(", "dbus", ".", "BusObject", ",", "error", ")", "{", "properties", ":=", "map", "[", "string", "]", "dbus", ".", "Variant", "{", "collectionInterface", "+", "\"", "\"", ":", "dbus", ".", "MakeVariant", "(", "label", ")", ",", "}", "\n", "var", "collection", ",", "prompt", "dbus", ".", "ObjectPath", "\n", "err", ":=", "s", ".", "object", ".", "Call", "(", "serviceInterface", "+", "\"", "\"", ",", "0", ",", "properties", ",", "\"", "\"", ")", ".", "Store", "(", "&", "collection", ",", "&", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "_", ",", "v", ",", "err", ":=", "s", ".", "handlePrompt", "(", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "v", ".", "String", "(", ")", "!=", "\"", "\"", "{", "collection", "=", "dbus", ".", "ObjectPath", "(", "v", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "return", "s", ".", "Object", "(", "serviceName", ",", "collection", ")", ",", "nil", "\n", "}" ]
// CreateCollection with the supplied label.
[ "CreateCollection", "with", "the", "supplied", "label", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L137-L158
153,219
zalando/go-keyring
secret_service/secret_service.go
CreateItem
func (s *SecretService) CreateItem(collection dbus.BusObject, label string, attributes map[string]string, secret Secret) error { properties := map[string]dbus.Variant{ itemInterface + ".Label": dbus.MakeVariant(label), itemInterface + ".Attributes": dbus.MakeVariant(attributes), } var item, prompt dbus.ObjectPath err := collection.Call(collectionInterface+".CreateItem", 0, properties, secret, true).Store(&item, &prompt) if err != nil { return err } _, _, err = s.handlePrompt(prompt) if err != nil { return err } return nil }
go
func (s *SecretService) CreateItem(collection dbus.BusObject, label string, attributes map[string]string, secret Secret) error { properties := map[string]dbus.Variant{ itemInterface + ".Label": dbus.MakeVariant(label), itemInterface + ".Attributes": dbus.MakeVariant(attributes), } var item, prompt dbus.ObjectPath err := collection.Call(collectionInterface+".CreateItem", 0, properties, secret, true).Store(&item, &prompt) if err != nil { return err } _, _, err = s.handlePrompt(prompt) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "SecretService", ")", "CreateItem", "(", "collection", "dbus", ".", "BusObject", ",", "label", "string", ",", "attributes", "map", "[", "string", "]", "string", ",", "secret", "Secret", ")", "error", "{", "properties", ":=", "map", "[", "string", "]", "dbus", ".", "Variant", "{", "itemInterface", "+", "\"", "\"", ":", "dbus", ".", "MakeVariant", "(", "label", ")", ",", "itemInterface", "+", "\"", "\"", ":", "dbus", ".", "MakeVariant", "(", "attributes", ")", ",", "}", "\n\n", "var", "item", ",", "prompt", "dbus", ".", "ObjectPath", "\n", "err", ":=", "collection", ".", "Call", "(", "collectionInterface", "+", "\"", "\"", ",", "0", ",", "properties", ",", "secret", ",", "true", ")", ".", "Store", "(", "&", "item", ",", "&", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "_", ",", "err", "=", "s", ".", "handlePrompt", "(", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CreateItem creates an item in a collection, with label, attributes and a // related secret.
[ "CreateItem", "creates", "an", "item", "in", "a", "collection", "with", "label", "attributes", "and", "a", "related", "secret", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L162-L181
153,220
zalando/go-keyring
secret_service/secret_service.go
handlePrompt
func (s *SecretService) handlePrompt(prompt dbus.ObjectPath) (bool, dbus.Variant, error) { if prompt != dbus.ObjectPath("/") { err := s.Object(serviceName, prompt).Call(promptInterface+".Prompt", 0, "").Err if err != nil { return false, dbus.MakeVariant(""), err } promptSignal := make(chan *dbus.Signal, 1) s.Signal(promptSignal) signal := <-promptSignal switch signal.Name { case promptInterface + ".Completed": dismissed := signal.Body[0].(bool) result := signal.Body[1].(dbus.Variant) return dismissed, result, nil } } return false, dbus.MakeVariant(""), nil }
go
func (s *SecretService) handlePrompt(prompt dbus.ObjectPath) (bool, dbus.Variant, error) { if prompt != dbus.ObjectPath("/") { err := s.Object(serviceName, prompt).Call(promptInterface+".Prompt", 0, "").Err if err != nil { return false, dbus.MakeVariant(""), err } promptSignal := make(chan *dbus.Signal, 1) s.Signal(promptSignal) signal := <-promptSignal switch signal.Name { case promptInterface + ".Completed": dismissed := signal.Body[0].(bool) result := signal.Body[1].(dbus.Variant) return dismissed, result, nil } } return false, dbus.MakeVariant(""), nil }
[ "func", "(", "s", "*", "SecretService", ")", "handlePrompt", "(", "prompt", "dbus", ".", "ObjectPath", ")", "(", "bool", ",", "dbus", ".", "Variant", ",", "error", ")", "{", "if", "prompt", "!=", "dbus", ".", "ObjectPath", "(", "\"", "\"", ")", "{", "err", ":=", "s", ".", "Object", "(", "serviceName", ",", "prompt", ")", ".", "Call", "(", "promptInterface", "+", "\"", "\"", ",", "0", ",", "\"", "\"", ")", ".", "Err", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "dbus", ".", "MakeVariant", "(", "\"", "\"", ")", ",", "err", "\n", "}", "\n\n", "promptSignal", ":=", "make", "(", "chan", "*", "dbus", ".", "Signal", ",", "1", ")", "\n", "s", ".", "Signal", "(", "promptSignal", ")", "\n\n", "signal", ":=", "<-", "promptSignal", "\n", "switch", "signal", ".", "Name", "{", "case", "promptInterface", "+", "\"", "\"", ":", "dismissed", ":=", "signal", ".", "Body", "[", "0", "]", ".", "(", "bool", ")", "\n", "result", ":=", "signal", ".", "Body", "[", "1", "]", ".", "(", "dbus", ".", "Variant", ")", "\n", "return", "dismissed", ",", "result", ",", "nil", "\n", "}", "\n\n", "}", "\n\n", "return", "false", ",", "dbus", ".", "MakeVariant", "(", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// handlePrompt checks if a prompt should be handles and handles it by // triggering the prompt and waiting for the Sercret service daemon to display // the prompt to the user.
[ "handlePrompt", "checks", "if", "a", "prompt", "should", "be", "handles", "and", "handles", "it", "by", "triggering", "the", "prompt", "and", "waiting", "for", "the", "Sercret", "service", "daemon", "to", "display", "the", "prompt", "to", "the", "user", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L186-L207
153,221
zalando/go-keyring
secret_service/secret_service.go
SearchItems
func (s *SecretService) SearchItems(collection dbus.BusObject, search interface{}) ([]dbus.ObjectPath, error) { var results []dbus.ObjectPath err := collection.Call(collectionInterface+".SearchItems", 0, search).Store(&results) if err != nil { return nil, err } return results, nil }
go
func (s *SecretService) SearchItems(collection dbus.BusObject, search interface{}) ([]dbus.ObjectPath, error) { var results []dbus.ObjectPath err := collection.Call(collectionInterface+".SearchItems", 0, search).Store(&results) if err != nil { return nil, err } return results, nil }
[ "func", "(", "s", "*", "SecretService", ")", "SearchItems", "(", "collection", "dbus", ".", "BusObject", ",", "search", "interface", "{", "}", ")", "(", "[", "]", "dbus", ".", "ObjectPath", ",", "error", ")", "{", "var", "results", "[", "]", "dbus", ".", "ObjectPath", "\n", "err", ":=", "collection", ".", "Call", "(", "collectionInterface", "+", "\"", "\"", ",", "0", ",", "search", ")", ".", "Store", "(", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "results", ",", "nil", "\n", "}" ]
// SearchItems returns a list of items matching the search object.
[ "SearchItems", "returns", "a", "list", "of", "items", "matching", "the", "search", "object", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L210-L218
153,222
zalando/go-keyring
secret_service/secret_service.go
GetSecret
func (s *SecretService) GetSecret(itemPath dbus.ObjectPath, session dbus.ObjectPath) (*Secret, error) { var secret Secret err := s.Object(serviceName, itemPath).Call(itemInterface+".GetSecret", 0, session).Store(&secret) if err != nil { return nil, err } return &secret, nil }
go
func (s *SecretService) GetSecret(itemPath dbus.ObjectPath, session dbus.ObjectPath) (*Secret, error) { var secret Secret err := s.Object(serviceName, itemPath).Call(itemInterface+".GetSecret", 0, session).Store(&secret) if err != nil { return nil, err } return &secret, nil }
[ "func", "(", "s", "*", "SecretService", ")", "GetSecret", "(", "itemPath", "dbus", ".", "ObjectPath", ",", "session", "dbus", ".", "ObjectPath", ")", "(", "*", "Secret", ",", "error", ")", "{", "var", "secret", "Secret", "\n", "err", ":=", "s", ".", "Object", "(", "serviceName", ",", "itemPath", ")", ".", "Call", "(", "itemInterface", "+", "\"", "\"", ",", "0", ",", "session", ")", ".", "Store", "(", "&", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "secret", ",", "nil", "\n", "}" ]
// GetSecret gets secret from an item in a given session.
[ "GetSecret", "gets", "secret", "from", "an", "item", "in", "a", "given", "session", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L221-L229
153,223
zalando/go-keyring
secret_service/secret_service.go
Delete
func (s *SecretService) Delete(itemPath dbus.ObjectPath) error { var prompt dbus.ObjectPath err := s.Object(serviceName, itemPath).Call(itemInterface+".Delete", 0).Store(&prompt) if err != nil { return err } _, _, err = s.handlePrompt(prompt) if err != nil { return err } return nil }
go
func (s *SecretService) Delete(itemPath dbus.ObjectPath) error { var prompt dbus.ObjectPath err := s.Object(serviceName, itemPath).Call(itemInterface+".Delete", 0).Store(&prompt) if err != nil { return err } _, _, err = s.handlePrompt(prompt) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "SecretService", ")", "Delete", "(", "itemPath", "dbus", ".", "ObjectPath", ")", "error", "{", "var", "prompt", "dbus", ".", "ObjectPath", "\n", "err", ":=", "s", ".", "Object", "(", "serviceName", ",", "itemPath", ")", ".", "Call", "(", "itemInterface", "+", "\"", "\"", ",", "0", ")", ".", "Store", "(", "&", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "_", ",", "err", "=", "s", ".", "handlePrompt", "(", "prompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Delete deletes an item from the collection.
[ "Delete", "deletes", "an", "item", "from", "the", "collection", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/secret_service/secret_service.go#L232-L245
153,224
zalando/go-keyring
keyring_linux.go
findItem
func (s secretServiceProvider) findItem(svc *ss.SecretService, service, user string) (dbus.ObjectPath, error) { collection := svc.GetLoginCollection() search := map[string]string{ "username": user, "service": service, } err := svc.Unlock(collection.Path()) if err != nil { return "", err } results, err := svc.SearchItems(collection, search) if err != nil { return "", err } if len(results) == 0 { return "", ErrNotFound } return results[0], nil }
go
func (s secretServiceProvider) findItem(svc *ss.SecretService, service, user string) (dbus.ObjectPath, error) { collection := svc.GetLoginCollection() search := map[string]string{ "username": user, "service": service, } err := svc.Unlock(collection.Path()) if err != nil { return "", err } results, err := svc.SearchItems(collection, search) if err != nil { return "", err } if len(results) == 0 { return "", ErrNotFound } return results[0], nil }
[ "func", "(", "s", "secretServiceProvider", ")", "findItem", "(", "svc", "*", "ss", ".", "SecretService", ",", "service", ",", "user", "string", ")", "(", "dbus", ".", "ObjectPath", ",", "error", ")", "{", "collection", ":=", "svc", ".", "GetLoginCollection", "(", ")", "\n\n", "search", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "user", ",", "\"", "\"", ":", "service", ",", "}", "\n\n", "err", ":=", "svc", ".", "Unlock", "(", "collection", ".", "Path", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "results", ",", "err", ":=", "svc", ".", "SearchItems", "(", "collection", ",", "search", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "results", ")", "==", "0", "{", "return", "\"", "\"", ",", "ErrNotFound", "\n", "}", "\n\n", "return", "results", "[", "0", "]", ",", "nil", "\n", "}" ]
// findItem looksup an item by service and user.
[ "findItem", "looksup", "an", "item", "by", "service", "and", "user", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring_linux.go#L51-L74
153,225
zalando/go-keyring
keyring_darwin.go
Set
func (k macOSXKeychain) Set(service, username, password string) error { return exec.Command( execPathKeychain, "add-generic-password", "-U", //update if exists "-s", service, "-a", username, "-w", password).Run() }
go
func (k macOSXKeychain) Set(service, username, password string) error { return exec.Command( execPathKeychain, "add-generic-password", "-U", //update if exists "-s", service, "-a", username, "-w", password).Run() }
[ "func", "(", "k", "macOSXKeychain", ")", "Set", "(", "service", ",", "username", ",", "password", "string", ")", "error", "{", "return", "exec", ".", "Command", "(", "execPathKeychain", ",", "\"", "\"", ",", "\"", "\"", ",", "//update if exists", "\"", "\"", ",", "service", ",", "\"", "\"", ",", "username", ",", "\"", "\"", ",", "password", ")", ".", "Run", "(", ")", "\n", "}" ]
// Set stores a secret in the keyring given a service name and a user.
[ "Set", "stores", "a", "secret", "in", "the", "keyring", "given", "a", "service", "name", "and", "a", "user", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring_darwin.go#L59-L67
153,226
zalando/go-keyring
keyring.go
Set
func Set(service, user, password string) error { return provider.Set(service, user, password) }
go
func Set(service, user, password string) error { return provider.Set(service, user, password) }
[ "func", "Set", "(", "service", ",", "user", ",", "password", "string", ")", "error", "{", "return", "provider", ".", "Set", "(", "service", ",", "user", ",", "password", ")", "\n", "}" ]
// Set password in keyring for user.
[ "Set", "password", "in", "keyring", "for", "user", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring.go#L26-L28
153,227
zalando/go-keyring
keyring.go
Get
func Get(service, user string) (string, error) { return provider.Get(service, user) }
go
func Get(service, user string) (string, error) { return provider.Get(service, user) }
[ "func", "Get", "(", "service", ",", "user", "string", ")", "(", "string", ",", "error", ")", "{", "return", "provider", ".", "Get", "(", "service", ",", "user", ")", "\n", "}" ]
// Get password from keyring given service and user name.
[ "Get", "password", "from", "keyring", "given", "service", "and", "user", "name", "." ]
a1018b80916574299c108cae7fd6c87f481b5265
https://github.com/zalando/go-keyring/blob/a1018b80916574299c108cae7fd6c87f481b5265/keyring.go#L31-L33
153,228
tdewolff/minify
json/json.go
Minify
func (o *Minifier) Minify(_ *minify.M, w io.Writer, r io.Reader, _ map[string]string) error { skipComma := true p := json.NewParser(r) defer p.Restore() for { state := p.State() gt, text := p.Next() if gt == json.ErrorGrammar { if p.Err() != io.EOF { return p.Err() } return nil } if !skipComma && gt != json.EndObjectGrammar && gt != json.EndArrayGrammar { if state == json.ObjectKeyState || state == json.ArrayState { if _, err := w.Write(commaBytes); err != nil { return err } } else if state == json.ObjectValueState { if _, err := w.Write(colonBytes); err != nil { return err } } } skipComma = gt == json.StartObjectGrammar || gt == json.StartArrayGrammar if _, err := w.Write(text); err != nil { return err } } }
go
func (o *Minifier) Minify(_ *minify.M, w io.Writer, r io.Reader, _ map[string]string) error { skipComma := true p := json.NewParser(r) defer p.Restore() for { state := p.State() gt, text := p.Next() if gt == json.ErrorGrammar { if p.Err() != io.EOF { return p.Err() } return nil } if !skipComma && gt != json.EndObjectGrammar && gt != json.EndArrayGrammar { if state == json.ObjectKeyState || state == json.ArrayState { if _, err := w.Write(commaBytes); err != nil { return err } } else if state == json.ObjectValueState { if _, err := w.Write(colonBytes); err != nil { return err } } } skipComma = gt == json.StartObjectGrammar || gt == json.StartArrayGrammar if _, err := w.Write(text); err != nil { return err } } }
[ "func", "(", "o", "*", "Minifier", ")", "Minify", "(", "_", "*", "minify", ".", "M", ",", "w", "io", ".", "Writer", ",", "r", "io", ".", "Reader", ",", "_", "map", "[", "string", "]", "string", ")", "error", "{", "skipComma", ":=", "true", "\n\n", "p", ":=", "json", ".", "NewParser", "(", "r", ")", "\n", "defer", "p", ".", "Restore", "(", ")", "\n\n", "for", "{", "state", ":=", "p", ".", "State", "(", ")", "\n", "gt", ",", "text", ":=", "p", ".", "Next", "(", ")", "\n", "if", "gt", "==", "json", ".", "ErrorGrammar", "{", "if", "p", ".", "Err", "(", ")", "!=", "io", ".", "EOF", "{", "return", "p", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "if", "!", "skipComma", "&&", "gt", "!=", "json", ".", "EndObjectGrammar", "&&", "gt", "!=", "json", ".", "EndArrayGrammar", "{", "if", "state", "==", "json", ".", "ObjectKeyState", "||", "state", "==", "json", ".", "ArrayState", "{", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "commaBytes", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "if", "state", "==", "json", ".", "ObjectValueState", "{", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "colonBytes", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "skipComma", "=", "gt", "==", "json", ".", "StartObjectGrammar", "||", "gt", "==", "json", ".", "StartArrayGrammar", "\n\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "text", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// Minify minifies JSON data, it reads from r and writes to w.
[ "Minify", "minifies", "JSON", "data", "it", "reads", "from", "r", "and", "writes", "to", "w", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/json/json.go#L30-L63
153,229
tdewolff/minify
minify.go
Match
func (m *M) Match(mediatype string) (string, map[string]string, MinifierFunc) { m.mutex.RLock() defer m.mutex.RUnlock() mimetype, params := parse.Mediatype([]byte(mediatype)) if minifier, ok := m.literal[string(mimetype)]; ok { // string conversion is optimized away return string(mimetype), params, minifier.Minify } for _, minifier := range m.pattern { if minifier.pattern.Match(mimetype) { return minifier.pattern.String(), params, minifier.Minify } } return string(mimetype), params, nil }
go
func (m *M) Match(mediatype string) (string, map[string]string, MinifierFunc) { m.mutex.RLock() defer m.mutex.RUnlock() mimetype, params := parse.Mediatype([]byte(mediatype)) if minifier, ok := m.literal[string(mimetype)]; ok { // string conversion is optimized away return string(mimetype), params, minifier.Minify } for _, minifier := range m.pattern { if minifier.pattern.Match(mimetype) { return minifier.pattern.String(), params, minifier.Minify } } return string(mimetype), params, nil }
[ "func", "(", "m", "*", "M", ")", "Match", "(", "mediatype", "string", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "MinifierFunc", ")", "{", "m", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "mimetype", ",", "params", ":=", "parse", ".", "Mediatype", "(", "[", "]", "byte", "(", "mediatype", ")", ")", "\n", "if", "minifier", ",", "ok", ":=", "m", ".", "literal", "[", "string", "(", "mimetype", ")", "]", ";", "ok", "{", "// string conversion is optimized away", "return", "string", "(", "mimetype", ")", ",", "params", ",", "minifier", ".", "Minify", "\n", "}", "\n\n", "for", "_", ",", "minifier", ":=", "range", "m", ".", "pattern", "{", "if", "minifier", ".", "pattern", ".", "Match", "(", "mimetype", ")", "{", "return", "minifier", ".", "pattern", ".", "String", "(", ")", ",", "params", ",", "minifier", ".", "Minify", "\n", "}", "\n", "}", "\n", "return", "string", "(", "mimetype", ")", ",", "params", ",", "nil", "\n", "}" ]
// Match returns the pattern and minifier that gets matched with the mediatype. // It returns nil when no matching minifier exists. // It has the same matching algorithm as Minify.
[ "Match", "returns", "the", "pattern", "and", "minifier", "that", "gets", "matched", "with", "the", "mediatype", ".", "It", "returns", "nil", "when", "no", "matching", "minifier", "exists", ".", "It", "has", "the", "same", "matching", "algorithm", "as", "Minify", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L125-L140
153,230
tdewolff/minify
minify.go
Reader
func (m *M) Reader(mediatype string, r io.Reader) io.Reader { pr, pw := io.Pipe() go func() { if err := m.Minify(mediatype, pw, r); err != nil { pw.CloseWithError(err) } else { pw.Close() } }() return pr }
go
func (m *M) Reader(mediatype string, r io.Reader) io.Reader { pr, pw := io.Pipe() go func() { if err := m.Minify(mediatype, pw, r); err != nil { pw.CloseWithError(err) } else { pw.Close() } }() return pr }
[ "func", "(", "m", "*", "M", ")", "Reader", "(", "mediatype", "string", ",", "r", "io", ".", "Reader", ")", "io", ".", "Reader", "{", "pr", ",", "pw", ":=", "io", ".", "Pipe", "(", ")", "\n", "go", "func", "(", ")", "{", "if", "err", ":=", "m", ".", "Minify", "(", "mediatype", ",", "pw", ",", "r", ")", ";", "err", "!=", "nil", "{", "pw", ".", "CloseWithError", "(", "err", ")", "\n", "}", "else", "{", "pw", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "pr", "\n", "}" ]
// Reader wraps a Reader interface and minifies the stream. // Errors from the minifier are returned by the reader.
[ "Reader", "wraps", "a", "Reader", "interface", "and", "minifies", "the", "stream", ".", "Errors", "from", "the", "minifier", "are", "returned", "by", "the", "reader", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L193-L203
153,231
tdewolff/minify
minify.go
Write
func (w *minifyWriter) Write(b []byte) (int, error) { return w.pw.Write(b) }
go
func (w *minifyWriter) Write(b []byte) (int, error) { return w.pw.Write(b) }
[ "func", "(", "w", "*", "minifyWriter", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "w", ".", "pw", ".", "Write", "(", "b", ")", "\n", "}" ]
// Write intercepts any writes to the writer.
[ "Write", "intercepts", "any", "writes", "to", "the", "writer", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L213-L215
153,232
tdewolff/minify
minify.go
Writer
func (m *M) Writer(mediatype string, w io.Writer) *minifyWriter { pr, pw := io.Pipe() mw := &minifyWriter{pw, sync.WaitGroup{}, nil} mw.wg.Add(1) go func() { defer mw.wg.Done() if err := m.Minify(mediatype, w, pr); err != nil { io.Copy(w, pr) mw.err = err } pr.Close() }() return mw }
go
func (m *M) Writer(mediatype string, w io.Writer) *minifyWriter { pr, pw := io.Pipe() mw := &minifyWriter{pw, sync.WaitGroup{}, nil} mw.wg.Add(1) go func() { defer mw.wg.Done() if err := m.Minify(mediatype, w, pr); err != nil { io.Copy(w, pr) mw.err = err } pr.Close() }() return mw }
[ "func", "(", "m", "*", "M", ")", "Writer", "(", "mediatype", "string", ",", "w", "io", ".", "Writer", ")", "*", "minifyWriter", "{", "pr", ",", "pw", ":=", "io", ".", "Pipe", "(", ")", "\n", "mw", ":=", "&", "minifyWriter", "{", "pw", ",", "sync", ".", "WaitGroup", "{", "}", ",", "nil", "}", "\n", "mw", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "mw", ".", "wg", ".", "Done", "(", ")", "\n\n", "if", "err", ":=", "m", ".", "Minify", "(", "mediatype", ",", "w", ",", "pr", ")", ";", "err", "!=", "nil", "{", "io", ".", "Copy", "(", "w", ",", "pr", ")", "\n", "mw", ".", "err", "=", "err", "\n", "}", "\n", "pr", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "return", "mw", "\n", "}" ]
// Writer wraps a Writer interface and minifies the stream. // Errors from the minifier are returned by Close on the writer. // The writer must be closed explicitly.
[ "Writer", "wraps", "a", "Writer", "interface", "and", "minifies", "the", "stream", ".", "Errors", "from", "the", "minifier", "are", "returned", "by", "Close", "on", "the", "writer", ".", "The", "writer", "must", "be", "closed", "explicitly", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L227-L241
153,233
tdewolff/minify
minify.go
WriteHeader
func (w *minifyResponseWriter) WriteHeader(status int) { w.ResponseWriter.Header().Del("Content-Length") w.ResponseWriter.WriteHeader(status) }
go
func (w *minifyResponseWriter) WriteHeader(status int) { w.ResponseWriter.Header().Del("Content-Length") w.ResponseWriter.WriteHeader(status) }
[ "func", "(", "w", "*", "minifyResponseWriter", ")", "WriteHeader", "(", "status", "int", ")", "{", "w", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Del", "(", "\"", "\"", ")", "\n", "w", ".", "ResponseWriter", ".", "WriteHeader", "(", "status", ")", "\n", "}" ]
// WriteHeader intercepts any header writes and removes the Content-Length header.
[ "WriteHeader", "intercepts", "any", "header", "writes", "and", "removes", "the", "Content", "-", "Length", "header", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L255-L258
153,234
tdewolff/minify
minify.go
Write
func (w *minifyResponseWriter) Write(b []byte) (int, error) { if w.writer == nil { // first write if mediatype := w.ResponseWriter.Header().Get("Content-Type"); mediatype != "" { w.mediatype = mediatype } w.writer = w.m.Writer(w.mediatype, w.ResponseWriter) } return w.writer.Write(b) }
go
func (w *minifyResponseWriter) Write(b []byte) (int, error) { if w.writer == nil { // first write if mediatype := w.ResponseWriter.Header().Get("Content-Type"); mediatype != "" { w.mediatype = mediatype } w.writer = w.m.Writer(w.mediatype, w.ResponseWriter) } return w.writer.Write(b) }
[ "func", "(", "w", "*", "minifyResponseWriter", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "w", ".", "writer", "==", "nil", "{", "// first write", "if", "mediatype", ":=", "w", ".", "ResponseWriter", ".", "Header", "(", ")", ".", "Get", "(", "\"", "\"", ")", ";", "mediatype", "!=", "\"", "\"", "{", "w", ".", "mediatype", "=", "mediatype", "\n", "}", "\n", "w", ".", "writer", "=", "w", ".", "m", ".", "Writer", "(", "w", ".", "mediatype", ",", "w", ".", "ResponseWriter", ")", "\n", "}", "\n", "return", "w", ".", "writer", ".", "Write", "(", "b", ")", "\n", "}" ]
// Write intercepts any writes to the response writer. // The first write will extract the Content-Type as the mediatype. Otherwise it falls back to the RequestURI extension.
[ "Write", "intercepts", "any", "writes", "to", "the", "response", "writer", ".", "The", "first", "write", "will", "extract", "the", "Content", "-", "Type", "as", "the", "mediatype", ".", "Otherwise", "it", "falls", "back", "to", "the", "RequestURI", "extension", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L262-L271
153,235
tdewolff/minify
minify.go
ResponseWriter
func (m *M) ResponseWriter(w http.ResponseWriter, r *http.Request) *minifyResponseWriter { mediatype := mime.TypeByExtension(path.Ext(r.RequestURI)) return &minifyResponseWriter{w, nil, m, mediatype} }
go
func (m *M) ResponseWriter(w http.ResponseWriter, r *http.Request) *minifyResponseWriter { mediatype := mime.TypeByExtension(path.Ext(r.RequestURI)) return &minifyResponseWriter{w, nil, m, mediatype} }
[ "func", "(", "m", "*", "M", ")", "ResponseWriter", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "*", "minifyResponseWriter", "{", "mediatype", ":=", "mime", ".", "TypeByExtension", "(", "path", ".", "Ext", "(", "r", ".", "RequestURI", ")", ")", "\n", "return", "&", "minifyResponseWriter", "{", "w", ",", "nil", ",", "m", ",", "mediatype", "}", "\n", "}" ]
// ResponseWriter minifies any writes to the http.ResponseWriter. // http.ResponseWriter loses all functionality such as Pusher, Hijacker, Flusher, ... // Minification might be slower than just sending the original file! Caching is advised.
[ "ResponseWriter", "minifies", "any", "writes", "to", "the", "http", ".", "ResponseWriter", ".", "http", ".", "ResponseWriter", "loses", "all", "functionality", "such", "as", "Pusher", "Hijacker", "Flusher", "...", "Minification", "might", "be", "slower", "than", "just", "sending", "the", "original", "file!", "Caching", "is", "advised", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L284-L287
153,236
tdewolff/minify
minify.go
Middleware
func (m *M) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mw := m.ResponseWriter(w, r) defer mw.Close() next.ServeHTTP(mw, r) }) }
go
func (m *M) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mw := m.ResponseWriter(w, r) defer mw.Close() next.ServeHTTP(mw, r) }) }
[ "func", "(", "m", "*", "M", ")", "Middleware", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "mw", ":=", "m", ".", "ResponseWriter", "(", "w", ",", "r", ")", "\n", "defer", "mw", ".", "Close", "(", ")", "\n\n", "next", ".", "ServeHTTP", "(", "mw", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// Middleware provides a middleware function that minifies content on the fly by intercepting writes to http.ResponseWriter. // http.ResponseWriter loses all functionality such as Pusher, Hijacker, Flusher, ... // Minification might be slower than just sending the original file! Caching is advised.
[ "Middleware", "provides", "a", "middleware", "function", "that", "minifies", "content", "on", "the", "fly", "by", "intercepting", "writes", "to", "http", ".", "ResponseWriter", ".", "http", ".", "ResponseWriter", "loses", "all", "functionality", "such", "as", "Pusher", "Hijacker", "Flusher", "...", "Minification", "might", "be", "slower", "than", "just", "sending", "the", "original", "file!", "Caching", "is", "advised", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/minify.go#L292-L299
153,237
tdewolff/minify
xml/buffer.go
Peek
func (z *TokenBuffer) Peek(pos int) *Token { pos += z.pos if pos >= len(z.buf) { if len(z.buf) > 0 && z.buf[len(z.buf)-1].TokenType == xml.ErrorToken { return &z.buf[len(z.buf)-1] } c := cap(z.buf) d := len(z.buf) - z.pos p := pos - z.pos + 1 // required peek length var buf []Token if 2*p > c { buf = make([]Token, 0, 2*c+p) } else { buf = z.buf } copy(buf[:d], z.buf[z.pos:]) buf = buf[:p] pos -= z.pos for i := d; i < p; i++ { z.read(&buf[i]) if buf[i].TokenType == xml.ErrorToken { buf = buf[:i+1] pos = i break } } z.pos, z.buf = 0, buf } return &z.buf[pos] }
go
func (z *TokenBuffer) Peek(pos int) *Token { pos += z.pos if pos >= len(z.buf) { if len(z.buf) > 0 && z.buf[len(z.buf)-1].TokenType == xml.ErrorToken { return &z.buf[len(z.buf)-1] } c := cap(z.buf) d := len(z.buf) - z.pos p := pos - z.pos + 1 // required peek length var buf []Token if 2*p > c { buf = make([]Token, 0, 2*c+p) } else { buf = z.buf } copy(buf[:d], z.buf[z.pos:]) buf = buf[:p] pos -= z.pos for i := d; i < p; i++ { z.read(&buf[i]) if buf[i].TokenType == xml.ErrorToken { buf = buf[:i+1] pos = i break } } z.pos, z.buf = 0, buf } return &z.buf[pos] }
[ "func", "(", "z", "*", "TokenBuffer", ")", "Peek", "(", "pos", "int", ")", "*", "Token", "{", "pos", "+=", "z", ".", "pos", "\n", "if", "pos", ">=", "len", "(", "z", ".", "buf", ")", "{", "if", "len", "(", "z", ".", "buf", ")", ">", "0", "&&", "z", ".", "buf", "[", "len", "(", "z", ".", "buf", ")", "-", "1", "]", ".", "TokenType", "==", "xml", ".", "ErrorToken", "{", "return", "&", "z", ".", "buf", "[", "len", "(", "z", ".", "buf", ")", "-", "1", "]", "\n", "}", "\n\n", "c", ":=", "cap", "(", "z", ".", "buf", ")", "\n", "d", ":=", "len", "(", "z", ".", "buf", ")", "-", "z", ".", "pos", "\n", "p", ":=", "pos", "-", "z", ".", "pos", "+", "1", "// required peek length", "\n", "var", "buf", "[", "]", "Token", "\n", "if", "2", "*", "p", ">", "c", "{", "buf", "=", "make", "(", "[", "]", "Token", ",", "0", ",", "2", "*", "c", "+", "p", ")", "\n", "}", "else", "{", "buf", "=", "z", ".", "buf", "\n", "}", "\n", "copy", "(", "buf", "[", ":", "d", "]", ",", "z", ".", "buf", "[", "z", ".", "pos", ":", "]", ")", "\n\n", "buf", "=", "buf", "[", ":", "p", "]", "\n", "pos", "-=", "z", ".", "pos", "\n", "for", "i", ":=", "d", ";", "i", "<", "p", ";", "i", "++", "{", "z", ".", "read", "(", "&", "buf", "[", "i", "]", ")", "\n", "if", "buf", "[", "i", "]", ".", "TokenType", "==", "xml", ".", "ErrorToken", "{", "buf", "=", "buf", "[", ":", "i", "+", "1", "]", "\n", "pos", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "z", ".", "pos", ",", "z", ".", "buf", "=", "0", ",", "buf", "\n", "}", "\n", "return", "&", "z", ".", "buf", "[", "pos", "]", "\n", "}" ]
// Peek returns the ith element and possibly does an allocation. // Peeking past an error will panic.
[ "Peek", "returns", "the", "ith", "element", "and", "possibly", "does", "an", "allocation", ".", "Peeking", "past", "an", "error", "will", "panic", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/xml/buffer.go#L41-L72
153,238
tdewolff/minify
xml/buffer.go
Shift
func (z *TokenBuffer) Shift() *Token { if z.pos >= len(z.buf) { t := &z.buf[:1][0] z.read(t) return t } t := &z.buf[z.pos] z.pos++ return t }
go
func (z *TokenBuffer) Shift() *Token { if z.pos >= len(z.buf) { t := &z.buf[:1][0] z.read(t) return t } t := &z.buf[z.pos] z.pos++ return t }
[ "func", "(", "z", "*", "TokenBuffer", ")", "Shift", "(", ")", "*", "Token", "{", "if", "z", ".", "pos", ">=", "len", "(", "z", ".", "buf", ")", "{", "t", ":=", "&", "z", ".", "buf", "[", ":", "1", "]", "[", "0", "]", "\n", "z", ".", "read", "(", "t", ")", "\n", "return", "t", "\n", "}", "\n", "t", ":=", "&", "z", ".", "buf", "[", "z", ".", "pos", "]", "\n", "z", ".", "pos", "++", "\n", "return", "t", "\n", "}" ]
// Shift returns the first element and advances position.
[ "Shift", "returns", "the", "first", "element", "and", "advances", "position", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/xml/buffer.go#L75-L84
153,239
tdewolff/minify
common.go
Mediatype
func Mediatype(b []byte) []byte { j := 0 start := 0 inString := false for i, c := range b { if !inString && parse.IsWhitespace(c) { if start != 0 { j += copy(b[j:], b[start:i]) } else { j += i } start = i + 1 } else if c == '"' { inString = !inString } } if start != 0 { j += copy(b[j:], b[start:]) return parse.ToLower(b[:j]) } return parse.ToLower(b) }
go
func Mediatype(b []byte) []byte { j := 0 start := 0 inString := false for i, c := range b { if !inString && parse.IsWhitespace(c) { if start != 0 { j += copy(b[j:], b[start:i]) } else { j += i } start = i + 1 } else if c == '"' { inString = !inString } } if start != 0 { j += copy(b[j:], b[start:]) return parse.ToLower(b[:j]) } return parse.ToLower(b) }
[ "func", "Mediatype", "(", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "j", ":=", "0", "\n", "start", ":=", "0", "\n", "inString", ":=", "false", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "if", "!", "inString", "&&", "parse", ".", "IsWhitespace", "(", "c", ")", "{", "if", "start", "!=", "0", "{", "j", "+=", "copy", "(", "b", "[", "j", ":", "]", ",", "b", "[", "start", ":", "i", "]", ")", "\n", "}", "else", "{", "j", "+=", "i", "\n", "}", "\n", "start", "=", "i", "+", "1", "\n", "}", "else", "if", "c", "==", "'\"'", "{", "inString", "=", "!", "inString", "\n", "}", "\n", "}", "\n", "if", "start", "!=", "0", "{", "j", "+=", "copy", "(", "b", "[", "j", ":", "]", ",", "b", "[", "start", ":", "]", ")", "\n", "return", "parse", ".", "ToLower", "(", "b", "[", ":", "j", "]", ")", "\n", "}", "\n", "return", "parse", ".", "ToLower", "(", "b", ")", "\n", "}" ]
// Mediatype minifies a given mediatype by removing all whitespace.
[ "Mediatype", "minifies", "a", "given", "mediatype", "by", "removing", "all", "whitespace", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/common.go#L16-L37
153,240
tdewolff/minify
svg/buffer.go
Attributes
func (z *TokenBuffer) Attributes(hashes ...svg.Hash) ([]*Token, *Token) { n := 0 for { if t := z.Peek(n); t.TokenType != xml.AttributeToken { break } n++ } if len(hashes) > cap(z.attrBuffer) { z.attrBuffer = make([]*Token, len(hashes)) } else { z.attrBuffer = z.attrBuffer[:len(hashes)] for i := range z.attrBuffer { z.attrBuffer[i] = nil } } var replacee *Token for i := z.pos; i < z.pos+n; i++ { attr := &z.buf[i] for j, hash := range hashes { if hash == attr.Hash { z.attrBuffer[j] = attr replacee = attr } } } return z.attrBuffer, replacee }
go
func (z *TokenBuffer) Attributes(hashes ...svg.Hash) ([]*Token, *Token) { n := 0 for { if t := z.Peek(n); t.TokenType != xml.AttributeToken { break } n++ } if len(hashes) > cap(z.attrBuffer) { z.attrBuffer = make([]*Token, len(hashes)) } else { z.attrBuffer = z.attrBuffer[:len(hashes)] for i := range z.attrBuffer { z.attrBuffer[i] = nil } } var replacee *Token for i := z.pos; i < z.pos+n; i++ { attr := &z.buf[i] for j, hash := range hashes { if hash == attr.Hash { z.attrBuffer[j] = attr replacee = attr } } } return z.attrBuffer, replacee }
[ "func", "(", "z", "*", "TokenBuffer", ")", "Attributes", "(", "hashes", "...", "svg", ".", "Hash", ")", "(", "[", "]", "*", "Token", ",", "*", "Token", ")", "{", "n", ":=", "0", "\n", "for", "{", "if", "t", ":=", "z", ".", "Peek", "(", "n", ")", ";", "t", ".", "TokenType", "!=", "xml", ".", "AttributeToken", "{", "break", "\n", "}", "\n", "n", "++", "\n", "}", "\n", "if", "len", "(", "hashes", ")", ">", "cap", "(", "z", ".", "attrBuffer", ")", "{", "z", ".", "attrBuffer", "=", "make", "(", "[", "]", "*", "Token", ",", "len", "(", "hashes", ")", ")", "\n", "}", "else", "{", "z", ".", "attrBuffer", "=", "z", ".", "attrBuffer", "[", ":", "len", "(", "hashes", ")", "]", "\n", "for", "i", ":=", "range", "z", ".", "attrBuffer", "{", "z", ".", "attrBuffer", "[", "i", "]", "=", "nil", "\n", "}", "\n", "}", "\n", "var", "replacee", "*", "Token", "\n", "for", "i", ":=", "z", ".", "pos", ";", "i", "<", "z", ".", "pos", "+", "n", ";", "i", "++", "{", "attr", ":=", "&", "z", ".", "buf", "[", "i", "]", "\n", "for", "j", ",", "hash", ":=", "range", "hashes", "{", "if", "hash", "==", "attr", ".", "Hash", "{", "z", ".", "attrBuffer", "[", "j", "]", "=", "attr", "\n", "replacee", "=", "attr", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "z", ".", "attrBuffer", ",", "replacee", "\n", "}" ]
// Attributes extracts the gives attribute hashes from a tag. // It returns in the same order pointers to the requested token data or nil.
[ "Attributes", "extracts", "the", "gives", "attribute", "hashes", "from", "a", "tag", ".", "It", "returns", "in", "the", "same", "order", "pointers", "to", "the", "requested", "token", "data", "or", "nil", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/svg/buffer.go#L103-L130
153,241
tdewolff/minify
svg/pathdata.go
shortenCurPosInstruction
func (p *PathData) shortenCurPosInstruction(cmd byte, coords [][]byte) PathDataState { state := p.state p.curBuffer = p.curBuffer[:0] if cmd != state.cmd && !(state.cmd == 'M' && cmd == 'L' || state.cmd == 'm' && cmd == 'l') { p.curBuffer = append(p.curBuffer, cmd) state.cmd = cmd state.prevDigit = false state.prevDigitIsInt = false } for i, coord := range coords { isFlag := false // Arc has boolean flags that can only be 0 or 1. Setting isFlag prevents from adding a dot before a zero (instead of a space). However, when the dot already was there, the command is malformed and could make the path longer than before, introducing bugs. if (cmd == 'A' || cmd == 'a') && (i%7 == 3 || i%7 == 4) && coord[0] != '.' { isFlag = true } coord = minify.Number(coord, p.o.Decimals) state.copyNumber(&p.curBuffer, coord, isFlag) } return state }
go
func (p *PathData) shortenCurPosInstruction(cmd byte, coords [][]byte) PathDataState { state := p.state p.curBuffer = p.curBuffer[:0] if cmd != state.cmd && !(state.cmd == 'M' && cmd == 'L' || state.cmd == 'm' && cmd == 'l') { p.curBuffer = append(p.curBuffer, cmd) state.cmd = cmd state.prevDigit = false state.prevDigitIsInt = false } for i, coord := range coords { isFlag := false // Arc has boolean flags that can only be 0 or 1. Setting isFlag prevents from adding a dot before a zero (instead of a space). However, when the dot already was there, the command is malformed and could make the path longer than before, introducing bugs. if (cmd == 'A' || cmd == 'a') && (i%7 == 3 || i%7 == 4) && coord[0] != '.' { isFlag = true } coord = minify.Number(coord, p.o.Decimals) state.copyNumber(&p.curBuffer, coord, isFlag) } return state }
[ "func", "(", "p", "*", "PathData", ")", "shortenCurPosInstruction", "(", "cmd", "byte", ",", "coords", "[", "]", "[", "]", "byte", ")", "PathDataState", "{", "state", ":=", "p", ".", "state", "\n", "p", ".", "curBuffer", "=", "p", ".", "curBuffer", "[", ":", "0", "]", "\n", "if", "cmd", "!=", "state", ".", "cmd", "&&", "!", "(", "state", ".", "cmd", "==", "'M'", "&&", "cmd", "==", "'L'", "||", "state", ".", "cmd", "==", "'m'", "&&", "cmd", "==", "'l'", ")", "{", "p", ".", "curBuffer", "=", "append", "(", "p", ".", "curBuffer", ",", "cmd", ")", "\n", "state", ".", "cmd", "=", "cmd", "\n", "state", ".", "prevDigit", "=", "false", "\n", "state", ".", "prevDigitIsInt", "=", "false", "\n", "}", "\n", "for", "i", ",", "coord", ":=", "range", "coords", "{", "isFlag", ":=", "false", "\n", "// Arc has boolean flags that can only be 0 or 1. Setting isFlag prevents from adding a dot before a zero (instead of a space). However, when the dot already was there, the command is malformed and could make the path longer than before, introducing bugs.", "if", "(", "cmd", "==", "'A'", "||", "cmd", "==", "'a'", ")", "&&", "(", "i", "%", "7", "==", "3", "||", "i", "%", "7", "==", "4", ")", "&&", "coord", "[", "0", "]", "!=", "'.'", "{", "isFlag", "=", "true", "\n", "}", "\n\n", "coord", "=", "minify", ".", "Number", "(", "coord", ",", "p", ".", "o", ".", "Decimals", ")", "\n", "state", ".", "copyNumber", "(", "&", "p", ".", "curBuffer", ",", "coord", ",", "isFlag", ")", "\n", "}", "\n", "return", "state", "\n", "}" ]
// shortenCurPosInstruction only minifies the coordinates.
[ "shortenCurPosInstruction", "only", "minifies", "the", "coordinates", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/svg/pathdata.go#L297-L317
153,242
tdewolff/minify
svg/pathdata.go
copyNumber
func (state *PathDataState) copyNumber(buffer *[]byte, coord []byte, isFlag bool) { if state.prevDigit && (coord[0] >= '0' && coord[0] <= '9' || coord[0] == '.' && state.prevDigitIsInt) { if coord[0] == '0' && !state.prevDigitIsInt { if isFlag { *buffer = append(*buffer, ' ', '0') state.prevDigitIsInt = true } else { *buffer = append(*buffer, '.', '0') // aggresively add dot so subsequent numbers could drop leading space // prevDigit stays true and prevDigitIsInt stays false } return } *buffer = append(*buffer, ' ') } state.prevDigit = true state.prevDigitIsInt = true if len(coord) > 2 && coord[len(coord)-2] == '0' && coord[len(coord)-1] == '0' { coord[len(coord)-2] = 'e' coord[len(coord)-1] = '2' state.prevDigitIsInt = false } else { for _, c := range coord { if c == '.' || c == 'e' || c == 'E' { state.prevDigitIsInt = false break } } } *buffer = append(*buffer, coord...) }
go
func (state *PathDataState) copyNumber(buffer *[]byte, coord []byte, isFlag bool) { if state.prevDigit && (coord[0] >= '0' && coord[0] <= '9' || coord[0] == '.' && state.prevDigitIsInt) { if coord[0] == '0' && !state.prevDigitIsInt { if isFlag { *buffer = append(*buffer, ' ', '0') state.prevDigitIsInt = true } else { *buffer = append(*buffer, '.', '0') // aggresively add dot so subsequent numbers could drop leading space // prevDigit stays true and prevDigitIsInt stays false } return } *buffer = append(*buffer, ' ') } state.prevDigit = true state.prevDigitIsInt = true if len(coord) > 2 && coord[len(coord)-2] == '0' && coord[len(coord)-1] == '0' { coord[len(coord)-2] = 'e' coord[len(coord)-1] = '2' state.prevDigitIsInt = false } else { for _, c := range coord { if c == '.' || c == 'e' || c == 'E' { state.prevDigitIsInt = false break } } } *buffer = append(*buffer, coord...) }
[ "func", "(", "state", "*", "PathDataState", ")", "copyNumber", "(", "buffer", "*", "[", "]", "byte", ",", "coord", "[", "]", "byte", ",", "isFlag", "bool", ")", "{", "if", "state", ".", "prevDigit", "&&", "(", "coord", "[", "0", "]", ">=", "'0'", "&&", "coord", "[", "0", "]", "<=", "'9'", "||", "coord", "[", "0", "]", "==", "'.'", "&&", "state", ".", "prevDigitIsInt", ")", "{", "if", "coord", "[", "0", "]", "==", "'0'", "&&", "!", "state", ".", "prevDigitIsInt", "{", "if", "isFlag", "{", "*", "buffer", "=", "append", "(", "*", "buffer", ",", "' '", ",", "'0'", ")", "\n", "state", ".", "prevDigitIsInt", "=", "true", "\n", "}", "else", "{", "*", "buffer", "=", "append", "(", "*", "buffer", ",", "'.'", ",", "'0'", ")", "// aggresively add dot so subsequent numbers could drop leading space", "\n", "// prevDigit stays true and prevDigitIsInt stays false", "}", "\n", "return", "\n", "}", "\n", "*", "buffer", "=", "append", "(", "*", "buffer", ",", "' '", ")", "\n", "}", "\n", "state", ".", "prevDigit", "=", "true", "\n", "state", ".", "prevDigitIsInt", "=", "true", "\n", "if", "len", "(", "coord", ")", ">", "2", "&&", "coord", "[", "len", "(", "coord", ")", "-", "2", "]", "==", "'0'", "&&", "coord", "[", "len", "(", "coord", ")", "-", "1", "]", "==", "'0'", "{", "coord", "[", "len", "(", "coord", ")", "-", "2", "]", "=", "'e'", "\n", "coord", "[", "len", "(", "coord", ")", "-", "1", "]", "=", "'2'", "\n", "state", ".", "prevDigitIsInt", "=", "false", "\n", "}", "else", "{", "for", "_", ",", "c", ":=", "range", "coord", "{", "if", "c", "==", "'.'", "||", "c", "==", "'e'", "||", "c", "==", "'E'", "{", "state", ".", "prevDigitIsInt", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "*", "buffer", "=", "append", "(", "*", "buffer", ",", "coord", "...", ")", "\n", "}" ]
// copyNumber will copy a number to the destination buffer, taking into account space or dot insertion to guarantee the shortest pathdata.
[ "copyNumber", "will", "copy", "a", "number", "to", "the", "destination", "buffer", "taking", "into", "account", "space", "or", "dot", "insertion", "to", "guarantee", "the", "shortest", "pathdata", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/svg/pathdata.go#L359-L388
153,243
tdewolff/minify
cmd/minify/util.go
NewConcatFileReader
func NewConcatFileReader(filenames []string, opener func(string) (io.ReadCloser, error)) (*concatFileReader, error) { var cur io.ReadCloser if len(filenames) > 0 { var filename string filename, filenames = filenames[0], filenames[1:] var err error if cur, err = opener(filename); err != nil { return nil, err } } else { cur = eofReader{} } return &concatFileReader{filenames, opener, nil, cur, 0}, nil }
go
func NewConcatFileReader(filenames []string, opener func(string) (io.ReadCloser, error)) (*concatFileReader, error) { var cur io.ReadCloser if len(filenames) > 0 { var filename string filename, filenames = filenames[0], filenames[1:] var err error if cur, err = opener(filename); err != nil { return nil, err } } else { cur = eofReader{} } return &concatFileReader{filenames, opener, nil, cur, 0}, nil }
[ "func", "NewConcatFileReader", "(", "filenames", "[", "]", "string", ",", "opener", "func", "(", "string", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", ")", "(", "*", "concatFileReader", ",", "error", ")", "{", "var", "cur", "io", ".", "ReadCloser", "\n", "if", "len", "(", "filenames", ")", ">", "0", "{", "var", "filename", "string", "\n", "filename", ",", "filenames", "=", "filenames", "[", "0", "]", ",", "filenames", "[", "1", ":", "]", "\n\n", "var", "err", "error", "\n", "if", "cur", ",", "err", "=", "opener", "(", "filename", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "cur", "=", "eofReader", "{", "}", "\n", "}", "\n", "return", "&", "concatFileReader", "{", "filenames", ",", "opener", ",", "nil", ",", "cur", ",", "0", "}", ",", "nil", "\n", "}" ]
// NewConcatFileReader reads from a list of filenames, and lazily loads files as it needs it. // It is a reader that reads a concatenation of those files separated by the separator. // You must call Close to close the last file in the list.
[ "NewConcatFileReader", "reads", "from", "a", "list", "of", "filenames", "and", "lazily", "loads", "files", "as", "it", "needs", "it", ".", "It", "is", "a", "reader", "that", "reads", "a", "concatenation", "of", "those", "files", "separated", "by", "the", "separator", ".", "You", "must", "call", "Close", "to", "close", "the", "last", "file", "in", "the", "list", "." ]
2524af8f5589b64967cb0dd441af44b9b3bc02a8
https://github.com/tdewolff/minify/blob/2524af8f5589b64967cb0dd441af44b9b3bc02a8/cmd/minify/util.go#L59-L73
153,244
heetch/confita
backend/etcd/etcd.go
NewBackend
func NewBackend(client *clientv3.Client, opts ...Option) *Backend { b := Backend{ client: client, } for _, opt := range opts { opt(&b) } return &b }
go
func NewBackend(client *clientv3.Client, opts ...Option) *Backend { b := Backend{ client: client, } for _, opt := range opts { opt(&b) } return &b }
[ "func", "NewBackend", "(", "client", "*", "clientv3", ".", "Client", ",", "opts", "...", "Option", ")", "*", "Backend", "{", "b", ":=", "Backend", "{", "client", ":", "client", ",", "}", "\n\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "&", "b", ")", "\n", "}", "\n\n", "return", "&", "b", "\n", "}" ]
// NewBackend creates a configuration loader that loads from etcd.
[ "NewBackend", "creates", "a", "configuration", "loader", "that", "loads", "from", "etcd", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/etcd/etcd.go#L21-L31
153,245
heetch/confita
backend/etcd/etcd.go
Get
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { if b.cache == nil && b.prefetch { err := b.fetchTree(ctx) if err != nil { return nil, err } } if b.cache != nil { return b.fromCache(ctx, key) } resp, err := b.client.Get(ctx, path.Join(b.prefix, key)) if err != nil { return nil, err } if len(resp.Kvs) == 0 { return nil, backend.ErrNotFound } return resp.Kvs[0].Value, nil }
go
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { if b.cache == nil && b.prefetch { err := b.fetchTree(ctx) if err != nil { return nil, err } } if b.cache != nil { return b.fromCache(ctx, key) } resp, err := b.client.Get(ctx, path.Join(b.prefix, key)) if err != nil { return nil, err } if len(resp.Kvs) == 0 { return nil, backend.ErrNotFound } return resp.Kvs[0].Value, nil }
[ "func", "(", "b", "*", "Backend", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "b", ".", "cache", "==", "nil", "&&", "b", ".", "prefetch", "{", "err", ":=", "b", ".", "fetchTree", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "b", ".", "cache", "!=", "nil", "{", "return", "b", ".", "fromCache", "(", "ctx", ",", "key", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "b", ".", "client", ".", "Get", "(", "ctx", ",", "path", ".", "Join", "(", "b", ".", "prefix", ",", "key", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "resp", ".", "Kvs", ")", "==", "0", "{", "return", "nil", ",", "backend", ".", "ErrNotFound", "\n", "}", "\n\n", "return", "resp", ".", "Kvs", "[", "0", "]", ".", "Value", ",", "nil", "\n", "}" ]
// Get loads the given key from etcd.
[ "Get", "loads", "the", "given", "key", "from", "etcd", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/etcd/etcd.go#L34-L56
153,246
heetch/confita
backend/backend.go
Func
func Func(name string, fn func(context.Context, string) ([]byte, error)) Backend { return &backendFunc{fn: fn, name: name} }
go
func Func(name string, fn func(context.Context, string) ([]byte, error)) Backend { return &backendFunc{fn: fn, name: name} }
[ "func", "Func", "(", "name", "string", ",", "fn", "func", "(", "context", ".", "Context", ",", "string", ")", "(", "[", "]", "byte", ",", "error", ")", ")", "Backend", "{", "return", "&", "backendFunc", "{", "fn", ":", "fn", ",", "name", ":", "name", "}", "\n", "}" ]
// Func creates a Backend from a function.
[ "Func", "creates", "a", "Backend", "from", "a", "function", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/backend.go#L20-L22
153,247
heetch/confita
backend/flags/flags.go
LoadStruct
func (b *Backend) LoadStruct(ctx context.Context, cfg *confita.StructConfig) error { for _, field := range cfg.Fields { f := field if f.Backend != "" && f.Backend != b.Name() { continue } // Display all the flags and their default values but override the field only if the user has explicitely // set the flag. k := f.Value.Kind() switch { case f.Value.Type().String() == "time.Duration": // define the flag and its default value v := flag.Duration(f.Key, time.Duration(f.Default.Int()), "") // this function must be executed after the flag.Parse call. defer func() { // if the user has set the flag, save the value in the field. if isFlagSet(f.Key) { f.Value.SetInt(int64(*v)) } }() case k == reflect.Bool: v := flag.Bool(f.Key, f.Default.Bool(), "") defer func() { if isFlagSet(f.Key) { f.Value.SetBool(*v) } }() case k >= reflect.Int && k <= reflect.Int64: v := flag.Int(f.Key, int(f.Default.Int()), "") defer func() { if isFlagSet(f.Key) { f.Value.SetInt(int64(*v)) } }() case k >= reflect.Uint && k <= reflect.Uint64: v := flag.Uint(f.Key, uint(f.Default.Uint()), "") defer func() { if isFlagSet(f.Key) { f.Value.SetUint(uint64(*v)) } }() case k >= reflect.Float32 && k <= reflect.Float64: v := flag.Float64(f.Key, f.Default.Float(), "") defer func() { if isFlagSet(f.Key) { f.Value.SetFloat(*v) } }() case k == reflect.String: v := flag.String(f.Key, f.Default.String(), "") defer func() { if isFlagSet(f.Key) { f.Value.SetString(*v) } }() default: flag.Var(&flagValue{f}, f.Key, "") } } flag.Parse() return nil }
go
func (b *Backend) LoadStruct(ctx context.Context, cfg *confita.StructConfig) error { for _, field := range cfg.Fields { f := field if f.Backend != "" && f.Backend != b.Name() { continue } // Display all the flags and their default values but override the field only if the user has explicitely // set the flag. k := f.Value.Kind() switch { case f.Value.Type().String() == "time.Duration": // define the flag and its default value v := flag.Duration(f.Key, time.Duration(f.Default.Int()), "") // this function must be executed after the flag.Parse call. defer func() { // if the user has set the flag, save the value in the field. if isFlagSet(f.Key) { f.Value.SetInt(int64(*v)) } }() case k == reflect.Bool: v := flag.Bool(f.Key, f.Default.Bool(), "") defer func() { if isFlagSet(f.Key) { f.Value.SetBool(*v) } }() case k >= reflect.Int && k <= reflect.Int64: v := flag.Int(f.Key, int(f.Default.Int()), "") defer func() { if isFlagSet(f.Key) { f.Value.SetInt(int64(*v)) } }() case k >= reflect.Uint && k <= reflect.Uint64: v := flag.Uint(f.Key, uint(f.Default.Uint()), "") defer func() { if isFlagSet(f.Key) { f.Value.SetUint(uint64(*v)) } }() case k >= reflect.Float32 && k <= reflect.Float64: v := flag.Float64(f.Key, f.Default.Float(), "") defer func() { if isFlagSet(f.Key) { f.Value.SetFloat(*v) } }() case k == reflect.String: v := flag.String(f.Key, f.Default.String(), "") defer func() { if isFlagSet(f.Key) { f.Value.SetString(*v) } }() default: flag.Var(&flagValue{f}, f.Key, "") } } flag.Parse() return nil }
[ "func", "(", "b", "*", "Backend", ")", "LoadStruct", "(", "ctx", "context", ".", "Context", ",", "cfg", "*", "confita", ".", "StructConfig", ")", "error", "{", "for", "_", ",", "field", ":=", "range", "cfg", ".", "Fields", "{", "f", ":=", "field", "\n\n", "if", "f", ".", "Backend", "!=", "\"", "\"", "&&", "f", ".", "Backend", "!=", "b", ".", "Name", "(", ")", "{", "continue", "\n", "}", "\n\n", "// Display all the flags and their default values but override the field only if the user has explicitely", "// set the flag.", "k", ":=", "f", ".", "Value", ".", "Kind", "(", ")", "\n", "switch", "{", "case", "f", ".", "Value", ".", "Type", "(", ")", ".", "String", "(", ")", "==", "\"", "\"", ":", "// define the flag and its default value", "v", ":=", "flag", ".", "Duration", "(", "f", ".", "Key", ",", "time", ".", "Duration", "(", "f", ".", "Default", ".", "Int", "(", ")", ")", ",", "\"", "\"", ")", "\n", "// this function must be executed after the flag.Parse call.", "defer", "func", "(", ")", "{", "// if the user has set the flag, save the value in the field.", "if", "isFlagSet", "(", "f", ".", "Key", ")", "{", "f", ".", "Value", ".", "SetInt", "(", "int64", "(", "*", "v", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "case", "k", "==", "reflect", ".", "Bool", ":", "v", ":=", "flag", ".", "Bool", "(", "f", ".", "Key", ",", "f", ".", "Default", ".", "Bool", "(", ")", ",", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "if", "isFlagSet", "(", "f", ".", "Key", ")", "{", "f", ".", "Value", ".", "SetBool", "(", "*", "v", ")", "\n", "}", "\n", "}", "(", ")", "\n", "case", "k", ">=", "reflect", ".", "Int", "&&", "k", "<=", "reflect", ".", "Int64", ":", "v", ":=", "flag", ".", "Int", "(", "f", ".", "Key", ",", "int", "(", "f", ".", "Default", ".", "Int", "(", ")", ")", ",", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "if", "isFlagSet", "(", "f", ".", "Key", ")", "{", "f", ".", "Value", ".", "SetInt", "(", "int64", "(", "*", "v", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "case", "k", ">=", "reflect", ".", "Uint", "&&", "k", "<=", "reflect", ".", "Uint64", ":", "v", ":=", "flag", ".", "Uint", "(", "f", ".", "Key", ",", "uint", "(", "f", ".", "Default", ".", "Uint", "(", ")", ")", ",", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "if", "isFlagSet", "(", "f", ".", "Key", ")", "{", "f", ".", "Value", ".", "SetUint", "(", "uint64", "(", "*", "v", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "case", "k", ">=", "reflect", ".", "Float32", "&&", "k", "<=", "reflect", ".", "Float64", ":", "v", ":=", "flag", ".", "Float64", "(", "f", ".", "Key", ",", "f", ".", "Default", ".", "Float", "(", ")", ",", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "if", "isFlagSet", "(", "f", ".", "Key", ")", "{", "f", ".", "Value", ".", "SetFloat", "(", "*", "v", ")", "\n", "}", "\n", "}", "(", ")", "\n", "case", "k", "==", "reflect", ".", "String", ":", "v", ":=", "flag", ".", "String", "(", "f", ".", "Key", ",", "f", ".", "Default", ".", "String", "(", ")", ",", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "if", "isFlagSet", "(", "f", ".", "Key", ")", "{", "f", ".", "Value", ".", "SetString", "(", "*", "v", ")", "\n", "}", "\n", "}", "(", ")", "\n", "default", ":", "flag", ".", "Var", "(", "&", "flagValue", "{", "f", "}", ",", "f", ".", "Key", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "flag", ".", "Parse", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// LoadStruct takes a struct config, define flags based on it and parse the command line args.
[ "LoadStruct", "takes", "a", "struct", "config", "define", "flags", "based", "on", "it", "and", "parse", "the", "command", "line", "args", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/flags/flags.go#L22-L87
153,248
heetch/confita
backend/flags/flags.go
Get
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { return nil, errors.New("not implemented") }
go
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { return nil, errors.New("not implemented") }
[ "func", "(", "b", "*", "Backend", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Get is not implemented.
[ "Get", "is", "not", "implemented", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/flags/flags.go#L106-L108
153,249
heetch/confita
backend/consul/consul.go
Get
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { if b.cache == nil && b.prefetch { err := b.fetchTree(ctx) if err != nil { return nil, err } } if b.cache != nil { return b.fromCache(ctx, key) } var opt api.QueryOptions kv, _, err := b.client.KV().Get(path.Join(b.prefix, key), opt.WithContext(ctx)) if err != nil { return nil, err } if kv == nil { return nil, backend.ErrNotFound } return kv.Value, nil }
go
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { if b.cache == nil && b.prefetch { err := b.fetchTree(ctx) if err != nil { return nil, err } } if b.cache != nil { return b.fromCache(ctx, key) } var opt api.QueryOptions kv, _, err := b.client.KV().Get(path.Join(b.prefix, key), opt.WithContext(ctx)) if err != nil { return nil, err } if kv == nil { return nil, backend.ErrNotFound } return kv.Value, nil }
[ "func", "(", "b", "*", "Backend", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "b", ".", "cache", "==", "nil", "&&", "b", ".", "prefetch", "{", "err", ":=", "b", ".", "fetchTree", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "b", ".", "cache", "!=", "nil", "{", "return", "b", ".", "fromCache", "(", "ctx", ",", "key", ")", "\n", "}", "\n\n", "var", "opt", "api", ".", "QueryOptions", "\n\n", "kv", ",", "_", ",", "err", ":=", "b", ".", "client", ".", "KV", "(", ")", ".", "Get", "(", "path", ".", "Join", "(", "b", ".", "prefix", ",", "key", ")", ",", "opt", ".", "WithContext", "(", "ctx", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "kv", "==", "nil", "{", "return", "nil", ",", "backend", ".", "ErrNotFound", "\n", "}", "\n\n", "return", "kv", ".", "Value", ",", "nil", "\n", "}" ]
// Get loads the given key from Consul.
[ "Get", "loads", "the", "given", "key", "from", "Consul", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/consul/consul.go#L34-L58
153,250
heetch/confita
backend/env/env.go
NewBackend
func NewBackend() backend.Backend { return backend.Func("env", func(ctx context.Context, key string) ([]byte, error) { val, ok := os.LookupEnv(key) if ok { return []byte(val), nil } key = strings.Replace(strings.ToUpper(key), "-", "_", -1) val, ok = os.LookupEnv(key) if ok { return []byte(val), nil } return nil, backend.ErrNotFound }) }
go
func NewBackend() backend.Backend { return backend.Func("env", func(ctx context.Context, key string) ([]byte, error) { val, ok := os.LookupEnv(key) if ok { return []byte(val), nil } key = strings.Replace(strings.ToUpper(key), "-", "_", -1) val, ok = os.LookupEnv(key) if ok { return []byte(val), nil } return nil, backend.ErrNotFound }) }
[ "func", "NewBackend", "(", ")", "backend", ".", "Backend", "{", "return", "backend", ".", "Func", "(", "\"", "\"", ",", "func", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "val", ",", "ok", ":=", "os", ".", "LookupEnv", "(", "key", ")", "\n", "if", "ok", "{", "return", "[", "]", "byte", "(", "val", ")", ",", "nil", "\n", "}", "\n\n", "key", "=", "strings", ".", "Replace", "(", "strings", ".", "ToUpper", "(", "key", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "val", ",", "ok", "=", "os", ".", "LookupEnv", "(", "key", ")", "\n", "if", "ok", "{", "return", "[", "]", "byte", "(", "val", ")", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "backend", ".", "ErrNotFound", "\n", "}", ")", "\n", "}" ]
// NewBackend creates a configuration loader that loads from the environment. // If the key is not found, this backend tries again by turning any kebabcase key to snakecase and // lowercase letters to uppercase.
[ "NewBackend", "creates", "a", "configuration", "loader", "that", "loads", "from", "the", "environment", ".", "If", "the", "key", "is", "not", "found", "this", "backend", "tries", "again", "by", "turning", "any", "kebabcase", "key", "to", "snakecase", "and", "lowercase", "letters", "to", "uppercase", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/env/env.go#L14-L30
153,251
heetch/confita
config.go
NewLoader
func NewLoader(backends ...backend.Backend) *Loader { l := Loader{ backends: backends, } if len(l.backends) == 0 { l.backends = append(l.backends, env.NewBackend()) } return &l }
go
func NewLoader(backends ...backend.Backend) *Loader { l := Loader{ backends: backends, } if len(l.backends) == 0 { l.backends = append(l.backends, env.NewBackend()) } return &l }
[ "func", "NewLoader", "(", "backends", "...", "backend", ".", "Backend", ")", "*", "Loader", "{", "l", ":=", "Loader", "{", "backends", ":", "backends", ",", "}", "\n\n", "if", "len", "(", "l", ".", "backends", ")", "==", "0", "{", "l", ".", "backends", "=", "append", "(", "l", ".", "backends", ",", "env", ".", "NewBackend", "(", ")", ")", "\n", "}", "\n\n", "return", "&", "l", "\n", "}" ]
// NewLoader creates a Loader. If no backend is specified, the loader uses the environment.
[ "NewLoader", "creates", "a", "Loader", ".", "If", "no", "backend", "is", "specified", "the", "loader", "uses", "the", "environment", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/config.go#L27-L37
153,252
heetch/confita
config.go
Load
func (l *Loader) Load(ctx context.Context, to interface{}) error { select { case <-ctx.Done(): return ctx.Err() default: } ref := reflect.ValueOf(to) if !ref.IsValid() || ref.Kind() != reflect.Ptr || ref.Elem().Kind() != reflect.Struct { return errors.New("provided target must be a pointer to struct") } ref = ref.Elem() s := l.parseStruct(&ref) s.S = to return l.resolve(ctx, s) }
go
func (l *Loader) Load(ctx context.Context, to interface{}) error { select { case <-ctx.Done(): return ctx.Err() default: } ref := reflect.ValueOf(to) if !ref.IsValid() || ref.Kind() != reflect.Ptr || ref.Elem().Kind() != reflect.Struct { return errors.New("provided target must be a pointer to struct") } ref = ref.Elem() s := l.parseStruct(&ref) s.S = to return l.resolve(ctx, s) }
[ "func", "(", "l", "*", "Loader", ")", "Load", "(", "ctx", "context", ".", "Context", ",", "to", "interface", "{", "}", ")", "error", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "default", ":", "}", "\n\n", "ref", ":=", "reflect", ".", "ValueOf", "(", "to", ")", "\n\n", "if", "!", "ref", ".", "IsValid", "(", ")", "||", "ref", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "||", "ref", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ref", "=", "ref", ".", "Elem", "(", ")", "\n\n", "s", ":=", "l", ".", "parseStruct", "(", "&", "ref", ")", "\n", "s", ".", "S", "=", "to", "\n", "return", "l", ".", "resolve", "(", "ctx", ",", "s", ")", "\n", "}" ]
// Load analyses all the Fields of the given struct for a "config" tag and queries each backend // in order for the corresponding key. The given context can be used for timeout and cancelation.
[ "Load", "analyses", "all", "the", "Fields", "of", "the", "given", "struct", "for", "a", "config", "tag", "and", "queries", "each", "backend", "in", "order", "for", "the", "corresponding", "key", ".", "The", "given", "context", "can", "be", "used", "for", "timeout", "and", "cancelation", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/config.go#L41-L59
153,253
heetch/confita
config.go
Set
func (f *FieldConfig) Set(data string) error { return convert(data, f.Value) }
go
func (f *FieldConfig) Set(data string) error { return convert(data, f.Value) }
[ "func", "(", "f", "*", "FieldConfig", ")", "Set", "(", "data", "string", ")", "error", "{", "return", "convert", "(", "data", ",", "f", ".", "Value", ")", "\n", "}" ]
// Set converts data into f.Value.
[ "Set", "converts", "data", "into", "f", ".", "Value", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/config.go#L226-L228
153,254
heetch/confita
backend/vault/vault.go
NewBackend
func NewBackend(client *api.Logical, path string) *Backend { return &Backend{ client: client, path: path, } }
go
func NewBackend(client *api.Logical, path string) *Backend { return &Backend{ client: client, path: path, } }
[ "func", "NewBackend", "(", "client", "*", "api", ".", "Logical", ",", "path", "string", ")", "*", "Backend", "{", "return", "&", "Backend", "{", "client", ":", "client", ",", "path", ":", "path", ",", "}", "\n", "}" ]
// NewBackend creates a configuration loader that loads from Vault // all the keys from the given path and holds them in memory.
[ "NewBackend", "creates", "a", "configuration", "loader", "that", "loads", "from", "Vault", "all", "the", "keys", "from", "the", "given", "path", "and", "holds", "them", "in", "memory", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/vault/vault.go#L20-L25
153,255
heetch/confita
backend/vault/vault.go
Get
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { var err error if b.secret == nil { b.secret, err = b.client.Read(b.path) if err != nil { return nil, err } if b.secret == nil { return nil, fmt.Errorf("secret not found at the following path: %s", b.path) } } if v, ok := b.secret.Data[key]; ok { return []byte(v.(string)), nil } return nil, backend.ErrNotFound }
go
func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { var err error if b.secret == nil { b.secret, err = b.client.Read(b.path) if err != nil { return nil, err } if b.secret == nil { return nil, fmt.Errorf("secret not found at the following path: %s", b.path) } } if v, ok := b.secret.Data[key]; ok { return []byte(v.(string)), nil } return nil, backend.ErrNotFound }
[ "func", "(", "b", "*", "Backend", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "err", "error", "\n\n", "if", "b", ".", "secret", "==", "nil", "{", "b", ".", "secret", ",", "err", "=", "b", ".", "client", ".", "Read", "(", "b", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "b", ".", "secret", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "b", ".", "path", ")", "\n", "}", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "b", ".", "secret", ".", "Data", "[", "key", "]", ";", "ok", "{", "return", "[", "]", "byte", "(", "v", ".", "(", "string", ")", ")", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "backend", ".", "ErrNotFound", "\n", "}" ]
// Get loads the given key from Vault.
[ "Get", "loads", "the", "given", "key", "from", "Vault", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/vault/vault.go#L28-L47
153,256
heetch/confita
backend/file/file.go
NewBackend
func NewBackend(path string) *Backend { name := filepath.Ext(path) if name != "" { name = name[1:] } return &Backend{ path: path, name: name, } }
go
func NewBackend(path string) *Backend { name := filepath.Ext(path) if name != "" { name = name[1:] } return &Backend{ path: path, name: name, } }
[ "func", "NewBackend", "(", "path", "string", ")", "*", "Backend", "{", "name", ":=", "filepath", ".", "Ext", "(", "path", ")", "\n", "if", "name", "!=", "\"", "\"", "{", "name", "=", "name", "[", "1", ":", "]", "\n", "}", "\n\n", "return", "&", "Backend", "{", "path", ":", "path", ",", "name", ":", "name", ",", "}", "\n", "}" ]
// NewBackend creates a configuration loader that loads from a file. // The content will get decoded based on the file extension.
[ "NewBackend", "creates", "a", "configuration", "loader", "that", "loads", "from", "a", "file", ".", "The", "content", "will", "get", "decoded", "based", "on", "the", "file", "extension", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/file/file.go#L23-L33
153,257
heetch/confita
backend/file/file.go
Unmarshal
func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error { f, err := os.Open(b.path) if err != nil { return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path) } defer f.Close() switch ext := filepath.Ext(b.path); ext { case ".json": err = json.NewDecoder(f).Decode(to) case ".yml": fallthrough case ".yaml": err = yaml.NewDecoder(f).Decode(to) case ".toml": _, err = toml.DecodeReader(f, to) default: err = errors.Errorf("unsupported extension \"%s\"", ext) } return errors.Wrapf(err, "failed to decode file \"%s\"", b.path) }
go
func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error { f, err := os.Open(b.path) if err != nil { return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path) } defer f.Close() switch ext := filepath.Ext(b.path); ext { case ".json": err = json.NewDecoder(f).Decode(to) case ".yml": fallthrough case ".yaml": err = yaml.NewDecoder(f).Decode(to) case ".toml": _, err = toml.DecodeReader(f, to) default: err = errors.Errorf("unsupported extension \"%s\"", ext) } return errors.Wrapf(err, "failed to decode file \"%s\"", b.path) }
[ "func", "(", "b", "*", "Backend", ")", "Unmarshal", "(", "ctx", "context", ".", "Context", ",", "to", "interface", "{", "}", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "b", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\\\"", "\\\"", "\"", ",", "b", ".", "path", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "switch", "ext", ":=", "filepath", ".", "Ext", "(", "b", ".", "path", ")", ";", "ext", "{", "case", "\"", "\"", ":", "err", "=", "json", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "to", ")", "\n", "case", "\"", "\"", ":", "fallthrough", "\n", "case", "\"", "\"", ":", "err", "=", "yaml", ".", "NewDecoder", "(", "f", ")", ".", "Decode", "(", "to", ")", "\n", "case", "\"", "\"", ":", "_", ",", "err", "=", "toml", ".", "DecodeReader", "(", "f", ",", "to", ")", "\n", "default", ":", "err", "=", "errors", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "ext", ")", "\n", "}", "\n\n", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\\\"", "\\\"", "\"", ",", "b", ".", "path", ")", "\n", "}" ]
// Unmarshal takes a struct pointer and unmarshals the file into it, // using either json or yaml based on the file extention.
[ "Unmarshal", "takes", "a", "struct", "pointer", "and", "unmarshals", "the", "file", "into", "it", "using", "either", "json", "or", "yaml", "based", "on", "the", "file", "extention", "." ]
ce4cc839aad348e349f27cda473af1f98ff74523
https://github.com/heetch/confita/blob/ce4cc839aad348e349f27cda473af1f98ff74523/backend/file/file.go#L37-L58
153,258
hajimehoshi/oto
internal/mux/mux.go
New
func New(channelNum, bitDepthInBytes int) *Mux { m := &Mux{ channelNum: channelNum, bitDepthInBytes: bitDepthInBytes, readers: map[io.Reader]*bufio.Reader{}, } runtime.SetFinalizer(m, (*Mux).Close) return m }
go
func New(channelNum, bitDepthInBytes int) *Mux { m := &Mux{ channelNum: channelNum, bitDepthInBytes: bitDepthInBytes, readers: map[io.Reader]*bufio.Reader{}, } runtime.SetFinalizer(m, (*Mux).Close) return m }
[ "func", "New", "(", "channelNum", ",", "bitDepthInBytes", "int", ")", "*", "Mux", "{", "m", ":=", "&", "Mux", "{", "channelNum", ":", "channelNum", ",", "bitDepthInBytes", ":", "bitDepthInBytes", ",", "readers", ":", "map", "[", "io", ".", "Reader", "]", "*", "bufio", ".", "Reader", "{", "}", ",", "}", "\n", "runtime", ".", "SetFinalizer", "(", "m", ",", "(", "*", "Mux", ")", ".", "Close", ")", "\n", "return", "m", "\n", "}" ]
// New creates a new Mux with the specified number of channels and bit depth.
[ "New", "creates", "a", "new", "Mux", "with", "the", "specified", "number", "of", "channels", "and", "bit", "depth", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L35-L43
153,259
hajimehoshi/oto
internal/mux/mux.go
Close
func (m *Mux) Close() error { m.m.Lock() runtime.SetFinalizer(m, nil) m.readers = nil m.closed = true m.m.Unlock() return nil }
go
func (m *Mux) Close() error { m.m.Lock() runtime.SetFinalizer(m, nil) m.readers = nil m.closed = true m.m.Unlock() return nil }
[ "func", "(", "m", "*", "Mux", ")", "Close", "(", ")", "error", "{", "m", ".", "m", ".", "Lock", "(", ")", "\n", "runtime", ".", "SetFinalizer", "(", "m", ",", "nil", ")", "\n", "m", ".", "readers", "=", "nil", "\n", "m", ".", "closed", "=", "true", "\n", "m", ".", "m", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Close invalidates the Mux. It doesn't close its readers.
[ "Close", "invalidates", "the", "Mux", ".", "It", "doesn", "t", "close", "its", "readers", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L145-L152
153,260
hajimehoshi/oto
internal/mux/mux.go
AddSource
func (m *Mux) AddSource(source io.Reader) { m.m.Lock() if m.closed { panic("mux: already closed") } if _, ok := m.readers[source]; ok { panic("mux: the io.Reader cannot be added multiple times") } m.readers[source] = bufio.NewReaderSize(source, 256) m.m.Unlock() }
go
func (m *Mux) AddSource(source io.Reader) { m.m.Lock() if m.closed { panic("mux: already closed") } if _, ok := m.readers[source]; ok { panic("mux: the io.Reader cannot be added multiple times") } m.readers[source] = bufio.NewReaderSize(source, 256) m.m.Unlock() }
[ "func", "(", "m", "*", "Mux", ")", "AddSource", "(", "source", "io", ".", "Reader", ")", "{", "m", ".", "m", ".", "Lock", "(", ")", "\n", "if", "m", ".", "closed", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "m", ".", "readers", "[", "source", "]", ";", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "m", ".", "readers", "[", "source", "]", "=", "bufio", ".", "NewReaderSize", "(", "source", ",", "256", ")", "\n", "m", ".", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// AddSource adds a reader to the Mux.
[ "AddSource", "adds", "a", "reader", "to", "the", "Mux", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L155-L165
153,261
hajimehoshi/oto
internal/mux/mux.go
RemoveSource
func (m *Mux) RemoveSource(source io.Reader) { m.m.Lock() if m.closed { panic("mux: already closed") } if _, ok := m.readers[source]; !ok { panic("mux: the io.Reader is already removed") } delete(m.readers, source) m.m.Unlock() }
go
func (m *Mux) RemoveSource(source io.Reader) { m.m.Lock() if m.closed { panic("mux: already closed") } if _, ok := m.readers[source]; !ok { panic("mux: the io.Reader is already removed") } delete(m.readers, source) m.m.Unlock() }
[ "func", "(", "m", "*", "Mux", ")", "RemoveSource", "(", "source", "io", ".", "Reader", ")", "{", "m", ".", "m", ".", "Lock", "(", ")", "\n", "if", "m", ".", "closed", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "m", ".", "readers", "[", "source", "]", ";", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "delete", "(", "m", ".", "readers", ",", "source", ")", "\n", "m", ".", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// RemoveSource removes a reader from the Mux.
[ "RemoveSource", "removes", "a", "reader", "from", "the", "Mux", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/internal/mux/mux.go#L168-L178
153,262
hajimehoshi/oto
pipe_js.go
pipe
func pipe() (io.ReadCloser, io.WriteCloser) { w := &pipeWriter{ consumed: make(chan struct{}), provided: make(chan struct{}), closed: make(chan struct{}), } r := &pipeReader{ w: w, closed: make(chan struct{}), } w.r = r return r, w }
go
func pipe() (io.ReadCloser, io.WriteCloser) { w := &pipeWriter{ consumed: make(chan struct{}), provided: make(chan struct{}), closed: make(chan struct{}), } r := &pipeReader{ w: w, closed: make(chan struct{}), } w.r = r return r, w }
[ "func", "pipe", "(", ")", "(", "io", ".", "ReadCloser", ",", "io", ".", "WriteCloser", ")", "{", "w", ":=", "&", "pipeWriter", "{", "consumed", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "provided", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "closed", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "r", ":=", "&", "pipeReader", "{", "w", ":", "w", ",", "closed", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "w", ".", "r", "=", "r", "\n", "return", "r", ",", "w", "\n", "}" ]
// pipe returns a set of an io.ReadCloser and an io.WriteCloser. // // This is basically same as io.Pipe, but is implemented in more effient way under the assumption that // this works on a single thread environment so that locks are not required.
[ "pipe", "returns", "a", "set", "of", "an", "io", ".", "ReadCloser", "and", "an", "io", ".", "WriteCloser", ".", "This", "is", "basically", "same", "as", "io", ".", "Pipe", "but", "is", "implemented", "in", "more", "effient", "way", "under", "the", "assumption", "that", "this", "works", "on", "a", "single", "thread", "environment", "so", "that", "locks", "are", "not", "required", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/pipe_js.go#L29-L41
153,263
hajimehoshi/oto
player.go
Close
func (p *Player) Close() error { runtime.SetFinalizer(p, nil) // Already closed if p.context == nil { return nil } // Close the pipe writer before RemoveSource, or Read-ing in the mux takes forever. if err := p.w.Close(); err != nil { return err } p.context.mux.RemoveSource(p.r) p.context = nil // Close the pipe reader after RemoveSource, or ErrClosedPipe happens at Read-ing. return p.r.Close() }
go
func (p *Player) Close() error { runtime.SetFinalizer(p, nil) // Already closed if p.context == nil { return nil } // Close the pipe writer before RemoveSource, or Read-ing in the mux takes forever. if err := p.w.Close(); err != nil { return err } p.context.mux.RemoveSource(p.r) p.context = nil // Close the pipe reader after RemoveSource, or ErrClosedPipe happens at Read-ing. return p.r.Close() }
[ "func", "(", "p", "*", "Player", ")", "Close", "(", ")", "error", "{", "runtime", ".", "SetFinalizer", "(", "p", ",", "nil", ")", "\n\n", "// Already closed", "if", "p", ".", "context", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Close the pipe writer before RemoveSource, or Read-ing in the mux takes forever.", "if", "err", ":=", "p", ".", "w", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "p", ".", "context", ".", "mux", ".", "RemoveSource", "(", "p", ".", "r", ")", "\n", "p", ".", "context", "=", "nil", "\n\n", "// Close the pipe reader after RemoveSource, or ErrClosedPipe happens at Read-ing.", "return", "p", ".", "r", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the Player and frees any resources associated with it. The Player is no longer // usable after calling Close.
[ "Close", "closes", "the", "Player", "and", "frees", "any", "resources", "associated", "with", "it", ".", "The", "Player", "is", "no", "longer", "usable", "after", "calling", "Close", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/player.go#L65-L83
153,264
hajimehoshi/oto
context.go
NewContext
func NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Context, error) { contextM.Lock() defer contextM.Unlock() if theContext != nil { panic("oto: NewContext can be called only once") } d, err := newDriver(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes) if err != nil { return nil, err } dw := &driverWriter{ driver: d, bufferSize: bufferSizeInBytes, bytesPerSecond: sampleRate * channelNum * bitDepthInBytes, } c := &Context{ driverWriter: dw, mux: mux.New(channelNum, bitDepthInBytes), errCh: make(chan error), } theContext = c go func() { if _, err := io.Copy(c.driverWriter, c.mux); err != nil { c.errCh <- err } close(c.errCh) }() return c, nil }
go
func NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Context, error) { contextM.Lock() defer contextM.Unlock() if theContext != nil { panic("oto: NewContext can be called only once") } d, err := newDriver(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes) if err != nil { return nil, err } dw := &driverWriter{ driver: d, bufferSize: bufferSizeInBytes, bytesPerSecond: sampleRate * channelNum * bitDepthInBytes, } c := &Context{ driverWriter: dw, mux: mux.New(channelNum, bitDepthInBytes), errCh: make(chan error), } theContext = c go func() { if _, err := io.Copy(c.driverWriter, c.mux); err != nil { c.errCh <- err } close(c.errCh) }() return c, nil }
[ "func", "NewContext", "(", "sampleRate", ",", "channelNum", ",", "bitDepthInBytes", ",", "bufferSizeInBytes", "int", ")", "(", "*", "Context", ",", "error", ")", "{", "contextM", ".", "Lock", "(", ")", "\n", "defer", "contextM", ".", "Unlock", "(", ")", "\n\n", "if", "theContext", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "d", ",", "err", ":=", "newDriver", "(", "sampleRate", ",", "channelNum", ",", "bitDepthInBytes", ",", "bufferSizeInBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dw", ":=", "&", "driverWriter", "{", "driver", ":", "d", ",", "bufferSize", ":", "bufferSizeInBytes", ",", "bytesPerSecond", ":", "sampleRate", "*", "channelNum", "*", "bitDepthInBytes", ",", "}", "\n", "c", ":=", "&", "Context", "{", "driverWriter", ":", "dw", ",", "mux", ":", "mux", ".", "New", "(", "channelNum", ",", "bitDepthInBytes", ")", ",", "errCh", ":", "make", "(", "chan", "error", ")", ",", "}", "\n", "theContext", "=", "c", "\n", "go", "func", "(", ")", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "c", ".", "driverWriter", ",", "c", ".", "mux", ")", ";", "err", "!=", "nil", "{", "c", ".", "errCh", "<-", "err", "\n", "}", "\n", "close", "(", "c", ".", "errCh", ")", "\n", "}", "(", ")", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewContext creates a new context, that creates and holds ready-to-use Player objects. // // The sampleRate argument specifies the number of samples that should be played during one second. // Usual numbers are 44100 or 48000. // // The channelNum argument specifies the number of channels. One channel is mono playback. Two // channels are stereo playback. No other values are supported. // // The bitDepthInBytes argument specifies the number of bytes per sample per channel. The usual value // is 2. Only values 1 and 2 are supported. // // The bufferSizeInBytes argument specifies the size of the buffer of the Context. This means, how // many bytes can Context remember before actually playing them. Bigger buffer can reduce the number // of Player's Write calls, thus reducing CPU time. Smaller buffer enables more precise timing. The // longest delay between when samples were written and when they started playing is equal to the size // of the buffer.
[ "NewContext", "creates", "a", "new", "context", "that", "creates", "and", "holds", "ready", "-", "to", "-", "use", "Player", "objects", ".", "The", "sampleRate", "argument", "specifies", "the", "number", "of", "samples", "that", "should", "be", "played", "during", "one", "second", ".", "Usual", "numbers", "are", "44100", "or", "48000", ".", "The", "channelNum", "argument", "specifies", "the", "number", "of", "channels", ".", "One", "channel", "is", "mono", "playback", ".", "Two", "channels", "are", "stereo", "playback", ".", "No", "other", "values", "are", "supported", ".", "The", "bitDepthInBytes", "argument", "specifies", "the", "number", "of", "bytes", "per", "sample", "per", "channel", ".", "The", "usual", "value", "is", "2", ".", "Only", "values", "1", "and", "2", "are", "supported", ".", "The", "bufferSizeInBytes", "argument", "specifies", "the", "size", "of", "the", "buffer", "of", "the", "Context", ".", "This", "means", "how", "many", "bytes", "can", "Context", "remember", "before", "actually", "playing", "them", ".", "Bigger", "buffer", "can", "reduce", "the", "number", "of", "Player", "s", "Write", "calls", "thus", "reducing", "CPU", "time", ".", "Smaller", "buffer", "enables", "more", "precise", "timing", ".", "The", "longest", "delay", "between", "when", "samples", "were", "written", "and", "when", "they", "started", "playing", "is", "equal", "to", "the", "size", "of", "the", "buffer", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L61-L91
153,265
hajimehoshi/oto
context.go
NewPlayer
func NewPlayer(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Player, error) { c, err := NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes) if err != nil { return nil, err } return c.NewPlayer(), nil }
go
func NewPlayer(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (*Player, error) { c, err := NewContext(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes) if err != nil { return nil, err } return c.NewPlayer(), nil }
[ "func", "NewPlayer", "(", "sampleRate", ",", "channelNum", ",", "bitDepthInBytes", ",", "bufferSizeInBytes", "int", ")", "(", "*", "Player", ",", "error", ")", "{", "c", ",", "err", ":=", "NewContext", "(", "sampleRate", ",", "channelNum", ",", "bitDepthInBytes", ",", "bufferSizeInBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "c", ".", "NewPlayer", "(", ")", ",", "nil", "\n", "}" ]
// NewPlayer is a short-hand of creating a Context by NewContext and a Player by the context's NewPlayer.
[ "NewPlayer", "is", "a", "short", "-", "hand", "of", "creating", "a", "Context", "by", "NewContext", "and", "a", "Player", "by", "the", "context", "s", "NewPlayer", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L94-L100
153,266
hajimehoshi/oto
context.go
NewPlayer
func (c *Context) NewPlayer() *Player { p := newPlayer(c) c.mux.AddSource(p.r) return p }
go
func (c *Context) NewPlayer() *Player { p := newPlayer(c) c.mux.AddSource(p.r) return p }
[ "func", "(", "c", "*", "Context", ")", "NewPlayer", "(", ")", "*", "Player", "{", "p", ":=", "newPlayer", "(", "c", ")", "\n", "c", ".", "mux", ".", "AddSource", "(", "p", ".", "r", ")", "\n", "return", "p", "\n", "}" ]
// NewPlayer creates a new, ready-to-use Player belonging to the Context.
[ "NewPlayer", "creates", "a", "new", "ready", "-", "to", "-", "use", "Player", "belonging", "to", "the", "Context", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L103-L107
153,267
hajimehoshi/oto
context.go
Close
func (c *Context) Close() error { contextM.Lock() theContext = nil contextM.Unlock() if err := c.driverWriter.Close(); err != nil { return err } if err := c.mux.Close(); err != nil { return err } return <-c.errCh }
go
func (c *Context) Close() error { contextM.Lock() theContext = nil contextM.Unlock() if err := c.driverWriter.Close(); err != nil { return err } if err := c.mux.Close(); err != nil { return err } return <-c.errCh }
[ "func", "(", "c", "*", "Context", ")", "Close", "(", ")", "error", "{", "contextM", ".", "Lock", "(", ")", "\n", "theContext", "=", "nil", "\n", "contextM", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "c", ".", "driverWriter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "mux", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "<-", "c", ".", "errCh", "\n", "}" ]
// Close closes the Context and its Players and frees any resources associated with it. The Context is no longer // usable after calling Close.
[ "Close", "closes", "the", "Context", "and", "its", "Players", "and", "frees", "any", "resources", "associated", "with", "it", ".", "The", "Context", "is", "no", "longer", "usable", "after", "calling", "Close", "." ]
ac73e202da9bf0b5596c1a6d4cd12fad992987d3
https://github.com/hajimehoshi/oto/blob/ac73e202da9bf0b5596c1a6d4cd12fad992987d3/context.go#L111-L123
153,268
yinqiwen/gsnova
common/protector/resolver.go
PickRandomIP
func (response *DnsResponse) PickRandomIP() (net.IP, error) { length := int64(len(response.records)) if length < 1 { return nil, errors.New("no IP address") } index, err := rand.Int(rand.Reader, big.NewInt(length)) if err != nil { return nil, err } record := response.records[index.Int64()] return record.IP, nil }
go
func (response *DnsResponse) PickRandomIP() (net.IP, error) { length := int64(len(response.records)) if length < 1 { return nil, errors.New("no IP address") } index, err := rand.Int(rand.Reader, big.NewInt(length)) if err != nil { return nil, err } record := response.records[index.Int64()] return record.IP, nil }
[ "func", "(", "response", "*", "DnsResponse", ")", "PickRandomIP", "(", ")", "(", "net", ".", "IP", ",", "error", ")", "{", "length", ":=", "int64", "(", "len", "(", "response", ".", "records", ")", ")", "\n", "if", "length", "<", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "index", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "big", ".", "NewInt", "(", "length", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "record", ":=", "response", ".", "records", "[", "index", ".", "Int64", "(", ")", "]", "\n", "return", "record", ".", "IP", ",", "nil", "\n", "}" ]
// PickRandomIP picks a random IP address from a DNS response
[ "PickRandomIP", "picks", "a", "random", "IP", "address", "from", "a", "DNS", "response" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/resolver.go#L24-L37
153,269
yinqiwen/gsnova
common/protector/resolver.go
DnsLookup
func DnsLookup(addr string, conn net.Conn) (*DnsResponse, error) { //log.Printf("Doing a DNS lookup on %s", addr) dnsResponse := &DnsResponse{ records: make([]DNSRecord, 0), } // create the connection to the DNS server dnsConn := &dns.Conn{Conn: conn} defer dnsConn.Close() m := new(dns.Msg) m.Id = dns.Id() // set the question section in the dns query // Fqdn returns the fully qualified domain name m.SetQuestion(dns.Fqdn(addr), dns.TypeA) m.RecursionDesired = true dnsConn.WriteMsg(m) response, err := dnsConn.ReadMsg() if err != nil { log.Printf("Could not process DNS response: %v", err) return nil, err } now := time.Now() // iterate over RRs containing the DNS answer for _, answer := range response.Answer { if a, ok := answer.(*dns.A); ok { // append the result to our list of records // the A records in the RDATA section of the DNS answer // contains the actual IP address dnsResponse.records = append(dnsResponse.records, DNSRecord{ IP: a.A, ExpireAt: now.Add(time.Duration(a.Hdr.Ttl) * time.Second), }) //log.Printf("###TTL:%d", a.Hdr.Ttl) } } return dnsResponse, nil }
go
func DnsLookup(addr string, conn net.Conn) (*DnsResponse, error) { //log.Printf("Doing a DNS lookup on %s", addr) dnsResponse := &DnsResponse{ records: make([]DNSRecord, 0), } // create the connection to the DNS server dnsConn := &dns.Conn{Conn: conn} defer dnsConn.Close() m := new(dns.Msg) m.Id = dns.Id() // set the question section in the dns query // Fqdn returns the fully qualified domain name m.SetQuestion(dns.Fqdn(addr), dns.TypeA) m.RecursionDesired = true dnsConn.WriteMsg(m) response, err := dnsConn.ReadMsg() if err != nil { log.Printf("Could not process DNS response: %v", err) return nil, err } now := time.Now() // iterate over RRs containing the DNS answer for _, answer := range response.Answer { if a, ok := answer.(*dns.A); ok { // append the result to our list of records // the A records in the RDATA section of the DNS answer // contains the actual IP address dnsResponse.records = append(dnsResponse.records, DNSRecord{ IP: a.A, ExpireAt: now.Add(time.Duration(a.Hdr.Ttl) * time.Second), }) //log.Printf("###TTL:%d", a.Hdr.Ttl) } } return dnsResponse, nil }
[ "func", "DnsLookup", "(", "addr", "string", ",", "conn", "net", ".", "Conn", ")", "(", "*", "DnsResponse", ",", "error", ")", "{", "//log.Printf(\"Doing a DNS lookup on %s\", addr)", "dnsResponse", ":=", "&", "DnsResponse", "{", "records", ":", "make", "(", "[", "]", "DNSRecord", ",", "0", ")", ",", "}", "\n\n", "// create the connection to the DNS server", "dnsConn", ":=", "&", "dns", ".", "Conn", "{", "Conn", ":", "conn", "}", "\n", "defer", "dnsConn", ".", "Close", "(", ")", "\n\n", "m", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "m", ".", "Id", "=", "dns", ".", "Id", "(", ")", "\n", "// set the question section in the dns query", "// Fqdn returns the fully qualified domain name", "m", ".", "SetQuestion", "(", "dns", ".", "Fqdn", "(", "addr", ")", ",", "dns", ".", "TypeA", ")", "\n", "m", ".", "RecursionDesired", "=", "true", "\n\n", "dnsConn", ".", "WriteMsg", "(", "m", ")", "\n\n", "response", ",", "err", ":=", "dnsConn", ".", "ReadMsg", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "// iterate over RRs containing the DNS answer", "for", "_", ",", "answer", ":=", "range", "response", ".", "Answer", "{", "if", "a", ",", "ok", ":=", "answer", ".", "(", "*", "dns", ".", "A", ")", ";", "ok", "{", "// append the result to our list of records", "// the A records in the RDATA section of the DNS answer", "// contains the actual IP address", "dnsResponse", ".", "records", "=", "append", "(", "dnsResponse", ".", "records", ",", "DNSRecord", "{", "IP", ":", "a", ".", "A", ",", "ExpireAt", ":", "now", ".", "Add", "(", "time", ".", "Duration", "(", "a", ".", "Hdr", ".", "Ttl", ")", "*", "time", ".", "Second", ")", ",", "}", ")", "\n", "//log.Printf(\"###TTL:%d\", a.Hdr.Ttl)", "}", "\n", "}", "\n", "return", "dnsResponse", ",", "nil", "\n", "}" ]
// dnsLookup is used whenever we need to conduct a DNS query over a given TCP connection
[ "dnsLookup", "is", "used", "whenever", "we", "need", "to", "conduct", "a", "DNS", "query", "over", "a", "given", "TCP", "connection" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/resolver.go#L48-L89
153,270
yinqiwen/gsnova
common/helper/bytes.go
PKCS7Unpad
func PKCS7Unpad(in []byte) []byte { if len(in) == 0 { return nil } padding := in[len(in)-1] if int(padding) > len(in) || padding > aes.BlockSize { return nil } else if padding == 0 { return nil } for i := len(in) - 1; i > len(in)-int(padding)-1; i-- { if in[i] != padding { return nil } } return in[:len(in)-int(padding)] }
go
func PKCS7Unpad(in []byte) []byte { if len(in) == 0 { return nil } padding := in[len(in)-1] if int(padding) > len(in) || padding > aes.BlockSize { return nil } else if padding == 0 { return nil } for i := len(in) - 1; i > len(in)-int(padding)-1; i-- { if in[i] != padding { return nil } } return in[:len(in)-int(padding)] }
[ "func", "PKCS7Unpad", "(", "in", "[", "]", "byte", ")", "[", "]", "byte", "{", "if", "len", "(", "in", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "padding", ":=", "in", "[", "len", "(", "in", ")", "-", "1", "]", "\n", "if", "int", "(", "padding", ")", ">", "len", "(", "in", ")", "||", "padding", ">", "aes", ".", "BlockSize", "{", "return", "nil", "\n", "}", "else", "if", "padding", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "for", "i", ":=", "len", "(", "in", ")", "-", "1", ";", "i", ">", "len", "(", "in", ")", "-", "int", "(", "padding", ")", "-", "1", ";", "i", "--", "{", "if", "in", "[", "i", "]", "!=", "padding", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "in", "[", ":", "len", "(", "in", ")", "-", "int", "(", "padding", ")", "]", "\n", "}" ]
// Returns slice of the original data without padding.
[ "Returns", "slice", "of", "the", "original", "data", "without", "padding", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/helper/bytes.go#L21-L39
153,271
yinqiwen/gsnova
common/helper/bytes.go
ToBytes
func ToBytes(s string) (uint64, error) { parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s)) if len(parts) < 3 { return 0, invalidByteQuantityError } value, err := strconv.ParseFloat(parts[1], 64) if err != nil || value <= 0 { return 0, invalidByteQuantityError } var bytes uint64 unit := strings.ToUpper(parts[2]) switch unit[:1] { case "T": bytes = uint64(value * TERABYTE) case "G": bytes = uint64(value * GIGABYTE) case "M": bytes = uint64(value * MEGABYTE) case "K": bytes = uint64(value * KILOBYTE) case "B": bytes = uint64(value * BYTE) } return bytes, nil }
go
func ToBytes(s string) (uint64, error) { parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s)) if len(parts) < 3 { return 0, invalidByteQuantityError } value, err := strconv.ParseFloat(parts[1], 64) if err != nil || value <= 0 { return 0, invalidByteQuantityError } var bytes uint64 unit := strings.ToUpper(parts[2]) switch unit[:1] { case "T": bytes = uint64(value * TERABYTE) case "G": bytes = uint64(value * GIGABYTE) case "M": bytes = uint64(value * MEGABYTE) case "K": bytes = uint64(value * KILOBYTE) case "B": bytes = uint64(value * BYTE) } return bytes, nil }
[ "func", "ToBytes", "(", "s", "string", ")", "(", "uint64", ",", "error", ")", "{", "parts", ":=", "bytesPattern", ".", "FindStringSubmatch", "(", "strings", ".", "TrimSpace", "(", "s", ")", ")", "\n", "if", "len", "(", "parts", ")", "<", "3", "{", "return", "0", ",", "invalidByteQuantityError", "\n", "}", "\n\n", "value", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "parts", "[", "1", "]", ",", "64", ")", "\n", "if", "err", "!=", "nil", "||", "value", "<=", "0", "{", "return", "0", ",", "invalidByteQuantityError", "\n", "}", "\n\n", "var", "bytes", "uint64", "\n", "unit", ":=", "strings", ".", "ToUpper", "(", "parts", "[", "2", "]", ")", "\n", "switch", "unit", "[", ":", "1", "]", "{", "case", "\"", "\"", ":", "bytes", "=", "uint64", "(", "value", "*", "TERABYTE", ")", "\n", "case", "\"", "\"", ":", "bytes", "=", "uint64", "(", "value", "*", "GIGABYTE", ")", "\n", "case", "\"", "\"", ":", "bytes", "=", "uint64", "(", "value", "*", "MEGABYTE", ")", "\n", "case", "\"", "\"", ":", "bytes", "=", "uint64", "(", "value", "*", "KILOBYTE", ")", "\n", "case", "\"", "\"", ":", "bytes", "=", "uint64", "(", "value", "*", "BYTE", ")", "\n", "}", "\n\n", "return", "bytes", ",", "nil", "\n", "}" ]
// ToBytes parses a string formatted by ByteSize as bytes.
[ "ToBytes", "parses", "a", "string", "formatted", "by", "ByteSize", "as", "bytes", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/helper/bytes.go#L100-L127
153,272
yinqiwen/gsnova
common/channel/kcp/local.go
WriteTo
func (c *connectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) { writer, ok := c.PacketConn.(io.Writer) if ok { return writer.Write(b) } return c.PacketConn.WriteTo(b, addr) }
go
func (c *connectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) { writer, ok := c.PacketConn.(io.Writer) if ok { return writer.Write(b) } return c.PacketConn.WriteTo(b, addr) }
[ "func", "(", "c", "*", "connectedUDPConn", ")", "WriteTo", "(", "b", "[", "]", "byte", ",", "addr", "net", ".", "Addr", ")", "(", "int", ",", "error", ")", "{", "writer", ",", "ok", ":=", "c", ".", "PacketConn", ".", "(", "io", ".", "Writer", ")", "\n", "if", "ok", "{", "return", "writer", ".", "Write", "(", "b", ")", "\n", "}", "\n", "return", "c", ".", "PacketConn", ".", "WriteTo", "(", "b", ",", "addr", ")", "\n", "}" ]
// WriteTo redirects all writes to the Write syscall, which is 4 times faster.
[ "WriteTo", "redirects", "all", "writes", "to", "the", "Write", "syscall", "which", "is", "4", "times", "faster", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/channel/kcp/local.go#L23-L29
153,273
yinqiwen/gsnova
common/netx/netx.go
DialTimeout
func DialTimeout(network string, addr string, timeout time.Duration) (net.Conn, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) conn, err := DialContext(ctx, network, addr) cancel() return conn, err }
go
func DialTimeout(network string, addr string, timeout time.Duration) (net.Conn, error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) conn, err := DialContext(ctx, network, addr) cancel() return conn, err }
[ "func", "DialTimeout", "(", "network", "string", ",", "addr", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "timeout", ")", "\n", "conn", ",", "err", ":=", "DialContext", "(", "ctx", ",", "network", ",", "addr", ")", "\n", "cancel", "(", ")", "\n", "return", "conn", ",", "err", "\n", "}" ]
// DialTimeout dials the given addr on the given net type using the configured // dial function, timing out after the given timeout.
[ "DialTimeout", "dials", "the", "given", "addr", "on", "the", "given", "net", "type", "using", "the", "configured", "dial", "function", "timing", "out", "after", "the", "given", "timeout", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L32-L37
153,274
yinqiwen/gsnova
common/netx/netx.go
DialContext
func DialContext(ctx context.Context, network string, addr string) (net.Conn, error) { return dial.Load().(func(context.Context, string, string) (net.Conn, error))(ctx, network, addr) }
go
func DialContext(ctx context.Context, network string, addr string) (net.Conn, error) { return dial.Load().(func(context.Context, string, string) (net.Conn, error))(ctx, network, addr) }
[ "func", "DialContext", "(", "ctx", "context", ".", "Context", ",", "network", "string", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "dial", ".", "Load", "(", ")", ".", "(", "func", "(", "context", ".", "Context", ",", "string", ",", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", ")", "(", "ctx", ",", "network", ",", "addr", ")", "\n", "}" ]
// DialContext dials the given addr on the given net type using the configured // dial function, with the given context.
[ "DialContext", "dials", "the", "given", "addr", "on", "the", "given", "net", "type", "using", "the", "configured", "dial", "function", "with", "the", "given", "context", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L49-L51
153,275
yinqiwen/gsnova
common/netx/netx.go
OverrideDial
func OverrideDial(dialFN func(ctx context.Context, net string, addr string) (net.Conn, error)) { dial.Store(dialFN) }
go
func OverrideDial(dialFN func(ctx context.Context, net string, addr string) (net.Conn, error)) { dial.Store(dialFN) }
[ "func", "OverrideDial", "(", "dialFN", "func", "(", "ctx", "context", ".", "Context", ",", "net", "string", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", ")", "{", "dial", ".", "Store", "(", "dialFN", ")", "\n", "}" ]
// OverrideDial overrides the global dial function.
[ "OverrideDial", "overrides", "the", "global", "dial", "function", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L54-L56
153,276
yinqiwen/gsnova
common/netx/netx.go
Resolve
func Resolve(network string, addr string) (*net.TCPAddr, error) { return resolveTCPAddr.Load().(func(string, string) (*net.TCPAddr, error))(network, addr) }
go
func Resolve(network string, addr string) (*net.TCPAddr, error) { return resolveTCPAddr.Load().(func(string, string) (*net.TCPAddr, error))(network, addr) }
[ "func", "Resolve", "(", "network", "string", ",", "addr", "string", ")", "(", "*", "net", ".", "TCPAddr", ",", "error", ")", "{", "return", "resolveTCPAddr", ".", "Load", "(", ")", ".", "(", "func", "(", "string", ",", "string", ")", "(", "*", "net", ".", "TCPAddr", ",", "error", ")", ")", "(", "network", ",", "addr", ")", "\n", "}" ]
// Resolve resolves the given tcp address using the configured resolve function.
[ "Resolve", "resolves", "the", "given", "tcp", "address", "using", "the", "configured", "resolve", "function", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L59-L61
153,277
yinqiwen/gsnova
common/netx/netx.go
OverrideResolve
func OverrideResolve(resolveFN func(net string, addr string) (*net.TCPAddr, error)) { resolveTCPAddr.Store(resolveFN) }
go
func OverrideResolve(resolveFN func(net string, addr string) (*net.TCPAddr, error)) { resolveTCPAddr.Store(resolveFN) }
[ "func", "OverrideResolve", "(", "resolveFN", "func", "(", "net", "string", ",", "addr", "string", ")", "(", "*", "net", ".", "TCPAddr", ",", "error", ")", ")", "{", "resolveTCPAddr", ".", "Store", "(", "resolveFN", ")", "\n", "}" ]
// OverrideResolve overrides the global resolve function.
[ "OverrideResolve", "overrides", "the", "global", "resolve", "function", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/netx/netx.go#L64-L66
153,278
yinqiwen/gsnova
common/channel/websocket/remote.go
WebsocketInvoke
func WebsocketInvoke(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } //logger.Info("req headers: %v", r.Header, r.R) ws, err := upgrader.Upgrade(w, r, nil) if err != nil { //log.WithField("err", err).Println("Upgrading to websockets") http.Error(w, "Error Upgrading to websockets", 400) return } session, err := pmux.Server(&mux.WsConn{Conn: ws}, channel.InitialPMuxConfig(&channel.DefaultServerCipher)) if nil != err { return } muxSession := &mux.ProxyMuxSession{Session: session} channel.ServProxyMuxSession(muxSession, nil, nil) //ws.WriteMessage(websocket.CloseMessage, []byte{}) }
go
func WebsocketInvoke(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } //logger.Info("req headers: %v", r.Header, r.R) ws, err := upgrader.Upgrade(w, r, nil) if err != nil { //log.WithField("err", err).Println("Upgrading to websockets") http.Error(w, "Error Upgrading to websockets", 400) return } session, err := pmux.Server(&mux.WsConn{Conn: ws}, channel.InitialPMuxConfig(&channel.DefaultServerCipher)) if nil != err { return } muxSession := &mux.ProxyMuxSession{Session: session} channel.ServProxyMuxSession(muxSession, nil, nil) //ws.WriteMessage(websocket.CloseMessage, []byte{}) }
[ "func", "WebsocketInvoke", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "r", ".", "Method", "!=", "\"", "\"", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "405", ")", "\n", "return", "\n", "}", "\n", "//logger.Info(\"req headers: %v\", r.Header, r.R)\r", "ws", ",", "err", ":=", "upgrader", ".", "Upgrade", "(", "w", ",", "r", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "//log.WithField(\"err\", err).Println(\"Upgrading to websockets\")\r", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "400", ")", "\n", "return", "\n", "}", "\n", "session", ",", "err", ":=", "pmux", ".", "Server", "(", "&", "mux", ".", "WsConn", "{", "Conn", ":", "ws", "}", ",", "channel", ".", "InitialPMuxConfig", "(", "&", "channel", ".", "DefaultServerCipher", ")", ")", "\n", "if", "nil", "!=", "err", "{", "return", "\n", "}", "\n", "muxSession", ":=", "&", "mux", ".", "ProxyMuxSession", "{", "Session", ":", "session", "}", "\n", "channel", ".", "ServProxyMuxSession", "(", "muxSession", ",", "nil", ",", "nil", ")", "\n", "//ws.WriteMessage(websocket.CloseMessage, []byte{})\r", "}" ]
// handleWebsocket connection. Update to
[ "handleWebsocket", "connection", ".", "Update", "to" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/channel/websocket/remote.go#L20-L40
153,279
yinqiwen/gsnova
remote/web.go
indexCallback
func indexCallback(w http.ResponseWriter, req *http.Request) { io.WriteString(w, strings.Replace(html, "${Version}", channel.Version, -1)) }
go
func indexCallback(w http.ResponseWriter, req *http.Request) { io.WriteString(w, strings.Replace(html, "${Version}", channel.Version, -1)) }
[ "func", "indexCallback", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "io", ".", "WriteString", "(", "w", ",", "strings", ".", "Replace", "(", "html", ",", "\"", "\"", ",", "channel", ".", "Version", ",", "-", "1", ")", ")", "\n", "}" ]
// hello world, the web server
[ "hello", "world", "the", "web", "server" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/remote/web.go#L17-L19
153,280
yinqiwen/gsnova
local/gsnova/gsnova_unix.go
ProtectConnections
func ProtectConnections(dnsServer string, p SocketProtector) { protector.Configure(p.Protect, dnsServer) //p := New(protector.Protect, dnsServer) netx.OverrideDial(protector.DialContext) netx.OverrideResolve(protector.Resolve) netx.OverrideListenUDP(protector.ListenUDP) netx.OverrideDialUDP(protector.DialUDP) }
go
func ProtectConnections(dnsServer string, p SocketProtector) { protector.Configure(p.Protect, dnsServer) //p := New(protector.Protect, dnsServer) netx.OverrideDial(protector.DialContext) netx.OverrideResolve(protector.Resolve) netx.OverrideListenUDP(protector.ListenUDP) netx.OverrideDialUDP(protector.DialUDP) }
[ "func", "ProtectConnections", "(", "dnsServer", "string", ",", "p", "SocketProtector", ")", "{", "protector", ".", "Configure", "(", "p", ".", "Protect", ",", "dnsServer", ")", "\n", "//p := New(protector.Protect, dnsServer)\r", "netx", ".", "OverrideDial", "(", "protector", ".", "DialContext", ")", "\n", "netx", ".", "OverrideResolve", "(", "protector", ".", "Resolve", ")", "\n", "netx", ".", "OverrideListenUDP", "(", "protector", ".", "ListenUDP", ")", "\n", "netx", ".", "OverrideDialUDP", "(", "protector", ".", "DialUDP", ")", "\n", "}" ]
// ProtectConnections allows connections made by Lantern to be protected from // routing via a VPN. This is useful when running Lantern as a VPN on Android, // because it keeps Lantern's own connections from being captured by the VPN and // resulting in an infinite loop.
[ "ProtectConnections", "allows", "connections", "made", "by", "Lantern", "to", "be", "protected", "from", "routing", "via", "a", "VPN", ".", "This", "is", "useful", "when", "running", "Lantern", "as", "a", "VPN", "on", "Android", "because", "it", "keeps", "Lantern", "s", "own", "connections", "from", "being", "captured", "by", "the", "VPN", "and", "resulting", "in", "an", "infinite", "loop", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/local/gsnova/gsnova_unix.go#L20-L27
153,281
yinqiwen/gsnova
local/gsnova/gsnova.go
SyncConfig
func SyncConfig(addr string, localDir string) (bool, error) { return local.SyncConfig(addr, localDir) }
go
func SyncConfig(addr string, localDir string) (bool, error) { return local.SyncConfig(addr, localDir) }
[ "func", "SyncConfig", "(", "addr", "string", ",", "localDir", "string", ")", "(", "bool", ",", "error", ")", "{", "return", "local", ".", "SyncConfig", "(", "addr", ",", "localDir", ")", "\n", "}" ]
//SyncConfig sync config files from running gsnova instance
[ "SyncConfig", "sync", "config", "files", "from", "running", "gsnova", "instance" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/local/gsnova/gsnova.go#L39-L41
153,282
yinqiwen/gsnova
common/protector/protected.go
cleanup
func (conn *ProtectedConnBase) cleanup() { conn.mutex.Lock() defer conn.mutex.Unlock() if conn.socketFd != socketError { //fmt.Printf("####Close %d\n", conn.socketFd) syscall.Close(conn.socketFd) conn.socketFd = socketError } }
go
func (conn *ProtectedConnBase) cleanup() { conn.mutex.Lock() defer conn.mutex.Unlock() if conn.socketFd != socketError { //fmt.Printf("####Close %d\n", conn.socketFd) syscall.Close(conn.socketFd) conn.socketFd = socketError } }
[ "func", "(", "conn", "*", "ProtectedConnBase", ")", "cleanup", "(", ")", "{", "conn", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "conn", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "conn", ".", "socketFd", "!=", "socketError", "{", "//fmt.Printf(\"####Close %d\\n\", conn.socketFd)", "syscall", ".", "Close", "(", "conn", ".", "socketFd", ")", "\n", "conn", ".", "socketFd", "=", "socketError", "\n", "}", "\n", "}" ]
// cleanup is ran whenever we encounter a socket error // we use a mutex since this connection is active in a variety // of goroutines and to prevent any possible race conditions
[ "cleanup", "is", "ran", "whenever", "we", "encounter", "a", "socket", "error", "we", "use", "a", "mutex", "since", "this", "connection", "is", "active", "in", "a", "variety", "of", "goroutines", "and", "to", "prevent", "any", "possible", "race", "conditions" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L90-L99
153,283
yinqiwen/gsnova
common/protector/protected.go
Resolve
func Resolve(network string, addr string) (*net.TCPAddr, error) { host, port, err := SplitHostPort(addr) if err != nil { return nil, err } // Check if we already have the IP address IPAddr := net.ParseIP(host) if IPAddr != nil { return &net.TCPAddr{IP: IPAddr, Port: port}, nil } // Create a datagram socket socketFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0) if err != nil { return nil, fmt.Errorf("Error creating socket: %v", err) } defer syscall.Close(socketFd) // Here we protect the underlying socket from the // VPN connection by passing the file descriptor // back to Java for exclusion err = currentProtect(socketFd) if err != nil { return nil, fmt.Errorf("Could not bind socket to system device: %v", err) } IPAddr = net.ParseIP(currentDnsServer) if IPAddr == nil { return nil, errors.New("invalid IP address") } var ip [4]byte copy(ip[:], IPAddr.To4()) sockAddr := syscall.SockaddrInet4{Addr: ip, Port: dnsPort} err = syscall.Connect(socketFd, &sockAddr) if err != nil { return nil, err } fd := uintptr(socketFd) file := os.NewFile(fd, "") defer file.Close() // return a copy of the network connection // represented by file fileConn, err := net.FileConn(file) if err != nil { log.Printf("Error returning a copy of the network connection: %v", err) return nil, err } setQueryTimeouts(fileConn) //log.Printf("performing dns lookup...!!") result, err := DnsLookup(host, fileConn) if err != nil { log.Printf("Error doing DNS resolution: %v", err) return nil, err } ipAddr, err := result.PickRandomIP() if err != nil { log.Printf("No IP address available: %v", err) return nil, err } return &net.TCPAddr{IP: ipAddr, Port: port}, nil }
go
func Resolve(network string, addr string) (*net.TCPAddr, error) { host, port, err := SplitHostPort(addr) if err != nil { return nil, err } // Check if we already have the IP address IPAddr := net.ParseIP(host) if IPAddr != nil { return &net.TCPAddr{IP: IPAddr, Port: port}, nil } // Create a datagram socket socketFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0) if err != nil { return nil, fmt.Errorf("Error creating socket: %v", err) } defer syscall.Close(socketFd) // Here we protect the underlying socket from the // VPN connection by passing the file descriptor // back to Java for exclusion err = currentProtect(socketFd) if err != nil { return nil, fmt.Errorf("Could not bind socket to system device: %v", err) } IPAddr = net.ParseIP(currentDnsServer) if IPAddr == nil { return nil, errors.New("invalid IP address") } var ip [4]byte copy(ip[:], IPAddr.To4()) sockAddr := syscall.SockaddrInet4{Addr: ip, Port: dnsPort} err = syscall.Connect(socketFd, &sockAddr) if err != nil { return nil, err } fd := uintptr(socketFd) file := os.NewFile(fd, "") defer file.Close() // return a copy of the network connection // represented by file fileConn, err := net.FileConn(file) if err != nil { log.Printf("Error returning a copy of the network connection: %v", err) return nil, err } setQueryTimeouts(fileConn) //log.Printf("performing dns lookup...!!") result, err := DnsLookup(host, fileConn) if err != nil { log.Printf("Error doing DNS resolution: %v", err) return nil, err } ipAddr, err := result.PickRandomIP() if err != nil { log.Printf("No IP address available: %v", err) return nil, err } return &net.TCPAddr{IP: ipAddr, Port: port}, nil }
[ "func", "Resolve", "(", "network", "string", ",", "addr", "string", ")", "(", "*", "net", ".", "TCPAddr", ",", "error", ")", "{", "host", ",", "port", ",", "err", ":=", "SplitHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Check if we already have the IP address", "IPAddr", ":=", "net", ".", "ParseIP", "(", "host", ")", "\n", "if", "IPAddr", "!=", "nil", "{", "return", "&", "net", ".", "TCPAddr", "{", "IP", ":", "IPAddr", ",", "Port", ":", "port", "}", ",", "nil", "\n", "}", "\n", "// Create a datagram socket", "socketFd", ",", "err", ":=", "syscall", ".", "Socket", "(", "syscall", ".", "AF_INET", ",", "syscall", ".", "SOCK_DGRAM", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "syscall", ".", "Close", "(", "socketFd", ")", "\n\n", "// Here we protect the underlying socket from the", "// VPN connection by passing the file descriptor", "// back to Java for exclusion", "err", "=", "currentProtect", "(", "socketFd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "IPAddr", "=", "net", ".", "ParseIP", "(", "currentDnsServer", ")", "\n", "if", "IPAddr", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "ip", "[", "4", "]", "byte", "\n", "copy", "(", "ip", "[", ":", "]", ",", "IPAddr", ".", "To4", "(", ")", ")", "\n", "sockAddr", ":=", "syscall", ".", "SockaddrInet4", "{", "Addr", ":", "ip", ",", "Port", ":", "dnsPort", "}", "\n\n", "err", "=", "syscall", ".", "Connect", "(", "socketFd", ",", "&", "sockAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fd", ":=", "uintptr", "(", "socketFd", ")", "\n", "file", ":=", "os", ".", "NewFile", "(", "fd", ",", "\"", "\"", ")", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "// return a copy of the network connection", "// represented by file", "fileConn", ",", "err", ":=", "net", ".", "FileConn", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "setQueryTimeouts", "(", "fileConn", ")", "\n\n", "//log.Printf(\"performing dns lookup...!!\")", "result", ",", "err", ":=", "DnsLookup", "(", "host", ",", "fileConn", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "ipAddr", ",", "err", ":=", "result", ".", "PickRandomIP", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "net", ".", "TCPAddr", "{", "IP", ":", "ipAddr", ",", "Port", ":", "port", "}", ",", "nil", "\n", "}" ]
// Resolve resolves the given address using a DNS lookup on a UDP socket // protected by the currnet Protector.
[ "Resolve", "resolves", "the", "given", "address", "using", "a", "DNS", "lookup", "on", "a", "UDP", "socket", "protected", "by", "the", "currnet", "Protector", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L191-L257
153,284
yinqiwen/gsnova
common/protector/protected.go
Close
func (conn *ProtectedConn) Close() (err error) { conn.mutex.Lock() defer conn.mutex.Unlock() if !conn.isClosed { conn.isClosed = true if conn.Conn == nil { if conn.socketFd == socketError { err = nil } else { err = syscall.Close(conn.socketFd) // update socket fd to socketError // to make it explicit this connection // has been closed conn.socketFd = socketError } } else { err = conn.Conn.Close() } } return err }
go
func (conn *ProtectedConn) Close() (err error) { conn.mutex.Lock() defer conn.mutex.Unlock() if !conn.isClosed { conn.isClosed = true if conn.Conn == nil { if conn.socketFd == socketError { err = nil } else { err = syscall.Close(conn.socketFd) // update socket fd to socketError // to make it explicit this connection // has been closed conn.socketFd = socketError } } else { err = conn.Conn.Close() } } return err }
[ "func", "(", "conn", "*", "ProtectedConn", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "conn", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "conn", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "!", "conn", ".", "isClosed", "{", "conn", ".", "isClosed", "=", "true", "\n", "if", "conn", ".", "Conn", "==", "nil", "{", "if", "conn", ".", "socketFd", "==", "socketError", "{", "err", "=", "nil", "\n", "}", "else", "{", "err", "=", "syscall", ".", "Close", "(", "conn", ".", "socketFd", ")", "\n", "// update socket fd to socketError", "// to make it explicit this connection", "// has been closed", "conn", ".", "socketFd", "=", "socketError", "\n", "}", "\n", "}", "else", "{", "err", "=", "conn", ".", "Conn", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Close is used to destroy a protected connection
[ "Close", "is", "used", "to", "destroy", "a", "protected", "connection" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L490-L511
153,285
yinqiwen/gsnova
common/protector/protected.go
setQueryTimeouts
func setQueryTimeouts(c net.Conn) { now := time.Now() c.SetReadDeadline(now.Add(readDeadline)) c.SetWriteDeadline(now.Add(writeDeadline)) }
go
func setQueryTimeouts(c net.Conn) { now := time.Now() c.SetReadDeadline(now.Add(readDeadline)) c.SetWriteDeadline(now.Add(writeDeadline)) }
[ "func", "setQueryTimeouts", "(", "c", "net", ".", "Conn", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "c", ".", "SetReadDeadline", "(", "now", ".", "Add", "(", "readDeadline", ")", ")", "\n", "c", ".", "SetWriteDeadline", "(", "now", ".", "Add", "(", "writeDeadline", ")", ")", "\n", "}" ]
// configure DNS query expiration
[ "configure", "DNS", "query", "expiration" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L514-L518
153,286
yinqiwen/gsnova
common/protector/protected.go
SplitHostPort
func SplitHostPort(addr string) (string, int, error) { host, sPort, err := net.SplitHostPort(addr) if err != nil { log.Printf("Could not split network address: %v", err) return "", 0, err } port, err := strconv.Atoi(sPort) if err != nil { log.Printf("No port number found %v", err) return "", 0, err } return host, port, nil }
go
func SplitHostPort(addr string) (string, int, error) { host, sPort, err := net.SplitHostPort(addr) if err != nil { log.Printf("Could not split network address: %v", err) return "", 0, err } port, err := strconv.Atoi(sPort) if err != nil { log.Printf("No port number found %v", err) return "", 0, err } return host, port, nil }
[ "func", "SplitHostPort", "(", "addr", "string", ")", "(", "string", ",", "int", ",", "error", ")", "{", "host", ",", "sPort", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", ",", "0", ",", "err", "\n", "}", "\n", "port", ",", "err", ":=", "strconv", ".", "Atoi", "(", "sPort", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\"", "\"", ",", "0", ",", "err", "\n", "}", "\n", "return", "host", ",", "port", ",", "nil", "\n", "}" ]
// wrapper around net.SplitHostPort that also converts // uses strconv to convert the port to an int
[ "wrapper", "around", "net", ".", "SplitHostPort", "that", "also", "converts", "uses", "strconv", "to", "convert", "the", "port", "to", "an", "int" ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/protector/protected.go#L522-L534
153,287
yinqiwen/gsnova
common/socks/socks.go
Reject
func (conn *SocksConn) Reject() error { if conn.socksVersion == socks4Version { return sendSocks4aResponseRejected(conn) } return sendSocks5ResponseRejected(conn, SocksRepGeneralFailure) }
go
func (conn *SocksConn) Reject() error { if conn.socksVersion == socks4Version { return sendSocks4aResponseRejected(conn) } return sendSocks5ResponseRejected(conn, SocksRepGeneralFailure) }
[ "func", "(", "conn", "*", "SocksConn", ")", "Reject", "(", ")", "error", "{", "if", "conn", ".", "socksVersion", "==", "socks4Version", "{", "return", "sendSocks4aResponseRejected", "(", "conn", ")", "\n", "}", "\n", "return", "sendSocks5ResponseRejected", "(", "conn", ",", "SocksRepGeneralFailure", ")", "\n", "}" ]
// Send a message to the proxy client that access was rejected or failed. This // sends back a "General Failure" error code. RejectReason should be used if // more specific error reporting is desired.
[ "Send", "a", "message", "to", "the", "proxy", "client", "that", "access", "was", "rejected", "or", "failed", ".", "This", "sends", "back", "a", "General", "Failure", "error", "code", ".", "RejectReason", "should", "be", "used", "if", "more", "specific", "error", "reporting", "is", "desired", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L102-L107
153,288
yinqiwen/gsnova
common/socks/socks.go
RejectReason
func (conn *SocksConn) RejectReason(reason byte) error { if conn.socksVersion == socks4Version { return sendSocks4aResponseRejected(conn) } return sendSocks5ResponseRejected(conn, reason) }
go
func (conn *SocksConn) RejectReason(reason byte) error { if conn.socksVersion == socks4Version { return sendSocks4aResponseRejected(conn) } return sendSocks5ResponseRejected(conn, reason) }
[ "func", "(", "conn", "*", "SocksConn", ")", "RejectReason", "(", "reason", "byte", ")", "error", "{", "if", "conn", ".", "socksVersion", "==", "socks4Version", "{", "return", "sendSocks4aResponseRejected", "(", "conn", ")", "\n", "}", "\n", "return", "sendSocks5ResponseRejected", "(", "conn", ",", "reason", ")", "\n", "}" ]
// Send a message to the proxy client that access was rejected, with the // specific error code indicating the reason behind the rejection. // For SOCKS4a, the reason is ignored.
[ "Send", "a", "message", "to", "the", "proxy", "client", "that", "access", "was", "rejected", "with", "the", "specific", "error", "code", "indicating", "the", "reason", "behind", "the", "rejection", ".", "For", "SOCKS4a", "the", "reason", "is", "ignored", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L112-L117
153,289
yinqiwen/gsnova
common/socks/socks.go
ListenSocks
func ListenSocks(network, laddr string) (*SocksListener, error) { ln, err := net.Listen(network, laddr) if err != nil { return nil, err } return NewSocksListener(ln), nil }
go
func ListenSocks(network, laddr string) (*SocksListener, error) { ln, err := net.Listen(network, laddr) if err != nil { return nil, err } return NewSocksListener(ln), nil }
[ "func", "ListenSocks", "(", "network", ",", "laddr", "string", ")", "(", "*", "SocksListener", ",", "error", ")", "{", "ln", ",", "err", ":=", "net", ".", "Listen", "(", "network", ",", "laddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewSocksListener", "(", "ln", ")", ",", "nil", "\n", "}" ]
// Open a net.Listener according to network and laddr, and return it as a // SocksListener.
[ "Open", "a", "net", ".", "Listener", "according", "to", "network", "and", "laddr", "and", "return", "it", "as", "a", "SocksListener", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L158-L164
153,290
yinqiwen/gsnova
common/socks/socks.go
socks5Handshake
func socks5Handshake(rw *bufio.ReadWriter) (req SocksRequest, err error) { // Negotiate the authentication method. var method byte if method, err = socks5NegotiateAuth(rw); err != nil { return } // Authenticate the client. if err = socks5Authenticate(rw, method, &req); err != nil { return } // Read the command. err = socks5ReadCommand(rw, &req) return }
go
func socks5Handshake(rw *bufio.ReadWriter) (req SocksRequest, err error) { // Negotiate the authentication method. var method byte if method, err = socks5NegotiateAuth(rw); err != nil { return } // Authenticate the client. if err = socks5Authenticate(rw, method, &req); err != nil { return } // Read the command. err = socks5ReadCommand(rw, &req) return }
[ "func", "socks5Handshake", "(", "rw", "*", "bufio", ".", "ReadWriter", ")", "(", "req", "SocksRequest", ",", "err", "error", ")", "{", "// Negotiate the authentication method.", "var", "method", "byte", "\n", "if", "method", ",", "err", "=", "socks5NegotiateAuth", "(", "rw", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Authenticate the client.", "if", "err", "=", "socks5Authenticate", "(", "rw", ",", "method", ",", "&", "req", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "// Read the command.", "err", "=", "socks5ReadCommand", "(", "rw", ",", "&", "req", ")", "\n", "return", "\n", "}" ]
// socks5handshake conducts the SOCKS5 handshake up to the point where the // client command is read and the proxy must open the outgoing connection. // Returns a SocksRequest.
[ "socks5handshake", "conducts", "the", "SOCKS5", "handshake", "up", "to", "the", "point", "where", "the", "client", "command", "is", "read", "and", "the", "proxy", "must", "open", "the", "outgoing", "connection", ".", "Returns", "a", "SocksRequest", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L294-L309
153,291
yinqiwen/gsnova
common/socks/socks.go
socks5NegotiateAuth
func socks5NegotiateAuth(rw *bufio.ReadWriter) (method byte, err error) { // Validate the version. if err = socksReadByteVerify(rw.Reader, "version", socks5Version); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: %s", err.Error()) return } // Read the number of methods. var nmethods byte if nmethods, err = socksReadByte(rw.Reader); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to read nmethods byte: %s", err.Error()) return } // Read the methods. var methods []byte if methods, err = socksReadBytes(rw.Reader, int(nmethods)); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to read methods bytes: %s", err.Error()) return } // Pick the most "suitable" method. method = socksAuthNoAcceptableMethods for _, m := range methods { switch m { case socksAuthNoneRequired: // Pick Username/Password over None if the client happens to // send both. if method == socksAuthNoAcceptableMethods { method = m } case socksAuthUsernamePassword: method = m } } // Send the negotiated method. var msg [2]byte msg[0] = socks5Version msg[1] = method if _, err = rw.Writer.Write(msg[:]); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to write negotiated method: %s", err.Error()) return } if err = socksFlushBuffers(rw); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to flush buffers: %s", err.Error()) return } return }
go
func socks5NegotiateAuth(rw *bufio.ReadWriter) (method byte, err error) { // Validate the version. if err = socksReadByteVerify(rw.Reader, "version", socks5Version); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: %s", err.Error()) return } // Read the number of methods. var nmethods byte if nmethods, err = socksReadByte(rw.Reader); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to read nmethods byte: %s", err.Error()) return } // Read the methods. var methods []byte if methods, err = socksReadBytes(rw.Reader, int(nmethods)); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to read methods bytes: %s", err.Error()) return } // Pick the most "suitable" method. method = socksAuthNoAcceptableMethods for _, m := range methods { switch m { case socksAuthNoneRequired: // Pick Username/Password over None if the client happens to // send both. if method == socksAuthNoAcceptableMethods { method = m } case socksAuthUsernamePassword: method = m } } // Send the negotiated method. var msg [2]byte msg[0] = socks5Version msg[1] = method if _, err = rw.Writer.Write(msg[:]); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to write negotiated method: %s", err.Error()) return } if err = socksFlushBuffers(rw); err != nil { err = newTemporaryNetError("socks5NegotiateAuth: Failed to flush buffers: %s", err.Error()) return } return }
[ "func", "socks5NegotiateAuth", "(", "rw", "*", "bufio", ".", "ReadWriter", ")", "(", "method", "byte", ",", "err", "error", ")", "{", "// Validate the version.", "if", "err", "=", "socksReadByteVerify", "(", "rw", ".", "Reader", ",", "\"", "\"", ",", "socks5Version", ")", ";", "err", "!=", "nil", "{", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "// Read the number of methods.", "var", "nmethods", "byte", "\n", "if", "nmethods", ",", "err", "=", "socksReadByte", "(", "rw", ".", "Reader", ")", ";", "err", "!=", "nil", "{", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "// Read the methods.", "var", "methods", "[", "]", "byte", "\n", "if", "methods", ",", "err", "=", "socksReadBytes", "(", "rw", ".", "Reader", ",", "int", "(", "nmethods", ")", ")", ";", "err", "!=", "nil", "{", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "// Pick the most \"suitable\" method.", "method", "=", "socksAuthNoAcceptableMethods", "\n", "for", "_", ",", "m", ":=", "range", "methods", "{", "switch", "m", "{", "case", "socksAuthNoneRequired", ":", "// Pick Username/Password over None if the client happens to", "// send both.", "if", "method", "==", "socksAuthNoAcceptableMethods", "{", "method", "=", "m", "\n", "}", "\n\n", "case", "socksAuthUsernamePassword", ":", "method", "=", "m", "\n", "}", "\n", "}", "\n\n", "// Send the negotiated method.", "var", "msg", "[", "2", "]", "byte", "\n", "msg", "[", "0", "]", "=", "socks5Version", "\n", "msg", "[", "1", "]", "=", "method", "\n", "if", "_", ",", "err", "=", "rw", ".", "Writer", ".", "Write", "(", "msg", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", "=", "socksFlushBuffers", "(", "rw", ")", ";", "err", "!=", "nil", "{", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "return", "\n", "}" ]
// socks5NegotiateAuth negotiates the authentication method and returns the // selected method as a byte. On negotiation failures an error is returned.
[ "socks5NegotiateAuth", "negotiates", "the", "authentication", "method", "and", "returns", "the", "selected", "method", "as", "a", "byte", ".", "On", "negotiation", "failures", "an", "error", "is", "returned", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L313-L364
153,292
yinqiwen/gsnova
common/socks/socks.go
socks5Authenticate
func socks5Authenticate(rw *bufio.ReadWriter, method byte, req *SocksRequest) (err error) { switch method { case socksAuthNoneRequired: // Straight into reading the connect. case socksAuthUsernamePassword: if err = socks5AuthRFC1929(rw, req); err != nil { return } case socksAuthNoAcceptableMethods: err = newTemporaryNetError("socks5Authenticate: SOCKS method select had no compatible methods") return default: err = newTemporaryNetError("socks5Authenticate: SOCKS method select picked a unsupported method 0x%02x", method) return } if err = socksFlushBuffers(rw); err != nil { err = newTemporaryNetError("socks5Authenticate: Failed to flush buffers: %s", err) return } return }
go
func socks5Authenticate(rw *bufio.ReadWriter, method byte, req *SocksRequest) (err error) { switch method { case socksAuthNoneRequired: // Straight into reading the connect. case socksAuthUsernamePassword: if err = socks5AuthRFC1929(rw, req); err != nil { return } case socksAuthNoAcceptableMethods: err = newTemporaryNetError("socks5Authenticate: SOCKS method select had no compatible methods") return default: err = newTemporaryNetError("socks5Authenticate: SOCKS method select picked a unsupported method 0x%02x", method) return } if err = socksFlushBuffers(rw); err != nil { err = newTemporaryNetError("socks5Authenticate: Failed to flush buffers: %s", err) return } return }
[ "func", "socks5Authenticate", "(", "rw", "*", "bufio", ".", "ReadWriter", ",", "method", "byte", ",", "req", "*", "SocksRequest", ")", "(", "err", "error", ")", "{", "switch", "method", "{", "case", "socksAuthNoneRequired", ":", "// Straight into reading the connect.", "case", "socksAuthUsernamePassword", ":", "if", "err", "=", "socks5AuthRFC1929", "(", "rw", ",", "req", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "case", "socksAuthNoAcceptableMethods", ":", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ")", "\n", "return", "\n\n", "default", ":", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "method", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", "=", "socksFlushBuffers", "(", "rw", ")", ";", "err", "!=", "nil", "{", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "return", "\n", "}" ]
// socks5Authenticate authenticates the client via the chosen authentication // mechanism.
[ "socks5Authenticate", "authenticates", "the", "client", "via", "the", "chosen", "authentication", "mechanism", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L368-L392
153,293
yinqiwen/gsnova
common/socks/socks.go
sendSocks5ResponseRejected
func sendSocks5ResponseRejected(w io.Writer, reason byte) error { return sendSocks5Response(w, reason) }
go
func sendSocks5ResponseRejected(w io.Writer, reason byte) error { return sendSocks5Response(w, reason) }
[ "func", "sendSocks5ResponseRejected", "(", "w", "io", ".", "Writer", ",", "reason", "byte", ")", "error", "{", "return", "sendSocks5Response", "(", "w", ",", "reason", ")", "\n", "}" ]
// Send a SOCKS5 response with the provided failure reason.
[ "Send", "a", "SOCKS5", "response", "with", "the", "provided", "failure", "reason", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L590-L592
153,294
yinqiwen/gsnova
common/socks/socks.go
sendSocks4aResponse
func sendSocks4aResponse(w io.Writer, code byte, addr *net.TCPAddr) error { var resp [8]byte resp[0] = socks4ResponseVersion resp[1] = code resp[2] = byte((addr.Port >> 8) & 0xff) resp[3] = byte((addr.Port >> 0) & 0xff) ipv4 := addr.IP.To4() if ipv4 != nil { resp[4] = ipv4[0] resp[5] = ipv4[1] resp[6] = ipv4[2] resp[7] = ipv4[3] } if _, err := w.Write(resp[:]); err != nil { err = newTemporaryNetError("sendSocks4aResponse: Failed to write response: %s", err.Error()) return err } return nil }
go
func sendSocks4aResponse(w io.Writer, code byte, addr *net.TCPAddr) error { var resp [8]byte resp[0] = socks4ResponseVersion resp[1] = code resp[2] = byte((addr.Port >> 8) & 0xff) resp[3] = byte((addr.Port >> 0) & 0xff) ipv4 := addr.IP.To4() if ipv4 != nil { resp[4] = ipv4[0] resp[5] = ipv4[1] resp[6] = ipv4[2] resp[7] = ipv4[3] } if _, err := w.Write(resp[:]); err != nil { err = newTemporaryNetError("sendSocks4aResponse: Failed to write response: %s", err.Error()) return err } return nil }
[ "func", "sendSocks4aResponse", "(", "w", "io", ".", "Writer", ",", "code", "byte", ",", "addr", "*", "net", ".", "TCPAddr", ")", "error", "{", "var", "resp", "[", "8", "]", "byte", "\n", "resp", "[", "0", "]", "=", "socks4ResponseVersion", "\n", "resp", "[", "1", "]", "=", "code", "\n", "resp", "[", "2", "]", "=", "byte", "(", "(", "addr", ".", "Port", ">>", "8", ")", "&", "0xff", ")", "\n", "resp", "[", "3", "]", "=", "byte", "(", "(", "addr", ".", "Port", ">>", "0", ")", "&", "0xff", ")", "\n", "ipv4", ":=", "addr", ".", "IP", ".", "To4", "(", ")", "\n", "if", "ipv4", "!=", "nil", "{", "resp", "[", "4", "]", "=", "ipv4", "[", "0", "]", "\n", "resp", "[", "5", "]", "=", "ipv4", "[", "1", "]", "\n", "resp", "[", "6", "]", "=", "ipv4", "[", "2", "]", "\n", "resp", "[", "7", "]", "=", "ipv4", "[", "3", "]", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "resp", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "err", "=", "newTemporaryNetError", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Send a SOCKS4a response with the given code and address. If the IP field // inside addr is not an IPv4 address, the IP portion of the response will be // four zero bytes.
[ "Send", "a", "SOCKS4a", "response", "with", "the", "given", "code", "and", "address", ".", "If", "the", "IP", "field", "inside", "addr", "is", "not", "an", "IPv4", "address", "the", "IP", "portion", "of", "the", "response", "will", "be", "four", "zero", "bytes", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L756-L776
153,295
yinqiwen/gsnova
common/socks/socks.go
sendSocks4aResponseGranted
func sendSocks4aResponseGranted(w io.Writer, addr *net.TCPAddr) error { return sendSocks4aResponse(w, socks4RequestGranted, addr) }
go
func sendSocks4aResponseGranted(w io.Writer, addr *net.TCPAddr) error { return sendSocks4aResponse(w, socks4RequestGranted, addr) }
[ "func", "sendSocks4aResponseGranted", "(", "w", "io", ".", "Writer", ",", "addr", "*", "net", ".", "TCPAddr", ")", "error", "{", "return", "sendSocks4aResponse", "(", "w", ",", "socks4RequestGranted", ",", "addr", ")", "\n", "}" ]
// Send a SOCKS4a response code 0x5a.
[ "Send", "a", "SOCKS4a", "response", "code", "0x5a", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/socks.go#L779-L781
153,296
yinqiwen/gsnova
common/socks/args.go
Get
func (args Args) Get(key string) (value string, ok bool) { if args == nil { return "", false } vals, ok := args[key] if !ok || len(vals) == 0 { return "", false } return vals[0], true }
go
func (args Args) Get(key string) (value string, ok bool) { if args == nil { return "", false } vals, ok := args[key] if !ok || len(vals) == 0 { return "", false } return vals[0], true }
[ "func", "(", "args", "Args", ")", "Get", "(", "key", "string", ")", "(", "value", "string", ",", "ok", "bool", ")", "{", "if", "args", "==", "nil", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "vals", ",", "ok", ":=", "args", "[", "key", "]", "\n", "if", "!", "ok", "||", "len", "(", "vals", ")", "==", "0", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "return", "vals", "[", "0", "]", ",", "true", "\n", "}" ]
// Get the first value associated with the given key. If there are any values // associated with the key, the value return has the value and ok is set to // true. If there are no values for the given key, value is "" and ok is false. // If you need access to multiple values, use the map directly.
[ "Get", "the", "first", "value", "associated", "with", "the", "given", "key", ".", "If", "there", "are", "any", "values", "associated", "with", "the", "key", "the", "value", "return", "has", "the", "value", "and", "ok", "is", "set", "to", "true", ".", "If", "there", "are", "no", "values", "for", "the", "given", "key", "value", "is", "and", "ok", "is", "false", ".", "If", "you", "need", "access", "to", "multiple", "values", "use", "the", "map", "directly", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L19-L28
153,297
yinqiwen/gsnova
common/socks/args.go
Add
func (args Args) Add(key, value string) { args[key] = append(args[key], value) }
go
func (args Args) Add(key, value string) { args[key] = append(args[key], value) }
[ "func", "(", "args", "Args", ")", "Add", "(", "key", ",", "value", "string", ")", "{", "args", "[", "key", "]", "=", "append", "(", "args", "[", "key", "]", ",", "value", ")", "\n", "}" ]
// Append value to the list of values for key.
[ "Append", "value", "to", "the", "list", "of", "values", "for", "key", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L31-L33
153,298
yinqiwen/gsnova
common/socks/args.go
indexUnescaped
func indexUnescaped(s string, term []byte) (int, string, error) { var i int unesc := make([]byte, 0) for i = 0; i < len(s); i++ { b := s[i] // A terminator byte? if bytes.IndexByte(term, b) != -1 { break } if b == '\\' { i++ if i >= len(s) { return 0, "", fmt.Errorf("nothing following final escape in %q", s) } b = s[i] } unesc = append(unesc, b) } return i, string(unesc), nil }
go
func indexUnescaped(s string, term []byte) (int, string, error) { var i int unesc := make([]byte, 0) for i = 0; i < len(s); i++ { b := s[i] // A terminator byte? if bytes.IndexByte(term, b) != -1 { break } if b == '\\' { i++ if i >= len(s) { return 0, "", fmt.Errorf("nothing following final escape in %q", s) } b = s[i] } unesc = append(unesc, b) } return i, string(unesc), nil }
[ "func", "indexUnescaped", "(", "s", "string", ",", "term", "[", "]", "byte", ")", "(", "int", ",", "string", ",", "error", ")", "{", "var", "i", "int", "\n", "unesc", ":=", "make", "(", "[", "]", "byte", ",", "0", ")", "\n", "for", "i", "=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "b", ":=", "s", "[", "i", "]", "\n", "// A terminator byte?", "if", "bytes", ".", "IndexByte", "(", "term", ",", "b", ")", "!=", "-", "1", "{", "break", "\n", "}", "\n", "if", "b", "==", "'\\\\'", "{", "i", "++", "\n", "if", "i", ">=", "len", "(", "s", ")", "{", "return", "0", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "b", "=", "s", "[", "i", "]", "\n", "}", "\n", "unesc", "=", "append", "(", "unesc", ",", "b", ")", "\n", "}", "\n", "return", "i", ",", "string", "(", "unesc", ")", ",", "nil", "\n", "}" ]
// Return the index of the next unescaped byte in s that is in the term set, or // else the length of the string if no terminators appear. Additionally return // the unescaped string up to the returned index.
[ "Return", "the", "index", "of", "the", "next", "unescaped", "byte", "in", "s", "that", "is", "in", "the", "term", "set", "or", "else", "the", "length", "of", "the", "string", "if", "no", "terminators", "appear", ".", "Additionally", "return", "the", "unescaped", "string", "up", "to", "the", "returned", "index", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L38-L57
153,299
yinqiwen/gsnova
common/socks/args.go
backslashEscape
func backslashEscape(s string, set []byte) string { var buf bytes.Buffer for _, b := range []byte(s) { if b == '\\' || bytes.IndexByte(set, b) != -1 { buf.WriteByte('\\') } buf.WriteByte(b) } return buf.String() }
go
func backslashEscape(s string, set []byte) string { var buf bytes.Buffer for _, b := range []byte(s) { if b == '\\' || bytes.IndexByte(set, b) != -1 { buf.WriteByte('\\') } buf.WriteByte(b) } return buf.String() }
[ "func", "backslashEscape", "(", "s", "string", ",", "set", "[", "]", "byte", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "b", ":=", "range", "[", "]", "byte", "(", "s", ")", "{", "if", "b", "==", "'\\\\'", "||", "bytes", ".", "IndexByte", "(", "set", ",", "b", ")", "!=", "-", "1", "{", "buf", ".", "WriteByte", "(", "'\\\\'", ")", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "b", ")", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Escape backslashes and all the bytes that are in set.
[ "Escape", "backslashes", "and", "all", "the", "bytes", "that", "are", "in", "set", "." ]
c6d0717839536ff88524feba6123ac37ea5fcf4e
https://github.com/yinqiwen/gsnova/blob/c6d0717839536ff88524feba6123ac37ea5fcf4e/common/socks/args.go#L180-L189