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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
152,000
moonrhythm/session
session.go
Flash
func (s *Session) Flash() *Flash { if s.flash != nil { return s.flash } s.flash = new(Flash) if b, ok := s.Get(flashKey).([]byte); ok { s.flash.decode(b) } return s.flash }
go
func (s *Session) Flash() *Flash { if s.flash != nil { return s.flash } s.flash = new(Flash) if b, ok := s.Get(flashKey).([]byte); ok { s.flash.decode(b) } return s.flash }
[ "func", "(", "s", "*", "Session", ")", "Flash", "(", ")", "*", "Flash", "{", "if", "s", ".", "flash", "!=", "nil", "{", "return", "s", ".", "flash", "\n", "}", "\n\n", "s", ".", "flash", "=", "new", "(", "Flash", ")", "\n", "if", "b", ",", ...
// Flash returns flash from session,
[ "Flash", "returns", "flash", "from", "session" ]
d2c990e98d2125bc454b7903d1f9299e1be6c84d
https://github.com/moonrhythm/session/blob/d2c990e98d2125bc454b7903d1f9299e1be6c84d/session.go#L179-L189
152,001
moonrhythm/session
session.go
Hijacked
func (s *Session) Hijacked() bool { if t, ok := s.Get(destroyedKey).(int64); ok { if t < time.Now().UnixNano()-int64(HijackedTime) { return true } } return false }
go
func (s *Session) Hijacked() bool { if t, ok := s.Get(destroyedKey).(int64); ok { if t < time.Now().UnixNano()-int64(HijackedTime) { return true } } return false }
[ "func", "(", "s", "*", "Session", ")", "Hijacked", "(", ")", "bool", "{", "if", "t", ",", "ok", ":=", "s", ".", "Get", "(", "destroyedKey", ")", ".", "(", "int64", ")", ";", "ok", "{", "if", "t", "<", "time", ".", "Now", "(", ")", ".", "Uni...
// Hijacked checks is session was hijacked
[ "Hijacked", "checks", "is", "session", "was", "hijacked" ]
d2c990e98d2125bc454b7903d1f9299e1be6c84d
https://github.com/moonrhythm/session/blob/d2c990e98d2125bc454b7903d1f9299e1be6c84d/session.go#L192-L199
152,002
moonrhythm/session
session.go
Regenerate
func (s *Session) Regenerate() error { if s.m == nil { return ErrNotPassMiddleware } return s.m.Regenerate(s) }
go
func (s *Session) Regenerate() error { if s.m == nil { return ErrNotPassMiddleware } return s.m.Regenerate(s) }
[ "func", "(", "s", "*", "Session", ")", "Regenerate", "(", ")", "error", "{", "if", "s", ".", "m", "==", "nil", "{", "return", "ErrNotPassMiddleware", "\n", "}", "\n", "return", "s", ".", "m", ".", "Regenerate", "(", "s", ")", "\n", "}" ]
// with scopedManager // Regenerate regenerates session id // use when change user access level to prevent session fixation // // Can use only with middleware
[ "with", "scopedManager", "Regenerate", "regenerates", "session", "id", "use", "when", "change", "user", "access", "level", "to", "prevent", "session", "fixation", "Can", "use", "only", "with", "middleware" ]
d2c990e98d2125bc454b7903d1f9299e1be6c84d
https://github.com/moonrhythm/session/blob/d2c990e98d2125bc454b7903d1f9299e1be6c84d/session.go#L207-L212
152,003
moonrhythm/session
session.go
Renew
func (s *Session) Renew() error { if s.m == nil { return ErrNotPassMiddleware } return s.m.Renew(s) }
go
func (s *Session) Renew() error { if s.m == nil { return ErrNotPassMiddleware } return s.m.Renew(s) }
[ "func", "(", "s", "*", "Session", ")", "Renew", "(", ")", "error", "{", "if", "s", ".", "m", "==", "nil", "{", "return", "ErrNotPassMiddleware", "\n", "}", "\n", "return", "s", ".", "m", ".", "Renew", "(", "s", ")", "\n", "}" ]
// Renew clear all data in current session and regenerate session id // // Can use only with middleware
[ "Renew", "clear", "all", "data", "in", "current", "session", "and", "regenerate", "session", "id", "Can", "use", "only", "with", "middleware" ]
d2c990e98d2125bc454b7903d1f9299e1be6c84d
https://github.com/moonrhythm/session/blob/d2c990e98d2125bc454b7903d1f9299e1be6c84d/session.go#L217-L222
152,004
moonrhythm/session
session.go
Destroy
func (s *Session) Destroy() error { if s.m == nil { return ErrNotPassMiddleware } return s.m.Destroy(s) }
go
func (s *Session) Destroy() error { if s.m == nil { return ErrNotPassMiddleware } return s.m.Destroy(s) }
[ "func", "(", "s", "*", "Session", ")", "Destroy", "(", ")", "error", "{", "if", "s", ".", "m", "==", "nil", "{", "return", "ErrNotPassMiddleware", "\n", "}", "\n", "return", "s", ".", "m", ".", "Destroy", "(", "s", ")", "\n", "}" ]
// Destroy destroys session from store // // Can use only with middleware
[ "Destroy", "destroys", "session", "from", "store", "Can", "use", "only", "with", "middleware" ]
d2c990e98d2125bc454b7903d1f9299e1be6c84d
https://github.com/moonrhythm/session/blob/d2c990e98d2125bc454b7903d1f9299e1be6c84d/session.go#L227-L232
152,005
moonrhythm/session
store/retry/retry.go
New
func New(store session.Store, maxAttempts int) session.Store { if maxAttempts <= 0 { maxAttempts = 3 } return &retryStore{ store: store, maxAttempts: maxAttempts, } }
go
func New(store session.Store, maxAttempts int) session.Store { if maxAttempts <= 0 { maxAttempts = 3 } return &retryStore{ store: store, maxAttempts: maxAttempts, } }
[ "func", "New", "(", "store", "session", ".", "Store", ",", "maxAttempts", "int", ")", "session", ".", "Store", "{", "if", "maxAttempts", "<=", "0", "{", "maxAttempts", "=", "3", "\n", "}", "\n", "return", "&", "retryStore", "{", "store", ":", "store", ...
// New creates new retry store
[ "New", "creates", "new", "retry", "store" ]
d2c990e98d2125bc454b7903d1f9299e1be6c84d
https://github.com/moonrhythm/session/blob/d2c990e98d2125bc454b7903d1f9299e1be6c84d/store/retry/retry.go#L8-L16
152,006
sorcix/irc
stream.go
Dial
func Dial(addr string) (*Conn, error) { c, err := net.Dial("tcp", addr) if err != nil { return nil, err } return NewConn(c), nil }
go
func Dial(addr string) (*Conn, error) { c, err := net.Dial("tcp", addr) if err != nil { return nil, err } return NewConn(c), nil }
[ "func", "Dial", "(", "addr", "string", ")", "(", "*", "Conn", ",", "error", ")", "{", "c", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "addr", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}",...
// Dial connects to the given address using net.Dial and // then returns a new Conn for the connection.
[ "Dial", "connects", "to", "the", "given", "address", "using", "net", ".", "Dial", "and", "then", "returns", "a", "new", "Conn", "for", "the", "connection", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/stream.go#L45-L53
152,007
sorcix/irc
stream.go
Decode
func (dec *Decoder) Decode() (m *Message, err error) { dec.mu.Lock() dec.line, err = dec.reader.ReadString(delim) dec.mu.Unlock() if err != nil { return nil, err } return ParseMessage(dec.line), nil }
go
func (dec *Decoder) Decode() (m *Message, err error) { dec.mu.Lock() dec.line, err = dec.reader.ReadString(delim) dec.mu.Unlock() if err != nil { return nil, err } return ParseMessage(dec.line), nil }
[ "func", "(", "dec", "*", "Decoder", ")", "Decode", "(", ")", "(", "m", "*", "Message", ",", "err", "error", ")", "{", "dec", ".", "mu", ".", "Lock", "(", ")", "\n", "dec", ".", "line", ",", "err", "=", "dec", ".", "reader", ".", "ReadString", ...
// Decode attempts to read a single Message from the stream. // // Returns a non-nil error if the read failed.
[ "Decode", "attempts", "to", "read", "a", "single", "Message", "from", "the", "stream", ".", "Returns", "a", "non", "-", "nil", "error", "if", "the", "read", "failed", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/stream.go#L77-L88
152,008
sorcix/irc
stream.go
Encode
func (enc *Encoder) Encode(m *Message) (err error) { _, err = enc.Write(m.Bytes()) return }
go
func (enc *Encoder) Encode(m *Message) (err error) { _, err = enc.Write(m.Bytes()) return }
[ "func", "(", "enc", "*", "Encoder", ")", "Encode", "(", "m", "*", "Message", ")", "(", "err", "error", ")", "{", "_", ",", "err", "=", "enc", ".", "Write", "(", "m", ".", "Bytes", "(", ")", ")", "\n\n", "return", "\n", "}" ]
// Encode writes the IRC encoding of m to the stream. // // This method may be used from multiple goroutines. // // Returns an non-nil error if the write to the underlying stream stopped early.
[ "Encode", "writes", "the", "IRC", "encoding", "of", "m", "to", "the", "stream", ".", "This", "method", "may", "be", "used", "from", "multiple", "goroutines", ".", "Returns", "an", "non", "-", "nil", "error", "if", "the", "write", "to", "the", "underlying...
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/stream.go#L108-L113
152,009
sorcix/irc
strings_legacy.go
indexByte
func indexByte(s string, c byte) int { for i := range s { if s[i] == c { return i } } return -1 }
go
func indexByte(s string, c byte) int { for i := range s { if s[i] == c { return i } } return -1 }
[ "func", "indexByte", "(", "s", "string", ",", "c", "byte", ")", "int", "{", "for", "i", ":=", "range", "s", "{", "if", "s", "[", "i", "]", "==", "c", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// indexByte implements strings.IndexByte for Go versions < 1.2.
[ "indexByte", "implements", "strings", ".", "IndexByte", "for", "Go", "versions", "<", "1", ".", "2", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/strings_legacy.go#L15-L22
152,010
mc2soft/pq-types
json_text.go
MarshalJSON
func (j JSONText) MarshalJSON() ([]byte, error) { if j == nil { return []byte(`null`), nil } return j, nil }
go
func (j JSONText) MarshalJSON() ([]byte, error) { if j == nil { return []byte(`null`), nil } return j, nil }
[ "func", "(", "j", "JSONText", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "j", "==", "nil", "{", "return", "[", "]", "byte", "(", "`null`", ")", ",", "nil", "\n", "}", "\n", "return", "j", ",", "nil", "\...
// MarshalJSON returns j as the JSON encoding of j.
[ "MarshalJSON", "returns", "j", "as", "the", "JSON", "encoding", "of", "j", "." ]
ada769d4011a027a5385b9c4e47976fe327350a6
https://github.com/mc2soft/pq-types/blob/ada769d4011a027a5385b9c4e47976fe327350a6/json_text.go#L22-L27
152,011
mc2soft/pq-types
int32_array.go
EqualWithoutOrder
func (a Int32Array) EqualWithoutOrder(b Int32Array) bool { if len(a) != len(b) { return false } sort.Sort(a) sort.Sort(b) for i := range a { if a[i] != b[i] { return false } } return true }
go
func (a Int32Array) EqualWithoutOrder(b Int32Array) bool { if len(a) != len(b) { return false } sort.Sort(a) sort.Sort(b) for i := range a { if a[i] != b[i] { return false } } return true }
[ "func", "(", "a", "Int32Array", ")", "EqualWithoutOrder", "(", "b", "Int32Array", ")", "bool", "{", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", "{", "return", "false", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "a", ")", "\n", "sort...
// EqualWithoutOrder returns true if two int32 arrays are equal without order, false otherwise. // It may sort both arrays in-place to do so.
[ "EqualWithoutOrder", "returns", "true", "if", "two", "int32", "arrays", "are", "equal", "without", "order", "false", "otherwise", ".", "It", "may", "sort", "both", "arrays", "in", "-", "place", "to", "do", "so", "." ]
ada769d4011a027a5385b9c4e47976fe327350a6
https://github.com/mc2soft/pq-types/blob/ada769d4011a027a5385b9c4e47976fe327350a6/int32_array.go#L77-L92
152,012
42wim/matterbridge-plus
matterclient/matterclient.go
GetChannels
func (m *MMClient) GetChannels() []*model.Channel { m.RLock() defer m.RUnlock() var channels []*model.Channel // our primary team channels first channels = append(channels, m.Team.Channels.Channels...) for _, t := range m.OtherTeams { if t.Id != m.Team.Id { channels = append(channels, t.Channels.Channels...) } } return channels }
go
func (m *MMClient) GetChannels() []*model.Channel { m.RLock() defer m.RUnlock() var channels []*model.Channel // our primary team channels first channels = append(channels, m.Team.Channels.Channels...) for _, t := range m.OtherTeams { if t.Id != m.Team.Id { channels = append(channels, t.Channels.Channels...) } } return channels }
[ "func", "(", "m", "*", "MMClient", ")", "GetChannels", "(", ")", "[", "]", "*", "model", ".", "Channel", "{", "m", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "RUnlock", "(", ")", "\n", "var", "channels", "[", "]", "*", "model", ".", "Chan...
// GetChannels returns all channels we're members off
[ "GetChannels", "returns", "all", "channels", "we", "re", "members", "off" ]
3e66a675bc939fecf20c4f880ea2f4a03747fcf7
https://github.com/42wim/matterbridge-plus/blob/3e66a675bc939fecf20c4f880ea2f4a03747fcf7/matterclient/matterclient.go#L469-L481
152,013
42wim/matterbridge-plus
matterclient/matterclient.go
GetMoreChannels
func (m *MMClient) GetMoreChannels() []*model.Channel { m.RLock() defer m.RUnlock() var channels []*model.Channel for _, t := range m.OtherTeams { channels = append(channels, t.MoreChannels.Channels...) } return channels }
go
func (m *MMClient) GetMoreChannels() []*model.Channel { m.RLock() defer m.RUnlock() var channels []*model.Channel for _, t := range m.OtherTeams { channels = append(channels, t.MoreChannels.Channels...) } return channels }
[ "func", "(", "m", "*", "MMClient", ")", "GetMoreChannels", "(", ")", "[", "]", "*", "model", ".", "Channel", "{", "m", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "RUnlock", "(", ")", "\n", "var", "channels", "[", "]", "*", "model", ".", "...
// GetMoreChannels returns existing channels where we're not a member off.
[ "GetMoreChannels", "returns", "existing", "channels", "where", "we", "re", "not", "a", "member", "off", "." ]
3e66a675bc939fecf20c4f880ea2f4a03747fcf7
https://github.com/42wim/matterbridge-plus/blob/3e66a675bc939fecf20c4f880ea2f4a03747fcf7/matterclient/matterclient.go#L484-L492
152,014
mc2soft/pq-types
postgis.go
Min
func (p *PostGISPolygon) Min() PostGISPoint { if len(p.Points) != 5 || p.Points[0] != p.Points[4] || p.Points[0].Lon != p.Points[1].Lon || p.Points[0].Lat != p.Points[3].Lat || p.Points[1].Lat != p.Points[2].Lat || p.Points[2].Lon != p.Points[3].Lon { panic("Not an envelope polygon") } return p.Points[0] }
go
func (p *PostGISPolygon) Min() PostGISPoint { if len(p.Points) != 5 || p.Points[0] != p.Points[4] || p.Points[0].Lon != p.Points[1].Lon || p.Points[0].Lat != p.Points[3].Lat || p.Points[1].Lat != p.Points[2].Lat || p.Points[2].Lon != p.Points[3].Lon { panic("Not an envelope polygon") } return p.Points[0] }
[ "func", "(", "p", "*", "PostGISPolygon", ")", "Min", "(", ")", "PostGISPoint", "{", "if", "len", "(", "p", ".", "Points", ")", "!=", "5", "||", "p", ".", "Points", "[", "0", "]", "!=", "p", ".", "Points", "[", "4", "]", "||", "p", ".", "Point...
// Min returns min side of rectangular polygon
[ "Min", "returns", "min", "side", "of", "rectangular", "polygon" ]
ada769d4011a027a5385b9c4e47976fe327350a6
https://github.com/mc2soft/pq-types/blob/ada769d4011a027a5385b9c4e47976fe327350a6/postgis.go#L123-L131
152,015
newrelic/go_nagios
go_nagios.go
Aggregate
func (status *NagiosStatus) Aggregate(otherStatuses []*NagiosStatus) { for _, s := range otherStatuses { if status.Value < s.Value { status.Value = s.Value } status.Message += " - " + s.Message } }
go
func (status *NagiosStatus) Aggregate(otherStatuses []*NagiosStatus) { for _, s := range otherStatuses { if status.Value < s.Value { status.Value = s.Value } status.Message += " - " + s.Message } }
[ "func", "(", "status", "*", "NagiosStatus", ")", "Aggregate", "(", "otherStatuses", "[", "]", "*", "NagiosStatus", ")", "{", "for", "_", ",", "s", ":=", "range", "otherStatuses", "{", "if", "status", ".", "Value", "<", "s", ".", "Value", "{", "status",...
// Take a bunch of NagiosStatus pointers and find the highest value, then // combine all the messages. Things win in the order of highest to lowest.
[ "Take", "a", "bunch", "of", "NagiosStatus", "pointers", "and", "find", "the", "highest", "value", "then", "combine", "all", "the", "messages", ".", "Things", "win", "in", "the", "order", "of", "highest", "to", "lowest", "." ]
a637e544c77892e3a67fcf4a08ddb3d838d3a242
https://github.com/newrelic/go_nagios/blob/a637e544c77892e3a67fcf4a08ddb3d838d3a242/go_nagios.go#L37-L45
152,016
newrelic/go_nagios
go_nagios.go
ExitWithStatus
func ExitWithStatus(status *NagiosStatus) { fmt.Fprintln(os.Stdout, valMessages[status.Value], status.Message) os.Exit(int(status.Value)) }
go
func ExitWithStatus(status *NagiosStatus) { fmt.Fprintln(os.Stdout, valMessages[status.Value], status.Message) os.Exit(int(status.Value)) }
[ "func", "ExitWithStatus", "(", "status", "*", "NagiosStatus", ")", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stdout", ",", "valMessages", "[", "status", ".", "Value", "]", ",", "status", ".", "Message", ")", "\n", "os", ".", "Exit", "(", "int", "...
// Exit with a particular NagiosStatus
[ "Exit", "with", "a", "particular", "NagiosStatus" ]
a637e544c77892e3a67fcf4a08ddb3d838d3a242
https://github.com/newrelic/go_nagios/blob/a637e544c77892e3a67fcf4a08ddb3d838d3a242/go_nagios.go#L68-L71
152,017
sorcix/irc
message.go
ParsePrefix
func ParsePrefix(raw string) (p *Prefix) { p = new(Prefix) user := indexByte(raw, prefixUser) host := indexByte(raw, prefixHost) switch { case user > 0 && host > user: p.Name = raw[:user] p.User = raw[user+1 : host] p.Host = raw[host+1:] case user > 0: p.Name = raw[:user] p.User = raw[user+1:] case host > 0: p.Name = raw[:host] p.Host = raw[host+1:] default: p.Name = raw } return p }
go
func ParsePrefix(raw string) (p *Prefix) { p = new(Prefix) user := indexByte(raw, prefixUser) host := indexByte(raw, prefixHost) switch { case user > 0 && host > user: p.Name = raw[:user] p.User = raw[user+1 : host] p.Host = raw[host+1:] case user > 0: p.Name = raw[:user] p.User = raw[user+1:] case host > 0: p.Name = raw[:host] p.Host = raw[host+1:] default: p.Name = raw } return p }
[ "func", "ParsePrefix", "(", "raw", "string", ")", "(", "p", "*", "Prefix", ")", "{", "p", "=", "new", "(", "Prefix", ")", "\n\n", "user", ":=", "indexByte", "(", "raw", ",", "prefixUser", ")", "\n", "host", ":=", "indexByte", "(", "raw", ",", "pref...
// ParsePrefix takes a string and attempts to create a Prefix struct.
[ "ParsePrefix", "takes", "a", "string", "and", "attempts", "to", "create", "a", "Prefix", "struct", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/message.go#L51-L79
152,018
sorcix/irc
message.go
Len
func (p *Prefix) Len() (length int) { length = len(p.Name) if len(p.User) > 0 { length = length + len(p.User) + 1 } if len(p.Host) > 0 { length = length + len(p.Host) + 1 } return }
go
func (p *Prefix) Len() (length int) { length = len(p.Name) if len(p.User) > 0 { length = length + len(p.User) + 1 } if len(p.Host) > 0 { length = length + len(p.Host) + 1 } return }
[ "func", "(", "p", "*", "Prefix", ")", "Len", "(", ")", "(", "length", "int", ")", "{", "length", "=", "len", "(", "p", ".", "Name", ")", "\n", "if", "len", "(", "p", ".", "User", ")", ">", "0", "{", "length", "=", "length", "+", "len", "(",...
// Len calculates the length of the string representation of this prefix.
[ "Len", "calculates", "the", "length", "of", "the", "string", "representation", "of", "this", "prefix", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/message.go#L82-L91
152,019
sorcix/irc
message.go
String
func (p *Prefix) String() (s string) { // Benchmarks revealed that in this case simple string concatenation // is actually faster than using a ByteBuffer as in (*Message).String() s = p.Name if len(p.User) > 0 { s = s + string(prefixUser) + p.User } if len(p.Host) > 0 { s = s + string(prefixHost) + p.Host } return }
go
func (p *Prefix) String() (s string) { // Benchmarks revealed that in this case simple string concatenation // is actually faster than using a ByteBuffer as in (*Message).String() s = p.Name if len(p.User) > 0 { s = s + string(prefixUser) + p.User } if len(p.Host) > 0 { s = s + string(prefixHost) + p.Host } return }
[ "func", "(", "p", "*", "Prefix", ")", "String", "(", ")", "(", "s", "string", ")", "{", "// Benchmarks revealed that in this case simple string concatenation", "// is actually faster than using a ByteBuffer as in (*Message).String()", "s", "=", "p", ".", "Name", "\n", "if...
// String returns a string representation of this prefix.
[ "String", "returns", "a", "string", "representation", "of", "this", "prefix", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/message.go#L101-L112
152,020
sorcix/irc
message.go
IsHostmask
func (p *Prefix) IsHostmask() bool { return len(p.User) > 0 && len(p.Host) > 0 }
go
func (p *Prefix) IsHostmask() bool { return len(p.User) > 0 && len(p.Host) > 0 }
[ "func", "(", "p", "*", "Prefix", ")", "IsHostmask", "(", ")", "bool", "{", "return", "len", "(", "p", ".", "User", ")", ">", "0", "&&", "len", "(", "p", ".", "Host", ")", ">", "0", "\n", "}" ]
// IsHostmask returns true if this prefix looks like a user hostmask.
[ "IsHostmask", "returns", "true", "if", "this", "prefix", "looks", "like", "a", "user", "hostmask", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/message.go#L115-L117
152,021
sorcix/irc
message.go
IsServer
func (p *Prefix) IsServer() bool { return len(p.User) <= 0 && len(p.Host) <= 0 // && indexByte(p.Name, '.') > 0 }
go
func (p *Prefix) IsServer() bool { return len(p.User) <= 0 && len(p.Host) <= 0 // && indexByte(p.Name, '.') > 0 }
[ "func", "(", "p", "*", "Prefix", ")", "IsServer", "(", ")", "bool", "{", "return", "len", "(", "p", ".", "User", ")", "<=", "0", "&&", "len", "(", "p", ".", "Host", ")", "<=", "0", "// && indexByte(p.Name, '.') > 0", "\n", "}" ]
// IsServer returns true if this prefix looks like a server name.
[ "IsServer", "returns", "true", "if", "this", "prefix", "looks", "like", "a", "server", "name", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/message.go#L120-L122
152,022
sorcix/irc
message.go
ParseMessage
func ParseMessage(raw string) (m *Message) { // Ignore empty messages. if raw = strings.TrimFunc(raw, cutsetFunc); len(raw) < 2 { return nil } i, j := 0, 0 m = new(Message) if raw[0] == prefix { // Prefix ends with a space. i = indexByte(raw, space) // Prefix string must not be empty if the indicator is present. if i < 2 { return nil } m.Prefix = ParsePrefix(raw[1:i]) // Skip space at the end of the prefix i++ } // Find end of command j = i + indexByte(raw[i:], space) // Extract command if j > i { m.Command = strings.ToUpper(raw[i:j]) } else { m.Command = strings.ToUpper(raw[i:]) // We're done here! return m } // Skip space after command j++ // Find prefix for trailer i = indexByte(raw[j:], prefix) if i < 0 || raw[j+i-1] != space { // There is no trailing argument! m.Params = strings.Split(raw[j:], string(space)) // We're done here! return m } // Compensate for index on substring i = i + j // Check if we need to parse arguments. if i > j { m.Params = strings.Split(raw[j:i-1], string(space)) } m.Trailing = raw[i+1:] // We need to re-encode the trailing argument even if it was empty. if len(m.Trailing) <= 0 { m.EmptyTrailing = true } return m }
go
func ParseMessage(raw string) (m *Message) { // Ignore empty messages. if raw = strings.TrimFunc(raw, cutsetFunc); len(raw) < 2 { return nil } i, j := 0, 0 m = new(Message) if raw[0] == prefix { // Prefix ends with a space. i = indexByte(raw, space) // Prefix string must not be empty if the indicator is present. if i < 2 { return nil } m.Prefix = ParsePrefix(raw[1:i]) // Skip space at the end of the prefix i++ } // Find end of command j = i + indexByte(raw[i:], space) // Extract command if j > i { m.Command = strings.ToUpper(raw[i:j]) } else { m.Command = strings.ToUpper(raw[i:]) // We're done here! return m } // Skip space after command j++ // Find prefix for trailer i = indexByte(raw[j:], prefix) if i < 0 || raw[j+i-1] != space { // There is no trailing argument! m.Params = strings.Split(raw[j:], string(space)) // We're done here! return m } // Compensate for index on substring i = i + j // Check if we need to parse arguments. if i > j { m.Params = strings.Split(raw[j:i-1], string(space)) } m.Trailing = raw[i+1:] // We need to re-encode the trailing argument even if it was empty. if len(m.Trailing) <= 0 { m.EmptyTrailing = true } return m }
[ "func", "ParseMessage", "(", "raw", "string", ")", "(", "m", "*", "Message", ")", "{", "// Ignore empty messages.", "if", "raw", "=", "strings", ".", "TrimFunc", "(", "raw", ",", "cutsetFunc", ")", ";", "len", "(", "raw", ")", "<", "2", "{", "return", ...
// ParseMessage takes a string and attempts to create a Message struct. // Returns nil if the Message is invalid.
[ "ParseMessage", "takes", "a", "string", "and", "attempts", "to", "create", "a", "Message", "struct", ".", "Returns", "nil", "if", "the", "Message", "is", "invalid", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/message.go#L165-L237
152,023
sorcix/irc
message.go
Len
func (m *Message) Len() (length int) { if m.Prefix != nil { length = m.Prefix.Len() + 2 // Include prefix and trailing space } length = length + len(m.Command) if len(m.Params) > 0 { length = length + len(m.Params) for _, param := range m.Params { length = length + len(param) } } if len(m.Trailing) > 0 || m.EmptyTrailing { length = length + len(m.Trailing) + 2 // Include prefix and space } return }
go
func (m *Message) Len() (length int) { if m.Prefix != nil { length = m.Prefix.Len() + 2 // Include prefix and trailing space } length = length + len(m.Command) if len(m.Params) > 0 { length = length + len(m.Params) for _, param := range m.Params { length = length + len(param) } } if len(m.Trailing) > 0 || m.EmptyTrailing { length = length + len(m.Trailing) + 2 // Include prefix and space } return }
[ "func", "(", "m", "*", "Message", ")", "Len", "(", ")", "(", "length", "int", ")", "{", "if", "m", ".", "Prefix", "!=", "nil", "{", "length", "=", "m", ".", "Prefix", ".", "Len", "(", ")", "+", "2", "// Include prefix and trailing space", "\n", "}"...
// Len calculates the length of the string representation of this message.
[ "Len", "calculates", "the", "length", "of", "the", "string", "representation", "of", "this", "message", "." ]
4c48692d6b6bca19faeab633f846e9d0f9d6f4c2
https://github.com/sorcix/irc/blob/4c48692d6b6bca19faeab633f846e9d0f9d6f4c2/message.go#L240-L260
152,024
moonrhythm/session
store/memory/memory.go
New
func New(config Config) session.Store { s := &memoryStore{ gcInterval: config.GCInterval, l: make(map[interface{}]*item), } if s.gcInterval > 0 { time.AfterFunc(s.gcInterval, s.gcWorker) } return s }
go
func New(config Config) session.Store { s := &memoryStore{ gcInterval: config.GCInterval, l: make(map[interface{}]*item), } if s.gcInterval > 0 { time.AfterFunc(s.gcInterval, s.gcWorker) } return s }
[ "func", "New", "(", "config", "Config", ")", "session", ".", "Store", "{", "s", ":=", "&", "memoryStore", "{", "gcInterval", ":", "config", ".", "GCInterval", ",", "l", ":", "make", "(", "map", "[", "interface", "{", "}", "]", "*", "item", ")", ","...
// New creates new memory store
[ "New", "creates", "new", "memory", "store" ]
d2c990e98d2125bc454b7903d1f9299e1be6c84d
https://github.com/moonrhythm/session/blob/d2c990e98d2125bc454b7903d1f9299e1be6c84d/store/memory/memory.go#L18-L27
152,025
lafriks/xormstore
util/time_stamp.go
AddDuration
func (ts TimeStamp) AddDuration(interval time.Duration) TimeStamp { return ts + TimeStamp(interval/time.Second) }
go
func (ts TimeStamp) AddDuration(interval time.Duration) TimeStamp { return ts + TimeStamp(interval/time.Second) }
[ "func", "(", "ts", "TimeStamp", ")", "AddDuration", "(", "interval", "time", ".", "Duration", ")", "TimeStamp", "{", "return", "ts", "+", "TimeStamp", "(", "interval", "/", "time", ".", "Second", ")", "\n", "}" ]
// AddDuration adds time.Duration and return sum
[ "AddDuration", "adds", "time", ".", "Duration", "and", "return", "sum" ]
9cab149ea91875cf056211bd6ef82379fce9cb67
https://github.com/lafriks/xormstore/blob/9cab149ea91875cf056211bd6ef82379fce9cb67/util/time_stamp.go#L21-L23
152,026
lafriks/xormstore
util/time_stamp.go
AsTime
func (ts TimeStamp) AsTime() (tm time.Time) { tm = time.Unix(int64(ts), 0).Local() return }
go
func (ts TimeStamp) AsTime() (tm time.Time) { tm = time.Unix(int64(ts), 0).Local() return }
[ "func", "(", "ts", "TimeStamp", ")", "AsTime", "(", ")", "(", "tm", "time", ".", "Time", ")", "{", "tm", "=", "time", ".", "Unix", "(", "int64", "(", "ts", ")", ",", "0", ")", ".", "Local", "(", ")", "\n", "return", "\n", "}" ]
// AsTime convert timestamp as time.Time in Local locale
[ "AsTime", "convert", "timestamp", "as", "time", ".", "Time", "in", "Local", "locale" ]
9cab149ea91875cf056211bd6ef82379fce9cb67
https://github.com/lafriks/xormstore/blob/9cab149ea91875cf056211bd6ef82379fce9cb67/util/time_stamp.go#L31-L34
152,027
lafriks/xormstore
util/time_stamp.go
Format
func (ts TimeStamp) Format(f string) string { return ts.AsTime().Format(f) }
go
func (ts TimeStamp) Format(f string) string { return ts.AsTime().Format(f) }
[ "func", "(", "ts", "TimeStamp", ")", "Format", "(", "f", "string", ")", "string", "{", "return", "ts", ".", "AsTime", "(", ")", ".", "Format", "(", "f", ")", "\n", "}" ]
// Format formats timestamp as
[ "Format", "formats", "timestamp", "as" ]
9cab149ea91875cf056211bd6ef82379fce9cb67
https://github.com/lafriks/xormstore/blob/9cab149ea91875cf056211bd6ef82379fce9cb67/util/time_stamp.go#L43-L45
152,028
lafriks/xormstore
xormstore.go
New
func New(e *xorm.Engine, keyPairs ...[]byte) (*Store, error) { return NewOptions(e, Options{}, keyPairs...) }
go
func New(e *xorm.Engine, keyPairs ...[]byte) (*Store, error) { return NewOptions(e, Options{}, keyPairs...) }
[ "func", "New", "(", "e", "*", "xorm", ".", "Engine", ",", "keyPairs", "...", "[", "]", "byte", ")", "(", "*", "Store", ",", "error", ")", "{", "return", "NewOptions", "(", "e", ",", "Options", "{", "}", ",", "keyPairs", "...", ")", "\n", "}" ]
// New creates a new xormstore session
[ "New", "creates", "a", "new", "xormstore", "session" ]
9cab149ea91875cf056211bd6ef82379fce9cb67
https://github.com/lafriks/xormstore/blob/9cab149ea91875cf056211bd6ef82379fce9cb67/xormstore.go#L90-L92
152,029
lafriks/xormstore
xormstore.go
NewOptions
func NewOptions(e *xorm.Engine, opts Options, keyPairs ...[]byte) (*Store, error) { st := &Store{ e: e, opts: opts, Codecs: securecookie.CodecsFromPairs(keyPairs...), SessionOpts: &sessions.Options{ Path: defaultPath, MaxAge: defaultMaxAge, }, } if st.opts.TableName == "" { st.opts.TableName = defaultTableName } if !st.opts.SkipCreateTable { if err := st.e.Sync2(&xormSession{tableName: st.opts.TableName}); err != nil { return nil, err } } return st, nil }
go
func NewOptions(e *xorm.Engine, opts Options, keyPairs ...[]byte) (*Store, error) { st := &Store{ e: e, opts: opts, Codecs: securecookie.CodecsFromPairs(keyPairs...), SessionOpts: &sessions.Options{ Path: defaultPath, MaxAge: defaultMaxAge, }, } if st.opts.TableName == "" { st.opts.TableName = defaultTableName } if !st.opts.SkipCreateTable { if err := st.e.Sync2(&xormSession{tableName: st.opts.TableName}); err != nil { return nil, err } } return st, nil }
[ "func", "NewOptions", "(", "e", "*", "xorm", ".", "Engine", ",", "opts", "Options", ",", "keyPairs", "...", "[", "]", "byte", ")", "(", "*", "Store", ",", "error", ")", "{", "st", ":=", "&", "Store", "{", "e", ":", "e", ",", "opts", ":", "opts"...
// NewOptions creates a new xormstore session with options
[ "NewOptions", "creates", "a", "new", "xormstore", "session", "with", "options" ]
9cab149ea91875cf056211bd6ef82379fce9cb67
https://github.com/lafriks/xormstore/blob/9cab149ea91875cf056211bd6ef82379fce9cb67/xormstore.go#L95-L116
152,030
vmware/govcloudair
api.go
NewRequest
func (c *Client) NewRequest(params map[string]string, method string, u url.URL, body io.Reader) *http.Request { p := url.Values{} // Build up our request parameters for k, v := range params { p.Add(k, v) } // Add the params to our URL u.RawQuery = p.Encode() // Build the request, no point in checking for errors here as we're just // passing a string version of an url.URL struct and http.NewRequest returns // error only if can't process an url.ParseRequestURI(). req, _ := http.NewRequest(method, u.String(), body) if c.VCDAuthHeader != "" && c.VCDToken != "" { // Add the authorization header req.Header.Add(c.VCDAuthHeader, c.VCDToken) // Add the Accept header for VCD req.Header.Add("Accept", "application/*+xml;version="+c.APIVersion) } return req }
go
func (c *Client) NewRequest(params map[string]string, method string, u url.URL, body io.Reader) *http.Request { p := url.Values{} // Build up our request parameters for k, v := range params { p.Add(k, v) } // Add the params to our URL u.RawQuery = p.Encode() // Build the request, no point in checking for errors here as we're just // passing a string version of an url.URL struct and http.NewRequest returns // error only if can't process an url.ParseRequestURI(). req, _ := http.NewRequest(method, u.String(), body) if c.VCDAuthHeader != "" && c.VCDToken != "" { // Add the authorization header req.Header.Add(c.VCDAuthHeader, c.VCDToken) // Add the Accept header for VCD req.Header.Add("Accept", "application/*+xml;version="+c.APIVersion) } return req }
[ "func", "(", "c", "*", "Client", ")", "NewRequest", "(", "params", "map", "[", "string", "]", "string", ",", "method", "string", ",", "u", "url", ".", "URL", ",", "body", "io", ".", "Reader", ")", "*", "http", ".", "Request", "{", "p", ":=", "url...
// NewRequest creates a new HTTP request and applies necessary auth headers if // set.
[ "NewRequest", "creates", "a", "new", "HTTP", "request", "and", "applies", "necessary", "auth", "headers", "if", "set", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api.go#L30-L56
152,031
vmware/govcloudair
api.go
parseErr
func parseErr(resp *http.Response) error { errBody := new(types.Error) // if there was an error decoding the body, just return that if err := decodeBody(resp, errBody); err != nil { return fmt.Errorf("error parsing error body for non-200 request: %s", err) } return fmt.Errorf("API Error: %d: %s", errBody.MajorErrorCode, errBody.Message) }
go
func parseErr(resp *http.Response) error { errBody := new(types.Error) // if there was an error decoding the body, just return that if err := decodeBody(resp, errBody); err != nil { return fmt.Errorf("error parsing error body for non-200 request: %s", err) } return fmt.Errorf("API Error: %d: %s", errBody.MajorErrorCode, errBody.Message) }
[ "func", "parseErr", "(", "resp", "*", "http", ".", "Response", ")", "error", "{", "errBody", ":=", "new", "(", "types", ".", "Error", ")", "\n\n", "// if there was an error decoding the body, just return that", "if", "err", ":=", "decodeBody", "(", "resp", ",", ...
// parseErr takes an error XML resp and returns a single string for use in error messages.
[ "parseErr", "takes", "an", "error", "XML", "resp", "and", "returns", "a", "single", "string", "for", "use", "in", "error", "messages", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api.go#L59-L69
152,032
vmware/govcloudair
api.go
decodeBody
func decodeBody(resp *http.Response, out interface{}) error { body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } // Unmarshal the XML. if err = xml.Unmarshal(body, &out); err != nil { return err } return nil }
go
func decodeBody(resp *http.Response, out interface{}) error { body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } // Unmarshal the XML. if err = xml.Unmarshal(body, &out); err != nil { return err } return nil }
[ "func", "decodeBody", "(", "resp", "*", "http", ".", "Response", ",", "out", "interface", "{", "}", ")", "error", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return",...
// decodeBody is used to XML decode a response body
[ "decodeBody", "is", "used", "to", "XML", "decode", "a", "response", "body" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api.go#L72-L85
152,033
vmware/govcloudair
api_vca.go
NewVAClient
func NewVAClient() (*VAClient, error) { var u *url.URL var err error if os.Getenv("VCLOUDAIR_ENDPOINT") != "" { u, err = url.ParseRequestURI(os.Getenv("VCLOUDAIR_ENDPOINT")) if err != nil { return &VAClient{}, fmt.Errorf("cannot parse endpoint coming from VCLOUDAIR_ENDPOINT") } } else { // Implicitly trust this URL parse. u, _ = url.ParseRequestURI("https://vchs.vmware.com/api") } VAClient := VAClient{ VAEndpoint: *u, Client: Client{ APIVersion: "5.6", // Patching things up as we're hitting several TLS timeouts. Http: http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSHandshakeTimeout: 120 * time.Second, }, }, }, } return &VAClient, nil }
go
func NewVAClient() (*VAClient, error) { var u *url.URL var err error if os.Getenv("VCLOUDAIR_ENDPOINT") != "" { u, err = url.ParseRequestURI(os.Getenv("VCLOUDAIR_ENDPOINT")) if err != nil { return &VAClient{}, fmt.Errorf("cannot parse endpoint coming from VCLOUDAIR_ENDPOINT") } } else { // Implicitly trust this URL parse. u, _ = url.ParseRequestURI("https://vchs.vmware.com/api") } VAClient := VAClient{ VAEndpoint: *u, Client: Client{ APIVersion: "5.6", // Patching things up as we're hitting several TLS timeouts. Http: http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSHandshakeTimeout: 120 * time.Second, }, }, }, } return &VAClient, nil }
[ "func", "NewVAClient", "(", ")", "(", "*", "VAClient", ",", "error", ")", "{", "var", "u", "*", "url", ".", "URL", "\n", "var", "err", "error", "\n\n", "if", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "u", ",", "err", "...
// NewVAClient returns a new empty client to authenticate against the vCloud Air // service, the vCloud Air endpoint can be overridden by setting the // VCLOUDAIR_ENDPOINT environment variable.
[ "NewVAClient", "returns", "a", "new", "empty", "client", "to", "authenticate", "against", "the", "vCloud", "Air", "service", "the", "vCloud", "Air", "endpoint", "can", "be", "overridden", "by", "setting", "the", "VCLOUDAIR_ENDPOINT", "environment", "variable", "."...
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api_vca.go#L236-L265
152,034
vmware/govcloudair
api_vca.go
Authenticate
func (c *VAClient) Authenticate(username, password, computeid, vdcid string) (Vdc, error) { // Authorize vaservicehref, err := c.vaauthorize(username, password) if err != nil { return Vdc{}, fmt.Errorf("error Authorizing: %s", err) } // Get Service vacomputehref, err := c.vaacquireservice(vaservicehref, computeid) if err != nil { return Vdc{}, fmt.Errorf("error Acquiring Service: %s", err) } // Get Compute vavdchref, err := c.vaacquirecompute(vacomputehref, vdcid) if err != nil { return Vdc{}, fmt.Errorf("error Acquiring Compute: %s", err) } // Get Backend Authorization if err = c.vagetbackendauth(vavdchref, computeid); err != nil { return Vdc{}, fmt.Errorf("error Acquiring Backend Authorization: %s", err) } v, err := c.Client.retrieveVDC() if err != nil { return Vdc{}, fmt.Errorf("error Acquiring VDC: %s", err) } return v, nil }
go
func (c *VAClient) Authenticate(username, password, computeid, vdcid string) (Vdc, error) { // Authorize vaservicehref, err := c.vaauthorize(username, password) if err != nil { return Vdc{}, fmt.Errorf("error Authorizing: %s", err) } // Get Service vacomputehref, err := c.vaacquireservice(vaservicehref, computeid) if err != nil { return Vdc{}, fmt.Errorf("error Acquiring Service: %s", err) } // Get Compute vavdchref, err := c.vaacquirecompute(vacomputehref, vdcid) if err != nil { return Vdc{}, fmt.Errorf("error Acquiring Compute: %s", err) } // Get Backend Authorization if err = c.vagetbackendauth(vavdchref, computeid); err != nil { return Vdc{}, fmt.Errorf("error Acquiring Backend Authorization: %s", err) } v, err := c.Client.retrieveVDC() if err != nil { return Vdc{}, fmt.Errorf("error Acquiring VDC: %s", err) } return v, nil }
[ "func", "(", "c", "*", "VAClient", ")", "Authenticate", "(", "username", ",", "password", ",", "computeid", ",", "vdcid", "string", ")", "(", "Vdc", ",", "error", ")", "{", "// Authorize", "vaservicehref", ",", "err", ":=", "c", ".", "vaauthorize", "(", ...
// Authenticate is an helper function that performs a complete login in vCloud // Air and in the backend vCloud Director instance.
[ "Authenticate", "is", "an", "helper", "function", "that", "performs", "a", "complete", "login", "in", "vCloud", "Air", "and", "in", "the", "backend", "vCloud", "Director", "instance", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api_vca.go#L269-L300
152,035
vmware/govcloudair
api_vca.go
Disconnect
func (c *VAClient) Disconnect() error { if c.Client.VCDToken == "" && c.Client.VCDAuthHeader == "" && c.VAToken == "" { return fmt.Errorf("cannot disconnect, client is not authenticated") } s := c.VAEndpoint s.Path += "/vchs/session" req := c.Client.NewRequest(map[string]string{}, "DELETE", s, nil) // Add the Accept header for vCA req.Header.Add("Accept", "application/xml;version=5.6") // Set Authorization Header req.Header.Add("x-vchs-authorization", c.VAToken) if _, err := checkResp(c.Client.Http.Do(req)); err != nil { return fmt.Errorf("error processing session delete for vchs: %s", err) } return nil }
go
func (c *VAClient) Disconnect() error { if c.Client.VCDToken == "" && c.Client.VCDAuthHeader == "" && c.VAToken == "" { return fmt.Errorf("cannot disconnect, client is not authenticated") } s := c.VAEndpoint s.Path += "/vchs/session" req := c.Client.NewRequest(map[string]string{}, "DELETE", s, nil) // Add the Accept header for vCA req.Header.Add("Accept", "application/xml;version=5.6") // Set Authorization Header req.Header.Add("x-vchs-authorization", c.VAToken) if _, err := checkResp(c.Client.Http.Do(req)); err != nil { return fmt.Errorf("error processing session delete for vchs: %s", err) } return nil }
[ "func", "(", "c", "*", "VAClient", ")", "Disconnect", "(", ")", "error", "{", "if", "c", ".", "Client", ".", "VCDToken", "==", "\"", "\"", "&&", "c", ".", "Client", ".", "VCDAuthHeader", "==", "\"", "\"", "&&", "c", ".", "VAToken", "==", "\"", "\...
// Disconnect performs a disconnection from the vCloud Air API endpoint.
[ "Disconnect", "performs", "a", "disconnection", "from", "the", "vCloud", "Air", "API", "endpoint", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api_vca.go#L303-L324
152,036
vmware/govcloudair
types/v56/link.go
Find
func (l LinkList) Find(predicate LinkPredicate) *Link { for _, lnk := range l { if predicate(lnk) { return lnk } } return nil }
go
func (l LinkList) Find(predicate LinkPredicate) *Link { for _, lnk := range l { if predicate(lnk) { return lnk } } return nil }
[ "func", "(", "l", "LinkList", ")", "Find", "(", "predicate", "LinkPredicate", ")", "*", "Link", "{", "for", "_", ",", "lnk", ":=", "range", "l", "{", "if", "predicate", "(", "lnk", ")", "{", "return", "lnk", "\n", "}", "\n", "}", "\n", "return", ...
// Find the first occurrence that matches the predicate
[ "Find", "the", "first", "occurrence", "that", "matches", "the", "predicate" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/types/v56/link.go#L26-L33
152,037
vmware/govcloudair
types/v56/link.go
ForType
func (l LinkList) ForType(tpe, rel string) *Link { return l.Find(byTypeAndRel(tpe, rel)) }
go
func (l LinkList) ForType(tpe, rel string) *Link { return l.Find(byTypeAndRel(tpe, rel)) }
[ "func", "(", "l", "LinkList", ")", "ForType", "(", "tpe", ",", "rel", "string", ")", "*", "Link", "{", "return", "l", ".", "Find", "(", "byTypeAndRel", "(", "tpe", ",", "rel", ")", ")", "\n", "}" ]
// ForType finds a link for a given type
[ "ForType", "finds", "a", "link", "for", "a", "given", "type" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/types/v56/link.go#L36-L38
152,038
vmware/govcloudair
types/v56/link.go
ForName
func (l LinkList) ForName(name, tpe, rel string) *Link { return l.Find(byNameTypeAndRel(name, tpe, rel)) }
go
func (l LinkList) ForName(name, tpe, rel string) *Link { return l.Find(byNameTypeAndRel(name, tpe, rel)) }
[ "func", "(", "l", "LinkList", ")", "ForName", "(", "name", ",", "tpe", ",", "rel", "string", ")", "*", "Link", "{", "return", "l", ".", "Find", "(", "byNameTypeAndRel", "(", "name", ",", "tpe", ",", "rel", ")", ")", "\n", "}" ]
// ForName finds a link for a given name and type
[ "ForName", "finds", "a", "link", "for", "a", "given", "name", "and", "type" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/types/v56/link.go#L41-L43
152,039
tumblr/tumblrclient.go
client.go
NewClient
func NewClient(consumerKey string, consumerSecret string) *Client { c := Client{} c.SetConsumer(consumerKey, consumerSecret) return &c }
go
func NewClient(consumerKey string, consumerSecret string) *Client { c := Client{} c.SetConsumer(consumerKey, consumerSecret) return &c }
[ "func", "NewClient", "(", "consumerKey", "string", ",", "consumerSecret", "string", ")", "*", "Client", "{", "c", ":=", "Client", "{", "}", "\n", "c", ".", "SetConsumer", "(", "consumerKey", ",", "consumerSecret", ")", "\n", "return", "&", "c", "\n", "}"...
// Constructor with only the consumer key and secret
[ "Constructor", "with", "only", "the", "consumer", "key", "and", "secret" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L25-L29
152,040
tumblr/tumblrclient.go
client.go
SetConsumer
func (c *Client) SetConsumer(consumerKey string, consumerSecret string) { c.consumer = oauth1.NewConfig(consumerKey, consumerSecret) c.client = nil }
go
func (c *Client) SetConsumer(consumerKey string, consumerSecret string) { c.consumer = oauth1.NewConfig(consumerKey, consumerSecret) c.client = nil }
[ "func", "(", "c", "*", "Client", ")", "SetConsumer", "(", "consumerKey", "string", ",", "consumerSecret", "string", ")", "{", "c", ".", "consumer", "=", "oauth1", ".", "NewConfig", "(", "consumerKey", ",", "consumerSecret", ")", "\n", "c", ".", "client", ...
// Set consumer credentials, invalidates any previously cached client
[ "Set", "consumer", "credentials", "invalidates", "any", "previously", "cached", "client" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L39-L42
152,041
tumblr/tumblrclient.go
client.go
SetToken
func (c *Client) SetToken(token string, tokenSecret string) { c.user = oauth1.NewToken(token, tokenSecret) c.client = nil }
go
func (c *Client) SetToken(token string, tokenSecret string) { c.user = oauth1.NewToken(token, tokenSecret) c.client = nil }
[ "func", "(", "c", "*", "Client", ")", "SetToken", "(", "token", "string", ",", "tokenSecret", "string", ")", "{", "c", ".", "user", "=", "oauth1", ".", "NewToken", "(", "token", ",", "tokenSecret", ")", "\n", "c", ".", "client", "=", "nil", "\n", "...
// Set user credentials, invalidates any previously cached client
[ "Set", "user", "credentials", "invalidates", "any", "previously", "cached", "client" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L45-L48
152,042
tumblr/tumblrclient.go
client.go
Get
func (c *Client) Get(endpoint string) (tumblr.Response, error) { return c.GetWithParams(endpoint, url.Values{}) }
go
func (c *Client) Get(endpoint string) (tumblr.Response, error) { return c.GetWithParams(endpoint, url.Values{}) }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "endpoint", "string", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "return", "c", ".", "GetWithParams", "(", "endpoint", ",", "url", ".", "Values", "{", "}", ")", "\n", "}" ]
// Issue GET request to Tumblr API
[ "Issue", "GET", "request", "to", "Tumblr", "API" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L51-L53
152,043
tumblr/tumblrclient.go
client.go
GetWithParams
func (c *Client) GetWithParams(endpoint string, params url.Values) (tumblr.Response, error) { return getResponse(c.GetHttpClient().Get(createRequestURI(appendPath(apiBase, endpoint), params))) }
go
func (c *Client) GetWithParams(endpoint string, params url.Values) (tumblr.Response, error) { return getResponse(c.GetHttpClient().Get(createRequestURI(appendPath(apiBase, endpoint), params))) }
[ "func", "(", "c", "*", "Client", ")", "GetWithParams", "(", "endpoint", "string", ",", "params", "url", ".", "Values", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "return", "getResponse", "(", "c", ".", "GetHttpClient", "(", ")", ".", ...
// Issue GET request to Tumblr API with param values
[ "Issue", "GET", "request", "to", "Tumblr", "API", "with", "param", "values" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L56-L58
152,044
tumblr/tumblrclient.go
client.go
Post
func (c *Client) Post(endpoint string) (tumblr.Response, error) { return c.PostWithParams(endpoint, url.Values{}) }
go
func (c *Client) Post(endpoint string) (tumblr.Response, error) { return c.PostWithParams(endpoint, url.Values{}) }
[ "func", "(", "c", "*", "Client", ")", "Post", "(", "endpoint", "string", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "return", "c", ".", "PostWithParams", "(", "endpoint", ",", "url", ".", "Values", "{", "}", ")", "\n", "}" ]
// Issue POST request to Tumblr API
[ "Issue", "POST", "request", "to", "Tumblr", "API" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L61-L63
152,045
tumblr/tumblrclient.go
client.go
PostWithParams
func (c *Client) PostWithParams(endpoint string, params url.Values) (tumblr.Response, error) { return getResponse(c.GetHttpClient().PostForm(appendPath(apiBase, endpoint), params)) }
go
func (c *Client) PostWithParams(endpoint string, params url.Values) (tumblr.Response, error) { return getResponse(c.GetHttpClient().PostForm(appendPath(apiBase, endpoint), params)) }
[ "func", "(", "c", "*", "Client", ")", "PostWithParams", "(", "endpoint", "string", ",", "params", "url", ".", "Values", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "return", "getResponse", "(", "c", ".", "GetHttpClient", "(", ")", ".",...
// Issue POST request to Tumblr API with param values
[ "Issue", "POST", "request", "to", "Tumblr", "API", "with", "param", "values" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L66-L68
152,046
tumblr/tumblrclient.go
client.go
Put
func (c *Client) Put(endpoint string) (tumblr.Response, error) { return c.PutWithParams(endpoint, url.Values{}) }
go
func (c *Client) Put(endpoint string) (tumblr.Response, error) { return c.PutWithParams(endpoint, url.Values{}) }
[ "func", "(", "c", "*", "Client", ")", "Put", "(", "endpoint", "string", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "return", "c", ".", "PutWithParams", "(", "endpoint", ",", "url", ".", "Values", "{", "}", ")", "\n", "}" ]
// Issue PUT request to Tumblr API
[ "Issue", "PUT", "request", "to", "Tumblr", "API" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L71-L73
152,047
tumblr/tumblrclient.go
client.go
Delete
func (c *Client) Delete(endpoint string) (tumblr.Response, error) { return c.DeleteWithParams(endpoint, url.Values{}) }
go
func (c *Client) Delete(endpoint string) (tumblr.Response, error) { return c.DeleteWithParams(endpoint, url.Values{}) }
[ "func", "(", "c", "*", "Client", ")", "Delete", "(", "endpoint", "string", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "return", "c", ".", "DeleteWithParams", "(", "endpoint", ",", "url", ".", "Values", "{", "}", ")", "\n", "}" ]
// Issue DELETE request to Tumblr API
[ "Issue", "DELETE", "request", "to", "Tumblr", "API" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L85-L87
152,048
tumblr/tumblrclient.go
client.go
DeleteWithParams
func (c *Client) DeleteWithParams(endpoint string, params url.Values) (tumblr.Response, error) { req, err := http.NewRequest("DELETE", createRequestURI(appendPath(apiBase, endpoint), params), strings.NewReader("")) if err == nil { return getResponse(c.GetHttpClient().Do(req)) } return tumblr.Response{}, err }
go
func (c *Client) DeleteWithParams(endpoint string, params url.Values) (tumblr.Response, error) { req, err := http.NewRequest("DELETE", createRequestURI(appendPath(apiBase, endpoint), params), strings.NewReader("")) if err == nil { return getResponse(c.GetHttpClient().Do(req)) } return tumblr.Response{}, err }
[ "func", "(", "c", "*", "Client", ")", "DeleteWithParams", "(", "endpoint", "string", ",", "params", "url", ".", "Values", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\""...
// Issue DELETE request to Tumblr API with param values
[ "Issue", "DELETE", "request", "to", "Tumblr", "API", "with", "param", "values" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L90-L96
152,049
tumblr/tumblrclient.go
client.go
GetHttpClient
func (c *Client) GetHttpClient() *http.Client { if c.consumer == nil { panic("Consumer credentials are not set") } if c.user == nil { c.SetToken("", "") } if c.client == nil { c.client = c.consumer.Client(context.TODO(), c.user) c.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } } return c.client }
go
func (c *Client) GetHttpClient() *http.Client { if c.consumer == nil { panic("Consumer credentials are not set") } if c.user == nil { c.SetToken("", "") } if c.client == nil { c.client = c.consumer.Client(context.TODO(), c.user) c.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } } return c.client }
[ "func", "(", "c", "*", "Client", ")", "GetHttpClient", "(", ")", "*", "http", ".", "Client", "{", "if", "c", ".", "consumer", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "user", "==", "nil", "{", "c", "."...
// Retrieve the underlying HTTP client
[ "Retrieve", "the", "underlying", "HTTP", "client" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L99-L113
152,050
tumblr/tumblrclient.go
client.go
appendPath
func appendPath(base string, path string) string { // if path starts with `/` shave it off if path[0] == '/' { path = path[1:] } return base + path }
go
func appendPath(base string, path string) string { // if path starts with `/` shave it off if path[0] == '/' { path = path[1:] } return base + path }
[ "func", "appendPath", "(", "base", "string", ",", "path", "string", ")", "string", "{", "// if path starts with `/` shave it off", "if", "path", "[", "0", "]", "==", "'/'", "{", "path", "=", "path", "[", "1", ":", "]", "\n", "}", "\n", "return", "base", ...
// Helper function to ease appending path to a base URI
[ "Helper", "function", "to", "ease", "appending", "path", "to", "a", "base", "URI" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L116-L122
152,051
tumblr/tumblrclient.go
client.go
createRequestURI
func createRequestURI(base string, params url.Values) string { if len(params) != 0 { base += "?" + params.Encode() } return base }
go
func createRequestURI(base string, params url.Values) string { if len(params) != 0 { base += "?" + params.Encode() } return base }
[ "func", "createRequestURI", "(", "base", "string", ",", "params", "url", ".", "Values", ")", "string", "{", "if", "len", "(", "params", ")", "!=", "0", "{", "base", "+=", "\"", "\"", "+", "params", ".", "Encode", "(", ")", "\n", "}", "\n", "return"...
// Helper function to create a URI with query params
[ "Helper", "function", "to", "create", "a", "URI", "with", "query", "params" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L125-L130
152,052
tumblr/tumblrclient.go
client.go
getResponse
func getResponse(resp *http.Response, e error) (tumblr.Response, error) { response := tumblr.Response{} if e != nil { return response, e } defer resp.Body.Close() response.Headers = resp.Header body, e := ioutil.ReadAll(resp.Body) if e != nil { return response, e } response = *tumblr.NewResponse(body, resp.Header) if resp.StatusCode < 200 || resp.StatusCode >= 400 { return response, errors.New(resp.Status) } return response, nil }
go
func getResponse(resp *http.Response, e error) (tumblr.Response, error) { response := tumblr.Response{} if e != nil { return response, e } defer resp.Body.Close() response.Headers = resp.Header body, e := ioutil.ReadAll(resp.Body) if e != nil { return response, e } response = *tumblr.NewResponse(body, resp.Header) if resp.StatusCode < 200 || resp.StatusCode >= 400 { return response, errors.New(resp.Status) } return response, nil }
[ "func", "getResponse", "(", "resp", "*", "http", ".", "Response", ",", "e", "error", ")", "(", "tumblr", ".", "Response", ",", "error", ")", "{", "response", ":=", "tumblr", ".", "Response", "{", "}", "\n", "if", "e", "!=", "nil", "{", "return", "r...
// Standard way of receiving data from the API response
[ "Standard", "way", "of", "receiving", "data", "from", "the", "API", "response" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L133-L149
152,053
tumblr/tumblrclient.go
client.go
GetPost
func (c *Client) GetPost(id uint64, blogName string) *tumblr.PostRef { return tumblr.NewPostRef(c, &tumblr.MiniPost{ Id: id, BlogName: blogName, }) }
go
func (c *Client) GetPost(id uint64, blogName string) *tumblr.PostRef { return tumblr.NewPostRef(c, &tumblr.MiniPost{ Id: id, BlogName: blogName, }) }
[ "func", "(", "c", "*", "Client", ")", "GetPost", "(", "id", "uint64", ",", "blogName", "string", ")", "*", "tumblr", ".", "PostRef", "{", "return", "tumblr", ".", "NewPostRef", "(", "c", ",", "&", "tumblr", ".", "MiniPost", "{", "Id", ":", "id", ",...
// Creates a PostRef out of an id and blog name
[ "Creates", "a", "PostRef", "out", "of", "an", "id", "and", "blog", "name" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L152-L157
152,054
tumblr/tumblrclient.go
client.go
GetBlog
func (c *Client) GetBlog(name string) *tumblr.BlogRef { return tumblr.NewBlogRef(c, name) }
go
func (c *Client) GetBlog(name string) *tumblr.BlogRef { return tumblr.NewBlogRef(c, name) }
[ "func", "(", "c", "*", "Client", ")", "GetBlog", "(", "name", "string", ")", "*", "tumblr", ".", "BlogRef", "{", "return", "tumblr", ".", "NewBlogRef", "(", "c", ",", "name", ")", "\n", "}" ]
// Creates a BlogRef out of the provided name
[ "Creates", "a", "BlogRef", "out", "of", "the", "provided", "name" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L160-L162
152,055
tumblr/tumblrclient.go
client.go
GetDashboard
func (c *Client) GetDashboard() (*tumblr.Dashboard, error) { return c.GetDashboardWithParams(url.Values{}) }
go
func (c *Client) GetDashboard() (*tumblr.Dashboard, error) { return c.GetDashboardWithParams(url.Values{}) }
[ "func", "(", "c", "*", "Client", ")", "GetDashboard", "(", ")", "(", "*", "tumblr", ".", "Dashboard", ",", "error", ")", "{", "return", "c", ".", "GetDashboardWithParams", "(", "url", ".", "Values", "{", "}", ")", "\n", "}" ]
// Makes a request for the user's dashboard
[ "Makes", "a", "request", "for", "the", "user", "s", "dashboard" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L170-L172
152,056
tumblr/tumblrclient.go
client.go
GetLikes
func (c *Client) GetLikes() (*tumblr.Likes, error) { return c.GetLikesWithParams(url.Values{}) }
go
func (c *Client) GetLikes() (*tumblr.Likes, error) { return c.GetLikesWithParams(url.Values{}) }
[ "func", "(", "c", "*", "Client", ")", "GetLikes", "(", ")", "(", "*", "tumblr", ".", "Likes", ",", "error", ")", "{", "return", "c", ".", "GetLikesWithParams", "(", "url", ".", "Values", "{", "}", ")", "\n", "}" ]
// Makes a request for
[ "Makes", "a", "request", "for" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L180-L182
152,057
tumblr/tumblrclient.go
client.go
TaggedSearch
func (c *Client) TaggedSearch(tag string) (*tumblr.SearchResults, error) { return tumblr.TaggedSearch(c, tag, url.Values{}) }
go
func (c *Client) TaggedSearch(tag string) (*tumblr.SearchResults, error) { return tumblr.TaggedSearch(c, tag, url.Values{}) }
[ "func", "(", "c", "*", "Client", ")", "TaggedSearch", "(", "tag", "string", ")", "(", "*", "tumblr", ".", "SearchResults", ",", "error", ")", "{", "return", "tumblr", ".", "TaggedSearch", "(", "c", ",", "tag", ",", "url", ".", "Values", "{", "}", "...
// Performs a tagged serach with this client, returning the result
[ "Performs", "a", "tagged", "serach", "with", "this", "client", "returning", "the", "result" ]
70fe57924421ea2913ef9e72a11984f01c1bc352
https://github.com/tumblr/tumblrclient.go/blob/70fe57924421ea2913ef9e72a11984f01c1bc352/client.go#L190-L192
152,058
vmware/govcloudair
v57/client.go
NewClient
func NewClient() (*Client, error) { var u *url.URL var err error if os.Getenv("VCLOUDAIR_ENDPOINT") != "" { u, err = url.ParseRequestURI(os.Getenv("VCLOUDAIR_ENDPOINT")) if err != nil { return nil, fmt.Errorf("cannot parse endpoint coming from VCLOUDAIR_ENDPOINT") } } else { // Implicitly trust this URL parse. u, _ = url.ParseRequestURI("https://vca.vmware.com/api") } return &Client{ VAEndpoint: *u, Region: os.Getenv("VCLOUDAIR_REGION"), VCDAuthHeader: "X-Vcloud-Authorization", http: http.Client{Transport: &http.Transport{TLSHandshakeTimeout: 120 * time.Second}}, }, nil }
go
func NewClient() (*Client, error) { var u *url.URL var err error if os.Getenv("VCLOUDAIR_ENDPOINT") != "" { u, err = url.ParseRequestURI(os.Getenv("VCLOUDAIR_ENDPOINT")) if err != nil { return nil, fmt.Errorf("cannot parse endpoint coming from VCLOUDAIR_ENDPOINT") } } else { // Implicitly trust this URL parse. u, _ = url.ParseRequestURI("https://vca.vmware.com/api") } return &Client{ VAEndpoint: *u, Region: os.Getenv("VCLOUDAIR_REGION"), VCDAuthHeader: "X-Vcloud-Authorization", http: http.Client{Transport: &http.Transport{TLSHandshakeTimeout: 120 * time.Second}}, }, nil }
[ "func", "NewClient", "(", ")", "(", "*", "Client", ",", "error", ")", "{", "var", "u", "*", "url", ".", "URL", "\n", "var", "err", "error", "\n\n", "if", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "u", ",", "err", "=", ...
// NewClient returns a new empty client to authenticate against the vCloud Air // service, the vCloud Air endpoint can be overridden by setting the // VCLOUDAIR_ENDPOINT environment variable.
[ "NewClient", "returns", "a", "new", "empty", "client", "to", "authenticate", "against", "the", "vCloud", "Air", "service", "the", "vCloud", "Air", "endpoint", "can", "be", "overridden", "by", "setting", "the", "VCLOUDAIR_ENDPOINT", "environment", "variable", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/v57/client.go#L38-L57
152,059
vmware/govcloudair
v57/client.go
Authenticate
func (c *Client) Authenticate(username, password string) error { if username == "" { username = os.Getenv("VCLOUDAIR_USERNAME") } if password == "" { password = os.Getenv("VCLOUDAIR_PASSWORD") } r, _ := http.NewRequest("POST", c.VAEndpoint.String()+LoginPath, nil) r.Header.Set("Accept", JSONMimeV57) r.SetBasicAuth(username, password) resp, err := c.http.Do(r) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { return fmt.Errorf("Could not complete request with vca, because (status %d) %s\n", resp.StatusCode, resp.Status) } var result oAuthClient dec := json.NewDecoder(resp.Body) if err := dec.Decode(&result); err != nil { return err } result.AuthToken = resp.Header.Get("vchs-authorization") c.VAToken = result.AuthToken result.Config = c instances, err := result.instances() if err != nil { return err } var attrs *accountInstanceAttrs for _, inst := range instances { attrs = inst.Attrs() if attrs != nil && (c.Region == "" || strings.HasPrefix(inst.Region, c.Region)) { c.Region = inst.Region break } } if attrs == nil { return fmt.Errorf("unable to determine session url") } attrs.client = c return attrs.Authenticate(username, password) }
go
func (c *Client) Authenticate(username, password string) error { if username == "" { username = os.Getenv("VCLOUDAIR_USERNAME") } if password == "" { password = os.Getenv("VCLOUDAIR_PASSWORD") } r, _ := http.NewRequest("POST", c.VAEndpoint.String()+LoginPath, nil) r.Header.Set("Accept", JSONMimeV57) r.SetBasicAuth(username, password) resp, err := c.http.Do(r) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { return fmt.Errorf("Could not complete request with vca, because (status %d) %s\n", resp.StatusCode, resp.Status) } var result oAuthClient dec := json.NewDecoder(resp.Body) if err := dec.Decode(&result); err != nil { return err } result.AuthToken = resp.Header.Get("vchs-authorization") c.VAToken = result.AuthToken result.Config = c instances, err := result.instances() if err != nil { return err } var attrs *accountInstanceAttrs for _, inst := range instances { attrs = inst.Attrs() if attrs != nil && (c.Region == "" || strings.HasPrefix(inst.Region, c.Region)) { c.Region = inst.Region break } } if attrs == nil { return fmt.Errorf("unable to determine session url") } attrs.client = c return attrs.Authenticate(username, password) }
[ "func", "(", "c", "*", "Client", ")", "Authenticate", "(", "username", ",", "password", "string", ")", "error", "{", "if", "username", "==", "\"", "\"", "{", "username", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "passwo...
// Authenticate is a helper function that performs a complete login in vCloud // Air and in the backend vCloud Director instance.
[ "Authenticate", "is", "a", "helper", "function", "that", "performs", "a", "complete", "login", "in", "vCloud", "Air", "and", "in", "the", "backend", "vCloud", "Director", "instance", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/v57/client.go#L73-L124
152,060
vmware/govcloudair
v57/client.go
BaseURL
func (c *Client) BaseURL() url.URL { if c.vcdHREF == nil { return url.URL{} } return *c.vcdHREF }
go
func (c *Client) BaseURL() url.URL { if c.vcdHREF == nil { return url.URL{} } return *c.vcdHREF }
[ "func", "(", "c", "*", "Client", ")", "BaseURL", "(", ")", "url", ".", "URL", "{", "if", "c", ".", "vcdHREF", "==", "nil", "{", "return", "url", ".", "URL", "{", "}", "\n", "}", "\n", "return", "*", "c", ".", "vcdHREF", "\n", "}" ]
// BaseURL the base uril for the vcloud director instance
[ "BaseURL", "the", "base", "uril", "for", "the", "vcloud", "director", "instance" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/v57/client.go#L127-L132
152,061
vmware/govcloudair
v57/client.go
DoHTTP
func (c *Client) DoHTTP(req *http.Request) (*http.Response, error) { if os.Getenv("VCLOUDAIR_DEBUG") != "" { dr, _ := httputil.DumpRequestOut(req, true) fmt.Println(string(dr)) } resp, err := c.http.Do(req) if err != nil { return nil, err } if os.Getenv("VCLOUDAIR_DEBUG") != "" { dr, _ := httputil.DumpResponse(resp, true) fmt.Println(string(dr)) } return resp, nil }
go
func (c *Client) DoHTTP(req *http.Request) (*http.Response, error) { if os.Getenv("VCLOUDAIR_DEBUG") != "" { dr, _ := httputil.DumpRequestOut(req, true) fmt.Println(string(dr)) } resp, err := c.http.Do(req) if err != nil { return nil, err } if os.Getenv("VCLOUDAIR_DEBUG") != "" { dr, _ := httputil.DumpResponse(resp, true) fmt.Println(string(dr)) } return resp, nil }
[ "func", "(", "c", "*", "Client", ")", "DoHTTP", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "if", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "dr", ",", "_", ...
// DoHTTP performs a http request
[ "DoHTTP", "performs", "a", "http", "request" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/v57/client.go#L135-L149
152,062
vmware/govcloudair
v57/client.go
NewAuthenticatedSession
func NewAuthenticatedSession(user, password string) (*Client, error) { client, err := NewClient() if err != nil { return nil, err } if err := client.Authenticate(user, password); err != nil { return nil, err } return client, nil }
go
func NewAuthenticatedSession(user, password string) (*Client, error) { client, err := NewClient() if err != nil { return nil, err } if err := client.Authenticate(user, password); err != nil { return nil, err } return client, nil }
[ "func", "NewAuthenticatedSession", "(", "user", ",", "password", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "client", ",", "err", ":=", "NewClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}"...
// NewAuthenticatedSession create a new vCloud Air authenticated client
[ "NewAuthenticatedSession", "create", "a", "new", "vCloud", "Air", "authenticated", "client" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/v57/client.go#L186-L197
152,063
vmware/govcloudair
vdc.go
GetVDCOrg
func (v *Vdc) GetVDCOrg() (Org, error) { for _, av := range v.Vdc.Link { if av.Rel == "up" && av.Type == "application/vnd.vmware.vcloud.org+xml" { u, err := url.ParseRequestURI(av.HREF) if err != nil { return Org{}, fmt.Errorf("error decoding vdc response: %s", err) } req := v.c.NewRequest(map[string]string{}, "GET", *u, nil) resp, err := checkResp(v.c.Http.Do(req)) if err != nil { return Org{}, fmt.Errorf("error retreiving org: %s", err) } org := NewOrg(v.c) if err = decodeBody(resp, org.Org); err != nil { return Org{}, fmt.Errorf("error decoding org response: %s", err) } // The request was successful return *org, nil } } return Org{}, fmt.Errorf("can't find VDC Org") }
go
func (v *Vdc) GetVDCOrg() (Org, error) { for _, av := range v.Vdc.Link { if av.Rel == "up" && av.Type == "application/vnd.vmware.vcloud.org+xml" { u, err := url.ParseRequestURI(av.HREF) if err != nil { return Org{}, fmt.Errorf("error decoding vdc response: %s", err) } req := v.c.NewRequest(map[string]string{}, "GET", *u, nil) resp, err := checkResp(v.c.Http.Do(req)) if err != nil { return Org{}, fmt.Errorf("error retreiving org: %s", err) } org := NewOrg(v.c) if err = decodeBody(resp, org.Org); err != nil { return Org{}, fmt.Errorf("error decoding org response: %s", err) } // The request was successful return *org, nil } } return Org{}, fmt.Errorf("can't find VDC Org") }
[ "func", "(", "v", "*", "Vdc", ")", "GetVDCOrg", "(", ")", "(", "Org", ",", "error", ")", "{", "for", "_", ",", "av", ":=", "range", "v", ".", "Vdc", ".", "Link", "{", "if", "av", ".", "Rel", "==", "\"", "\"", "&&", "av", ".", "Type", "==", ...
// Doesn't work with vCloud API 5.5, only vCloud Air
[ "Doesn", "t", "work", "with", "vCloud", "API", "5", ".", "5", "only", "vCloud", "Air" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/vdc.go#L109-L138
152,064
vmware/govcloudair
api_vcd.go
Authenticate
func (c *VCDClient) Authenticate(username, password, org, vdcname string) (Org, Vdc, error) { // LoginUrl err := c.vcdloginurl() if err != nil { return Org{}, Vdc{}, fmt.Errorf("error finding LoginUrl: %s", err) } // Authorize err = c.vcdauthorize(username, password, org) if err != nil { return Org{}, Vdc{}, fmt.Errorf("error authorizing: %s", err) } // Get Org o, err := c.RetrieveOrg(vdcname) if err != nil { return Org{}, Vdc{}, fmt.Errorf("error acquiring Org: %s", err) } vdc, err := c.Client.retrieveVDC() if err != nil { return Org{}, Vdc{}, fmt.Errorf("error retrieving the organization VDC") } return o, vdc, nil }
go
func (c *VCDClient) Authenticate(username, password, org, vdcname string) (Org, Vdc, error) { // LoginUrl err := c.vcdloginurl() if err != nil { return Org{}, Vdc{}, fmt.Errorf("error finding LoginUrl: %s", err) } // Authorize err = c.vcdauthorize(username, password, org) if err != nil { return Org{}, Vdc{}, fmt.Errorf("error authorizing: %s", err) } // Get Org o, err := c.RetrieveOrg(vdcname) if err != nil { return Org{}, Vdc{}, fmt.Errorf("error acquiring Org: %s", err) } vdc, err := c.Client.retrieveVDC() if err != nil { return Org{}, Vdc{}, fmt.Errorf("error retrieving the organization VDC") } return o, vdc, nil }
[ "func", "(", "c", "*", "VCDClient", ")", "Authenticate", "(", "username", ",", "password", ",", "org", ",", "vdcname", "string", ")", "(", "Org", ",", "Vdc", ",", "error", ")", "{", "// LoginUrl", "err", ":=", "c", ".", "vcdloginurl", "(", ")", "\n",...
// Authenticate is an helper function that performs a login in vCloud Director.
[ "Authenticate", "is", "an", "helper", "function", "that", "performs", "a", "login", "in", "vCloud", "Director", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api_vcd.go#L199-L225
152,065
vmware/govcloudair
api_vcd.go
Disconnect
func (c *VCDClient) Disconnect() error { if c.Client.VCDToken == "" && c.Client.VCDAuthHeader == "" { return fmt.Errorf("cannot disconnect, client is not authenticated") } req := c.Client.NewRequest(map[string]string{}, "DELETE", c.sessionHREF, nil) // Add the Accept header for vCA req.Header.Add("Accept", "application/xml;version=5.5") // Set Authorization Header req.Header.Add(c.Client.VCDAuthHeader, c.Client.VCDToken) if _, err := checkResp(c.Client.Http.Do(req)); err != nil { return fmt.Errorf("error processing session delete for vCloud Director: %s", err) } return nil }
go
func (c *VCDClient) Disconnect() error { if c.Client.VCDToken == "" && c.Client.VCDAuthHeader == "" { return fmt.Errorf("cannot disconnect, client is not authenticated") } req := c.Client.NewRequest(map[string]string{}, "DELETE", c.sessionHREF, nil) // Add the Accept header for vCA req.Header.Add("Accept", "application/xml;version=5.5") // Set Authorization Header req.Header.Add(c.Client.VCDAuthHeader, c.Client.VCDToken) if _, err := checkResp(c.Client.Http.Do(req)); err != nil { return fmt.Errorf("error processing session delete for vCloud Director: %s", err) } return nil }
[ "func", "(", "c", "*", "VCDClient", ")", "Disconnect", "(", ")", "error", "{", "if", "c", ".", "Client", ".", "VCDToken", "==", "\"", "\"", "&&", "c", ".", "Client", ".", "VCDAuthHeader", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", ...
// Disconnect performs a disconnection from the vCloud Director API endpoint.
[ "Disconnect", "performs", "a", "disconnection", "from", "the", "vCloud", "Director", "API", "endpoint", "." ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/api_vcd.go#L228-L245
152,066
tent/hawk-go
hawk.go
ParseBewit
func ParseBewit(bewit string) (*Auth, error) { if len(bewit)%4 != 0 { bewit += strings.Repeat("=", 4-len(bewit)%4) } decoded, err := base64.URLEncoding.DecodeString(bewit) if err != nil { return nil, AuthFormatError{"bewit", "malformed base64 encoding"} } components := bytes.SplitN(decoded, []byte(`\`), 4) if len(components) != 4 { return nil, AuthFormatError{"bewit", "missing components"} } auth := &Auth{ Credentials: Credentials{ID: string(components[0])}, Ext: string(components[3]), Method: "GET", ActualTimestamp: Now(), IsBewit: true, } ts, err := strconv.ParseInt(string(components[1]), 10, 64) if err != nil { return nil, AuthFormatError{"ts", "not an integer"} } auth.Timestamp = time.Unix(ts, 0) auth.MAC = make([]byte, base64.StdEncoding.DecodedLen(len(components[2]))) n, err := base64.StdEncoding.Decode(auth.MAC, components[2]) if err != nil { return nil, AuthFormatError{"mac", "malformed base64 encoding"} } auth.MAC = auth.MAC[:n] return auth, nil }
go
func ParseBewit(bewit string) (*Auth, error) { if len(bewit)%4 != 0 { bewit += strings.Repeat("=", 4-len(bewit)%4) } decoded, err := base64.URLEncoding.DecodeString(bewit) if err != nil { return nil, AuthFormatError{"bewit", "malformed base64 encoding"} } components := bytes.SplitN(decoded, []byte(`\`), 4) if len(components) != 4 { return nil, AuthFormatError{"bewit", "missing components"} } auth := &Auth{ Credentials: Credentials{ID: string(components[0])}, Ext: string(components[3]), Method: "GET", ActualTimestamp: Now(), IsBewit: true, } ts, err := strconv.ParseInt(string(components[1]), 10, 64) if err != nil { return nil, AuthFormatError{"ts", "not an integer"} } auth.Timestamp = time.Unix(ts, 0) auth.MAC = make([]byte, base64.StdEncoding.DecodedLen(len(components[2]))) n, err := base64.StdEncoding.Decode(auth.MAC, components[2]) if err != nil { return nil, AuthFormatError{"mac", "malformed base64 encoding"} } auth.MAC = auth.MAC[:n] return auth, nil }
[ "func", "ParseBewit", "(", "bewit", "string", ")", "(", "*", "Auth", ",", "error", ")", "{", "if", "len", "(", "bewit", ")", "%", "4", "!=", "0", "{", "bewit", "+=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "4", "-", "len", "(", "bewit",...
// ParseBewit parses a bewit token provided in a URL parameter and populates an // Auth. If an error is returned it will always be of type AuthFormatError.
[ "ParseBewit", "parses", "a", "bewit", "token", "provided", "in", "a", "URL", "parameter", "and", "populates", "an", "Auth", ".", "If", "an", "error", "is", "returned", "it", "will", "always", "be", "of", "type", "AuthFormatError", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L153-L188
152,067
tent/hawk-go
hawk.go
NewAuthFromRequest
func NewAuthFromRequest(req *http.Request, creds CredentialsLookupFunc, nonce NonceCheckFunc) (*Auth, error) { header := req.Header.Get("Authorization") bewit := req.URL.Query().Get("bewit") var auth *Auth var err error if header != "" { auth, err = ParseRequestHeader(header) if err != nil { return nil, err } } if auth == nil && bewit != "" { if req.Method != "GET" && req.Method != "HEAD" { return nil, ErrInvalidBewitMethod } auth, err = ParseBewit(bewit) if err != nil { return nil, err } } if auth == nil { return nil, ErrNoAuth } auth.Method = req.Method auth.RequestURI = req.URL.Path if req.URL.RawQuery != "" { auth.RequestURI += "?" + req.URL.RawQuery } if bewit != "" { auth.Method = "GET" bewitPattern, _ := regexp.Compile(`\?bewit=` + bewit + `\z|bewit=` + bewit + `&|&bewit=` + bewit + `\z`) auth.RequestURI = bewitPattern.ReplaceAllString(auth.RequestURI, "") } auth.Host, auth.Port = extractReqHostPort(req) if creds != nil { err = creds(&auth.Credentials) if err != nil { return nil, err } } if nonce != nil && !auth.IsBewit && !nonce(auth.Nonce, auth.Timestamp, &auth.Credentials) { return nil, ErrReplay } return auth, nil }
go
func NewAuthFromRequest(req *http.Request, creds CredentialsLookupFunc, nonce NonceCheckFunc) (*Auth, error) { header := req.Header.Get("Authorization") bewit := req.URL.Query().Get("bewit") var auth *Auth var err error if header != "" { auth, err = ParseRequestHeader(header) if err != nil { return nil, err } } if auth == nil && bewit != "" { if req.Method != "GET" && req.Method != "HEAD" { return nil, ErrInvalidBewitMethod } auth, err = ParseBewit(bewit) if err != nil { return nil, err } } if auth == nil { return nil, ErrNoAuth } auth.Method = req.Method auth.RequestURI = req.URL.Path if req.URL.RawQuery != "" { auth.RequestURI += "?" + req.URL.RawQuery } if bewit != "" { auth.Method = "GET" bewitPattern, _ := regexp.Compile(`\?bewit=` + bewit + `\z|bewit=` + bewit + `&|&bewit=` + bewit + `\z`) auth.RequestURI = bewitPattern.ReplaceAllString(auth.RequestURI, "") } auth.Host, auth.Port = extractReqHostPort(req) if creds != nil { err = creds(&auth.Credentials) if err != nil { return nil, err } } if nonce != nil && !auth.IsBewit && !nonce(auth.Nonce, auth.Timestamp, &auth.Credentials) { return nil, ErrReplay } return auth, nil }
[ "func", "NewAuthFromRequest", "(", "req", "*", "http", ".", "Request", ",", "creds", "CredentialsLookupFunc", ",", "nonce", "NonceCheckFunc", ")", "(", "*", "Auth", ",", "error", ")", "{", "header", ":=", "req", ".", "Header", ".", "Get", "(", "\"", "\""...
// NewAuthFromRequest parses a request containing an Authorization header or // bewit parameter and populates an Auth. If creds is not nil it will be called // to look up the associated credentials. If nonce is not nil it will be called // to make sure the nonce is not replayed. // // If the request does not contain a bewit or Authorization header, ErrNoAuth is // returned. If the request contains a bewit and it is not a GET or HEAD // request, ErrInvalidBewitMethod is returned. If there is an error parsing the // provided auth details, an AuthFormatError will be returned. If creds returns // an error, it will be returned. If nonce returns false, ErrReplay will be // returned.
[ "NewAuthFromRequest", "parses", "a", "request", "containing", "an", "Authorization", "header", "or", "bewit", "parameter", "and", "populates", "an", "Auth", ".", "If", "creds", "is", "not", "nil", "it", "will", "be", "called", "to", "look", "up", "the", "ass...
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L201-L247
152,068
tent/hawk-go
hawk.go
NewRequestAuth
func NewRequestAuth(req *http.Request, creds *Credentials, tsOffset time.Duration) *Auth { auth := &Auth{ Method: req.Method, Credentials: *creds, Timestamp: Now().Add(tsOffset), Nonce: nonce(), RequestURI: req.URL.RequestURI(), } auth.Host, auth.Port = extractReqHostPort(req) return auth }
go
func NewRequestAuth(req *http.Request, creds *Credentials, tsOffset time.Duration) *Auth { auth := &Auth{ Method: req.Method, Credentials: *creds, Timestamp: Now().Add(tsOffset), Nonce: nonce(), RequestURI: req.URL.RequestURI(), } auth.Host, auth.Port = extractReqHostPort(req) return auth }
[ "func", "NewRequestAuth", "(", "req", "*", "http", ".", "Request", ",", "creds", "*", "Credentials", ",", "tsOffset", "time", ".", "Duration", ")", "*", "Auth", "{", "auth", ":=", "&", "Auth", "{", "Method", ":", "req", ".", "Method", ",", "Credentials...
// NewRequestAuth builds a client Auth based on req and creds. tsOffset will be // applied to Now when setting the timestamp.
[ "NewRequestAuth", "builds", "a", "client", "Auth", "based", "on", "req", "and", "creds", ".", "tsOffset", "will", "be", "applied", "to", "Now", "when", "setting", "the", "timestamp", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L274-L284
152,069
tent/hawk-go
hawk.go
NewURLAuth
func NewURLAuth(uri string, creds *Credentials, tsOffset time.Duration) (*Auth, error) { u, err := url.Parse(uri) if err != nil { return nil, err } auth := &Auth{ Method: "GET", Credentials: *creds, Timestamp: Now().Add(tsOffset), } if u.Path != "" { // url.Parse unescapes the path, which is unexpected auth.RequestURI = "/" + strings.SplitN(uri[8:], "/", 2)[1] } else { auth.RequestURI = "/" } auth.Host, auth.Port = extractURLHostPort(u) return auth, nil }
go
func NewURLAuth(uri string, creds *Credentials, tsOffset time.Duration) (*Auth, error) { u, err := url.Parse(uri) if err != nil { return nil, err } auth := &Auth{ Method: "GET", Credentials: *creds, Timestamp: Now().Add(tsOffset), } if u.Path != "" { // url.Parse unescapes the path, which is unexpected auth.RequestURI = "/" + strings.SplitN(uri[8:], "/", 2)[1] } else { auth.RequestURI = "/" } auth.Host, auth.Port = extractURLHostPort(u) return auth, nil }
[ "func", "NewURLAuth", "(", "uri", "string", ",", "creds", "*", "Credentials", ",", "tsOffset", "time", ".", "Duration", ")", "(", "*", "Auth", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "uri", ")", "\n", "if", "err", ...
// NewRequestAuth builds a client Auth based on uri and creds. tsOffset will be // applied to Now when setting the timestamp.
[ "NewRequestAuth", "builds", "a", "client", "Auth", "based", "on", "uri", "and", "creds", ".", "tsOffset", "will", "be", "applied", "to", "Now", "when", "setting", "the", "timestamp", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L288-L306
152,070
tent/hawk-go
hawk.go
ParseHeader
func (auth *Auth) ParseHeader(header string, t AuthType) error { if len(header) < 4 || strings.ToLower(header[:4]) != "hawk" { return AuthFormatError{"scheme", "must be Hawk"} } fields, err := lexHeader(header[4:]) if err != nil { return err } if hash, ok := fields["hash"]; ok { auth.Hash, err = base64.StdEncoding.DecodeString(hash) if err != nil { return AuthFormatError{"hash", "malformed base64 encoding"} } } auth.Ext = fields["ext"] mac := fields["mac"] if mac == "" { return AuthFormatError{"mac", "missing or empty"} } auth.MAC, err = base64.StdEncoding.DecodeString(mac) if err != nil { return AuthFormatError{"mac", "malformed base64 encoding"} } if t == AuthHeader { auth.Credentials.App = fields["app"] auth.Credentials.Delegate = fields["dlg"] auth.Credentials.ID = fields["id"] if ts, ok := fields["ts"]; ok { tsint, err := strconv.ParseInt(ts, 10, 64) if err != nil { return AuthFormatError{"ts", "not an integer"} } auth.Timestamp = time.Unix(tsint, 0) } auth.Nonce = fields["nonce"] } return nil }
go
func (auth *Auth) ParseHeader(header string, t AuthType) error { if len(header) < 4 || strings.ToLower(header[:4]) != "hawk" { return AuthFormatError{"scheme", "must be Hawk"} } fields, err := lexHeader(header[4:]) if err != nil { return err } if hash, ok := fields["hash"]; ok { auth.Hash, err = base64.StdEncoding.DecodeString(hash) if err != nil { return AuthFormatError{"hash", "malformed base64 encoding"} } } auth.Ext = fields["ext"] mac := fields["mac"] if mac == "" { return AuthFormatError{"mac", "missing or empty"} } auth.MAC, err = base64.StdEncoding.DecodeString(mac) if err != nil { return AuthFormatError{"mac", "malformed base64 encoding"} } if t == AuthHeader { auth.Credentials.App = fields["app"] auth.Credentials.Delegate = fields["dlg"] auth.Credentials.ID = fields["id"] if ts, ok := fields["ts"]; ok { tsint, err := strconv.ParseInt(ts, 10, 64) if err != nil { return AuthFormatError{"ts", "not an integer"} } auth.Timestamp = time.Unix(tsint, 0) } auth.Nonce = fields["nonce"] } return nil }
[ "func", "(", "auth", "*", "Auth", ")", "ParseHeader", "(", "header", "string", ",", "t", "AuthType", ")", "error", "{", "if", "len", "(", "header", ")", "<", "4", "||", "strings", ".", "ToLower", "(", "header", "[", ":", "4", "]", ")", "!=", "\""...
// ParseHeader parses a Hawk request or response header and populates auth. // t must be AuthHeader if the header is an Authorization header from a request // or AuthResponse if the header is a Server-Authorization header from // a response.
[ "ParseHeader", "parses", "a", "Hawk", "request", "or", "response", "header", "and", "populates", "auth", ".", "t", "must", "be", "AuthHeader", "if", "the", "header", "is", "an", "Authorization", "header", "from", "a", "request", "or", "AuthResponse", "if", "...
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L423-L464
152,071
tent/hawk-go
hawk.go
Valid
func (auth *Auth) Valid() error { t := AuthHeader if auth.IsBewit { t = AuthBewit if auth.Method != "GET" && auth.Method != "HEAD" { return ErrInvalidBewitMethod } if auth.ActualTimestamp.After(auth.Timestamp) { return ErrBewitExpired } } else { skew := auth.ActualTimestamp.Sub(auth.Timestamp) if abs(skew) > MaxTimestampSkew { return ErrTimestampSkew } } if !hmac.Equal(auth.mac(t), auth.MAC) { if auth.IsBewit && strings.HasPrefix(auth.RequestURI, "http") && len(auth.RequestURI) > 9 { // try just the path uri := auth.RequestURI auth.RequestURI = "/" + strings.SplitN(auth.RequestURI[8:], "/", 2)[1] if auth.Valid() == nil { return nil } auth.RequestURI = uri } return ErrInvalidMAC } return nil }
go
func (auth *Auth) Valid() error { t := AuthHeader if auth.IsBewit { t = AuthBewit if auth.Method != "GET" && auth.Method != "HEAD" { return ErrInvalidBewitMethod } if auth.ActualTimestamp.After(auth.Timestamp) { return ErrBewitExpired } } else { skew := auth.ActualTimestamp.Sub(auth.Timestamp) if abs(skew) > MaxTimestampSkew { return ErrTimestampSkew } } if !hmac.Equal(auth.mac(t), auth.MAC) { if auth.IsBewit && strings.HasPrefix(auth.RequestURI, "http") && len(auth.RequestURI) > 9 { // try just the path uri := auth.RequestURI auth.RequestURI = "/" + strings.SplitN(auth.RequestURI[8:], "/", 2)[1] if auth.Valid() == nil { return nil } auth.RequestURI = uri } return ErrInvalidMAC } return nil }
[ "func", "(", "auth", "*", "Auth", ")", "Valid", "(", ")", "error", "{", "t", ":=", "AuthHeader", "\n", "if", "auth", ".", "IsBewit", "{", "t", "=", "AuthBewit", "\n", "if", "auth", ".", "Method", "!=", "\"", "\"", "&&", "auth", ".", "Method", "!=...
// Valid confirms that the timestamp is within skew and verifies the MAC. // // If the request is valid, nil will be returned. If auth is a bewit and the // method is not GET or HEAD, ErrInvalidBewitMethod will be returned. If auth is // a bewit and the timestamp is after the the specified expiry, ErrBewitExpired // will be returned. If auth is from a request header and the timestamp is // outside the maximum skew, ErrTimestampSkew will be returned. If the MAC is // not the expected value, ErrInvalidMAC will be returned.
[ "Valid", "confirms", "that", "the", "timestamp", "is", "within", "skew", "and", "verifies", "the", "MAC", ".", "If", "the", "request", "is", "valid", "nil", "will", "be", "returned", ".", "If", "auth", "is", "a", "bewit", "and", "the", "method", "is", ...
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L474-L503
152,072
tent/hawk-go
hawk.go
ValidResponse
func (auth *Auth) ValidResponse(header string) error { if header == "" { return ErrMissingServerAuth } err := auth.ParseHeader(header, AuthResponse) if err != nil { return err } if !hmac.Equal(auth.mac(AuthResponse), auth.MAC) { return ErrInvalidMAC } return nil }
go
func (auth *Auth) ValidResponse(header string) error { if header == "" { return ErrMissingServerAuth } err := auth.ParseHeader(header, AuthResponse) if err != nil { return err } if !hmac.Equal(auth.mac(AuthResponse), auth.MAC) { return ErrInvalidMAC } return nil }
[ "func", "(", "auth", "*", "Auth", ")", "ValidResponse", "(", "header", "string", ")", "error", "{", "if", "header", "==", "\"", "\"", "{", "return", "ErrMissingServerAuth", "\n", "}", "\n", "err", ":=", "auth", ".", "ParseHeader", "(", "header", ",", "...
// ValidResponse checks that a response Server-Authorization header is correct. // // ErrMissingServerAuth is returned if header is an empty string. ErrInvalidMAC // is returned if the MAC is not the expected value.
[ "ValidResponse", "checks", "that", "a", "response", "Server", "-", "Authorization", "header", "is", "correct", ".", "ErrMissingServerAuth", "is", "returned", "if", "header", "is", "an", "empty", "string", ".", "ErrInvalidMAC", "is", "returned", "if", "the", "MAC...
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L516-L528
152,073
tent/hawk-go
hawk.go
ValidHash
func (auth *Auth) ValidHash(h hash.Hash) bool { h.Write([]byte("\n")) return bytes.Equal(h.Sum(nil), auth.Hash) }
go
func (auth *Auth) ValidHash(h hash.Hash) bool { h.Write([]byte("\n")) return bytes.Equal(h.Sum(nil), auth.Hash) }
[ "func", "(", "auth", "*", "Auth", ")", "ValidHash", "(", "h", "hash", ".", "Hash", ")", "bool", "{", "h", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", ")", "\n", "return", "bytes", ".", "Equal", "(", "h", ".", "Sum", "(",...
// ValidHash writes the final newline to h and checks if it matches auth.Hash.
[ "ValidHash", "writes", "the", "final", "newline", "to", "h", "and", "checks", "if", "it", "matches", "auth", ".", "Hash", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L541-L544
152,074
tent/hawk-go
hawk.go
SetHash
func (auth *Auth) SetHash(h hash.Hash) { h.Write([]byte("\n")) auth.Hash = h.Sum(nil) auth.ReqHash = false }
go
func (auth *Auth) SetHash(h hash.Hash) { h.Write([]byte("\n")) auth.Hash = h.Sum(nil) auth.ReqHash = false }
[ "func", "(", "auth", "*", "Auth", ")", "SetHash", "(", "h", "hash", ".", "Hash", ")", "{", "h", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", ")", "\n", "auth", ".", "Hash", "=", "h", ".", "Sum", "(", "nil", ")", "\n", ...
// SetHash writes the final newline to h and sets auth.Hash to the sum. This is // used to specify a response payload hash.
[ "SetHash", "writes", "the", "final", "newline", "to", "h", "and", "sets", "auth", ".", "Hash", "to", "the", "sum", ".", "This", "is", "used", "to", "specify", "a", "response", "payload", "hash", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L548-L552
152,075
tent/hawk-go
hawk.go
ResponseHeader
func (auth *Auth) ResponseHeader(ext string) string { auth.Ext = ext if auth.ReqHash { auth.Hash = nil } h := `Hawk mac="` + base64.StdEncoding.EncodeToString(auth.mac(AuthResponse)) + `"` if auth.Ext != "" { h += `, ext="` + auth.Ext + `"` } if auth.Hash != nil { h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"` } return h }
go
func (auth *Auth) ResponseHeader(ext string) string { auth.Ext = ext if auth.ReqHash { auth.Hash = nil } h := `Hawk mac="` + base64.StdEncoding.EncodeToString(auth.mac(AuthResponse)) + `"` if auth.Ext != "" { h += `, ext="` + auth.Ext + `"` } if auth.Hash != nil { h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"` } return h }
[ "func", "(", "auth", "*", "Auth", ")", "ResponseHeader", "(", "ext", "string", ")", "string", "{", "auth", ".", "Ext", "=", "ext", "\n", "if", "auth", ".", "ReqHash", "{", "auth", ".", "Hash", "=", "nil", "\n", "}", "\n\n", "h", ":=", "`Hawk mac=\"...
// ResponseHeader builds a response header based on the auth and provided ext, // which may be an empty string. Use PayloadHash and SetHash before // ResponseHeader to include a hash of the response payload.
[ "ResponseHeader", "builds", "a", "response", "header", "based", "on", "the", "auth", "and", "provided", "ext", "which", "may", "be", "an", "empty", "string", ".", "Use", "PayloadHash", "and", "SetHash", "before", "ResponseHeader", "to", "include", "a", "hash",...
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L557-L572
152,076
tent/hawk-go
hawk.go
RequestHeader
func (auth *Auth) RequestHeader() string { auth.MAC = auth.mac(AuthHeader) h := `Hawk id="` + auth.Credentials.ID + `", mac="` + base64.StdEncoding.EncodeToString(auth.MAC) + `", ts="` + strconv.FormatInt(auth.Timestamp.Unix(), 10) + `", nonce="` + auth.Nonce + `"` if len(auth.Hash) > 0 { h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"` } if auth.Ext != "" { h += `, ext="` + auth.Ext + `"` } if auth.Credentials.App != "" { h += `, app="` + auth.Credentials.App + `"` } if auth.Credentials.Delegate != "" { h += `, dlg="` + auth.Credentials.Delegate + `"` } return h }
go
func (auth *Auth) RequestHeader() string { auth.MAC = auth.mac(AuthHeader) h := `Hawk id="` + auth.Credentials.ID + `", mac="` + base64.StdEncoding.EncodeToString(auth.MAC) + `", ts="` + strconv.FormatInt(auth.Timestamp.Unix(), 10) + `", nonce="` + auth.Nonce + `"` if len(auth.Hash) > 0 { h += `, hash="` + base64.StdEncoding.EncodeToString(auth.Hash) + `"` } if auth.Ext != "" { h += `, ext="` + auth.Ext + `"` } if auth.Credentials.App != "" { h += `, app="` + auth.Credentials.App + `"` } if auth.Credentials.Delegate != "" { h += `, dlg="` + auth.Credentials.Delegate + `"` } return h }
[ "func", "(", "auth", "*", "Auth", ")", "RequestHeader", "(", ")", "string", "{", "auth", ".", "MAC", "=", "auth", ".", "mac", "(", "AuthHeader", ")", "\n\n", "h", ":=", "`Hawk id=\"`", "+", "auth", ".", "Credentials", ".", "ID", "+", "`\", mac=\"`", ...
// RequestHeader builds a request header based on the auth.
[ "RequestHeader", "builds", "a", "request", "header", "based", "on", "the", "auth", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L575-L597
152,077
tent/hawk-go
hawk.go
Bewit
func (auth *Auth) Bewit() string { auth.Method = "GET" auth.Nonce = "" return strings.TrimRight(base64.URLEncoding.EncodeToString([]byte(auth.Credentials.ID+`\`+ strconv.FormatInt(auth.Timestamp.Unix(), 10)+`\`+ base64.StdEncoding.EncodeToString(auth.mac(AuthBewit))+`\`+ auth.Ext)), "=") }
go
func (auth *Auth) Bewit() string { auth.Method = "GET" auth.Nonce = "" return strings.TrimRight(base64.URLEncoding.EncodeToString([]byte(auth.Credentials.ID+`\`+ strconv.FormatInt(auth.Timestamp.Unix(), 10)+`\`+ base64.StdEncoding.EncodeToString(auth.mac(AuthBewit))+`\`+ auth.Ext)), "=") }
[ "func", "(", "auth", "*", "Auth", ")", "Bewit", "(", ")", "string", "{", "auth", ".", "Method", "=", "\"", "\"", "\n", "auth", ".", "Nonce", "=", "\"", "\"", "\n", "return", "strings", ".", "TrimRight", "(", "base64", ".", "URLEncoding", ".", "Enco...
// Bewit creates and encoded request bewit parameter based on the auth.
[ "Bewit", "creates", "and", "encoded", "request", "bewit", "parameter", "based", "on", "the", "auth", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L600-L607
152,078
tent/hawk-go
hawk.go
NormalizedString
func (auth *Auth) NormalizedString(t AuthType) string { str := "hawk." + headerVersion + "." + t.String() + "\n" + strconv.FormatInt(auth.Timestamp.Unix(), 10) + "\n" + auth.Nonce + "\n" + auth.Method + "\n" + auth.RequestURI + "\n" + auth.Host + "\n" + auth.Port + "\n" + base64.StdEncoding.EncodeToString(auth.Hash) + "\n" + auth.Ext + "\n" if auth.Credentials.App != "" { str += auth.Credentials.App + "\n" str += auth.Credentials.Delegate + "\n" } return str }
go
func (auth *Auth) NormalizedString(t AuthType) string { str := "hawk." + headerVersion + "." + t.String() + "\n" + strconv.FormatInt(auth.Timestamp.Unix(), 10) + "\n" + auth.Nonce + "\n" + auth.Method + "\n" + auth.RequestURI + "\n" + auth.Host + "\n" + auth.Port + "\n" + base64.StdEncoding.EncodeToString(auth.Hash) + "\n" + auth.Ext + "\n" if auth.Credentials.App != "" { str += auth.Credentials.App + "\n" str += auth.Credentials.Delegate + "\n" } return str }
[ "func", "(", "auth", "*", "Auth", ")", "NormalizedString", "(", "t", "AuthType", ")", "string", "{", "str", ":=", "\"", "\"", "+", "headerVersion", "+", "\"", "\"", "+", "t", ".", "String", "(", ")", "+", "\"", "\\n", "\"", "+", "strconv", ".", "...
// NormalizedString builds the string that will be HMACed to create a request // MAC.
[ "NormalizedString", "builds", "the", "string", "that", "will", "be", "HMACed", "to", "create", "a", "request", "MAC", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L611-L628
152,079
tent/hawk-go
hawk.go
StaleTimestampHeader
func (auth *Auth) StaleTimestampHeader() string { ts := strconv.FormatInt(Now().Unix(), 10) return `Hawk ts="` + ts + `", tsm="` + base64.StdEncoding.EncodeToString(auth.tsMac(ts)) + `", error="Stale timestamp"` }
go
func (auth *Auth) StaleTimestampHeader() string { ts := strconv.FormatInt(Now().Unix(), 10) return `Hawk ts="` + ts + `", tsm="` + base64.StdEncoding.EncodeToString(auth.tsMac(ts)) + `", error="Stale timestamp"` }
[ "func", "(", "auth", "*", "Auth", ")", "StaleTimestampHeader", "(", ")", "string", "{", "ts", ":=", "strconv", ".", "FormatInt", "(", "Now", "(", ")", ".", "Unix", "(", ")", ",", "10", ")", "\n", "return", "`Hawk ts=\"`", "+", "ts", "+", "`\", tsm=\"...
// StaleTimestampHeader builds a signed WWW-Authenticate response header for use // when Valid returns ErrTimestampSkew.
[ "StaleTimestampHeader", "builds", "a", "signed", "WWW", "-", "Authenticate", "response", "header", "for", "use", "when", "Valid", "returns", "ErrTimestampSkew", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L644-L649
152,080
tent/hawk-go
hawk.go
UpdateOffset
func (auth *Auth) UpdateOffset(header string) (time.Duration, error) { if len(header) < 4 || strings.ToLower(header[:4]) != "hawk" { return 0, AuthFormatError{"scheme", "must be Hawk"} } matches := tsHeaderRegex.FindAllStringSubmatch(header, 3) var err error var ts time.Time var tsm []byte for _, match := range matches { switch match[1] { case "ts": t, err := strconv.ParseInt(match[2], 10, 64) if err != nil { return 0, AuthFormatError{"ts", "not an integer"} } ts = time.Unix(t, 0) case "tsm": tsm, err = base64.StdEncoding.DecodeString(match[2]) if err != nil { return 0, AuthFormatError{"tsm", "malformed base64 encoding"} } } } if !hmac.Equal(tsm, auth.tsMac(strconv.FormatInt(ts.Unix(), 10))) { return 0, ErrInvalidMAC } offset := ts.Sub(Now()) auth.Timestamp = ts auth.Nonce = nonce() return offset, nil }
go
func (auth *Auth) UpdateOffset(header string) (time.Duration, error) { if len(header) < 4 || strings.ToLower(header[:4]) != "hawk" { return 0, AuthFormatError{"scheme", "must be Hawk"} } matches := tsHeaderRegex.FindAllStringSubmatch(header, 3) var err error var ts time.Time var tsm []byte for _, match := range matches { switch match[1] { case "ts": t, err := strconv.ParseInt(match[2], 10, 64) if err != nil { return 0, AuthFormatError{"ts", "not an integer"} } ts = time.Unix(t, 0) case "tsm": tsm, err = base64.StdEncoding.DecodeString(match[2]) if err != nil { return 0, AuthFormatError{"tsm", "malformed base64 encoding"} } } } if !hmac.Equal(tsm, auth.tsMac(strconv.FormatInt(ts.Unix(), 10))) { return 0, ErrInvalidMAC } offset := ts.Sub(Now()) auth.Timestamp = ts auth.Nonce = nonce() return offset, nil }
[ "func", "(", "auth", "*", "Auth", ")", "UpdateOffset", "(", "header", "string", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "len", "(", "header", ")", "<", "4", "||", "strings", ".", "ToLower", "(", "header", "[", ":", "4", "...
// UpdateOffset parses a signed WWW-Authenticate response header containing // a stale timestamp error and updates auth.Timestamp with an adjusted // timestamp.
[ "UpdateOffset", "parses", "a", "signed", "WWW", "-", "Authenticate", "response", "header", "containing", "a", "stale", "timestamp", "error", "and", "updates", "auth", ".", "Timestamp", "with", "an", "adjusted", "timestamp", "." ]
d341ea31895747c3b8f64837fef40ccf0c1143af
https://github.com/tent/hawk-go/blob/d341ea31895747c3b8f64837fef40ccf0c1143af/hawk.go#L656-L691
152,081
vmware/govcloudair
orgvdcnetwork.go
NewOrgVDCNetwork
func NewOrgVDCNetwork(c *Client) *OrgVDCNetwork { return &OrgVDCNetwork{ OrgVDCNetwork: new(types.OrgVDCNetwork), c: c, } }
go
func NewOrgVDCNetwork(c *Client) *OrgVDCNetwork { return &OrgVDCNetwork{ OrgVDCNetwork: new(types.OrgVDCNetwork), c: c, } }
[ "func", "NewOrgVDCNetwork", "(", "c", "*", "Client", ")", "*", "OrgVDCNetwork", "{", "return", "&", "OrgVDCNetwork", "{", "OrgVDCNetwork", ":", "new", "(", "types", ".", "OrgVDCNetwork", ")", ",", "c", ":", "c", ",", "}", "\n", "}" ]
// NewOrgVDCNetwork creates an org vdc network client
[ "NewOrgVDCNetwork", "creates", "an", "org", "vdc", "network", "client" ]
daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46
https://github.com/vmware/govcloudair/blob/daf883c2f1db1a1b08e3dc15b2a9f98c877a8d46/orgvdcnetwork.go#L27-L32
152,082
ammario/ipisp
asn.go
ParseASN
func ParseASN(asn string) (ASN, error) { // A special value from the API. // More info: https://github.com/ammario/ipisp/issues/10. if asn == "NA" { return 0, nil } // Make case insensitive asn = strings.ToUpper(asn) if len(asn) > 2 && asn[:2] == "AS" { asn = asn[2:] } nn, err := strconv.Atoi(asn) return ASN(nn), errors.Wrap(err, "failed to conv into to string") }
go
func ParseASN(asn string) (ASN, error) { // A special value from the API. // More info: https://github.com/ammario/ipisp/issues/10. if asn == "NA" { return 0, nil } // Make case insensitive asn = strings.ToUpper(asn) if len(asn) > 2 && asn[:2] == "AS" { asn = asn[2:] } nn, err := strconv.Atoi(asn) return ASN(nn), errors.Wrap(err, "failed to conv into to string") }
[ "func", "ParseASN", "(", "asn", "string", ")", "(", "ASN", ",", "error", ")", "{", "// A special value from the API.", "// More info: https://github.com/ammario/ipisp/issues/10.", "if", "asn", "==", "\"", "\"", "{", "return", "0", ",", "nil", "\n", "}", "\n", "/...
// ParseASN parses a string like `AS2341` into ASN `2341`.
[ "ParseASN", "parses", "a", "string", "like", "AS2341", "into", "ASN", "2341", "." ]
2225ac7a237a562eba212b29d8e7f7277fb9ea9b
https://github.com/ammario/ipisp/blob/2225ac7a237a562eba212b29d8e7f7277fb9ea9b/asn.go#L15-L29
152,083
go-audio/generator
examples/realtime/main.go
f64ToF32Copy
func f64ToF32Copy(dst []float32, src []float64) { for i := range src { dst[i] = float32(src[i]) } }
go
func f64ToF32Copy(dst []float32, src []float64) { for i := range src { dst[i] = float32(src[i]) } }
[ "func", "f64ToF32Copy", "(", "dst", "[", "]", "float32", ",", "src", "[", "]", "float64", ")", "{", "for", "i", ":=", "range", "src", "{", "dst", "[", "i", "]", "=", "float32", "(", "src", "[", "i", "]", ")", "\n", "}", "\n", "}" ]
// portaudio doesn't support float64 so we need to copy our data over to the // destination buffer.
[ "portaudio", "doesn", "t", "support", "float64", "so", "we", "need", "to", "copy", "our", "data", "over", "to", "the", "destination", "buffer", "." ]
dbf5ce2499f1911b33391781c7a31a773d9f6fd5
https://github.com/go-audio/generator/blob/dbf5ce2499f1911b33391781c7a31a773d9f6fd5/examples/realtime/main.go#L116-L120
152,084
ammario/ipisp
client.go
parseASNs
func parseASNs(asnList string) ([]ASN, error) { tokens := strings.Split(strings.TrimSpace(asnList), " ") if len(tokens) == 0 { return nil, errors.New("no ASNs") } asns := make([]ASN, len(tokens)) for i, tok := range tokens { asn, err := ParseASN(tok) if err != nil { return nil, errors.Wrap(err, "failed to parse asn") } asns[i] = ASN(asn) } return asns, nil }
go
func parseASNs(asnList string) ([]ASN, error) { tokens := strings.Split(strings.TrimSpace(asnList), " ") if len(tokens) == 0 { return nil, errors.New("no ASNs") } asns := make([]ASN, len(tokens)) for i, tok := range tokens { asn, err := ParseASN(tok) if err != nil { return nil, errors.Wrap(err, "failed to parse asn") } asns[i] = ASN(asn) } return asns, nil }
[ "func", "parseASNs", "(", "asnList", "string", ")", "(", "[", "]", "ASN", ",", "error", ")", "{", "tokens", ":=", "strings", ".", "Split", "(", "strings", ".", "TrimSpace", "(", "asnList", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "tokens"...
// parseASNs parses an ASN list like "1024 1111 11202". // If it doesn't return an error, the returned slice has at least one entry.
[ "parseASNs", "parses", "an", "ASN", "list", "like", "1024", "1111", "11202", ".", "If", "it", "doesn", "t", "return", "an", "error", "the", "returned", "slice", "has", "at", "least", "one", "entry", "." ]
2225ac7a237a562eba212b29d8e7f7277fb9ea9b
https://github.com/ammario/ipisp/blob/2225ac7a237a562eba212b29d8e7f7277fb9ea9b/client.go#L23-L40
152,085
xyproto/pstore
userstate.go
SetTablePrefix
func (state *UserState) SetTablePrefix(prefix string) { db.SetColumnNames(prefix+"_a_list", prefix+"_a_set", prefix+"_owner", prefix+"_a_kv_") }
go
func (state *UserState) SetTablePrefix(prefix string) { db.SetColumnNames(prefix+"_a_list", prefix+"_a_set", prefix+"_owner", prefix+"_a_kv_") }
[ "func", "(", "state", "*", "UserState", ")", "SetTablePrefix", "(", "prefix", "string", ")", "{", "db", ".", "SetColumnNames", "(", "prefix", "+", "\"", "\"", ",", "prefix", "+", "\"", "\"", ",", "prefix", "+", "\"", "\"", ",", "prefix", "+", "\"", ...
// Set a custom PostgreSQL database table prefix
[ "Set", "a", "custom", "PostgreSQL", "database", "table", "prefix" ]
65a49d4318bbbc2bca0a3e23eba6ad8f337b07ed
https://github.com/xyproto/pstore/blob/65a49d4318bbbc2bca0a3e23eba6ad8f337b07ed/userstate.go#L157-L159
152,086
xyproto/pstore
userstate.go
HasEmail
func (state *UserState) HasEmail(email string) (string, error) { if email == "" { return "", ErrNotFound } usernames, err := state.AllUsernames() if err != nil { return "", err } for _, username := range usernames { if user_email, err := state.Email(username); err != nil { return "", err } else { if user_email == email { return username, nil } } } return "", ErrNotFound }
go
func (state *UserState) HasEmail(email string) (string, error) { if email == "" { return "", ErrNotFound } usernames, err := state.AllUsernames() if err != nil { return "", err } for _, username := range usernames { if user_email, err := state.Email(username); err != nil { return "", err } else { if user_email == email { return username, nil } } } return "", ErrNotFound }
[ "func", "(", "state", "*", "UserState", ")", "HasEmail", "(", "email", "string", ")", "(", "string", ",", "error", ")", "{", "if", "email", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "ErrNotFound", "\n", "}", "\n", "usernames", ",", "err", "...
// HasEmail finds the user that has a given e-mail address. // Returns the username and nil if found or a blank string and ErrNotFound if not.
[ "HasEmail", "finds", "the", "user", "that", "has", "a", "given", "e", "-", "mail", "address", ".", "Returns", "the", "username", "and", "nil", "if", "found", "or", "a", "blank", "string", "and", "ErrNotFound", "if", "not", "." ]
65a49d4318bbbc2bca0a3e23eba6ad8f337b07ed
https://github.com/xyproto/pstore/blob/65a49d4318bbbc2bca0a3e23eba6ad8f337b07ed/userstate.go#L187-L205
152,087
xyproto/pstore
userstate.go
SetUsernameCookie
func (state *UserState) SetUsernameCookie(w http.ResponseWriter, username string) error { if username == "" { return errors.New("Can't set cookie for empty username") } if !state.HasUser(username) { return errors.New("Can't store cookie for non-existing user") } // Create a cookie that lasts for a while ("timeout" seconds), // this is the equivalent of a session for a given username. cookie.SetSecureCookiePath(w, "user", username, state.cookieTime, "/", state.cookieSecret) return nil }
go
func (state *UserState) SetUsernameCookie(w http.ResponseWriter, username string) error { if username == "" { return errors.New("Can't set cookie for empty username") } if !state.HasUser(username) { return errors.New("Can't store cookie for non-existing user") } // Create a cookie that lasts for a while ("timeout" seconds), // this is the equivalent of a session for a given username. cookie.SetSecureCookiePath(w, "user", username, state.cookieTime, "/", state.cookieSecret) return nil }
[ "func", "(", "state", "*", "UserState", ")", "SetUsernameCookie", "(", "w", "http", ".", "ResponseWriter", ",", "username", "string", ")", "error", "{", "if", "username", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n"...
// SetUsernameCookie stores the given username in a cookie in the browser, if possible. // Will return an error if the username is empty or the user does not exist.
[ "SetUsernameCookie", "stores", "the", "given", "username", "in", "a", "cookie", "in", "the", "browser", "if", "possible", ".", "Will", "return", "an", "error", "if", "the", "username", "is", "empty", "or", "the", "user", "does", "not", "exist", "." ]
65a49d4318bbbc2bca0a3e23eba6ad8f337b07ed
https://github.com/xyproto/pstore/blob/65a49d4318bbbc2bca0a3e23eba6ad8f337b07ed/userstate.go#L282-L293
152,088
ammario/ipisp
whois_client.go
NewWhoisClient
func NewWhoisClient() (Client, error) { var err error client := &whoisClient{} client.Conn, err = net.DialTimeout("tcp", cymruNetcatAddress, Timeout) client.ncmu = &sync.Mutex{} if err != nil { return nil, errors.WithStack(err) } client.w = bufio.NewWriter(client.Conn) client.sc = bufio.NewScanner(client.Conn) client.Conn.SetDeadline(time.Now().Add(time.Second * 15)) client.w.Write([]byte("begin")) client.w.Write(ncEOL) client.w.Write([]byte("verbose")) client.w.Write(ncEOL) err = client.w.Flush() if err != nil { return client, errors.Wrap(err, "failed to write to client") } // Discard first hello line client.sc.Scan() client.sc.Bytes() return client, errors.Wrap(client.sc.Err(), "failed to read from scanner") }
go
func NewWhoisClient() (Client, error) { var err error client := &whoisClient{} client.Conn, err = net.DialTimeout("tcp", cymruNetcatAddress, Timeout) client.ncmu = &sync.Mutex{} if err != nil { return nil, errors.WithStack(err) } client.w = bufio.NewWriter(client.Conn) client.sc = bufio.NewScanner(client.Conn) client.Conn.SetDeadline(time.Now().Add(time.Second * 15)) client.w.Write([]byte("begin")) client.w.Write(ncEOL) client.w.Write([]byte("verbose")) client.w.Write(ncEOL) err = client.w.Flush() if err != nil { return client, errors.Wrap(err, "failed to write to client") } // Discard first hello line client.sc.Scan() client.sc.Bytes() return client, errors.Wrap(client.sc.Err(), "failed to read from scanner") }
[ "func", "NewWhoisClient", "(", ")", "(", "Client", ",", "error", ")", "{", "var", "err", "error", "\n\n", "client", ":=", "&", "whoisClient", "{", "}", "\n", "client", ".", "Conn", ",", "err", "=", "net", ".", "DialTimeout", "(", "\"", "\"", ",", "...
// NewWhoisClient returns a connected WHOIS client. // This client should be used for bulk lookups.
[ "NewWhoisClient", "returns", "a", "connected", "WHOIS", "client", ".", "This", "client", "should", "be", "used", "for", "bulk", "lookups", "." ]
2225ac7a237a562eba212b29d8e7f7277fb9ea9b
https://github.com/ammario/ipisp/blob/2225ac7a237a562eba212b29d8e7f7277fb9ea9b/whois_client.go#L44-L72
152,089
ammario/ipisp
whois_client.go
LookupIP
func (c *whoisClient) LookupIP(ip net.IP) (*Response, error) { resp, err := c.LookupIPs([]net.IP{ip}) if len(resp) == 0 { return nil, err } return &resp[0], err }
go
func (c *whoisClient) LookupIP(ip net.IP) (*Response, error) { resp, err := c.LookupIPs([]net.IP{ip}) if len(resp) == 0 { return nil, err } return &resp[0], err }
[ "func", "(", "c", "*", "whoisClient", ")", "LookupIP", "(", "ip", "net", ".", "IP", ")", "(", "*", "Response", ",", "error", ")", "{", "resp", ",", "err", ":=", "c", ".", "LookupIPs", "(", "[", "]", "net", ".", "IP", "{", "ip", "}", ")", "\n"...
// LookupIP is a single IP convenience proxy of LookupIPs
[ "LookupIP", "is", "a", "single", "IP", "convenience", "proxy", "of", "LookupIPs" ]
2225ac7a237a562eba212b29d8e7f7277fb9ea9b
https://github.com/ammario/ipisp/blob/2225ac7a237a562eba212b29d8e7f7277fb9ea9b/whois_client.go#L175-L181
152,090
ammario/ipisp
whois_client.go
LookupASNs
func (c *whoisClient) LookupASNs(asns []ASN) (resp []Response, err error) { resp = make([]Response, 0, len(asns)) c.ncmu.Lock() defer c.ncmu.Unlock() for _, asn := range asns { c.w.WriteString(asn.String()) c.w.Write(ncEOL) if err = c.w.Flush(); err != nil { return resp, err } } c.Conn.SetDeadline(time.Now().Add(time.Second*5 + (time.Second * time.Duration(len(asns))))) // Raw response var raw []byte var tokens [][]byte var asn int var finished bool // Read results for !finished && c.sc.Scan() { raw = c.sc.Bytes() if bytes.HasPrefix(raw, []byte("Error: ")) { return resp, errors.Errorf("recieved err: %v", raw) } tokens = bytes.Split(raw, []byte{'|'}) if len(tokens) != netcatASNTokensLength { return resp, ErrUnexpectedTokens } // Trim excess whitespace from tokens for i := range tokens { tokens[i] = bytes.TrimSpace(tokens[i]) } re := Response{} // Read ASN if asn, err = strconv.Atoi(string(tokens[0])); err != nil { return nil, errors.Wrapf(err, "failed to atoi %s", tokens[0]) } re.ASN = ASN(asn) // Read country re.Country = string(tokens[1]) // Read registry re.Registry = string(bytes.ToUpper(tokens[2])) // Read allocated. Ignore error as a lot of entries don't have an allocated value. re.AllocatedAt, _ = time.Parse("2006-01-02", string(tokens[3])) // Read name re.Name = ParseName(string(tokens[4])) // Add to response slice resp = append(resp, re) if len(resp) == cap(resp) { finished = true } } return resp, err }
go
func (c *whoisClient) LookupASNs(asns []ASN) (resp []Response, err error) { resp = make([]Response, 0, len(asns)) c.ncmu.Lock() defer c.ncmu.Unlock() for _, asn := range asns { c.w.WriteString(asn.String()) c.w.Write(ncEOL) if err = c.w.Flush(); err != nil { return resp, err } } c.Conn.SetDeadline(time.Now().Add(time.Second*5 + (time.Second * time.Duration(len(asns))))) // Raw response var raw []byte var tokens [][]byte var asn int var finished bool // Read results for !finished && c.sc.Scan() { raw = c.sc.Bytes() if bytes.HasPrefix(raw, []byte("Error: ")) { return resp, errors.Errorf("recieved err: %v", raw) } tokens = bytes.Split(raw, []byte{'|'}) if len(tokens) != netcatASNTokensLength { return resp, ErrUnexpectedTokens } // Trim excess whitespace from tokens for i := range tokens { tokens[i] = bytes.TrimSpace(tokens[i]) } re := Response{} // Read ASN if asn, err = strconv.Atoi(string(tokens[0])); err != nil { return nil, errors.Wrapf(err, "failed to atoi %s", tokens[0]) } re.ASN = ASN(asn) // Read country re.Country = string(tokens[1]) // Read registry re.Registry = string(bytes.ToUpper(tokens[2])) // Read allocated. Ignore error as a lot of entries don't have an allocated value. re.AllocatedAt, _ = time.Parse("2006-01-02", string(tokens[3])) // Read name re.Name = ParseName(string(tokens[4])) // Add to response slice resp = append(resp, re) if len(resp) == cap(resp) { finished = true } } return resp, err }
[ "func", "(", "c", "*", "whoisClient", ")", "LookupASNs", "(", "asns", "[", "]", "ASN", ")", "(", "resp", "[", "]", "Response", ",", "err", "error", ")", "{", "resp", "=", "make", "(", "[", "]", "Response", ",", "0", ",", "len", "(", "asns", ")"...
// LookupASNs looks up ASNs. Response IP and Range fields are zeroed
[ "LookupASNs", "looks", "up", "ASNs", ".", "Response", "IP", "and", "Range", "fields", "are", "zeroed" ]
2225ac7a237a562eba212b29d8e7f7277fb9ea9b
https://github.com/ammario/ipisp/blob/2225ac7a237a562eba212b29d8e7f7277fb9ea9b/whois_client.go#L184-L246
152,091
ammario/ipisp
whois_client.go
LookupASN
func (c *whoisClient) LookupASN(asn ASN) (*Response, error) { resp, err := c.LookupASNs([]ASN{asn}) return &resp[0], err }
go
func (c *whoisClient) LookupASN(asn ASN) (*Response, error) { resp, err := c.LookupASNs([]ASN{asn}) return &resp[0], err }
[ "func", "(", "c", "*", "whoisClient", ")", "LookupASN", "(", "asn", "ASN", ")", "(", "*", "Response", ",", "error", ")", "{", "resp", ",", "err", ":=", "c", ".", "LookupASNs", "(", "[", "]", "ASN", "{", "asn", "}", ")", "\n", "return", "&", "re...
// LookupASN is a single ASN convenience proxy of LookupASNs
[ "LookupASN", "is", "a", "single", "ASN", "convenience", "proxy", "of", "LookupASNs" ]
2225ac7a237a562eba212b29d8e7f7277fb9ea9b
https://github.com/ammario/ipisp/blob/2225ac7a237a562eba212b29d8e7f7277fb9ea9b/whois_client.go#L249-L252
152,092
G-Research/go-ntlm-auth
ntlm/ntlm.go
DoNTLMRequest
func DoNTLMRequest(httpClient *http.Client, request *http.Request) (*http.Response, error) { handshakeReq, err := cloneRequest(request) if err != nil { return nil, err } res, err := httpClient.Do(handshakeReq) if err != nil && res == nil { return nil, err } //If the status is 401 then we need to re-authenticate, otherwise it was successful if res.StatusCode == 401 { auth, authOk := getDefaultCredentialsAuth() if authOk { negotiateMessageBytes, err := auth.GetNegotiateBytes() if err != nil { return nil, err } defer auth.ReleaseContext() negotiateReq, err := cloneRequest(request) if err != nil { return nil, err } challengeMessage, err := sendNegotiateRequest(httpClient, negotiateReq, negotiateMessageBytes) if err != nil { return nil, err } challengeReq, err := cloneRequest(request) if err != nil { return nil, err } responseBytes, err := auth.GetResponseBytes(challengeMessage) res, err := sendChallengeRequest(httpClient, challengeReq, responseBytes) if err != nil { return nil, err } return res, nil } } return res, nil }
go
func DoNTLMRequest(httpClient *http.Client, request *http.Request) (*http.Response, error) { handshakeReq, err := cloneRequest(request) if err != nil { return nil, err } res, err := httpClient.Do(handshakeReq) if err != nil && res == nil { return nil, err } //If the status is 401 then we need to re-authenticate, otherwise it was successful if res.StatusCode == 401 { auth, authOk := getDefaultCredentialsAuth() if authOk { negotiateMessageBytes, err := auth.GetNegotiateBytes() if err != nil { return nil, err } defer auth.ReleaseContext() negotiateReq, err := cloneRequest(request) if err != nil { return nil, err } challengeMessage, err := sendNegotiateRequest(httpClient, negotiateReq, negotiateMessageBytes) if err != nil { return nil, err } challengeReq, err := cloneRequest(request) if err != nil { return nil, err } responseBytes, err := auth.GetResponseBytes(challengeMessage) res, err := sendChallengeRequest(httpClient, challengeReq, responseBytes) if err != nil { return nil, err } return res, nil } } return res, nil }
[ "func", "DoNTLMRequest", "(", "httpClient", "*", "http", ".", "Client", ",", "request", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "handshakeReq", ",", "err", ":=", "cloneRequest", "(", "request", ")", ...
// DoNTLMRequest Perform a request using NTLM authentication
[ "DoNTLMRequest", "Perform", "a", "request", "using", "NTLM", "authentication" ]
6314d66e1d8ffd12a8da4be59eb4467b60dde719
https://github.com/G-Research/go-ntlm-auth/blob/6314d66e1d8ffd12a8da4be59eb4467b60dde719/ntlm/ntlm.go#L15-L65
152,093
foolin/gocsv
gocsv.go
Read
func Read(file string, isGbk bool) (list []map[string]interface{}, err error) { //catch panic defer func() { if rerr := recover(); rerr != nil { err = errors.New(fmt.Sprintf("read csv file: %v, error: %v", file, rerr)) } }() list = make([]map[string]interface{}, 0); err = ReadRaw(file, isGbk, func(fields []Field) error { item := make(map[string]interface{}) for _, f := range fields { if len(f.Name) <= 0 { continue } var itemValue interface{} var innerr error switch f.Kind { case "int": itemValue, innerr = strconv.ParseInt(f.Value, 10, 64) if innerr != nil { itemValue = 0 } case "float": itemValue, innerr = strconv.ParseFloat(f.Value, 64) if innerr != nil { itemValue = 0 } default: itemValue = f.Value } item[f.Name] = itemValue } list = append(list, item) return nil }) return list, err }
go
func Read(file string, isGbk bool) (list []map[string]interface{}, err error) { //catch panic defer func() { if rerr := recover(); rerr != nil { err = errors.New(fmt.Sprintf("read csv file: %v, error: %v", file, rerr)) } }() list = make([]map[string]interface{}, 0); err = ReadRaw(file, isGbk, func(fields []Field) error { item := make(map[string]interface{}) for _, f := range fields { if len(f.Name) <= 0 { continue } var itemValue interface{} var innerr error switch f.Kind { case "int": itemValue, innerr = strconv.ParseInt(f.Value, 10, 64) if innerr != nil { itemValue = 0 } case "float": itemValue, innerr = strconv.ParseFloat(f.Value, 64) if innerr != nil { itemValue = 0 } default: itemValue = f.Value } item[f.Name] = itemValue } list = append(list, item) return nil }) return list, err }
[ "func", "Read", "(", "file", "string", ",", "isGbk", "bool", ")", "(", "list", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "err", "error", ")", "{", "//catch panic", "defer", "func", "(", ")", "{", "if", "rerr", ":=", "recover"...
//Read read for map array
[ "Read", "read", "for", "map", "array" ]
d1cfc1a54940e0b038e7f221a362c8c51eacd2c9
https://github.com/foolin/gocsv/blob/d1cfc1a54940e0b038e7f221a362c8c51eacd2c9/gocsv.go#L24-L61
152,094
foolin/gocsv
gocsv.go
format
func format(name string) string { return fmt.Sprintf("%v%v", strings.ToLower(name[0:1]), name[1:]) }
go
func format(name string) string { return fmt.Sprintf("%v%v", strings.ToLower(name[0:1]), name[1:]) }
[ "func", "format", "(", "name", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "ToLower", "(", "name", "[", "0", ":", "1", "]", ")", ",", "name", "[", "1", ":", "]", ")", "\n", "}" ]
//format format name
[ "format", "format", "name" ]
d1cfc1a54940e0b038e7f221a362c8c51eacd2c9
https://github.com/foolin/gocsv/blob/d1cfc1a54940e0b038e7f221a362c8c51eacd2c9/gocsv.go#L348-L350
152,095
go-audio/generator
osc.go
Fill
func (o *Osc) Fill(buf *audio.FloatBuffer) error { if o == nil { return nil } numChans := 1 if f := buf.Format; f != nil { numChans = f.NumChannels } fameCount := buf.NumFrames() var sample float64 for i := 0; i < fameCount; i++ { sample = o.Sample() for j := 0; j < numChans; j++ { buf.Data[i+j] = sample } } return nil }
go
func (o *Osc) Fill(buf *audio.FloatBuffer) error { if o == nil { return nil } numChans := 1 if f := buf.Format; f != nil { numChans = f.NumChannels } fameCount := buf.NumFrames() var sample float64 for i := 0; i < fameCount; i++ { sample = o.Sample() for j := 0; j < numChans; j++ { buf.Data[i+j] = sample } } return nil }
[ "func", "(", "o", "*", "Osc", ")", "Fill", "(", "buf", "*", "audio", ".", "FloatBuffer", ")", "error", "{", "if", "o", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "numChans", ":=", "1", "\n", "if", "f", ":=", "buf", ".", "Format", ";", ...
// Fill fills up the pass audio Buffer with the output of the oscillator.
[ "Fill", "fills", "up", "the", "pass", "audio", "Buffer", "with", "the", "output", "of", "the", "oscillator", "." ]
dbf5ce2499f1911b33391781c7a31a773d9f6fd5
https://github.com/go-audio/generator/blob/dbf5ce2499f1911b33391781c7a31a773d9f6fd5/osc.go#L71-L88
152,096
eidolon/wordwrap
wordwrap.go
doBreakWords
func doBreakWords(words []string, limit int) []string { var result []string for _, word := range words { if len(word) > limit { var parts []string var partBuf bytes.Buffer for _, char := range word { atLimit := partBuf.Len() == limit if atLimit { parts = append(parts, partBuf.String()) partBuf.Reset() } partBuf.WriteRune(char) } if partBuf.Len() > 0 { parts = append(parts, partBuf.String()) } for _, part := range parts { result = append(result, part) } } else { result = append(result, word) } } return result }
go
func doBreakWords(words []string, limit int) []string { var result []string for _, word := range words { if len(word) > limit { var parts []string var partBuf bytes.Buffer for _, char := range word { atLimit := partBuf.Len() == limit if atLimit { parts = append(parts, partBuf.String()) partBuf.Reset() } partBuf.WriteRune(char) } if partBuf.Len() > 0 { parts = append(parts, partBuf.String()) } for _, part := range parts { result = append(result, part) } } else { result = append(result, word) } } return result }
[ "func", "doBreakWords", "(", "words", "[", "]", "string", ",", "limit", "int", ")", "[", "]", "string", "{", "var", "result", "[", "]", "string", "\n\n", "for", "_", ",", "word", ":=", "range", "words", "{", "if", "len", "(", "word", ")", ">", "l...
// Break up any words in a given array of words that exceed the given limit.
[ "Break", "up", "any", "words", "in", "a", "given", "array", "of", "words", "that", "exceed", "the", "given", "limit", "." ]
e0f54129b8bb1d473949f54546a365468435aeaf
https://github.com/eidolon/wordwrap/blob/e0f54129b8bb1d473949f54546a365468435aeaf/wordwrap.go#L91-L124
152,097
ammario/ipisp
name.go
ParseName
func ParseName(raw string) Name { n := Name{ Raw: raw, Short: raw, Long: raw, } tokens := strings.Split(raw, " - ") switch { case len(tokens) == 0: // Just use raw name. case len(tokens) == 1: n.Short = tokens[0] case len(tokens) == 2: n.Short = tokens[0] n.Long = tokens[1] } n.Short = stripAS(n.Short) n.Long = stripAS(n.Long) return n }
go
func ParseName(raw string) Name { n := Name{ Raw: raw, Short: raw, Long: raw, } tokens := strings.Split(raw, " - ") switch { case len(tokens) == 0: // Just use raw name. case len(tokens) == 1: n.Short = tokens[0] case len(tokens) == 2: n.Short = tokens[0] n.Long = tokens[1] } n.Short = stripAS(n.Short) n.Long = stripAS(n.Long) return n }
[ "func", "ParseName", "(", "raw", "string", ")", "Name", "{", "n", ":=", "Name", "{", "Raw", ":", "raw", ",", "Short", ":", "raw", ",", "Long", ":", "raw", ",", "}", "\n\n", "tokens", ":=", "strings", ".", "Split", "(", "raw", ",", "\"", "\"", "...
// ParseName attempts to parse the provided raw name. // The returned Short and Long names are subject to change. Use Raw if you // require determinism.
[ "ParseName", "attempts", "to", "parse", "the", "provided", "raw", "name", ".", "The", "returned", "Short", "and", "Long", "names", "are", "subject", "to", "change", ".", "Use", "Raw", "if", "you", "require", "determinism", "." ]
2225ac7a237a562eba212b29d8e7f7277fb9ea9b
https://github.com/ammario/ipisp/blob/2225ac7a237a562eba212b29d8e7f7277fb9ea9b/name.go#L25-L46
152,098
Robpol86/logrus-custom-formatter
colors.go
Color
func Color(entry *logrus.Entry, formatter *CustomFormatter, s string) string { if !formatter.ForceColors && formatter.DisableColors { return s } // Determine color. Default is info. var levelColor int switch entry.Level { case logrus.DebugLevel: levelColor = formatter.ColorDebug case logrus.WarnLevel: levelColor = formatter.ColorWarn case logrus.ErrorLevel: levelColor = formatter.ColorError case logrus.PanicLevel: levelColor = formatter.ColorPanic case logrus.FatalLevel: levelColor = formatter.ColorFatal default: levelColor = formatter.ColorInfo } if levelColor == AnsiReset { return s } // Colorize. return "\033[" + strconv.Itoa(levelColor) + "m" + s + "\033[0m" }
go
func Color(entry *logrus.Entry, formatter *CustomFormatter, s string) string { if !formatter.ForceColors && formatter.DisableColors { return s } // Determine color. Default is info. var levelColor int switch entry.Level { case logrus.DebugLevel: levelColor = formatter.ColorDebug case logrus.WarnLevel: levelColor = formatter.ColorWarn case logrus.ErrorLevel: levelColor = formatter.ColorError case logrus.PanicLevel: levelColor = formatter.ColorPanic case logrus.FatalLevel: levelColor = formatter.ColorFatal default: levelColor = formatter.ColorInfo } if levelColor == AnsiReset { return s } // Colorize. return "\033[" + strconv.Itoa(levelColor) + "m" + s + "\033[0m" }
[ "func", "Color", "(", "entry", "*", "logrus", ".", "Entry", ",", "formatter", "*", "CustomFormatter", ",", "s", "string", ")", "string", "{", "if", "!", "formatter", ".", "ForceColors", "&&", "formatter", ".", "DisableColors", "{", "return", "s", "\n", "...
// Color colorizes the input string and returns it with ANSI color codes.
[ "Color", "colorizes", "the", "input", "string", "and", "returns", "it", "with", "ANSI", "color", "codes", "." ]
ba99911cd0e4ade6bf41bf080e923bde0ed46b98
https://github.com/Robpol86/logrus-custom-formatter/blob/ba99911cd0e4ade6bf41bf080e923bde0ed46b98/colors.go#L105-L132
152,099
Robpol86/logrus-custom-formatter
colors.go
WindowsNativeANSI
func WindowsNativeANSI() bool { enabled, _ := windowsNativeANSI(true, false, nil) if enabled { return enabled } enabled, _ = windowsNativeANSI(false, false, nil) return enabled }
go
func WindowsNativeANSI() bool { enabled, _ := windowsNativeANSI(true, false, nil) if enabled { return enabled } enabled, _ = windowsNativeANSI(false, false, nil) return enabled }
[ "func", "WindowsNativeANSI", "(", ")", "bool", "{", "enabled", ",", "_", ":=", "windowsNativeANSI", "(", "true", ",", "false", ",", "nil", ")", "\n", "if", "enabled", "{", "return", "enabled", "\n", "}", "\n", "enabled", ",", "_", "=", "windowsNativeANSI...
// WindowsNativeANSI returns true if either the stderr or stdout consoles natively support ANSI color codes. On // non-Windows platforms this always returns false.
[ "WindowsNativeANSI", "returns", "true", "if", "either", "the", "stderr", "or", "stdout", "consoles", "natively", "support", "ANSI", "color", "codes", ".", "On", "non", "-", "Windows", "platforms", "this", "always", "returns", "false", "." ]
ba99911cd0e4ade6bf41bf080e923bde0ed46b98
https://github.com/Robpol86/logrus-custom-formatter/blob/ba99911cd0e4ade6bf41bf080e923bde0ed46b98/colors.go#L136-L143