id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
6,100
google/safebrowsing
database.go
Lookup
func (db *database) Lookup(hash hashPrefix) (h hashPrefix, tds []ThreatDescriptor) { if !hash.IsFull() { panic("hash is not full") } db.ml.RLock() for td, hs := range db.tfl { if n := hs.Lookup(hash); n > 0 { h = hash[:n] tds = append(tds, td) } } db.ml.RUnlock() return h, tds }
go
func (db *database) Lookup(hash hashPrefix) (h hashPrefix, tds []ThreatDescriptor) { if !hash.IsFull() { panic("hash is not full") } db.ml.RLock() for td, hs := range db.tfl { if n := hs.Lookup(hash); n > 0 { h = hash[:n] tds = append(tds, td) } } db.ml.RUnlock() return h, tds }
[ "func", "(", "db", "*", "database", ")", "Lookup", "(", "hash", "hashPrefix", ")", "(", "h", "hashPrefix", ",", "tds", "[", "]", "ThreatDescriptor", ")", "{", "if", "!", "hash", ".", "IsFull", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "db", ".", "ml", ".", "RLock", "(", ")", "\n", "for", "td", ",", "hs", ":=", "range", "db", ".", "tfl", "{", "if", "n", ":=", "hs", ".", "Lookup", "(", "hash", ")", ";", "n", ">", "0", "{", "h", "=", "hash", "[", ":", "n", "]", "\n", "tds", "=", "append", "(", "tds", ",", "td", ")", "\n", "}", "\n", "}", "\n", "db", ".", "ml", ".", "RUnlock", "(", ")", "\n", "return", "h", ",", "tds", "\n", "}" ]
// Lookup looks up the full hash in the threat list and returns a partial // hash and a set of ThreatDescriptors that may match the full hash.
[ "Lookup", "looks", "up", "the", "full", "hash", "in", "the", "threat", "list", "and", "returns", "a", "partial", "hash", "and", "a", "set", "of", "ThreatDescriptors", "that", "may", "match", "the", "full", "hash", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L281-L295
6,101
google/safebrowsing
database.go
setError
func (db *database) setError(err error) { db.tfu = nil db.ml.Lock() if db.err == nil { db.readyCh = make(chan struct{}) } db.tfl, db.err, db.last = nil, err, time.Time{} db.ml.Unlock() }
go
func (db *database) setError(err error) { db.tfu = nil db.ml.Lock() if db.err == nil { db.readyCh = make(chan struct{}) } db.tfl, db.err, db.last = nil, err, time.Time{} db.ml.Unlock() }
[ "func", "(", "db", "*", "database", ")", "setError", "(", "err", "error", ")", "{", "db", ".", "tfu", "=", "nil", "\n\n", "db", ".", "ml", ".", "Lock", "(", ")", "\n", "if", "db", ".", "err", "==", "nil", "{", "db", ".", "readyCh", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "}", "\n", "db", ".", "tfl", ",", "db", ".", "err", ",", "db", ".", "last", "=", "nil", ",", "err", ",", "time", ".", "Time", "{", "}", "\n", "db", ".", "ml", ".", "Unlock", "(", ")", "\n", "}" ]
// setError clears the database state and sets the last error to be err. // // This assumes that the db.mu lock is already held.
[ "setError", "clears", "the", "database", "state", "and", "sets", "the", "last", "error", "to", "be", "err", ".", "This", "assumes", "that", "the", "db", ".", "mu", "lock", "is", "already", "held", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L300-L309
6,102
google/safebrowsing
database.go
isStale
func (db *database) isStale(lastUpdate time.Time) bool { if db.config.now().Sub(lastUpdate) > 2*(db.config.UpdatePeriod+jitter) { return true } return false }
go
func (db *database) isStale(lastUpdate time.Time) bool { if db.config.now().Sub(lastUpdate) > 2*(db.config.UpdatePeriod+jitter) { return true } return false }
[ "func", "(", "db", "*", "database", ")", "isStale", "(", "lastUpdate", "time", ".", "Time", ")", "bool", "{", "if", "db", ".", "config", ".", "now", "(", ")", ".", "Sub", "(", "lastUpdate", ")", ">", "2", "*", "(", "db", ".", "config", ".", "UpdatePeriod", "+", "jitter", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isStale checks whether the last successful update should be considered stale. // Staleness is defined as being older than two of the configured update periods // plus jitter.
[ "isStale", "checks", "whether", "the", "last", "successful", "update", "should", "be", "considered", "stale", ".", "Staleness", "is", "defined", "as", "being", "older", "than", "two", "of", "the", "configured", "update", "periods", "plus", "jitter", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L314-L319
6,103
google/safebrowsing
database.go
setStale
func (db *database) setStale() { if db.err == nil { db.readyCh = make(chan struct{}) } db.err = errStale }
go
func (db *database) setStale() { if db.err == nil { db.readyCh = make(chan struct{}) } db.err = errStale }
[ "func", "(", "db", "*", "database", ")", "setStale", "(", ")", "{", "if", "db", ".", "err", "==", "nil", "{", "db", ".", "readyCh", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "}", "\n", "db", ".", "err", "=", "errStale", "\n", "}" ]
// setStale sets the error state to a stale message, without clearing // the database state. // // This assumes that the db.ml lock is already held.
[ "setStale", "sets", "the", "error", "state", "to", "a", "stale", "message", "without", "clearing", "the", "database", "state", ".", "This", "assumes", "that", "the", "db", ".", "ml", "lock", "is", "already", "held", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L325-L330
6,104
google/safebrowsing
database.go
clearError
func (db *database) clearError() { db.ml.Lock() defer db.ml.Unlock() if db.err != nil { close(db.readyCh) } db.err = nil }
go
func (db *database) clearError() { db.ml.Lock() defer db.ml.Unlock() if db.err != nil { close(db.readyCh) } db.err = nil }
[ "func", "(", "db", "*", "database", ")", "clearError", "(", ")", "{", "db", ".", "ml", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "ml", ".", "Unlock", "(", ")", "\n\n", "if", "db", ".", "err", "!=", "nil", "{", "close", "(", "db", ".", "readyCh", ")", "\n", "}", "\n", "db", ".", "err", "=", "nil", "\n", "}" ]
// clearError clears the db error state, and unblocks any callers of // WaitUntilReady. // // This assumes that the db.mu lock is already held.
[ "clearError", "clears", "the", "db", "error", "state", "and", "unblocks", "any", "callers", "of", "WaitUntilReady", ".", "This", "assumes", "that", "the", "db", ".", "mu", "lock", "is", "already", "held", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L336-L344
6,105
google/safebrowsing
database.go
generateThreatsForUpdate
func (db *database) generateThreatsForUpdate() { if db.tfu == nil { db.tfu = make(threatsForUpdate) } db.ml.RLock() for td, hs := range db.tfl { phs := db.tfu[td] phs.Hashes = hs.Export() db.tfu[td] = phs } db.ml.RUnlock() }
go
func (db *database) generateThreatsForUpdate() { if db.tfu == nil { db.tfu = make(threatsForUpdate) } db.ml.RLock() for td, hs := range db.tfl { phs := db.tfu[td] phs.Hashes = hs.Export() db.tfu[td] = phs } db.ml.RUnlock() }
[ "func", "(", "db", "*", "database", ")", "generateThreatsForUpdate", "(", ")", "{", "if", "db", ".", "tfu", "==", "nil", "{", "db", ".", "tfu", "=", "make", "(", "threatsForUpdate", ")", "\n", "}", "\n\n", "db", ".", "ml", ".", "RLock", "(", ")", "\n", "for", "td", ",", "hs", ":=", "range", "db", ".", "tfl", "{", "phs", ":=", "db", ".", "tfu", "[", "td", "]", "\n", "phs", ".", "Hashes", "=", "hs", ".", "Export", "(", ")", "\n", "db", ".", "tfu", "[", "td", "]", "=", "phs", "\n", "}", "\n", "db", ".", "ml", ".", "RUnlock", "(", ")", "\n", "}" ]
// generateThreatsForUpdate regenerates the threatsForUpdate hashes from // the threatsForLookup. We do this to avoid holding onto the hash lists for // a long time, needlessly occupying lots of memory. // // This assumes that the db.mu lock is already held.
[ "generateThreatsForUpdate", "regenerates", "the", "threatsForUpdate", "hashes", "from", "the", "threatsForLookup", ".", "We", "do", "this", "to", "avoid", "holding", "onto", "the", "hash", "lists", "for", "a", "long", "time", "needlessly", "occupying", "lots", "of", "memory", ".", "This", "assumes", "that", "the", "db", ".", "mu", "lock", "is", "already", "held", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L351-L363
6,106
google/safebrowsing
database.go
generateThreatsForLookups
func (db *database) generateThreatsForLookups(last time.Time) { tfl := make(threatsForLookup) for td, phs := range db.tfu { var hs hashSet hs.Import(phs.Hashes) tfl[td] = hs phs.Hashes = nil // Clear hashes to keep memory usage low db.tfu[td] = phs } db.ml.Lock() wasBad := db.err != nil db.tfl, db.last = tfl, last db.ml.Unlock() if wasBad { db.clearError() db.log.Printf("database is now healthy") } }
go
func (db *database) generateThreatsForLookups(last time.Time) { tfl := make(threatsForLookup) for td, phs := range db.tfu { var hs hashSet hs.Import(phs.Hashes) tfl[td] = hs phs.Hashes = nil // Clear hashes to keep memory usage low db.tfu[td] = phs } db.ml.Lock() wasBad := db.err != nil db.tfl, db.last = tfl, last db.ml.Unlock() if wasBad { db.clearError() db.log.Printf("database is now healthy") } }
[ "func", "(", "db", "*", "database", ")", "generateThreatsForLookups", "(", "last", "time", ".", "Time", ")", "{", "tfl", ":=", "make", "(", "threatsForLookup", ")", "\n", "for", "td", ",", "phs", ":=", "range", "db", ".", "tfu", "{", "var", "hs", "hashSet", "\n", "hs", ".", "Import", "(", "phs", ".", "Hashes", ")", "\n", "tfl", "[", "td", "]", "=", "hs", "\n\n", "phs", ".", "Hashes", "=", "nil", "// Clear hashes to keep memory usage low", "\n", "db", ".", "tfu", "[", "td", "]", "=", "phs", "\n", "}", "\n\n", "db", ".", "ml", ".", "Lock", "(", ")", "\n", "wasBad", ":=", "db", ".", "err", "!=", "nil", "\n", "db", ".", "tfl", ",", "db", ".", "last", "=", "tfl", ",", "last", "\n", "db", ".", "ml", ".", "Unlock", "(", ")", "\n\n", "if", "wasBad", "{", "db", ".", "clearError", "(", ")", "\n", "db", ".", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// generateThreatsForLookups regenerates the threatsForLookup data structure // from the threatsForUpdate data structure and stores the last timestamp. // Since the hashes are effectively stored as a set inside the threatsForLookup, // we clear out the hashes slice in threatsForUpdate so that it can be GCed. // // This assumes that the db.mu lock is already held.
[ "generateThreatsForLookups", "regenerates", "the", "threatsForLookup", "data", "structure", "from", "the", "threatsForUpdate", "data", "structure", "and", "stores", "the", "last", "timestamp", ".", "Since", "the", "hashes", "are", "effectively", "stored", "as", "a", "set", "inside", "the", "threatsForLookup", "we", "clear", "out", "the", "hashes", "slice", "in", "threatsForUpdate", "so", "that", "it", "can", "be", "GCed", ".", "This", "assumes", "that", "the", "db", ".", "mu", "lock", "is", "already", "held", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L371-L391
6,107
google/safebrowsing
database.go
saveDatabase
func saveDatabase(path string, db databaseFormat) (err error) { var file *os.File file, err = os.Create(path) if err != nil { return err } defer func() { if cerr := file.Close(); err == nil { err = cerr } }() gz, err := gzip.NewWriterLevel(file, gzip.BestCompression) if err != nil { return err } defer func() { if zerr := gz.Close(); err == nil { err = zerr } }() encoder := gob.NewEncoder(gz) if err = encoder.Encode(db); err != nil { return err } return nil }
go
func saveDatabase(path string, db databaseFormat) (err error) { var file *os.File file, err = os.Create(path) if err != nil { return err } defer func() { if cerr := file.Close(); err == nil { err = cerr } }() gz, err := gzip.NewWriterLevel(file, gzip.BestCompression) if err != nil { return err } defer func() { if zerr := gz.Close(); err == nil { err = zerr } }() encoder := gob.NewEncoder(gz) if err = encoder.Encode(db); err != nil { return err } return nil }
[ "func", "saveDatabase", "(", "path", "string", ",", "db", "databaseFormat", ")", "(", "err", "error", ")", "{", "var", "file", "*", "os", ".", "File", "\n", "file", ",", "err", "=", "os", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "cerr", ":=", "file", ".", "Close", "(", ")", ";", "err", "==", "nil", "{", "err", "=", "cerr", "\n", "}", "\n", "}", "(", ")", "\n\n", "gz", ",", "err", ":=", "gzip", ".", "NewWriterLevel", "(", "file", ",", "gzip", ".", "BestCompression", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "zerr", ":=", "gz", ".", "Close", "(", ")", ";", "err", "==", "nil", "{", "err", "=", "zerr", "\n", "}", "\n", "}", "(", ")", "\n\n", "encoder", ":=", "gob", ".", "NewEncoder", "(", "gz", ")", "\n", "if", "err", "=", "encoder", ".", "Encode", "(", "db", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// saveDatabase saves the database threat list to a file.
[ "saveDatabase", "saves", "the", "database", "threat", "list", "to", "a", "file", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L394-L421
6,108
google/safebrowsing
database.go
loadDatabase
func loadDatabase(path string) (db databaseFormat, err error) { var file *os.File file, err = os.Open(path) if err != nil { return db, err } defer func() { if cerr := file.Close(); err == nil { err = cerr } }() gz, err := gzip.NewReader(file) if err != nil { return db, err } defer func() { if zerr := gz.Close(); err == nil { err = zerr } }() decoder := gob.NewDecoder(gz) if err = decoder.Decode(&db); err != nil { return db, err } for _, dv := range db.Table { if !bytes.Equal(dv.SHA256, dv.Hashes.SHA256()) { return db, errors.New("safebrowsing: threat list SHA256 mismatch") } } return db, nil }
go
func loadDatabase(path string) (db databaseFormat, err error) { var file *os.File file, err = os.Open(path) if err != nil { return db, err } defer func() { if cerr := file.Close(); err == nil { err = cerr } }() gz, err := gzip.NewReader(file) if err != nil { return db, err } defer func() { if zerr := gz.Close(); err == nil { err = zerr } }() decoder := gob.NewDecoder(gz) if err = decoder.Decode(&db); err != nil { return db, err } for _, dv := range db.Table { if !bytes.Equal(dv.SHA256, dv.Hashes.SHA256()) { return db, errors.New("safebrowsing: threat list SHA256 mismatch") } } return db, nil }
[ "func", "loadDatabase", "(", "path", "string", ")", "(", "db", "databaseFormat", ",", "err", "error", ")", "{", "var", "file", "*", "os", ".", "File", "\n", "file", ",", "err", "=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "db", ",", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "cerr", ":=", "file", ".", "Close", "(", ")", ";", "err", "==", "nil", "{", "err", "=", "cerr", "\n", "}", "\n", "}", "(", ")", "\n\n", "gz", ",", "err", ":=", "gzip", ".", "NewReader", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "db", ",", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "zerr", ":=", "gz", ".", "Close", "(", ")", ";", "err", "==", "nil", "{", "err", "=", "zerr", "\n", "}", "\n", "}", "(", ")", "\n\n", "decoder", ":=", "gob", ".", "NewDecoder", "(", "gz", ")", "\n", "if", "err", "=", "decoder", ".", "Decode", "(", "&", "db", ")", ";", "err", "!=", "nil", "{", "return", "db", ",", "err", "\n", "}", "\n", "for", "_", ",", "dv", ":=", "range", "db", ".", "Table", "{", "if", "!", "bytes", ".", "Equal", "(", "dv", ".", "SHA256", ",", "dv", ".", "Hashes", ".", "SHA256", "(", ")", ")", "{", "return", "db", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "db", ",", "nil", "\n", "}" ]
// loadDatabase loads the database state from a file.
[ "loadDatabase", "loads", "the", "database", "state", "from", "a", "file", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L424-L456
6,109
google/safebrowsing
database.go
update
func (tfu threatsForUpdate) update(resp *pb.FetchThreatListUpdatesResponse) error { // For each update response do the removes and adds for _, m := range resp.GetListUpdateResponses() { td := ThreatDescriptor{ PlatformType: PlatformType(m.PlatformType), ThreatType: ThreatType(m.ThreatType), ThreatEntryType: ThreatEntryType(m.ThreatEntryType), } phs, ok := tfu[td] switch m.ResponseType { case pb.FetchThreatListUpdatesResponse_ListUpdateResponse_PARTIAL_UPDATE: if !ok { return errors.New("safebrowsing: partial update received for non-existent key") } case pb.FetchThreatListUpdatesResponse_ListUpdateResponse_FULL_UPDATE: if len(m.Removals) > 0 { return errors.New("safebrowsing: indices to be removed included in a full update") } phs = partialHashes{} default: return errors.New("safebrowsing: unknown response type") } // Hashes must be sorted for removal logic to work properly. phs.Hashes.Sort() for _, removal := range m.Removals { idxs, err := decodeIndices(removal) if err != nil { return err } for _, i := range idxs { if i < 0 || i >= int32(len(phs.Hashes)) { return errors.New("safebrowsing: invalid removal index") } phs.Hashes[i] = "" } } // If any removal was performed, compact the list of hashes. if len(m.Removals) > 0 { compactHashes := phs.Hashes[:0] for _, h := range phs.Hashes { if h != "" { compactHashes = append(compactHashes, h) } } phs.Hashes = compactHashes } for _, addition := range m.Additions { hashes, err := decodeHashes(addition) if err != nil { return err } phs.Hashes = append(phs.Hashes, hashes...) } // Hashes must be sorted for SHA256 checksum to be correct. phs.Hashes.Sort() if err := phs.Hashes.Validate(); err != nil { return err } if cs := m.GetChecksum(); cs != nil { phs.SHA256 = cs.Sha256 } if !bytes.Equal(phs.SHA256, phs.Hashes.SHA256()) { return errors.New("safebrowsing: threat list SHA256 mismatch") } phs.State = m.NewClientState tfu[td] = phs } return nil }
go
func (tfu threatsForUpdate) update(resp *pb.FetchThreatListUpdatesResponse) error { // For each update response do the removes and adds for _, m := range resp.GetListUpdateResponses() { td := ThreatDescriptor{ PlatformType: PlatformType(m.PlatformType), ThreatType: ThreatType(m.ThreatType), ThreatEntryType: ThreatEntryType(m.ThreatEntryType), } phs, ok := tfu[td] switch m.ResponseType { case pb.FetchThreatListUpdatesResponse_ListUpdateResponse_PARTIAL_UPDATE: if !ok { return errors.New("safebrowsing: partial update received for non-existent key") } case pb.FetchThreatListUpdatesResponse_ListUpdateResponse_FULL_UPDATE: if len(m.Removals) > 0 { return errors.New("safebrowsing: indices to be removed included in a full update") } phs = partialHashes{} default: return errors.New("safebrowsing: unknown response type") } // Hashes must be sorted for removal logic to work properly. phs.Hashes.Sort() for _, removal := range m.Removals { idxs, err := decodeIndices(removal) if err != nil { return err } for _, i := range idxs { if i < 0 || i >= int32(len(phs.Hashes)) { return errors.New("safebrowsing: invalid removal index") } phs.Hashes[i] = "" } } // If any removal was performed, compact the list of hashes. if len(m.Removals) > 0 { compactHashes := phs.Hashes[:0] for _, h := range phs.Hashes { if h != "" { compactHashes = append(compactHashes, h) } } phs.Hashes = compactHashes } for _, addition := range m.Additions { hashes, err := decodeHashes(addition) if err != nil { return err } phs.Hashes = append(phs.Hashes, hashes...) } // Hashes must be sorted for SHA256 checksum to be correct. phs.Hashes.Sort() if err := phs.Hashes.Validate(); err != nil { return err } if cs := m.GetChecksum(); cs != nil { phs.SHA256 = cs.Sha256 } if !bytes.Equal(phs.SHA256, phs.Hashes.SHA256()) { return errors.New("safebrowsing: threat list SHA256 mismatch") } phs.State = m.NewClientState tfu[td] = phs } return nil }
[ "func", "(", "tfu", "threatsForUpdate", ")", "update", "(", "resp", "*", "pb", ".", "FetchThreatListUpdatesResponse", ")", "error", "{", "// For each update response do the removes and adds", "for", "_", ",", "m", ":=", "range", "resp", ".", "GetListUpdateResponses", "(", ")", "{", "td", ":=", "ThreatDescriptor", "{", "PlatformType", ":", "PlatformType", "(", "m", ".", "PlatformType", ")", ",", "ThreatType", ":", "ThreatType", "(", "m", ".", "ThreatType", ")", ",", "ThreatEntryType", ":", "ThreatEntryType", "(", "m", ".", "ThreatEntryType", ")", ",", "}", "\n\n", "phs", ",", "ok", ":=", "tfu", "[", "td", "]", "\n", "switch", "m", ".", "ResponseType", "{", "case", "pb", ".", "FetchThreatListUpdatesResponse_ListUpdateResponse_PARTIAL_UPDATE", ":", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "pb", ".", "FetchThreatListUpdatesResponse_ListUpdateResponse_FULL_UPDATE", ":", "if", "len", "(", "m", ".", "Removals", ")", ">", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "phs", "=", "partialHashes", "{", "}", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Hashes must be sorted for removal logic to work properly.", "phs", ".", "Hashes", ".", "Sort", "(", ")", "\n\n", "for", "_", ",", "removal", ":=", "range", "m", ".", "Removals", "{", "idxs", ",", "err", ":=", "decodeIndices", "(", "removal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "idxs", "{", "if", "i", "<", "0", "||", "i", ">=", "int32", "(", "len", "(", "phs", ".", "Hashes", ")", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "phs", ".", "Hashes", "[", "i", "]", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "// If any removal was performed, compact the list of hashes.", "if", "len", "(", "m", ".", "Removals", ")", ">", "0", "{", "compactHashes", ":=", "phs", ".", "Hashes", "[", ":", "0", "]", "\n", "for", "_", ",", "h", ":=", "range", "phs", ".", "Hashes", "{", "if", "h", "!=", "\"", "\"", "{", "compactHashes", "=", "append", "(", "compactHashes", ",", "h", ")", "\n", "}", "\n", "}", "\n", "phs", ".", "Hashes", "=", "compactHashes", "\n", "}", "\n\n", "for", "_", ",", "addition", ":=", "range", "m", ".", "Additions", "{", "hashes", ",", "err", ":=", "decodeHashes", "(", "addition", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "phs", ".", "Hashes", "=", "append", "(", "phs", ".", "Hashes", ",", "hashes", "...", ")", "\n", "}", "\n\n", "// Hashes must be sorted for SHA256 checksum to be correct.", "phs", ".", "Hashes", ".", "Sort", "(", ")", "\n", "if", "err", ":=", "phs", ".", "Hashes", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "cs", ":=", "m", ".", "GetChecksum", "(", ")", ";", "cs", "!=", "nil", "{", "phs", ".", "SHA256", "=", "cs", ".", "Sha256", "\n", "}", "\n", "if", "!", "bytes", ".", "Equal", "(", "phs", ".", "SHA256", ",", "phs", ".", "Hashes", ".", "SHA256", "(", ")", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "phs", ".", "State", "=", "m", ".", "NewClientState", "\n", "tfu", "[", "td", "]", "=", "phs", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// update updates the threat list according to the API response.
[ "update", "updates", "the", "threat", "list", "according", "to", "the", "API", "response", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/database.go#L459-L536
6,110
google/safebrowsing
cmd/sbserver/main.go
unmarshal
func unmarshal(req *http.Request, pbReq proto.Message) (string, error) { var mime string alt := req.URL.Query().Get("alt") if alt == "" { alt = req.Header.Get("Content-Type") } switch alt { case "json", mimeJSON: mime = mimeJSON case "proto", mimeProto: mime = mimeProto default: return mime, errors.New("invalid interchange format") } switch req.Header.Get("Content-Type") { case mimeJSON: if err := jsonpb.Unmarshal(req.Body, pbReq); err != nil { return mime, err } case mimeProto: body, err := ioutil.ReadAll(req.Body) if err != nil { return mime, err } if err := proto.Unmarshal(body, pbReq); err != nil { return mime, err } } return mime, nil }
go
func unmarshal(req *http.Request, pbReq proto.Message) (string, error) { var mime string alt := req.URL.Query().Get("alt") if alt == "" { alt = req.Header.Get("Content-Type") } switch alt { case "json", mimeJSON: mime = mimeJSON case "proto", mimeProto: mime = mimeProto default: return mime, errors.New("invalid interchange format") } switch req.Header.Get("Content-Type") { case mimeJSON: if err := jsonpb.Unmarshal(req.Body, pbReq); err != nil { return mime, err } case mimeProto: body, err := ioutil.ReadAll(req.Body) if err != nil { return mime, err } if err := proto.Unmarshal(body, pbReq); err != nil { return mime, err } } return mime, nil }
[ "func", "unmarshal", "(", "req", "*", "http", ".", "Request", ",", "pbReq", "proto", ".", "Message", ")", "(", "string", ",", "error", ")", "{", "var", "mime", "string", "\n", "alt", ":=", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "alt", "==", "\"", "\"", "{", "alt", "=", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "}", "\n", "switch", "alt", "{", "case", "\"", "\"", ",", "mimeJSON", ":", "mime", "=", "mimeJSON", "\n", "case", "\"", "\"", ",", "mimeProto", ":", "mime", "=", "mimeProto", "\n", "default", ":", "return", "mime", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "{", "case", "mimeJSON", ":", "if", "err", ":=", "jsonpb", ".", "Unmarshal", "(", "req", ".", "Body", ",", "pbReq", ")", ";", "err", "!=", "nil", "{", "return", "mime", ",", "err", "\n", "}", "\n", "case", "mimeProto", ":", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "req", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "mime", ",", "err", "\n", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "body", ",", "pbReq", ")", ";", "err", "!=", "nil", "{", "return", "mime", ",", "err", "\n", "}", "\n", "}", "\n", "return", "mime", ",", "nil", "\n", "}" ]
// unmarshal reads pbResp from req. The mime will either be JSON or ProtoBuf.
[ "unmarshal", "reads", "pbResp", "from", "req", ".", "The", "mime", "will", "either", "be", "JSON", "or", "ProtoBuf", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/cmd/sbserver/main.go#L251-L281
6,111
google/safebrowsing
cmd/sbserver/main.go
marshal
func marshal(resp http.ResponseWriter, pbResp proto.Message, mime string) error { resp.Header().Set("Content-Type", mime) switch mime { case mimeProto: body, err := proto.Marshal(pbResp) if err != nil { return err } if _, err := resp.Write(body); err != nil { return err } case mimeJSON: var m jsonpb.Marshaler var b bytes.Buffer if err := m.Marshal(&b, pbResp); err != nil { return err } if _, err := resp.Write(b.Bytes()); err != nil { return err } default: return errors.New("invalid interchange format") } return nil }
go
func marshal(resp http.ResponseWriter, pbResp proto.Message, mime string) error { resp.Header().Set("Content-Type", mime) switch mime { case mimeProto: body, err := proto.Marshal(pbResp) if err != nil { return err } if _, err := resp.Write(body); err != nil { return err } case mimeJSON: var m jsonpb.Marshaler var b bytes.Buffer if err := m.Marshal(&b, pbResp); err != nil { return err } if _, err := resp.Write(b.Bytes()); err != nil { return err } default: return errors.New("invalid interchange format") } return nil }
[ "func", "marshal", "(", "resp", "http", ".", "ResponseWriter", ",", "pbResp", "proto", ".", "Message", ",", "mime", "string", ")", "error", "{", "resp", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "mime", ")", "\n", "switch", "mime", "{", "case", "mimeProto", ":", "body", ",", "err", ":=", "proto", ".", "Marshal", "(", "pbResp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "resp", ".", "Write", "(", "body", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "mimeJSON", ":", "var", "m", "jsonpb", ".", "Marshaler", "\n", "var", "b", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "m", ".", "Marshal", "(", "&", "b", ",", "pbResp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "resp", ".", "Write", "(", "b", ".", "Bytes", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// marshal writes pbResp into resp. The mime can either be JSON or ProtoBuf.
[ "marshal", "writes", "pbResp", "into", "resp", ".", "The", "mime", "can", "either", "be", "JSON", "or", "ProtoBuf", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/cmd/sbserver/main.go#L284-L308
6,112
google/safebrowsing
cmd/sbserver/main.go
serveStatus
func serveStatus(resp http.ResponseWriter, req *http.Request, sb *safebrowsing.SafeBrowser) { stats, sbErr := sb.Status() errStr := "" if sbErr != nil { errStr = sbErr.Error() } buf, err := json.Marshal(struct { Stats safebrowsing.Stats Error string }{stats, errStr}) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } resp.Header().Set("Content-Type", mimeJSON) resp.Write(buf) }
go
func serveStatus(resp http.ResponseWriter, req *http.Request, sb *safebrowsing.SafeBrowser) { stats, sbErr := sb.Status() errStr := "" if sbErr != nil { errStr = sbErr.Error() } buf, err := json.Marshal(struct { Stats safebrowsing.Stats Error string }{stats, errStr}) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } resp.Header().Set("Content-Type", mimeJSON) resp.Write(buf) }
[ "func", "serveStatus", "(", "resp", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "sb", "*", "safebrowsing", ".", "SafeBrowser", ")", "{", "stats", ",", "sbErr", ":=", "sb", ".", "Status", "(", ")", "\n", "errStr", ":=", "\"", "\"", "\n", "if", "sbErr", "!=", "nil", "{", "errStr", "=", "sbErr", ".", "Error", "(", ")", "\n", "}", "\n", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "struct", "{", "Stats", "safebrowsing", ".", "Stats", "\n", "Error", "string", "\n", "}", "{", "stats", ",", "errStr", "}", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "resp", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "resp", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "mimeJSON", ")", "\n", "resp", ".", "Write", "(", "buf", ")", "\n", "}" ]
// serveStatus writes a simple JSON with server status information to resp.
[ "serveStatus", "writes", "a", "simple", "JSON", "with", "server", "status", "information", "to", "resp", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/cmd/sbserver/main.go#L311-L327
6,113
google/safebrowsing
cmd/sbserver/main.go
serveRedirector
func serveRedirector(resp http.ResponseWriter, req *http.Request, sb *safebrowsing.SafeBrowser, fs http.FileSystem) { rawURL := req.URL.Query().Get("url") if rawURL == "" || req.URL.Path != "/r" { http.NotFound(resp, req) return } parsedURL, err := url.Parse(rawURL) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } threats, err := sb.LookupURLsContext(req.Context(), []string{rawURL}) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } if len(threats[0]) == 0 { http.Redirect(resp, req, rawURL, http.StatusFound) return } t := template.New("Safe Browsing Interstitial") for _, threat := range threats[0] { if tmpl, ok := threatTemplate[threat.ThreatType]; ok { t, err = parseTemplates(fs, t, tmpl, "/interstitial.html") if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } err = t.Execute(resp, map[string]interface{}{ "Threat": threat, "Url": parsedURL}) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) } return } } http.Error(resp, err.Error(), http.StatusInternalServerError) }
go
func serveRedirector(resp http.ResponseWriter, req *http.Request, sb *safebrowsing.SafeBrowser, fs http.FileSystem) { rawURL := req.URL.Query().Get("url") if rawURL == "" || req.URL.Path != "/r" { http.NotFound(resp, req) return } parsedURL, err := url.Parse(rawURL) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } threats, err := sb.LookupURLsContext(req.Context(), []string{rawURL}) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } if len(threats[0]) == 0 { http.Redirect(resp, req, rawURL, http.StatusFound) return } t := template.New("Safe Browsing Interstitial") for _, threat := range threats[0] { if tmpl, ok := threatTemplate[threat.ThreatType]; ok { t, err = parseTemplates(fs, t, tmpl, "/interstitial.html") if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } err = t.Execute(resp, map[string]interface{}{ "Threat": threat, "Url": parsedURL}) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) } return } } http.Error(resp, err.Error(), http.StatusInternalServerError) }
[ "func", "serveRedirector", "(", "resp", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "sb", "*", "safebrowsing", ".", "SafeBrowser", ",", "fs", "http", ".", "FileSystem", ")", "{", "rawURL", ":=", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "rawURL", "==", "\"", "\"", "||", "req", ".", "URL", ".", "Path", "!=", "\"", "\"", "{", "http", ".", "NotFound", "(", "resp", ",", "req", ")", "\n", "return", "\n", "}", "\n", "parsedURL", ",", "err", ":=", "url", ".", "Parse", "(", "rawURL", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "resp", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "threats", ",", "err", ":=", "sb", ".", "LookupURLsContext", "(", "req", ".", "Context", "(", ")", ",", "[", "]", "string", "{", "rawURL", "}", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "resp", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "if", "len", "(", "threats", "[", "0", "]", ")", "==", "0", "{", "http", ".", "Redirect", "(", "resp", ",", "req", ",", "rawURL", ",", "http", ".", "StatusFound", ")", "\n", "return", "\n", "}", "\n\n", "t", ":=", "template", ".", "New", "(", "\"", "\"", ")", "\n", "for", "_", ",", "threat", ":=", "range", "threats", "[", "0", "]", "{", "if", "tmpl", ",", "ok", ":=", "threatTemplate", "[", "threat", ".", "ThreatType", "]", ";", "ok", "{", "t", ",", "err", "=", "parseTemplates", "(", "fs", ",", "t", ",", "tmpl", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "resp", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "err", "=", "t", ".", "Execute", "(", "resp", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "threat", ",", "\"", "\"", ":", "parsedURL", "}", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "resp", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "http", ".", "Error", "(", "resp", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}" ]
// serveRedirector implements a basic HTTP redirector that will filter out // redirect URLs that are unsafe according to the Safe Browsing API.
[ "serveRedirector", "implements", "a", "basic", "HTTP", "redirector", "that", "will", "filter", "out", "redirect", "URLs", "that", "are", "unsafe", "according", "to", "the", "Safe", "Browsing", "API", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/cmd/sbserver/main.go#L456-L495
6,114
google/safebrowsing
urls.go
generateHashes
func generateHashes(url string) (map[hashPrefix]string, error) { patterns, err := generatePatterns(url) if err != nil { return nil, err } hashes := make(map[hashPrefix]string) for _, p := range patterns { hashes[hashFromPattern(p)] = p } return hashes, nil }
go
func generateHashes(url string) (map[hashPrefix]string, error) { patterns, err := generatePatterns(url) if err != nil { return nil, err } hashes := make(map[hashPrefix]string) for _, p := range patterns { hashes[hashFromPattern(p)] = p } return hashes, nil }
[ "func", "generateHashes", "(", "url", "string", ")", "(", "map", "[", "hashPrefix", "]", "string", ",", "error", ")", "{", "patterns", ",", "err", ":=", "generatePatterns", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "hashes", ":=", "make", "(", "map", "[", "hashPrefix", "]", "string", ")", "\n", "for", "_", ",", "p", ":=", "range", "patterns", "{", "hashes", "[", "hashFromPattern", "(", "p", ")", "]", "=", "p", "\n", "}", "\n", "return", "hashes", ",", "nil", "\n", "}" ]
// generateHashes returns a set of full hashes for all patterns in the URL.
[ "generateHashes", "returns", "a", "set", "of", "full", "hashes", "for", "all", "patterns", "in", "the", "URL", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L75-L86
6,115
google/safebrowsing
urls.go
generatePatterns
func generatePatterns(url string) ([]string, error) { hosts, err := generateLookupHosts(url) if err != nil { return nil, err } paths, err := generateLookupPaths(url) if err != nil { return nil, err } var patterns []string for _, h := range hosts { for _, p := range paths { patterns = append(patterns, h+p) } } return patterns, nil }
go
func generatePatterns(url string) ([]string, error) { hosts, err := generateLookupHosts(url) if err != nil { return nil, err } paths, err := generateLookupPaths(url) if err != nil { return nil, err } var patterns []string for _, h := range hosts { for _, p := range paths { patterns = append(patterns, h+p) } } return patterns, nil }
[ "func", "generatePatterns", "(", "url", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "hosts", ",", "err", ":=", "generateLookupHosts", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "paths", ",", "err", ":=", "generateLookupPaths", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "patterns", "[", "]", "string", "\n", "for", "_", ",", "h", ":=", "range", "hosts", "{", "for", "_", ",", "p", ":=", "range", "paths", "{", "patterns", "=", "append", "(", "patterns", ",", "h", "+", "p", ")", "\n", "}", "\n", "}", "\n", "return", "patterns", ",", "nil", "\n", "}" ]
// generatePatterns returns all possible host-suffix and path-prefix patterns // for the input URL.
[ "generatePatterns", "returns", "all", "possible", "host", "-", "suffix", "and", "path", "-", "prefix", "patterns", "for", "the", "input", "URL", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L90-L106
6,116
google/safebrowsing
urls.go
isHex
func isHex(c byte) bool { switch { case '0' <= c && c <= '9': return true case 'a' <= c && c <= 'f': return true case 'A' <= c && c <= 'F': return true } return false }
go
func isHex(c byte) bool { switch { case '0' <= c && c <= '9': return true case 'a' <= c && c <= 'f': return true case 'A' <= c && c <= 'F': return true } return false }
[ "func", "isHex", "(", "c", "byte", ")", "bool", "{", "switch", "{", "case", "'0'", "<=", "c", "&&", "c", "<=", "'9'", ":", "return", "true", "\n", "case", "'a'", "<=", "c", "&&", "c", "<=", "'f'", ":", "return", "true", "\n", "case", "'A'", "<=", "c", "&&", "c", "<=", "'F'", ":", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isHex reports whether c is a hexadecimal character.
[ "isHex", "reports", "whether", "c", "is", "a", "hexadecimal", "character", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L109-L119
6,117
google/safebrowsing
urls.go
isUnicode
func isUnicode(s string) bool { for _, c := range []byte(s) { // For legacy reasons, 0x80 is not considered a Unicode character. if c > 0x80 { return true } } return false }
go
func isUnicode(s string) bool { for _, c := range []byte(s) { // For legacy reasons, 0x80 is not considered a Unicode character. if c > 0x80 { return true } } return false }
[ "func", "isUnicode", "(", "s", "string", ")", "bool", "{", "for", "_", ",", "c", ":=", "range", "[", "]", "byte", "(", "s", ")", "{", "// For legacy reasons, 0x80 is not considered a Unicode character.", "if", "c", ">", "0x80", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isUnicode reports whether s is a Unicode string.
[ "isUnicode", "reports", "whether", "s", "is", "a", "Unicode", "string", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L135-L143
6,118
google/safebrowsing
urls.go
escape
func escape(s string) string { var b bytes.Buffer for _, c := range []byte(s) { if c < 0x20 || c >= 0x7f || c == ' ' || c == '#' || c == '%' { b.WriteString(fmt.Sprintf("%%%02x", c)) } else { b.WriteByte(c) } } return b.String() }
go
func escape(s string) string { var b bytes.Buffer for _, c := range []byte(s) { if c < 0x20 || c >= 0x7f || c == ' ' || c == '#' || c == '%' { b.WriteString(fmt.Sprintf("%%%02x", c)) } else { b.WriteByte(c) } } return b.String() }
[ "func", "escape", "(", "s", "string", ")", "string", "{", "var", "b", "bytes", ".", "Buffer", "\n", "for", "_", ",", "c", ":=", "range", "[", "]", "byte", "(", "s", ")", "{", "if", "c", "<", "0x20", "||", "c", ">=", "0x7f", "||", "c", "==", "' '", "||", "c", "==", "'#'", "||", "c", "==", "'%'", "{", "b", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ")", ")", "\n", "}", "else", "{", "b", ".", "WriteByte", "(", "c", ")", "\n", "}", "\n", "}", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// escape returns the percent-encoded form of the string s.
[ "escape", "returns", "the", "percent", "-", "encoded", "form", "of", "the", "string", "s", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L164-L174
6,119
google/safebrowsing
urls.go
unescape
func unescape(s string) string { var b bytes.Buffer for len(s) > 0 { if len(s) >= 3 && s[0] == '%' && isHex(s[1]) && isHex(s[2]) { b.WriteByte(unhex(s[1])<<4 | unhex(s[2])) s = s[3:] } else { b.WriteByte(s[0]) s = s[1:] } } return b.String() }
go
func unescape(s string) string { var b bytes.Buffer for len(s) > 0 { if len(s) >= 3 && s[0] == '%' && isHex(s[1]) && isHex(s[2]) { b.WriteByte(unhex(s[1])<<4 | unhex(s[2])) s = s[3:] } else { b.WriteByte(s[0]) s = s[1:] } } return b.String() }
[ "func", "unescape", "(", "s", "string", ")", "string", "{", "var", "b", "bytes", ".", "Buffer", "\n", "for", "len", "(", "s", ")", ">", "0", "{", "if", "len", "(", "s", ")", ">=", "3", "&&", "s", "[", "0", "]", "==", "'%'", "&&", "isHex", "(", "s", "[", "1", "]", ")", "&&", "isHex", "(", "s", "[", "2", "]", ")", "{", "b", ".", "WriteByte", "(", "unhex", "(", "s", "[", "1", "]", ")", "<<", "4", "|", "unhex", "(", "s", "[", "2", "]", ")", ")", "\n", "s", "=", "s", "[", "3", ":", "]", "\n", "}", "else", "{", "b", ".", "WriteByte", "(", "s", "[", "0", "]", ")", "\n", "s", "=", "s", "[", "1", ":", "]", "\n", "}", "\n", "}", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// unescape returns the decoded form of a percent-encoded string s.
[ "unescape", "returns", "the", "decoded", "form", "of", "a", "percent", "-", "encoded", "string", "s", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L177-L189
6,120
google/safebrowsing
urls.go
recursiveUnescape
func recursiveUnescape(s string) (string, error) { const maxDepth = 1024 for i := 0; i < maxDepth; i++ { t := unescape(s) if t == s { return s, nil } s = t } return "", errors.New("safebrowsing: unescaping is too recursive") }
go
func recursiveUnescape(s string) (string, error) { const maxDepth = 1024 for i := 0; i < maxDepth; i++ { t := unescape(s) if t == s { return s, nil } s = t } return "", errors.New("safebrowsing: unescaping is too recursive") }
[ "func", "recursiveUnescape", "(", "s", "string", ")", "(", "string", ",", "error", ")", "{", "const", "maxDepth", "=", "1024", "\n", "for", "i", ":=", "0", ";", "i", "<", "maxDepth", ";", "i", "++", "{", "t", ":=", "unescape", "(", "s", ")", "\n", "if", "t", "==", "s", "{", "return", "s", ",", "nil", "\n", "}", "\n", "s", "=", "t", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// recursiveUnescape unescapes the string s recursively until it cannot be // unescaped anymore. It reports an error if the unescaping process seemed to // have no end.
[ "recursiveUnescape", "unescapes", "the", "string", "s", "recursively", "until", "it", "cannot", "be", "unescaped", "anymore", ".", "It", "reports", "an", "error", "if", "the", "unescaping", "process", "seemed", "to", "have", "no", "end", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L194-L204
6,121
google/safebrowsing
urls.go
normalizeEscape
func normalizeEscape(s string) (string, error) { u, err := recursiveUnescape(s) if err != nil { return "", err } return escape(u), nil }
go
func normalizeEscape(s string) (string, error) { u, err := recursiveUnescape(s) if err != nil { return "", err } return escape(u), nil }
[ "func", "normalizeEscape", "(", "s", "string", ")", "(", "string", ",", "error", ")", "{", "u", ",", "err", ":=", "recursiveUnescape", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "escape", "(", "u", ")", ",", "nil", "\n", "}" ]
// normalizeEscape performs a recursive unescape and then escapes the string // exactly once. It reports an error if it was unable to unescape the string.
[ "normalizeEscape", "performs", "a", "recursive", "unescape", "and", "then", "escapes", "the", "string", "exactly", "once", ".", "It", "reports", "an", "error", "if", "it", "was", "unable", "to", "unescape", "the", "string", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L208-L214
6,122
google/safebrowsing
urls.go
parseHost
func parseHost(hostish string) (host string, err error) { i := strings.LastIndex(hostish, "@") if i < 0 { host = hostish } else { host = hostish[i+1:] } if strings.HasPrefix(host, "[") { // Parse an IP-Literal per RFC 3986 and RFC 6874. // For example: "[fe80::1] or "[fe80::1%25en0]" i := strings.LastIndex(host, "]") if i < 0 { return "", errors.New("safebrowsing: missing ']' in host") } } // Remove the port if it is there. host = portRegexp.ReplaceAllString(host, "") // Convert internationalized hostnames to IDNA. u := unescape(host) if isUnicode(u) { host, err = idna.ToASCII(u) if err != nil { return "", err } } // Remove any superfluous '.' characters in the hostname. host = dotsRegexp.ReplaceAllString(host, ".") host = strings.Trim(host, ".") // Canonicalize IP addresses. if iphost := parseIPAddress(host); iphost != "" { host = iphost } else { host = strings.ToLower(host) } return host, nil }
go
func parseHost(hostish string) (host string, err error) { i := strings.LastIndex(hostish, "@") if i < 0 { host = hostish } else { host = hostish[i+1:] } if strings.HasPrefix(host, "[") { // Parse an IP-Literal per RFC 3986 and RFC 6874. // For example: "[fe80::1] or "[fe80::1%25en0]" i := strings.LastIndex(host, "]") if i < 0 { return "", errors.New("safebrowsing: missing ']' in host") } } // Remove the port if it is there. host = portRegexp.ReplaceAllString(host, "") // Convert internationalized hostnames to IDNA. u := unescape(host) if isUnicode(u) { host, err = idna.ToASCII(u) if err != nil { return "", err } } // Remove any superfluous '.' characters in the hostname. host = dotsRegexp.ReplaceAllString(host, ".") host = strings.Trim(host, ".") // Canonicalize IP addresses. if iphost := parseIPAddress(host); iphost != "" { host = iphost } else { host = strings.ToLower(host) } return host, nil }
[ "func", "parseHost", "(", "hostish", "string", ")", "(", "host", "string", ",", "err", "error", ")", "{", "i", ":=", "strings", ".", "LastIndex", "(", "hostish", ",", "\"", "\"", ")", "\n", "if", "i", "<", "0", "{", "host", "=", "hostish", "\n", "}", "else", "{", "host", "=", "hostish", "[", "i", "+", "1", ":", "]", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "host", ",", "\"", "\"", ")", "{", "// Parse an IP-Literal per RFC 3986 and RFC 6874.", "// For example: \"[fe80::1] or \"[fe80::1%25en0]\"", "i", ":=", "strings", ".", "LastIndex", "(", "host", ",", "\"", "\"", ")", "\n", "if", "i", "<", "0", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "// Remove the port if it is there.", "host", "=", "portRegexp", ".", "ReplaceAllString", "(", "host", ",", "\"", "\"", ")", "\n\n", "// Convert internationalized hostnames to IDNA.", "u", ":=", "unescape", "(", "host", ")", "\n", "if", "isUnicode", "(", "u", ")", "{", "host", ",", "err", "=", "idna", ".", "ToASCII", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Remove any superfluous '.' characters in the hostname.", "host", "=", "dotsRegexp", ".", "ReplaceAllString", "(", "host", ",", "\"", "\"", ")", "\n", "host", "=", "strings", ".", "Trim", "(", "host", ",", "\"", "\"", ")", "\n", "// Canonicalize IP addresses.", "if", "iphost", ":=", "parseIPAddress", "(", "host", ")", ";", "iphost", "!=", "\"", "\"", "{", "host", "=", "iphost", "\n", "}", "else", "{", "host", "=", "strings", ".", "ToLower", "(", "host", ")", "\n", "}", "\n", "return", "host", ",", "nil", "\n", "}" ]
// parseHost parses a string to get host by the stripping the // username, password, and port.
[ "parseHost", "parses", "a", "string", "to", "get", "host", "by", "the", "stripping", "the", "username", "password", "and", "port", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L239-L276
6,123
google/safebrowsing
urls.go
parseURL
func parseURL(urlStr string) (parsedURL *url.URL, err error) { // For legacy reasons, this is a simplified version of the net/url logic. // // Few cases where net/url was not helpful: // 1. URLs are are expected to have no escaped encoding in the host but to // be escaped in the path. Safe Browsing allows escaped characters in both. // 2. Also it has different behavior with and without a scheme for absolute // paths. Safe Browsing test web URLs only; and a scheme is optional. // If missing, we assume that it is an "http". // 3. We strip off the fragment and the escaped query as they are not // required for building patterns for Safe Browsing. parsedURL = new(url.URL) // Remove the URL fragment. // Also, we decode and encode the URL. // The '#' in a fragment is not friendly to that. rest, _ := split(urlStr, "#", true) // Start by stripping any leading and trailing whitespace. rest = strings.TrimSpace(rest) // Remove any embedded tabs and CR/LF characters which aren't escaped. rest = strings.Replace(rest, "\t", "", -1) rest = strings.Replace(rest, "\r", "", -1) rest = strings.Replace(rest, "\n", "", -1) rest, err = normalizeEscape(rest) if err != nil { return nil, err } parsedURL.Scheme, rest = getScheme(rest) rest, parsedURL.RawQuery = split(rest, "?", true) // Add HTTP as scheme if none. var hostish string if !strings.HasPrefix(rest, "//") && parsedURL.Scheme != "" { return nil, errors.New("safebrowsing: invalid path") } if parsedURL.Scheme == "" { parsedURL.Scheme = "http" hostish, rest = split(rest, "/", false) } else { hostish, rest = split(rest[2:], "/", false) } if hostish == "" { return nil, errors.New("safebrowsing: missing hostname") } parsedURL.Host, err = parseHost(hostish) if err != nil { return nil, err } // Format the path. p := path.Clean(rest) if p == "." { p = "/" } else if rest[len(rest)-1] == '/' && p[len(p)-1] != '/' { p += "/" } parsedURL.Path = p return parsedURL, nil }
go
func parseURL(urlStr string) (parsedURL *url.URL, err error) { // For legacy reasons, this is a simplified version of the net/url logic. // // Few cases where net/url was not helpful: // 1. URLs are are expected to have no escaped encoding in the host but to // be escaped in the path. Safe Browsing allows escaped characters in both. // 2. Also it has different behavior with and without a scheme for absolute // paths. Safe Browsing test web URLs only; and a scheme is optional. // If missing, we assume that it is an "http". // 3. We strip off the fragment and the escaped query as they are not // required for building patterns for Safe Browsing. parsedURL = new(url.URL) // Remove the URL fragment. // Also, we decode and encode the URL. // The '#' in a fragment is not friendly to that. rest, _ := split(urlStr, "#", true) // Start by stripping any leading and trailing whitespace. rest = strings.TrimSpace(rest) // Remove any embedded tabs and CR/LF characters which aren't escaped. rest = strings.Replace(rest, "\t", "", -1) rest = strings.Replace(rest, "\r", "", -1) rest = strings.Replace(rest, "\n", "", -1) rest, err = normalizeEscape(rest) if err != nil { return nil, err } parsedURL.Scheme, rest = getScheme(rest) rest, parsedURL.RawQuery = split(rest, "?", true) // Add HTTP as scheme if none. var hostish string if !strings.HasPrefix(rest, "//") && parsedURL.Scheme != "" { return nil, errors.New("safebrowsing: invalid path") } if parsedURL.Scheme == "" { parsedURL.Scheme = "http" hostish, rest = split(rest, "/", false) } else { hostish, rest = split(rest[2:], "/", false) } if hostish == "" { return nil, errors.New("safebrowsing: missing hostname") } parsedURL.Host, err = parseHost(hostish) if err != nil { return nil, err } // Format the path. p := path.Clean(rest) if p == "." { p = "/" } else if rest[len(rest)-1] == '/' && p[len(p)-1] != '/' { p += "/" } parsedURL.Path = p return parsedURL, nil }
[ "func", "parseURL", "(", "urlStr", "string", ")", "(", "parsedURL", "*", "url", ".", "URL", ",", "err", "error", ")", "{", "// For legacy reasons, this is a simplified version of the net/url logic.", "//", "// Few cases where net/url was not helpful:", "// 1. URLs are are expected to have no escaped encoding in the host but to", "// be escaped in the path. Safe Browsing allows escaped characters in both.", "// 2. Also it has different behavior with and without a scheme for absolute", "// paths. Safe Browsing test web URLs only; and a scheme is optional.", "// If missing, we assume that it is an \"http\".", "// 3. We strip off the fragment and the escaped query as they are not", "// required for building patterns for Safe Browsing.", "parsedURL", "=", "new", "(", "url", ".", "URL", ")", "\n", "// Remove the URL fragment.", "// Also, we decode and encode the URL.", "// The '#' in a fragment is not friendly to that.", "rest", ",", "_", ":=", "split", "(", "urlStr", ",", "\"", "\"", ",", "true", ")", "\n", "// Start by stripping any leading and trailing whitespace.", "rest", "=", "strings", ".", "TrimSpace", "(", "rest", ")", "\n", "// Remove any embedded tabs and CR/LF characters which aren't escaped.", "rest", "=", "strings", ".", "Replace", "(", "rest", ",", "\"", "\\t", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "rest", "=", "strings", ".", "Replace", "(", "rest", ",", "\"", "\\r", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "rest", "=", "strings", ".", "Replace", "(", "rest", ",", "\"", "\\n", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "rest", ",", "err", "=", "normalizeEscape", "(", "rest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "parsedURL", ".", "Scheme", ",", "rest", "=", "getScheme", "(", "rest", ")", "\n", "rest", ",", "parsedURL", ".", "RawQuery", "=", "split", "(", "rest", ",", "\"", "\"", ",", "true", ")", "\n\n", "// Add HTTP as scheme if none.", "var", "hostish", "string", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "rest", ",", "\"", "\"", ")", "&&", "parsedURL", ".", "Scheme", "!=", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "parsedURL", ".", "Scheme", "==", "\"", "\"", "{", "parsedURL", ".", "Scheme", "=", "\"", "\"", "\n", "hostish", ",", "rest", "=", "split", "(", "rest", ",", "\"", "\"", ",", "false", ")", "\n", "}", "else", "{", "hostish", ",", "rest", "=", "split", "(", "rest", "[", "2", ":", "]", ",", "\"", "\"", ",", "false", ")", "\n", "}", "\n", "if", "hostish", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "parsedURL", ".", "Host", ",", "err", "=", "parseHost", "(", "hostish", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Format the path.", "p", ":=", "path", ".", "Clean", "(", "rest", ")", "\n", "if", "p", "==", "\"", "\"", "{", "p", "=", "\"", "\"", "\n", "}", "else", "if", "rest", "[", "len", "(", "rest", ")", "-", "1", "]", "==", "'/'", "&&", "p", "[", "len", "(", "p", ")", "-", "1", "]", "!=", "'/'", "{", "p", "+=", "\"", "\"", "\n", "}", "\n", "parsedURL", ".", "Path", "=", "p", "\n", "return", "parsedURL", ",", "nil", "\n", "}" ]
// parseURL parses urlStr as a url.URL and reports an error if not possible.
[ "parseURL", "parses", "urlStr", "as", "a", "url", ".", "URL", "and", "reports", "an", "error", "if", "not", "possible", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L279-L337
6,124
google/safebrowsing
urls.go
generateLookupHosts
func generateLookupHosts(urlStr string) ([]string, error) { // Safe Browsing policy asks to generate lookup hosts for the URL. // Those are formed by the domain and also up to 4 hostnames suffixes. // The last component or sometimes the pair isn't examined alone, // since it's the TLD or country code. The database for TLDs is here: // https://publicsuffix.org/list/ // // Note that we do not need to be clever about stopping at the "real" TLD. // We just check a few extra components regardless. It's not significantly // slower on the server side to check some extra hashes. Also the client // does not need to keep a database of TLDs. const maxHostComponents = 7 host, err := canonicalHost(urlStr) if err != nil { return nil, err } // handle IPv4 and IPv6 addresses. ip := net.ParseIP(strings.Trim(host, "[]")) if ip != nil { return []string{host}, nil } hostComponents := strings.Split(host, ".") numComponents := len(hostComponents) - maxHostComponents if numComponents < 1 { numComponents = 1 } hosts := []string{host} for i := numComponents; i < len(hostComponents)-1; i++ { hosts = append(hosts, strings.Join(hostComponents[i:], ".")) } return hosts, nil }
go
func generateLookupHosts(urlStr string) ([]string, error) { // Safe Browsing policy asks to generate lookup hosts for the URL. // Those are formed by the domain and also up to 4 hostnames suffixes. // The last component or sometimes the pair isn't examined alone, // since it's the TLD or country code. The database for TLDs is here: // https://publicsuffix.org/list/ // // Note that we do not need to be clever about stopping at the "real" TLD. // We just check a few extra components regardless. It's not significantly // slower on the server side to check some extra hashes. Also the client // does not need to keep a database of TLDs. const maxHostComponents = 7 host, err := canonicalHost(urlStr) if err != nil { return nil, err } // handle IPv4 and IPv6 addresses. ip := net.ParseIP(strings.Trim(host, "[]")) if ip != nil { return []string{host}, nil } hostComponents := strings.Split(host, ".") numComponents := len(hostComponents) - maxHostComponents if numComponents < 1 { numComponents = 1 } hosts := []string{host} for i := numComponents; i < len(hostComponents)-1; i++ { hosts = append(hosts, strings.Join(hostComponents[i:], ".")) } return hosts, nil }
[ "func", "generateLookupHosts", "(", "urlStr", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "// Safe Browsing policy asks to generate lookup hosts for the URL.", "// Those are formed by the domain and also up to 4 hostnames suffixes.", "// The last component or sometimes the pair isn't examined alone,", "// since it's the TLD or country code. The database for TLDs is here:", "//\thttps://publicsuffix.org/list/", "//", "// Note that we do not need to be clever about stopping at the \"real\" TLD.", "// We just check a few extra components regardless. It's not significantly", "// slower on the server side to check some extra hashes. Also the client", "// does not need to keep a database of TLDs.", "const", "maxHostComponents", "=", "7", "\n\n", "host", ",", "err", ":=", "canonicalHost", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// handle IPv4 and IPv6 addresses.", "ip", ":=", "net", ".", "ParseIP", "(", "strings", ".", "Trim", "(", "host", ",", "\"", "\"", ")", ")", "\n", "if", "ip", "!=", "nil", "{", "return", "[", "]", "string", "{", "host", "}", ",", "nil", "\n", "}", "\n", "hostComponents", ":=", "strings", ".", "Split", "(", "host", ",", "\"", "\"", ")", "\n\n", "numComponents", ":=", "len", "(", "hostComponents", ")", "-", "maxHostComponents", "\n", "if", "numComponents", "<", "1", "{", "numComponents", "=", "1", "\n", "}", "\n\n", "hosts", ":=", "[", "]", "string", "{", "host", "}", "\n", "for", "i", ":=", "numComponents", ";", "i", "<", "len", "(", "hostComponents", ")", "-", "1", ";", "i", "++", "{", "hosts", "=", "append", "(", "hosts", ",", "strings", ".", "Join", "(", "hostComponents", "[", "i", ":", "]", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "hosts", ",", "nil", "\n", "}" ]
// generateLookupHosts returns a list of host-suffixes for the input URL.
[ "generateLookupHosts", "returns", "a", "list", "of", "host", "-", "suffixes", "for", "the", "input", "URL", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L423-L457
6,125
google/safebrowsing
urls.go
generateLookupPaths
func generateLookupPaths(urlStr string) ([]string, error) { const maxPathComponents = 4 parsedURL, err := parseURL(urlStr) if err != nil { return nil, err } path := parsedURL.Path paths := []string{"/"} var pathComponents []string for _, p := range strings.Split(path, "/") { if p != "" { pathComponents = append(pathComponents, p) } } numComponents := len(pathComponents) if numComponents > maxPathComponents { numComponents = maxPathComponents } for i := 1; i < numComponents; i++ { paths = append(paths, "/"+strings.Join(pathComponents[:i], "/")+"/") } if path != "/" { paths = append(paths, path) } if len(parsedURL.RawQuery) > 0 { paths = append(paths, path+"?"+parsedURL.RawQuery) } return paths, nil }
go
func generateLookupPaths(urlStr string) ([]string, error) { const maxPathComponents = 4 parsedURL, err := parseURL(urlStr) if err != nil { return nil, err } path := parsedURL.Path paths := []string{"/"} var pathComponents []string for _, p := range strings.Split(path, "/") { if p != "" { pathComponents = append(pathComponents, p) } } numComponents := len(pathComponents) if numComponents > maxPathComponents { numComponents = maxPathComponents } for i := 1; i < numComponents; i++ { paths = append(paths, "/"+strings.Join(pathComponents[:i], "/")+"/") } if path != "/" { paths = append(paths, path) } if len(parsedURL.RawQuery) > 0 { paths = append(paths, path+"?"+parsedURL.RawQuery) } return paths, nil }
[ "func", "generateLookupPaths", "(", "urlStr", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "const", "maxPathComponents", "=", "4", "\n\n", "parsedURL", ",", "err", ":=", "parseURL", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "path", ":=", "parsedURL", ".", "Path", "\n\n", "paths", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "var", "pathComponents", "[", "]", "string", "\n", "for", "_", ",", "p", ":=", "range", "strings", ".", "Split", "(", "path", ",", "\"", "\"", ")", "{", "if", "p", "!=", "\"", "\"", "{", "pathComponents", "=", "append", "(", "pathComponents", ",", "p", ")", "\n", "}", "\n", "}", "\n\n", "numComponents", ":=", "len", "(", "pathComponents", ")", "\n", "if", "numComponents", ">", "maxPathComponents", "{", "numComponents", "=", "maxPathComponents", "\n", "}", "\n\n", "for", "i", ":=", "1", ";", "i", "<", "numComponents", ";", "i", "++", "{", "paths", "=", "append", "(", "paths", ",", "\"", "\"", "+", "strings", ".", "Join", "(", "pathComponents", "[", ":", "i", "]", ",", "\"", "\"", ")", "+", "\"", "\"", ")", "\n", "}", "\n", "if", "path", "!=", "\"", "\"", "{", "paths", "=", "append", "(", "paths", ",", "path", ")", "\n", "}", "\n", "if", "len", "(", "parsedURL", ".", "RawQuery", ")", ">", "0", "{", "paths", "=", "append", "(", "paths", ",", "path", "+", "\"", "\"", "+", "parsedURL", ".", "RawQuery", ")", "\n", "}", "\n", "return", "paths", ",", "nil", "\n", "}" ]
// generateLookupPaths returns a list path-prefixes for the input URL.
[ "generateLookupPaths", "returns", "a", "list", "path", "-", "prefixes", "for", "the", "input", "URL", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/urls.go#L470-L502
6,126
google/safebrowsing
hash.go
hashFromPattern
func hashFromPattern(pattern string) hashPrefix { hash := sha256.New() hash.Write([]byte(pattern)) return hashPrefix(hash.Sum(nil)) }
go
func hashFromPattern(pattern string) hashPrefix { hash := sha256.New() hash.Write([]byte(pattern)) return hashPrefix(hash.Sum(nil)) }
[ "func", "hashFromPattern", "(", "pattern", "string", ")", "hashPrefix", "{", "hash", ":=", "sha256", ".", "New", "(", ")", "\n", "hash", ".", "Write", "(", "[", "]", "byte", "(", "pattern", ")", ")", "\n", "return", "hashPrefix", "(", "hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// hashFromPattern returns a full hash for the given URL pattern.
[ "hashFromPattern", "returns", "a", "full", "hash", "for", "the", "given", "URL", "pattern", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/hash.go#L39-L43
6,127
google/safebrowsing
hash.go
HasPrefix
func (h hashPrefix) HasPrefix(other hashPrefix) bool { return strings.HasPrefix(string(h), string(other)) }
go
func (h hashPrefix) HasPrefix(other hashPrefix) bool { return strings.HasPrefix(string(h), string(other)) }
[ "func", "(", "h", "hashPrefix", ")", "HasPrefix", "(", "other", "hashPrefix", ")", "bool", "{", "return", "strings", ".", "HasPrefix", "(", "string", "(", "h", ")", ",", "string", "(", "other", ")", ")", "\n", "}" ]
// HasPrefix reports whether other is a prefix of h.
[ "HasPrefix", "reports", "whether", "other", "is", "a", "prefix", "of", "h", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/hash.go#L46-L48
6,128
google/safebrowsing
hash.go
IsValid
func (h hashPrefix) IsValid() bool { return len(h) >= minHashPrefixLength && len(h) <= maxHashPrefixLength }
go
func (h hashPrefix) IsValid() bool { return len(h) >= minHashPrefixLength && len(h) <= maxHashPrefixLength }
[ "func", "(", "h", "hashPrefix", ")", "IsValid", "(", ")", "bool", "{", "return", "len", "(", "h", ")", ">=", "minHashPrefixLength", "&&", "len", "(", "h", ")", "<=", "maxHashPrefixLength", "\n", "}" ]
// IsValid reports whether the hash is a valid partial or full hash.
[ "IsValid", "reports", "whether", "the", "hash", "is", "a", "valid", "partial", "or", "full", "hash", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/hash.go#L56-L58
6,129
google/safebrowsing
hash.go
decodeHashes
func decodeHashes(input *pb.ThreatEntrySet) ([]hashPrefix, error) { switch input.CompressionType { case pb.CompressionType_RAW: raw := input.GetRawHashes() if raw == nil { return nil, errors.New("safebrowsing: nil raw hashes") } if raw.PrefixSize < minHashPrefixLength || raw.PrefixSize > maxHashPrefixLength { return nil, errors.New("safebrowsing: invalid hash prefix length") } if len(raw.RawHashes)%int(raw.PrefixSize) != 0 { return nil, errors.New("safebrowsing: invalid raw hashes") } hashes := make([]hashPrefix, len(raw.RawHashes)/int(raw.PrefixSize)) for i := range hashes { hashes[i] = hashPrefix(raw.RawHashes[:raw.PrefixSize]) raw.RawHashes = raw.RawHashes[raw.PrefixSize:] } return hashes, nil case pb.CompressionType_RICE: values, err := decodeRiceIntegers(input.GetRiceHashes()) if err != nil { return nil, err } hashes := make([]hashPrefix, 0, len(values)) var buf [4]byte for _, h := range values { binary.LittleEndian.PutUint32(buf[:], h) hashes = append(hashes, hashPrefix(buf[:])) } return hashes, nil default: return nil, errors.New("safebrowsing: invalid compression type") } }
go
func decodeHashes(input *pb.ThreatEntrySet) ([]hashPrefix, error) { switch input.CompressionType { case pb.CompressionType_RAW: raw := input.GetRawHashes() if raw == nil { return nil, errors.New("safebrowsing: nil raw hashes") } if raw.PrefixSize < minHashPrefixLength || raw.PrefixSize > maxHashPrefixLength { return nil, errors.New("safebrowsing: invalid hash prefix length") } if len(raw.RawHashes)%int(raw.PrefixSize) != 0 { return nil, errors.New("safebrowsing: invalid raw hashes") } hashes := make([]hashPrefix, len(raw.RawHashes)/int(raw.PrefixSize)) for i := range hashes { hashes[i] = hashPrefix(raw.RawHashes[:raw.PrefixSize]) raw.RawHashes = raw.RawHashes[raw.PrefixSize:] } return hashes, nil case pb.CompressionType_RICE: values, err := decodeRiceIntegers(input.GetRiceHashes()) if err != nil { return nil, err } hashes := make([]hashPrefix, 0, len(values)) var buf [4]byte for _, h := range values { binary.LittleEndian.PutUint32(buf[:], h) hashes = append(hashes, hashPrefix(buf[:])) } return hashes, nil default: return nil, errors.New("safebrowsing: invalid compression type") } }
[ "func", "decodeHashes", "(", "input", "*", "pb", ".", "ThreatEntrySet", ")", "(", "[", "]", "hashPrefix", ",", "error", ")", "{", "switch", "input", ".", "CompressionType", "{", "case", "pb", ".", "CompressionType_RAW", ":", "raw", ":=", "input", ".", "GetRawHashes", "(", ")", "\n", "if", "raw", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "raw", ".", "PrefixSize", "<", "minHashPrefixLength", "||", "raw", ".", "PrefixSize", ">", "maxHashPrefixLength", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "raw", ".", "RawHashes", ")", "%", "int", "(", "raw", ".", "PrefixSize", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "hashes", ":=", "make", "(", "[", "]", "hashPrefix", ",", "len", "(", "raw", ".", "RawHashes", ")", "/", "int", "(", "raw", ".", "PrefixSize", ")", ")", "\n", "for", "i", ":=", "range", "hashes", "{", "hashes", "[", "i", "]", "=", "hashPrefix", "(", "raw", ".", "RawHashes", "[", ":", "raw", ".", "PrefixSize", "]", ")", "\n", "raw", ".", "RawHashes", "=", "raw", ".", "RawHashes", "[", "raw", ".", "PrefixSize", ":", "]", "\n", "}", "\n", "return", "hashes", ",", "nil", "\n", "case", "pb", ".", "CompressionType_RICE", ":", "values", ",", "err", ":=", "decodeRiceIntegers", "(", "input", ".", "GetRiceHashes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "hashes", ":=", "make", "(", "[", "]", "hashPrefix", ",", "0", ",", "len", "(", "values", ")", ")", "\n", "var", "buf", "[", "4", "]", "byte", "\n", "for", "_", ",", "h", ":=", "range", "values", "{", "binary", ".", "LittleEndian", ".", "PutUint32", "(", "buf", "[", ":", "]", ",", "h", ")", "\n", "hashes", "=", "append", "(", "hashes", ",", "hashPrefix", "(", "buf", "[", ":", "]", ")", ")", "\n", "}", "\n", "return", "hashes", ",", "nil", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// decodeHashes takes a ThreatEntrySet and returns a list of hashes that should // be added to the local database.
[ "decodeHashes", "takes", "a", "ThreatEntrySet", "and", "returns", "a", "list", "of", "hashes", "that", "should", "be", "added", "to", "the", "local", "database", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/hash.go#L158-L192
6,130
google/safebrowsing
hash.go
decodeIndices
func decodeIndices(input *pb.ThreatEntrySet) ([]int32, error) { switch input.CompressionType { case pb.CompressionType_RAW: raw := input.GetRawIndices() if raw == nil { return nil, errors.New("safebrowsing: invalid raw indices") } return raw.Indices, nil case pb.CompressionType_RICE: values, err := decodeRiceIntegers(input.GetRiceIndices()) if err != nil { return nil, err } indices := make([]int32, 0, len(values)) for _, v := range values { indices = append(indices, int32(v)) } return indices, nil default: return nil, errors.New("safebrowsing: invalid compression type") } }
go
func decodeIndices(input *pb.ThreatEntrySet) ([]int32, error) { switch input.CompressionType { case pb.CompressionType_RAW: raw := input.GetRawIndices() if raw == nil { return nil, errors.New("safebrowsing: invalid raw indices") } return raw.Indices, nil case pb.CompressionType_RICE: values, err := decodeRiceIntegers(input.GetRiceIndices()) if err != nil { return nil, err } indices := make([]int32, 0, len(values)) for _, v := range values { indices = append(indices, int32(v)) } return indices, nil default: return nil, errors.New("safebrowsing: invalid compression type") } }
[ "func", "decodeIndices", "(", "input", "*", "pb", ".", "ThreatEntrySet", ")", "(", "[", "]", "int32", ",", "error", ")", "{", "switch", "input", ".", "CompressionType", "{", "case", "pb", ".", "CompressionType_RAW", ":", "raw", ":=", "input", ".", "GetRawIndices", "(", ")", "\n", "if", "raw", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "raw", ".", "Indices", ",", "nil", "\n", "case", "pb", ".", "CompressionType_RICE", ":", "values", ",", "err", ":=", "decodeRiceIntegers", "(", "input", ".", "GetRiceIndices", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "indices", ":=", "make", "(", "[", "]", "int32", ",", "0", ",", "len", "(", "values", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "values", "{", "indices", "=", "append", "(", "indices", ",", "int32", "(", "v", ")", ")", "\n", "}", "\n", "return", "indices", ",", "nil", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// decodeIndices takes a ThreatEntrySet for removals returned by the server and // returns a list of indices that the client should remove from its database.
[ "decodeIndices", "takes", "a", "ThreatEntrySet", "for", "removals", "returned", "by", "the", "server", "and", "returns", "a", "list", "of", "indices", "that", "the", "client", "should", "remove", "from", "its", "database", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/hash.go#L196-L217
6,131
google/safebrowsing
hash.go
decodeRiceIntegers
func decodeRiceIntegers(rice *pb.RiceDeltaEncoding) ([]uint32, error) { if rice == nil { return nil, errors.New("safebrowsing: missing rice encoded data") } if rice.RiceParameter < 0 || rice.RiceParameter > 32 { return nil, errors.New("safebrowsing: invalid k parameter") } values := []uint32{uint32(rice.FirstValue)} br := newBitReader(rice.EncodedData) rd := newRiceDecoder(br, uint32(rice.RiceParameter)) for i := 0; i < int(rice.NumEntries); i++ { delta, err := rd.ReadValue() if err != nil { return nil, err } values = append(values, values[i]+delta) } if br.BitsRemaining() >= 8 { return nil, errors.New("safebrowsing: unconsumed rice encoded data") } return values, nil }
go
func decodeRiceIntegers(rice *pb.RiceDeltaEncoding) ([]uint32, error) { if rice == nil { return nil, errors.New("safebrowsing: missing rice encoded data") } if rice.RiceParameter < 0 || rice.RiceParameter > 32 { return nil, errors.New("safebrowsing: invalid k parameter") } values := []uint32{uint32(rice.FirstValue)} br := newBitReader(rice.EncodedData) rd := newRiceDecoder(br, uint32(rice.RiceParameter)) for i := 0; i < int(rice.NumEntries); i++ { delta, err := rd.ReadValue() if err != nil { return nil, err } values = append(values, values[i]+delta) } if br.BitsRemaining() >= 8 { return nil, errors.New("safebrowsing: unconsumed rice encoded data") } return values, nil }
[ "func", "decodeRiceIntegers", "(", "rice", "*", "pb", ".", "RiceDeltaEncoding", ")", "(", "[", "]", "uint32", ",", "error", ")", "{", "if", "rice", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "rice", ".", "RiceParameter", "<", "0", "||", "rice", ".", "RiceParameter", ">", "32", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "values", ":=", "[", "]", "uint32", "{", "uint32", "(", "rice", ".", "FirstValue", ")", "}", "\n", "br", ":=", "newBitReader", "(", "rice", ".", "EncodedData", ")", "\n", "rd", ":=", "newRiceDecoder", "(", "br", ",", "uint32", "(", "rice", ".", "RiceParameter", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "rice", ".", "NumEntries", ")", ";", "i", "++", "{", "delta", ",", "err", ":=", "rd", ".", "ReadValue", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "values", "=", "append", "(", "values", ",", "values", "[", "i", "]", "+", "delta", ")", "\n", "}", "\n\n", "if", "br", ".", "BitsRemaining", "(", ")", ">=", "8", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "values", ",", "nil", "\n", "}" ]
// decodeRiceIntegers decodes a list of Golomb-Rice encoded integers.
[ "decodeRiceIntegers", "decodes", "a", "list", "of", "Golomb", "-", "Rice", "encoded", "integers", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/hash.go#L220-L243
6,132
google/safebrowsing
hash.go
BitsRemaining
func (br *bitReader) BitsRemaining() int { n := 8 * len(br.buf) for m := br.mask | 1; m != 1; m >>= 1 { n-- } return n }
go
func (br *bitReader) BitsRemaining() int { n := 8 * len(br.buf) for m := br.mask | 1; m != 1; m >>= 1 { n-- } return n }
[ "func", "(", "br", "*", "bitReader", ")", "BitsRemaining", "(", ")", "int", "{", "n", ":=", "8", "*", "len", "(", "br", ".", "buf", ")", "\n", "for", "m", ":=", "br", ".", "mask", "|", "1", ";", "m", "!=", "1", ";", "m", ">>=", "1", "{", "n", "--", "\n", "}", "\n", "return", "n", "\n", "}" ]
// BitsRemaining reports the number of bits left to read.
[ "BitsRemaining", "reports", "the", "number", "of", "bits", "left", "to", "read", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/hash.go#L328-L334
6,133
google/safebrowsing
safebrowser.go
setDefaults
func (c *Config) setDefaults() bool { if c.ServerURL == "" { c.ServerURL = DefaultServerURL } if len(c.ThreatLists) == 0 { c.ThreatLists = DefaultThreatLists } if c.UpdatePeriod <= 0 { c.UpdatePeriod = DefaultUpdatePeriod } if c.RequestTimeout <= 0 { c.RequestTimeout = DefaultRequestTimeout } if c.compressionTypes == nil { c.compressionTypes = []pb.CompressionType{pb.CompressionType_RAW, pb.CompressionType_RICE} } return true }
go
func (c *Config) setDefaults() bool { if c.ServerURL == "" { c.ServerURL = DefaultServerURL } if len(c.ThreatLists) == 0 { c.ThreatLists = DefaultThreatLists } if c.UpdatePeriod <= 0 { c.UpdatePeriod = DefaultUpdatePeriod } if c.RequestTimeout <= 0 { c.RequestTimeout = DefaultRequestTimeout } if c.compressionTypes == nil { c.compressionTypes = []pb.CompressionType{pb.CompressionType_RAW, pb.CompressionType_RICE} } return true }
[ "func", "(", "c", "*", "Config", ")", "setDefaults", "(", ")", "bool", "{", "if", "c", ".", "ServerURL", "==", "\"", "\"", "{", "c", ".", "ServerURL", "=", "DefaultServerURL", "\n", "}", "\n", "if", "len", "(", "c", ".", "ThreatLists", ")", "==", "0", "{", "c", ".", "ThreatLists", "=", "DefaultThreatLists", "\n", "}", "\n", "if", "c", ".", "UpdatePeriod", "<=", "0", "{", "c", ".", "UpdatePeriod", "=", "DefaultUpdatePeriod", "\n", "}", "\n", "if", "c", ".", "RequestTimeout", "<=", "0", "{", "c", ".", "RequestTimeout", "=", "DefaultRequestTimeout", "\n", "}", "\n", "if", "c", ".", "compressionTypes", "==", "nil", "{", "c", ".", "compressionTypes", "=", "[", "]", "pb", ".", "CompressionType", "{", "pb", ".", "CompressionType_RAW", ",", "pb", ".", "CompressionType_RICE", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// setDefaults configures Config to have default parameters. // It reports whether the current configuration is valid.
[ "setDefaults", "configures", "Config", "to", "have", "default", "parameters", ".", "It", "reports", "whether", "the", "current", "configuration", "is", "valid", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/safebrowser.go#L236-L253
6,134
google/safebrowsing
safebrowser.go
NewSafeBrowser
func NewSafeBrowser(conf Config) (*SafeBrowser, error) { conf = conf.copy() if !conf.setDefaults() { return nil, errors.New("safebrowsing: invalid configuration") } // Create the SafeBrowsing object. if conf.api == nil { var err error conf.api, err = newNetAPI(conf.ServerURL, conf.APIKey, conf.ProxyURL) if err != nil { return nil, err } } if conf.now == nil { conf.now = time.Now } sb := &SafeBrowser{ config: conf, api: conf.api, c: cache{now: conf.now}, } // TODO: Verify that config.ThreatLists is a subset of the list obtained // by "/v4/threatLists" API endpoint. // Convert threat lists slice to a map for O(1) lookup. sb.lists = make(map[ThreatDescriptor]bool) for _, td := range conf.ThreatLists { sb.lists[td] = true } // Setup the logger. w := conf.Logger if conf.Logger == nil { w = ioutil.Discard } sb.log = log.New(w, "safebrowsing: ", log.Ldate|log.Ltime|log.Lshortfile) delay := time.Duration(0) // If database file is provided, use that to initialize. if !sb.db.Init(&sb.config, sb.log) { ctx, cancel := context.WithTimeout(context.Background(), sb.config.RequestTimeout) delay, _ = sb.db.Update(ctx, sb.api) cancel() } else { if age := sb.db.SinceLastUpdate(); age < sb.config.UpdatePeriod { delay = sb.config.UpdatePeriod - age } } // Start the background list updater. sb.done = make(chan bool) go sb.updater(delay) return sb, nil }
go
func NewSafeBrowser(conf Config) (*SafeBrowser, error) { conf = conf.copy() if !conf.setDefaults() { return nil, errors.New("safebrowsing: invalid configuration") } // Create the SafeBrowsing object. if conf.api == nil { var err error conf.api, err = newNetAPI(conf.ServerURL, conf.APIKey, conf.ProxyURL) if err != nil { return nil, err } } if conf.now == nil { conf.now = time.Now } sb := &SafeBrowser{ config: conf, api: conf.api, c: cache{now: conf.now}, } // TODO: Verify that config.ThreatLists is a subset of the list obtained // by "/v4/threatLists" API endpoint. // Convert threat lists slice to a map for O(1) lookup. sb.lists = make(map[ThreatDescriptor]bool) for _, td := range conf.ThreatLists { sb.lists[td] = true } // Setup the logger. w := conf.Logger if conf.Logger == nil { w = ioutil.Discard } sb.log = log.New(w, "safebrowsing: ", log.Ldate|log.Ltime|log.Lshortfile) delay := time.Duration(0) // If database file is provided, use that to initialize. if !sb.db.Init(&sb.config, sb.log) { ctx, cancel := context.WithTimeout(context.Background(), sb.config.RequestTimeout) delay, _ = sb.db.Update(ctx, sb.api) cancel() } else { if age := sb.db.SinceLastUpdate(); age < sb.config.UpdatePeriod { delay = sb.config.UpdatePeriod - age } } // Start the background list updater. sb.done = make(chan bool) go sb.updater(delay) return sb, nil }
[ "func", "NewSafeBrowser", "(", "conf", "Config", ")", "(", "*", "SafeBrowser", ",", "error", ")", "{", "conf", "=", "conf", ".", "copy", "(", ")", "\n", "if", "!", "conf", ".", "setDefaults", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Create the SafeBrowsing object.", "if", "conf", ".", "api", "==", "nil", "{", "var", "err", "error", "\n", "conf", ".", "api", ",", "err", "=", "newNetAPI", "(", "conf", ".", "ServerURL", ",", "conf", ".", "APIKey", ",", "conf", ".", "ProxyURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "conf", ".", "now", "==", "nil", "{", "conf", ".", "now", "=", "time", ".", "Now", "\n", "}", "\n", "sb", ":=", "&", "SafeBrowser", "{", "config", ":", "conf", ",", "api", ":", "conf", ".", "api", ",", "c", ":", "cache", "{", "now", ":", "conf", ".", "now", "}", ",", "}", "\n\n", "// TODO: Verify that config.ThreatLists is a subset of the list obtained", "// by \"/v4/threatLists\" API endpoint.", "// Convert threat lists slice to a map for O(1) lookup.", "sb", ".", "lists", "=", "make", "(", "map", "[", "ThreatDescriptor", "]", "bool", ")", "\n", "for", "_", ",", "td", ":=", "range", "conf", ".", "ThreatLists", "{", "sb", ".", "lists", "[", "td", "]", "=", "true", "\n", "}", "\n\n", "// Setup the logger.", "w", ":=", "conf", ".", "Logger", "\n", "if", "conf", ".", "Logger", "==", "nil", "{", "w", "=", "ioutil", ".", "Discard", "\n", "}", "\n", "sb", ".", "log", "=", "log", ".", "New", "(", "w", ",", "\"", "\"", ",", "log", ".", "Ldate", "|", "log", ".", "Ltime", "|", "log", ".", "Lshortfile", ")", "\n\n", "delay", ":=", "time", ".", "Duration", "(", "0", ")", "\n", "// If database file is provided, use that to initialize.", "if", "!", "sb", ".", "db", ".", "Init", "(", "&", "sb", ".", "config", ",", "sb", ".", "log", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "sb", ".", "config", ".", "RequestTimeout", ")", "\n", "delay", ",", "_", "=", "sb", ".", "db", ".", "Update", "(", "ctx", ",", "sb", ".", "api", ")", "\n", "cancel", "(", ")", "\n", "}", "else", "{", "if", "age", ":=", "sb", ".", "db", ".", "SinceLastUpdate", "(", ")", ";", "age", "<", "sb", ".", "config", ".", "UpdatePeriod", "{", "delay", "=", "sb", ".", "config", ".", "UpdatePeriod", "-", "age", "\n", "}", "\n", "}", "\n\n", "// Start the background list updater.", "sb", ".", "done", "=", "make", "(", "chan", "bool", ")", "\n", "go", "sb", ".", "updater", "(", "delay", ")", "\n", "return", "sb", ",", "nil", "\n", "}" ]
// NewSafeBrowser creates a new SafeBrowser. // // The conf struct allows the user to configure many aspects of the // SafeBrowser's operation.
[ "NewSafeBrowser", "creates", "a", "new", "SafeBrowser", ".", "The", "conf", "struct", "allows", "the", "user", "to", "configure", "many", "aspects", "of", "the", "SafeBrowser", "s", "operation", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/safebrowser.go#L296-L351
6,135
google/safebrowsing
safebrowser.go
Status
func (sb *SafeBrowser) Status() (Stats, error) { stats := Stats{ QueriesByDatabase: atomic.LoadInt64(&sb.stats.QueriesByDatabase), QueriesByCache: atomic.LoadInt64(&sb.stats.QueriesByCache), QueriesByAPI: atomic.LoadInt64(&sb.stats.QueriesByAPI), QueriesFail: atomic.LoadInt64(&sb.stats.QueriesFail), DatabaseUpdateLag: sb.db.UpdateLag(), } return stats, sb.db.Status() }
go
func (sb *SafeBrowser) Status() (Stats, error) { stats := Stats{ QueriesByDatabase: atomic.LoadInt64(&sb.stats.QueriesByDatabase), QueriesByCache: atomic.LoadInt64(&sb.stats.QueriesByCache), QueriesByAPI: atomic.LoadInt64(&sb.stats.QueriesByAPI), QueriesFail: atomic.LoadInt64(&sb.stats.QueriesFail), DatabaseUpdateLag: sb.db.UpdateLag(), } return stats, sb.db.Status() }
[ "func", "(", "sb", "*", "SafeBrowser", ")", "Status", "(", ")", "(", "Stats", ",", "error", ")", "{", "stats", ":=", "Stats", "{", "QueriesByDatabase", ":", "atomic", ".", "LoadInt64", "(", "&", "sb", ".", "stats", ".", "QueriesByDatabase", ")", ",", "QueriesByCache", ":", "atomic", ".", "LoadInt64", "(", "&", "sb", ".", "stats", ".", "QueriesByCache", ")", ",", "QueriesByAPI", ":", "atomic", ".", "LoadInt64", "(", "&", "sb", ".", "stats", ".", "QueriesByAPI", ")", ",", "QueriesFail", ":", "atomic", ".", "LoadInt64", "(", "&", "sb", ".", "stats", ".", "QueriesFail", ")", ",", "DatabaseUpdateLag", ":", "sb", ".", "db", ".", "UpdateLag", "(", ")", ",", "}", "\n", "return", "stats", ",", "sb", ".", "db", ".", "Status", "(", ")", "\n", "}" ]
// Status reports the status of SafeBrowser. It returns some statistics // regarding the operation, and an error representing the status of its // internal state. Most errors are transient and will recover themselves // after some period.
[ "Status", "reports", "the", "status", "of", "SafeBrowser", ".", "It", "returns", "some", "statistics", "regarding", "the", "operation", "and", "an", "error", "representing", "the", "status", "of", "its", "internal", "state", ".", "Most", "errors", "are", "transient", "and", "will", "recover", "themselves", "after", "some", "period", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/safebrowser.go#L357-L366
6,136
google/safebrowsing
safebrowser.go
WaitUntilReady
func (sb *SafeBrowser) WaitUntilReady(ctx context.Context) error { if atomic.LoadUint32(&sb.closed) == 1 { return errClosed } select { case <-sb.db.Ready(): return nil case <-ctx.Done(): return ctx.Err() case <-sb.done: return errClosed } }
go
func (sb *SafeBrowser) WaitUntilReady(ctx context.Context) error { if atomic.LoadUint32(&sb.closed) == 1 { return errClosed } select { case <-sb.db.Ready(): return nil case <-ctx.Done(): return ctx.Err() case <-sb.done: return errClosed } }
[ "func", "(", "sb", "*", "SafeBrowser", ")", "WaitUntilReady", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "atomic", ".", "LoadUint32", "(", "&", "sb", ".", "closed", ")", "==", "1", "{", "return", "errClosed", "\n", "}", "\n", "select", "{", "case", "<-", "sb", ".", "db", ".", "Ready", "(", ")", ":", "return", "nil", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "sb", ".", "done", ":", "return", "errClosed", "\n", "}", "\n", "}" ]
// WaitUntilReady blocks until the database is not in an error state. // Returns nil when the database is ready. Returns an error if the provided // context is canceled or if the SafeBrowser instance is Closed.
[ "WaitUntilReady", "blocks", "until", "the", "database", "is", "not", "in", "an", "error", "state", ".", "Returns", "nil", "when", "the", "database", "is", "ready", ".", "Returns", "an", "error", "if", "the", "provided", "context", "is", "canceled", "or", "if", "the", "SafeBrowser", "instance", "is", "Closed", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/safebrowser.go#L371-L383
6,137
google/safebrowsing
safebrowser.go
Close
func (sb *SafeBrowser) Close() error { if atomic.LoadUint32(&sb.closed) == 0 { atomic.StoreUint32(&sb.closed, 1) close(sb.done) } return nil }
go
func (sb *SafeBrowser) Close() error { if atomic.LoadUint32(&sb.closed) == 0 { atomic.StoreUint32(&sb.closed, 1) close(sb.done) } return nil }
[ "func", "(", "sb", "*", "SafeBrowser", ")", "Close", "(", ")", "error", "{", "if", "atomic", ".", "LoadUint32", "(", "&", "sb", ".", "closed", ")", "==", "0", "{", "atomic", ".", "StoreUint32", "(", "&", "sb", ".", "closed", ",", "1", ")", "\n", "close", "(", "sb", ".", "done", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close cleans up all resources. // This method must not be called concurrently with other lookup methods.
[ "Close", "cleans", "up", "all", "resources", ".", "This", "method", "must", "not", "be", "called", "concurrently", "with", "other", "lookup", "methods", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/safebrowser.go#L576-L582
6,138
google/safebrowsing
api.go
doRequest
func (a *netAPI) doRequest(ctx context.Context, requestPath string, req proto.Message, resp proto.Message) error { p, err := proto.Marshal(req) if err != nil { return err } u := *a.url // Make a copy of URL u.Path = requestPath httpReq, err := http.NewRequest("POST", u.String(), bytes.NewReader(p)) httpReq.Header.Add("Content-Type", "application/x-protobuf") httpReq = httpReq.WithContext(ctx) httpResp, err := a.client.Do(httpReq) if err != nil { return err } defer httpResp.Body.Close() if httpResp.StatusCode != 200 { return fmt.Errorf("safebrowsing: unexpected server response code: %d", httpResp.StatusCode) } body, err := ioutil.ReadAll(httpResp.Body) if err != nil { return err } return proto.Unmarshal(body, resp) }
go
func (a *netAPI) doRequest(ctx context.Context, requestPath string, req proto.Message, resp proto.Message) error { p, err := proto.Marshal(req) if err != nil { return err } u := *a.url // Make a copy of URL u.Path = requestPath httpReq, err := http.NewRequest("POST", u.String(), bytes.NewReader(p)) httpReq.Header.Add("Content-Type", "application/x-protobuf") httpReq = httpReq.WithContext(ctx) httpResp, err := a.client.Do(httpReq) if err != nil { return err } defer httpResp.Body.Close() if httpResp.StatusCode != 200 { return fmt.Errorf("safebrowsing: unexpected server response code: %d", httpResp.StatusCode) } body, err := ioutil.ReadAll(httpResp.Body) if err != nil { return err } return proto.Unmarshal(body, resp) }
[ "func", "(", "a", "*", "netAPI", ")", "doRequest", "(", "ctx", "context", ".", "Context", ",", "requestPath", "string", ",", "req", "proto", ".", "Message", ",", "resp", "proto", ".", "Message", ")", "error", "{", "p", ",", "err", ":=", "proto", ".", "Marshal", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "u", ":=", "*", "a", ".", "url", "// Make a copy of URL", "\n", "u", ".", "Path", "=", "requestPath", "\n", "httpReq", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "u", ".", "String", "(", ")", ",", "bytes", ".", "NewReader", "(", "p", ")", ")", "\n", "httpReq", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "httpReq", "=", "httpReq", ".", "WithContext", "(", "ctx", ")", "\n", "httpResp", ",", "err", ":=", "a", ".", "client", ".", "Do", "(", "httpReq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "httpResp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "httpResp", ".", "StatusCode", "!=", "200", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "httpResp", ".", "StatusCode", ")", "\n", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "httpResp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "proto", ".", "Unmarshal", "(", "body", ",", "resp", ")", "\n", "}" ]
// doRequests performs a POST to requestPath. It uses the marshaled form of req // as the request body payload, and automatically unmarshals the response body // payload as resp.
[ "doRequests", "performs", "a", "POST", "to", "requestPath", ".", "It", "uses", "the", "marshaled", "form", "of", "req", "as", "the", "request", "body", "payload", "and", "automatically", "unmarshals", "the", "response", "body", "payload", "as", "resp", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/api.go#L81-L105
6,139
google/safebrowsing
api.go
ListUpdate
func (a *netAPI) ListUpdate(ctx context.Context, req *pb.FetchThreatListUpdatesRequest) (*pb.FetchThreatListUpdatesResponse, error) { resp := new(pb.FetchThreatListUpdatesResponse) return resp, a.doRequest(ctx, fetchUpdatePath, req, resp) }
go
func (a *netAPI) ListUpdate(ctx context.Context, req *pb.FetchThreatListUpdatesRequest) (*pb.FetchThreatListUpdatesResponse, error) { resp := new(pb.FetchThreatListUpdatesResponse) return resp, a.doRequest(ctx, fetchUpdatePath, req, resp) }
[ "func", "(", "a", "*", "netAPI", ")", "ListUpdate", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "FetchThreatListUpdatesRequest", ")", "(", "*", "pb", ".", "FetchThreatListUpdatesResponse", ",", "error", ")", "{", "resp", ":=", "new", "(", "pb", ".", "FetchThreatListUpdatesResponse", ")", "\n", "return", "resp", ",", "a", ".", "doRequest", "(", "ctx", ",", "fetchUpdatePath", ",", "req", ",", "resp", ")", "\n", "}" ]
// ListUpdate issues a FetchThreatListUpdates API call and returns the response.
[ "ListUpdate", "issues", "a", "FetchThreatListUpdates", "API", "call", "and", "returns", "the", "response", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/api.go#L108-L111
6,140
google/safebrowsing
api.go
HashLookup
func (a *netAPI) HashLookup(ctx context.Context, req *pb.FindFullHashesRequest) (*pb.FindFullHashesResponse, error) { resp := new(pb.FindFullHashesResponse) return resp, a.doRequest(ctx, findHashPath, req, resp) }
go
func (a *netAPI) HashLookup(ctx context.Context, req *pb.FindFullHashesRequest) (*pb.FindFullHashesResponse, error) { resp := new(pb.FindFullHashesResponse) return resp, a.doRequest(ctx, findHashPath, req, resp) }
[ "func", "(", "a", "*", "netAPI", ")", "HashLookup", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "FindFullHashesRequest", ")", "(", "*", "pb", ".", "FindFullHashesResponse", ",", "error", ")", "{", "resp", ":=", "new", "(", "pb", ".", "FindFullHashesResponse", ")", "\n", "return", "resp", ",", "a", ".", "doRequest", "(", "ctx", ",", "findHashPath", ",", "req", ",", "resp", ")", "\n", "}" ]
// HashLookup issues a FindFullHashes API call and returns the response.
[ "HashLookup", "issues", "a", "FindFullHashes", "API", "call", "and", "returns", "the", "response", "." ]
92a16cf6d02871018d6a426fb7886e34022c5c59
https://github.com/google/safebrowsing/blob/92a16cf6d02871018d6a426fb7886e34022c5c59/api.go#L114-L117
6,141
gorilla/feeds
json.go
MarshalJSON
func (a *JSONAttachment) MarshalJSON() ([]byte, error) { type EmbeddedJSONAttachment JSONAttachment return json.Marshal(&struct { Duration float64 `json:"duration_in_seconds,omitempty"` *EmbeddedJSONAttachment }{ EmbeddedJSONAttachment: (*EmbeddedJSONAttachment)(a), Duration: a.Duration.Seconds(), }) }
go
func (a *JSONAttachment) MarshalJSON() ([]byte, error) { type EmbeddedJSONAttachment JSONAttachment return json.Marshal(&struct { Duration float64 `json:"duration_in_seconds,omitempty"` *EmbeddedJSONAttachment }{ EmbeddedJSONAttachment: (*EmbeddedJSONAttachment)(a), Duration: a.Duration.Seconds(), }) }
[ "func", "(", "a", "*", "JSONAttachment", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "type", "EmbeddedJSONAttachment", "JSONAttachment", "\n", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Duration", "float64", "`json:\"duration_in_seconds,omitempty\"`", "\n", "*", "EmbeddedJSONAttachment", "\n", "}", "{", "EmbeddedJSONAttachment", ":", "(", "*", "EmbeddedJSONAttachment", ")", "(", "a", ")", ",", "Duration", ":", "a", ".", "Duration", ".", "Seconds", "(", ")", ",", "}", ")", "\n", "}" ]
// MarshalJSON implements the json.Marshaler interface. // The Duration field is marshaled in seconds, all other fields are marshaled // based upon the definitions in struct tags.
[ "MarshalJSON", "implements", "the", "json", ".", "Marshaler", "interface", ".", "The", "Duration", "field", "is", "marshaled", "in", "seconds", "all", "other", "fields", "are", "marshaled", "based", "upon", "the", "definitions", "in", "struct", "tags", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/json.go#L32-L41
6,142
gorilla/feeds
json.go
UnmarshalJSON
func (a *JSONAttachment) UnmarshalJSON(data []byte) error { type EmbeddedJSONAttachment JSONAttachment var raw struct { Duration float64 `json:"duration_in_seconds,omitempty"` *EmbeddedJSONAttachment } raw.EmbeddedJSONAttachment = (*EmbeddedJSONAttachment)(a) err := json.Unmarshal(data, &raw) if err != nil { return err } if raw.Duration > 0 { nsec := int64(raw.Duration * float64(time.Second)) raw.EmbeddedJSONAttachment.Duration = time.Duration(nsec) } return nil }
go
func (a *JSONAttachment) UnmarshalJSON(data []byte) error { type EmbeddedJSONAttachment JSONAttachment var raw struct { Duration float64 `json:"duration_in_seconds,omitempty"` *EmbeddedJSONAttachment } raw.EmbeddedJSONAttachment = (*EmbeddedJSONAttachment)(a) err := json.Unmarshal(data, &raw) if err != nil { return err } if raw.Duration > 0 { nsec := int64(raw.Duration * float64(time.Second)) raw.EmbeddedJSONAttachment.Duration = time.Duration(nsec) } return nil }
[ "func", "(", "a", "*", "JSONAttachment", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "type", "EmbeddedJSONAttachment", "JSONAttachment", "\n", "var", "raw", "struct", "{", "Duration", "float64", "`json:\"duration_in_seconds,omitempty\"`", "\n", "*", "EmbeddedJSONAttachment", "\n", "}", "\n", "raw", ".", "EmbeddedJSONAttachment", "=", "(", "*", "EmbeddedJSONAttachment", ")", "(", "a", ")", "\n\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "raw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "raw", ".", "Duration", ">", "0", "{", "nsec", ":=", "int64", "(", "raw", ".", "Duration", "*", "float64", "(", "time", ".", "Second", ")", ")", "\n", "raw", ".", "EmbeddedJSONAttachment", ".", "Duration", "=", "time", ".", "Duration", "(", "nsec", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements the json.Unmarshaler interface. // The Duration field is expected to be in seconds, all other field types // match the struct definition.
[ "UnmarshalJSON", "implements", "the", "json", ".", "Unmarshaler", "interface", ".", "The", "Duration", "field", "is", "expected", "to", "be", "in", "seconds", "all", "other", "field", "types", "match", "the", "struct", "definition", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/json.go#L46-L65
6,143
gorilla/feeds
json.go
ToJSON
func (f *JSONFeed) ToJSON() (string, error) { data, err := json.MarshalIndent(f, "", " ") if err != nil { return "", err } return string(data), nil }
go
func (f *JSONFeed) ToJSON() (string, error) { data, err := json.MarshalIndent(f, "", " ") if err != nil { return "", err } return string(data), nil }
[ "func", "(", "f", "*", "JSONFeed", ")", "ToJSON", "(", ")", "(", "string", ",", "error", ")", "{", "data", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "f", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "string", "(", "data", ")", ",", "nil", "\n", "}" ]
// ToJSON encodes f into a JSON string. Returns an error if marshalling fails.
[ "ToJSON", "encodes", "f", "into", "a", "JSON", "string", ".", "Returns", "an", "error", "if", "marshalling", "fails", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/json.go#L121-L128
6,144
gorilla/feeds
json.go
JSONFeed
func (f *JSON) JSONFeed() *JSONFeed { feed := &JSONFeed{ Version: jsonFeedVersion, Title: f.Title, Description: f.Description, } if f.Link != nil { feed.HomePageUrl = f.Link.Href } if f.Author != nil { feed.Author = &JSONAuthor{ Name: f.Author.Name, } } for _, e := range f.Items { feed.Items = append(feed.Items, newJSONItem(e)) } return feed }
go
func (f *JSON) JSONFeed() *JSONFeed { feed := &JSONFeed{ Version: jsonFeedVersion, Title: f.Title, Description: f.Description, } if f.Link != nil { feed.HomePageUrl = f.Link.Href } if f.Author != nil { feed.Author = &JSONAuthor{ Name: f.Author.Name, } } for _, e := range f.Items { feed.Items = append(feed.Items, newJSONItem(e)) } return feed }
[ "func", "(", "f", "*", "JSON", ")", "JSONFeed", "(", ")", "*", "JSONFeed", "{", "feed", ":=", "&", "JSONFeed", "{", "Version", ":", "jsonFeedVersion", ",", "Title", ":", "f", ".", "Title", ",", "Description", ":", "f", ".", "Description", ",", "}", "\n\n", "if", "f", ".", "Link", "!=", "nil", "{", "feed", ".", "HomePageUrl", "=", "f", ".", "Link", ".", "Href", "\n", "}", "\n", "if", "f", ".", "Author", "!=", "nil", "{", "feed", ".", "Author", "=", "&", "JSONAuthor", "{", "Name", ":", "f", ".", "Author", ".", "Name", ",", "}", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "f", ".", "Items", "{", "feed", ".", "Items", "=", "append", "(", "feed", ".", "Items", ",", "newJSONItem", "(", "e", ")", ")", "\n", "}", "\n", "return", "feed", "\n", "}" ]
// JSONFeed creates a new JSONFeed with a generic Feed struct's data.
[ "JSONFeed", "creates", "a", "new", "JSONFeed", "with", "a", "generic", "Feed", "struct", "s", "data", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/json.go#L131-L150
6,145
gorilla/feeds
rss.go
newRssItem
func newRssItem(i *Item) *RssItem { item := &RssItem{ Title: i.Title, Link: i.Link.Href, Description: i.Description, Guid: i.Id, PubDate: anyTimeFormat(time.RFC1123Z, i.Created, i.Updated), } if len(i.Content) > 0 { item.Content = &RssContent{Content: i.Content} } if i.Source != nil { item.Source = i.Source.Href } // Define a closure if i.Enclosure != nil && i.Enclosure.Type != "" && i.Enclosure.Length != "" { item.Enclosure = &RssEnclosure{Url: i.Enclosure.Url, Type: i.Enclosure.Type, Length: i.Enclosure.Length} } if i.Author != nil { item.Author = i.Author.Name } return item }
go
func newRssItem(i *Item) *RssItem { item := &RssItem{ Title: i.Title, Link: i.Link.Href, Description: i.Description, Guid: i.Id, PubDate: anyTimeFormat(time.RFC1123Z, i.Created, i.Updated), } if len(i.Content) > 0 { item.Content = &RssContent{Content: i.Content} } if i.Source != nil { item.Source = i.Source.Href } // Define a closure if i.Enclosure != nil && i.Enclosure.Type != "" && i.Enclosure.Length != "" { item.Enclosure = &RssEnclosure{Url: i.Enclosure.Url, Type: i.Enclosure.Type, Length: i.Enclosure.Length} } if i.Author != nil { item.Author = i.Author.Name } return item }
[ "func", "newRssItem", "(", "i", "*", "Item", ")", "*", "RssItem", "{", "item", ":=", "&", "RssItem", "{", "Title", ":", "i", ".", "Title", ",", "Link", ":", "i", ".", "Link", ".", "Href", ",", "Description", ":", "i", ".", "Description", ",", "Guid", ":", "i", ".", "Id", ",", "PubDate", ":", "anyTimeFormat", "(", "time", ".", "RFC1123Z", ",", "i", ".", "Created", ",", "i", ".", "Updated", ")", ",", "}", "\n", "if", "len", "(", "i", ".", "Content", ")", ">", "0", "{", "item", ".", "Content", "=", "&", "RssContent", "{", "Content", ":", "i", ".", "Content", "}", "\n", "}", "\n", "if", "i", ".", "Source", "!=", "nil", "{", "item", ".", "Source", "=", "i", ".", "Source", ".", "Href", "\n", "}", "\n\n", "// Define a closure", "if", "i", ".", "Enclosure", "!=", "nil", "&&", "i", ".", "Enclosure", ".", "Type", "!=", "\"", "\"", "&&", "i", ".", "Enclosure", ".", "Length", "!=", "\"", "\"", "{", "item", ".", "Enclosure", "=", "&", "RssEnclosure", "{", "Url", ":", "i", ".", "Enclosure", ".", "Url", ",", "Type", ":", "i", ".", "Enclosure", ".", "Type", ",", "Length", ":", "i", ".", "Enclosure", ".", "Length", "}", "\n", "}", "\n\n", "if", "i", ".", "Author", "!=", "nil", "{", "item", ".", "Author", "=", "i", ".", "Author", ".", "Name", "\n", "}", "\n", "return", "item", "\n", "}" ]
// create a new RssItem with a generic Item struct's data
[ "create", "a", "new", "RssItem", "with", "a", "generic", "Item", "struct", "s", "data" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/rss.go#L95-L119
6,146
gorilla/feeds
rss.go
RssFeed
func (r *Rss) RssFeed() *RssFeed { pub := anyTimeFormat(time.RFC1123Z, r.Created, r.Updated) build := anyTimeFormat(time.RFC1123Z, r.Updated) author := "" if r.Author != nil { author = r.Author.Email if len(r.Author.Name) > 0 { author = fmt.Sprintf("%s (%s)", r.Author.Email, r.Author.Name) } } var image *RssImage if r.Image != nil { image = &RssImage{Url: r.Image.Url, Title: r.Image.Title, Link: r.Image.Link, Width: r.Image.Width, Height: r.Image.Height} } channel := &RssFeed{ Title: r.Title, Link: r.Link.Href, Description: r.Description, ManagingEditor: author, PubDate: pub, LastBuildDate: build, Copyright: r.Copyright, Image: image, } for _, i := range r.Items { channel.Items = append(channel.Items, newRssItem(i)) } return channel }
go
func (r *Rss) RssFeed() *RssFeed { pub := anyTimeFormat(time.RFC1123Z, r.Created, r.Updated) build := anyTimeFormat(time.RFC1123Z, r.Updated) author := "" if r.Author != nil { author = r.Author.Email if len(r.Author.Name) > 0 { author = fmt.Sprintf("%s (%s)", r.Author.Email, r.Author.Name) } } var image *RssImage if r.Image != nil { image = &RssImage{Url: r.Image.Url, Title: r.Image.Title, Link: r.Image.Link, Width: r.Image.Width, Height: r.Image.Height} } channel := &RssFeed{ Title: r.Title, Link: r.Link.Href, Description: r.Description, ManagingEditor: author, PubDate: pub, LastBuildDate: build, Copyright: r.Copyright, Image: image, } for _, i := range r.Items { channel.Items = append(channel.Items, newRssItem(i)) } return channel }
[ "func", "(", "r", "*", "Rss", ")", "RssFeed", "(", ")", "*", "RssFeed", "{", "pub", ":=", "anyTimeFormat", "(", "time", ".", "RFC1123Z", ",", "r", ".", "Created", ",", "r", ".", "Updated", ")", "\n", "build", ":=", "anyTimeFormat", "(", "time", ".", "RFC1123Z", ",", "r", ".", "Updated", ")", "\n", "author", ":=", "\"", "\"", "\n", "if", "r", ".", "Author", "!=", "nil", "{", "author", "=", "r", ".", "Author", ".", "Email", "\n", "if", "len", "(", "r", ".", "Author", ".", "Name", ")", ">", "0", "{", "author", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "Author", ".", "Email", ",", "r", ".", "Author", ".", "Name", ")", "\n", "}", "\n", "}", "\n\n", "var", "image", "*", "RssImage", "\n", "if", "r", ".", "Image", "!=", "nil", "{", "image", "=", "&", "RssImage", "{", "Url", ":", "r", ".", "Image", ".", "Url", ",", "Title", ":", "r", ".", "Image", ".", "Title", ",", "Link", ":", "r", ".", "Image", ".", "Link", ",", "Width", ":", "r", ".", "Image", ".", "Width", ",", "Height", ":", "r", ".", "Image", ".", "Height", "}", "\n", "}", "\n\n", "channel", ":=", "&", "RssFeed", "{", "Title", ":", "r", ".", "Title", ",", "Link", ":", "r", ".", "Link", ".", "Href", ",", "Description", ":", "r", ".", "Description", ",", "ManagingEditor", ":", "author", ",", "PubDate", ":", "pub", ",", "LastBuildDate", ":", "build", ",", "Copyright", ":", "r", ".", "Copyright", ",", "Image", ":", "image", ",", "}", "\n", "for", "_", ",", "i", ":=", "range", "r", ".", "Items", "{", "channel", ".", "Items", "=", "append", "(", "channel", ".", "Items", ",", "newRssItem", "(", "i", ")", ")", "\n", "}", "\n", "return", "channel", "\n", "}" ]
// create a new RssFeed with a generic Feed struct's data
[ "create", "a", "new", "RssFeed", "with", "a", "generic", "Feed", "struct", "s", "data" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/rss.go#L122-L152
6,147
gorilla/feeds
feed.go
Add
func (f *Feed) Add(item *Item) { f.Items = append(f.Items, item) }
go
func (f *Feed) Add(item *Item) { f.Items = append(f.Items, item) }
[ "func", "(", "f", "*", "Feed", ")", "Add", "(", "item", "*", "Item", ")", "{", "f", ".", "Items", "=", "append", "(", "f", ".", "Items", ",", "item", ")", "\n", "}" ]
// add a new Item to a Feed
[ "add", "a", "new", "Item", "to", "a", "Feed" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L56-L58
6,148
gorilla/feeds
feed.go
anyTimeFormat
func anyTimeFormat(format string, times ...time.Time) string { for _, t := range times { if !t.IsZero() { return t.Format(format) } } return "" }
go
func anyTimeFormat(format string, times ...time.Time) string { for _, t := range times { if !t.IsZero() { return t.Format(format) } } return "" }
[ "func", "anyTimeFormat", "(", "format", "string", ",", "times", "...", "time", ".", "Time", ")", "string", "{", "for", "_", ",", "t", ":=", "range", "times", "{", "if", "!", "t", ".", "IsZero", "(", ")", "{", "return", "t", ".", "Format", "(", "format", ")", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// returns the first non-zero time formatted as a string or ""
[ "returns", "the", "first", "non", "-", "zero", "time", "formatted", "as", "a", "string", "or" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L61-L68
6,149
gorilla/feeds
feed.go
ToAtom
func (f *Feed) ToAtom() (string, error) { a := &Atom{f} return ToXML(a) }
go
func (f *Feed) ToAtom() (string, error) { a := &Atom{f} return ToXML(a) }
[ "func", "(", "f", "*", "Feed", ")", "ToAtom", "(", ")", "(", "string", ",", "error", ")", "{", "a", ":=", "&", "Atom", "{", "f", "}", "\n", "return", "ToXML", "(", "a", ")", "\n", "}" ]
// creates an Atom representation of this feed
[ "creates", "an", "Atom", "representation", "of", "this", "feed" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L102-L105
6,150
gorilla/feeds
feed.go
WriteAtom
func (f *Feed) WriteAtom(w io.Writer) error { return WriteXML(&Atom{f}, w) }
go
func (f *Feed) WriteAtom(w io.Writer) error { return WriteXML(&Atom{f}, w) }
[ "func", "(", "f", "*", "Feed", ")", "WriteAtom", "(", "w", "io", ".", "Writer", ")", "error", "{", "return", "WriteXML", "(", "&", "Atom", "{", "f", "}", ",", "w", ")", "\n", "}" ]
// WriteAtom writes an Atom representation of this feed to the writer.
[ "WriteAtom", "writes", "an", "Atom", "representation", "of", "this", "feed", "to", "the", "writer", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L108-L110
6,151
gorilla/feeds
feed.go
ToRss
func (f *Feed) ToRss() (string, error) { r := &Rss{f} return ToXML(r) }
go
func (f *Feed) ToRss() (string, error) { r := &Rss{f} return ToXML(r) }
[ "func", "(", "f", "*", "Feed", ")", "ToRss", "(", ")", "(", "string", ",", "error", ")", "{", "r", ":=", "&", "Rss", "{", "f", "}", "\n", "return", "ToXML", "(", "r", ")", "\n", "}" ]
// creates an Rss representation of this feed
[ "creates", "an", "Rss", "representation", "of", "this", "feed" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L113-L116
6,152
gorilla/feeds
feed.go
WriteRss
func (f *Feed) WriteRss(w io.Writer) error { return WriteXML(&Rss{f}, w) }
go
func (f *Feed) WriteRss(w io.Writer) error { return WriteXML(&Rss{f}, w) }
[ "func", "(", "f", "*", "Feed", ")", "WriteRss", "(", "w", "io", ".", "Writer", ")", "error", "{", "return", "WriteXML", "(", "&", "Rss", "{", "f", "}", ",", "w", ")", "\n", "}" ]
// WriteRss writes an RSS representation of this feed to the writer.
[ "WriteRss", "writes", "an", "RSS", "representation", "of", "this", "feed", "to", "the", "writer", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L119-L121
6,153
gorilla/feeds
feed.go
ToJSON
func (f *Feed) ToJSON() (string, error) { j := &JSON{f} return j.ToJSON() }
go
func (f *Feed) ToJSON() (string, error) { j := &JSON{f} return j.ToJSON() }
[ "func", "(", "f", "*", "Feed", ")", "ToJSON", "(", ")", "(", "string", ",", "error", ")", "{", "j", ":=", "&", "JSON", "{", "f", "}", "\n", "return", "j", ".", "ToJSON", "(", ")", "\n", "}" ]
// ToJSON creates a JSON Feed representation of this feed
[ "ToJSON", "creates", "a", "JSON", "Feed", "representation", "of", "this", "feed" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L124-L127
6,154
gorilla/feeds
feed.go
WriteJSON
func (f *Feed) WriteJSON(w io.Writer) error { j := &JSON{f} feed := j.JSONFeed() e := json.NewEncoder(w) e.SetIndent("", " ") return e.Encode(feed) }
go
func (f *Feed) WriteJSON(w io.Writer) error { j := &JSON{f} feed := j.JSONFeed() e := json.NewEncoder(w) e.SetIndent("", " ") return e.Encode(feed) }
[ "func", "(", "f", "*", "Feed", ")", "WriteJSON", "(", "w", "io", ".", "Writer", ")", "error", "{", "j", ":=", "&", "JSON", "{", "f", "}", "\n", "feed", ":=", "j", ".", "JSONFeed", "(", ")", "\n\n", "e", ":=", "json", ".", "NewEncoder", "(", "w", ")", "\n", "e", ".", "SetIndent", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "e", ".", "Encode", "(", "feed", ")", "\n", "}" ]
// WriteJSON writes an JSON representation of this feed to the writer.
[ "WriteJSON", "writes", "an", "JSON", "representation", "of", "this", "feed", "to", "the", "writer", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L130-L137
6,155
gorilla/feeds
feed.go
Sort
func (f *Feed) Sort(less func(a, b *Item) bool) { lessFunc := func(i, j int) bool { return less(f.Items[i], f.Items[j]) } sort.SliceStable(f.Items, lessFunc) }
go
func (f *Feed) Sort(less func(a, b *Item) bool) { lessFunc := func(i, j int) bool { return less(f.Items[i], f.Items[j]) } sort.SliceStable(f.Items, lessFunc) }
[ "func", "(", "f", "*", "Feed", ")", "Sort", "(", "less", "func", "(", "a", ",", "b", "*", "Item", ")", "bool", ")", "{", "lessFunc", ":=", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "less", "(", "f", ".", "Items", "[", "i", "]", ",", "f", ".", "Items", "[", "j", "]", ")", "\n", "}", "\n", "sort", ".", "SliceStable", "(", "f", ".", "Items", ",", "lessFunc", ")", "\n", "}" ]
// Sort sorts the Items in the feed with the given less function.
[ "Sort", "sorts", "the", "Items", "in", "the", "feed", "with", "the", "given", "less", "function", "." ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/feed.go#L140-L145
6,156
gorilla/feeds
uuid.go
NewUUID
func NewUUID() *UUID { u := &UUID{} _, err := rand.Read(u[:16]) if err != nil { panic(err) } u[8] = (u[8] | 0x80) & 0xBf u[6] = (u[6] | 0x40) & 0x4f return u }
go
func NewUUID() *UUID { u := &UUID{} _, err := rand.Read(u[:16]) if err != nil { panic(err) } u[8] = (u[8] | 0x80) & 0xBf u[6] = (u[6] | 0x40) & 0x4f return u }
[ "func", "NewUUID", "(", ")", "*", "UUID", "{", "u", ":=", "&", "UUID", "{", "}", "\n", "_", ",", "err", ":=", "rand", ".", "Read", "(", "u", "[", ":", "16", "]", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "u", "[", "8", "]", "=", "(", "u", "[", "8", "]", "|", "0x80", ")", "&", "0xBf", "\n", "u", "[", "6", "]", "=", "(", "u", "[", "6", "]", "|", "0x40", ")", "&", "0x4f", "\n", "return", "u", "\n", "}" ]
// create a new uuid v4
[ "create", "a", "new", "uuid", "v4" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/uuid.go#L13-L23
6,157
gorilla/feeds
atom.go
AtomFeed
func (a *Atom) AtomFeed() *AtomFeed { updated := anyTimeFormat(time.RFC3339, a.Updated, a.Created) feed := &AtomFeed{ Xmlns: ns, Title: a.Title, Link: &AtomLink{Href: a.Link.Href, Rel: a.Link.Rel}, Subtitle: a.Description, Id: a.Link.Href, Updated: updated, Rights: a.Copyright, } if a.Author != nil { feed.Author = &AtomAuthor{AtomPerson: AtomPerson{Name: a.Author.Name, Email: a.Author.Email}} } for _, e := range a.Items { feed.Entries = append(feed.Entries, newAtomEntry(e)) } return feed }
go
func (a *Atom) AtomFeed() *AtomFeed { updated := anyTimeFormat(time.RFC3339, a.Updated, a.Created) feed := &AtomFeed{ Xmlns: ns, Title: a.Title, Link: &AtomLink{Href: a.Link.Href, Rel: a.Link.Rel}, Subtitle: a.Description, Id: a.Link.Href, Updated: updated, Rights: a.Copyright, } if a.Author != nil { feed.Author = &AtomAuthor{AtomPerson: AtomPerson{Name: a.Author.Name, Email: a.Author.Email}} } for _, e := range a.Items { feed.Entries = append(feed.Entries, newAtomEntry(e)) } return feed }
[ "func", "(", "a", "*", "Atom", ")", "AtomFeed", "(", ")", "*", "AtomFeed", "{", "updated", ":=", "anyTimeFormat", "(", "time", ".", "RFC3339", ",", "a", ".", "Updated", ",", "a", ".", "Created", ")", "\n", "feed", ":=", "&", "AtomFeed", "{", "Xmlns", ":", "ns", ",", "Title", ":", "a", ".", "Title", ",", "Link", ":", "&", "AtomLink", "{", "Href", ":", "a", ".", "Link", ".", "Href", ",", "Rel", ":", "a", ".", "Link", ".", "Rel", "}", ",", "Subtitle", ":", "a", ".", "Description", ",", "Id", ":", "a", ".", "Link", ".", "Href", ",", "Updated", ":", "updated", ",", "Rights", ":", "a", ".", "Copyright", ",", "}", "\n", "if", "a", ".", "Author", "!=", "nil", "{", "feed", ".", "Author", "=", "&", "AtomAuthor", "{", "AtomPerson", ":", "AtomPerson", "{", "Name", ":", "a", ".", "Author", ".", "Name", ",", "Email", ":", "a", ".", "Author", ".", "Email", "}", "}", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "a", ".", "Items", "{", "feed", ".", "Entries", "=", "append", "(", "feed", ".", "Entries", ",", "newAtomEntry", "(", "e", ")", ")", "\n", "}", "\n", "return", "feed", "\n", "}" ]
// create a new AtomFeed with a generic Feed struct's data
[ "create", "a", "new", "AtomFeed", "with", "a", "generic", "Feed", "struct", "s", "data" ]
2079b9bbce59c062ad62eecb771e3ed3a772b8e4
https://github.com/gorilla/feeds/blob/2079b9bbce59c062ad62eecb771e3ed3a772b8e4/atom.go#L141-L159
6,158
modern-go/reflect2
unsafe_link.go
add
func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer { return unsafe.Pointer(uintptr(p) + x) }
go
func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer { return unsafe.Pointer(uintptr(p) + x) }
[ "func", "add", "(", "p", "unsafe", ".", "Pointer", ",", "x", "uintptr", ",", "whySafe", "string", ")", "unsafe", ".", "Pointer", "{", "return", "unsafe", ".", "Pointer", "(", "uintptr", "(", "p", ")", "+", "x", ")", "\n", "}" ]
// add returns p+x. // // The whySafe string is ignored, so that the function still inlines // as efficiently as p+x, but all call sites should use the string to // record why the addition is safe, which is to say why the addition // does not cause x to advance to the very end of p's allocation // and therefore point incorrectly at the next block in memory.
[ "add", "returns", "p", "+", "x", ".", "The", "whySafe", "string", "is", "ignored", "so", "that", "the", "function", "still", "inlines", "as", "efficiently", "as", "p", "+", "x", "but", "all", "call", "sites", "should", "use", "the", "string", "to", "record", "why", "the", "addition", "is", "safe", "which", "is", "to", "say", "why", "the", "addition", "does", "not", "cause", "x", "to", "advance", "to", "the", "very", "end", "of", "p", "s", "allocation", "and", "therefore", "point", "incorrectly", "at", "the", "next", "block", "in", "memory", "." ]
94122c33edd36123c84d5368cfb2b69df93a0ec8
https://github.com/modern-go/reflect2/blob/94122c33edd36123c84d5368cfb2b69df93a0ec8/unsafe_link.go#L57-L59
6,159
modern-go/reflect2
type_map.go
discoverTypes
func discoverTypes() { types = make(map[string]reflect.Type) packages = make(map[string]map[string]reflect.Type) ver := runtime.Version() if ver == "go1.5" || strings.HasPrefix(ver, "go1.5.") { loadGo15Types() } else if ver == "go1.6" || strings.HasPrefix(ver, "go1.6.") { loadGo15Types() } else { loadGo17Types() } }
go
func discoverTypes() { types = make(map[string]reflect.Type) packages = make(map[string]map[string]reflect.Type) ver := runtime.Version() if ver == "go1.5" || strings.HasPrefix(ver, "go1.5.") { loadGo15Types() } else if ver == "go1.6" || strings.HasPrefix(ver, "go1.6.") { loadGo15Types() } else { loadGo17Types() } }
[ "func", "discoverTypes", "(", ")", "{", "types", "=", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", "\n", "packages", "=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "reflect", ".", "Type", ")", "\n\n", "ver", ":=", "runtime", ".", "Version", "(", ")", "\n", "if", "ver", "==", "\"", "\"", "||", "strings", ".", "HasPrefix", "(", "ver", ",", "\"", "\"", ")", "{", "loadGo15Types", "(", ")", "\n", "}", "else", "if", "ver", "==", "\"", "\"", "||", "strings", ".", "HasPrefix", "(", "ver", ",", "\"", "\"", ")", "{", "loadGo15Types", "(", ")", "\n", "}", "else", "{", "loadGo17Types", "(", ")", "\n", "}", "\n", "}" ]
// discoverTypes initializes types and packages
[ "discoverTypes", "initializes", "types", "and", "packages" ]
94122c33edd36123c84d5368cfb2b69df93a0ec8
https://github.com/modern-go/reflect2/blob/94122c33edd36123c84d5368cfb2b69df93a0ec8/type_map.go#L26-L38
6,160
modern-go/reflect2
type_map.go
TypeByName
func TypeByName(typeName string) Type { initOnce.Do(discoverTypes) return Type2(types[typeName]) }
go
func TypeByName(typeName string) Type { initOnce.Do(discoverTypes) return Type2(types[typeName]) }
[ "func", "TypeByName", "(", "typeName", "string", ")", "Type", "{", "initOnce", ".", "Do", "(", "discoverTypes", ")", "\n", "return", "Type2", "(", "types", "[", "typeName", "]", ")", "\n", "}" ]
// TypeByName return the type by its name, just like Class.forName in java
[ "TypeByName", "return", "the", "type", "by", "its", "name", "just", "like", "Class", ".", "forName", "in", "java" ]
94122c33edd36123c84d5368cfb2b69df93a0ec8
https://github.com/modern-go/reflect2/blob/94122c33edd36123c84d5368cfb2b69df93a0ec8/type_map.go#L100-L103
6,161
modern-go/reflect2
type_map.go
TypeByPackageName
func TypeByPackageName(pkgPath string, name string) Type { initOnce.Do(discoverTypes) pkgTypes := packages[pkgPath] if pkgTypes == nil { return nil } return Type2(pkgTypes[name]) }
go
func TypeByPackageName(pkgPath string, name string) Type { initOnce.Do(discoverTypes) pkgTypes := packages[pkgPath] if pkgTypes == nil { return nil } return Type2(pkgTypes[name]) }
[ "func", "TypeByPackageName", "(", "pkgPath", "string", ",", "name", "string", ")", "Type", "{", "initOnce", ".", "Do", "(", "discoverTypes", ")", "\n", "pkgTypes", ":=", "packages", "[", "pkgPath", "]", "\n", "if", "pkgTypes", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "Type2", "(", "pkgTypes", "[", "name", "]", ")", "\n", "}" ]
// TypeByPackageName return the type by its package and name
[ "TypeByPackageName", "return", "the", "type", "by", "its", "package", "and", "name" ]
94122c33edd36123c84d5368cfb2b69df93a0ec8
https://github.com/modern-go/reflect2/blob/94122c33edd36123c84d5368cfb2b69df93a0ec8/type_map.go#L106-L113
6,162
ncw/swift
dlo.go
DynamicLargeObjectCreateFile
func (c *Connection) DynamicLargeObjectCreateFile(opts *LargeObjectOpts) (LargeObjectFile, error) { lo, err := c.largeObjectCreate(opts) if err != nil { return nil, err } return withBuffer(opts, &DynamicLargeObjectCreateFile{ largeObjectCreateFile: *lo, }), nil }
go
func (c *Connection) DynamicLargeObjectCreateFile(opts *LargeObjectOpts) (LargeObjectFile, error) { lo, err := c.largeObjectCreate(opts) if err != nil { return nil, err } return withBuffer(opts, &DynamicLargeObjectCreateFile{ largeObjectCreateFile: *lo, }), nil }
[ "func", "(", "c", "*", "Connection", ")", "DynamicLargeObjectCreateFile", "(", "opts", "*", "LargeObjectOpts", ")", "(", "LargeObjectFile", ",", "error", ")", "{", "lo", ",", "err", ":=", "c", ".", "largeObjectCreate", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "withBuffer", "(", "opts", ",", "&", "DynamicLargeObjectCreateFile", "{", "largeObjectCreateFile", ":", "*", "lo", ",", "}", ")", ",", "nil", "\n", "}" ]
// DynamicLargeObjectCreateFile creates a dynamic large object // returning an object which satisfies io.Writer, io.Seeker, io.Closer // and io.ReaderFrom. The flags are as passes to the // largeObjectCreate method.
[ "DynamicLargeObjectCreateFile", "creates", "a", "dynamic", "large", "object", "returning", "an", "object", "which", "satisfies", "io", ".", "Writer", "io", ".", "Seeker", "io", ".", "Closer", "and", "io", ".", "ReaderFrom", ".", "The", "flags", "are", "as", "passes", "to", "the", "largeObjectCreate", "method", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/dlo.go#L16-L25
6,163
ncw/swift
dlo.go
DynamicLargeObjectCreate
func (c *Connection) DynamicLargeObjectCreate(opts *LargeObjectOpts) (LargeObjectFile, error) { opts.Flags = os.O_TRUNC | os.O_CREATE return c.DynamicLargeObjectCreateFile(opts) }
go
func (c *Connection) DynamicLargeObjectCreate(opts *LargeObjectOpts) (LargeObjectFile, error) { opts.Flags = os.O_TRUNC | os.O_CREATE return c.DynamicLargeObjectCreateFile(opts) }
[ "func", "(", "c", "*", "Connection", ")", "DynamicLargeObjectCreate", "(", "opts", "*", "LargeObjectOpts", ")", "(", "LargeObjectFile", ",", "error", ")", "{", "opts", ".", "Flags", "=", "os", ".", "O_TRUNC", "|", "os", ".", "O_CREATE", "\n", "return", "c", ".", "DynamicLargeObjectCreateFile", "(", "opts", ")", "\n", "}" ]
// DynamicLargeObjectCreate creates or truncates an existing dynamic // large object returning a writeable object. This sets opts.Flags to // an appropriate value before calling DynamicLargeObjectCreateFile
[ "DynamicLargeObjectCreate", "creates", "or", "truncates", "an", "existing", "dynamic", "large", "object", "returning", "a", "writeable", "object", ".", "This", "sets", "opts", ".", "Flags", "to", "an", "appropriate", "value", "before", "calling", "DynamicLargeObjectCreateFile" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/dlo.go#L30-L33
6,164
ncw/swift
dlo.go
DynamicLargeObjectDelete
func (c *Connection) DynamicLargeObjectDelete(container string, path string) error { return c.LargeObjectDelete(container, path) }
go
func (c *Connection) DynamicLargeObjectDelete(container string, path string) error { return c.LargeObjectDelete(container, path) }
[ "func", "(", "c", "*", "Connection", ")", "DynamicLargeObjectDelete", "(", "container", "string", ",", "path", "string", ")", "error", "{", "return", "c", ".", "LargeObjectDelete", "(", "container", ",", "path", ")", "\n", "}" ]
// DynamicLargeObjectDelete deletes a dynamic large object and all of its segments.
[ "DynamicLargeObjectDelete", "deletes", "a", "dynamic", "large", "object", "and", "all", "of", "its", "segments", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/dlo.go#L36-L38
6,165
ncw/swift
dlo.go
DynamicLargeObjectMove
func (c *Connection) DynamicLargeObjectMove(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string) error { info, headers, err := c.Object(dstContainer, srcObjectName) if err != nil { return err } segmentContainer, segmentPath := parseFullPath(headers["X-Object-Manifest"]) if err := c.createDLOManifest(dstContainer, dstObjectName, segmentContainer+"/"+segmentPath, info.ContentType); err != nil { return err } if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { return err } return nil }
go
func (c *Connection) DynamicLargeObjectMove(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string) error { info, headers, err := c.Object(dstContainer, srcObjectName) if err != nil { return err } segmentContainer, segmentPath := parseFullPath(headers["X-Object-Manifest"]) if err := c.createDLOManifest(dstContainer, dstObjectName, segmentContainer+"/"+segmentPath, info.ContentType); err != nil { return err } if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Connection", ")", "DynamicLargeObjectMove", "(", "srcContainer", "string", ",", "srcObjectName", "string", ",", "dstContainer", "string", ",", "dstObjectName", "string", ")", "error", "{", "info", ",", "headers", ",", "err", ":=", "c", ".", "Object", "(", "dstContainer", ",", "srcObjectName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "segmentContainer", ",", "segmentPath", ":=", "parseFullPath", "(", "headers", "[", "\"", "\"", "]", ")", "\n", "if", "err", ":=", "c", ".", "createDLOManifest", "(", "dstContainer", ",", "dstObjectName", ",", "segmentContainer", "+", "\"", "\"", "+", "segmentPath", ",", "info", ".", "ContentType", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "ObjectDelete", "(", "srcContainer", ",", "srcObjectName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DynamicLargeObjectMove moves a dynamic large object from srcContainer, srcObjectName to dstContainer, dstObjectName
[ "DynamicLargeObjectMove", "moves", "a", "dynamic", "large", "object", "from", "srcContainer", "srcObjectName", "to", "dstContainer", "dstObjectName" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/dlo.go#L41-L57
6,166
ncw/swift
dlo.go
createDLOManifest
func (c *Connection) createDLOManifest(container string, objectName string, prefix string, contentType string) error { headers := make(Headers) headers["X-Object-Manifest"] = prefix manifest, err := c.ObjectCreate(container, objectName, false, "", contentType, headers) if err != nil { return err } if err := manifest.Close(); err != nil { return err } return nil }
go
func (c *Connection) createDLOManifest(container string, objectName string, prefix string, contentType string) error { headers := make(Headers) headers["X-Object-Manifest"] = prefix manifest, err := c.ObjectCreate(container, objectName, false, "", contentType, headers) if err != nil { return err } if err := manifest.Close(); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Connection", ")", "createDLOManifest", "(", "container", "string", ",", "objectName", "string", ",", "prefix", "string", ",", "contentType", "string", ")", "error", "{", "headers", ":=", "make", "(", "Headers", ")", "\n", "headers", "[", "\"", "\"", "]", "=", "prefix", "\n", "manifest", ",", "err", ":=", "c", ".", "ObjectCreate", "(", "container", ",", "objectName", ",", "false", ",", "\"", "\"", ",", "contentType", ",", "headers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "manifest", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// createDLOManifest creates a dynamic large object manifest
[ "createDLOManifest", "creates", "a", "dynamic", "large", "object", "manifest" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/dlo.go#L60-L73
6,167
ncw/swift
auth.go
newAuth
func newAuth(c *Connection) (Authenticator, error) { AuthVersion := c.AuthVersion if AuthVersion == 0 { if strings.Contains(c.AuthUrl, "v3") { AuthVersion = 3 } else if strings.Contains(c.AuthUrl, "v2") { AuthVersion = 2 } else if strings.Contains(c.AuthUrl, "v1") { AuthVersion = 1 } else { return nil, newErrorf(500, "Can't find AuthVersion in AuthUrl - set explicitly") } } switch AuthVersion { case 1: return &v1Auth{}, nil case 2: return &v2Auth{ // Guess as to whether using API key or // password it will try both eventually so // this is just an optimization. useApiKey: len(c.ApiKey) >= 32, }, nil case 3: return &v3Auth{}, nil } return nil, newErrorf(500, "Auth Version %d not supported", AuthVersion) }
go
func newAuth(c *Connection) (Authenticator, error) { AuthVersion := c.AuthVersion if AuthVersion == 0 { if strings.Contains(c.AuthUrl, "v3") { AuthVersion = 3 } else if strings.Contains(c.AuthUrl, "v2") { AuthVersion = 2 } else if strings.Contains(c.AuthUrl, "v1") { AuthVersion = 1 } else { return nil, newErrorf(500, "Can't find AuthVersion in AuthUrl - set explicitly") } } switch AuthVersion { case 1: return &v1Auth{}, nil case 2: return &v2Auth{ // Guess as to whether using API key or // password it will try both eventually so // this is just an optimization. useApiKey: len(c.ApiKey) >= 32, }, nil case 3: return &v3Auth{}, nil } return nil, newErrorf(500, "Auth Version %d not supported", AuthVersion) }
[ "func", "newAuth", "(", "c", "*", "Connection", ")", "(", "Authenticator", ",", "error", ")", "{", "AuthVersion", ":=", "c", ".", "AuthVersion", "\n", "if", "AuthVersion", "==", "0", "{", "if", "strings", ".", "Contains", "(", "c", ".", "AuthUrl", ",", "\"", "\"", ")", "{", "AuthVersion", "=", "3", "\n", "}", "else", "if", "strings", ".", "Contains", "(", "c", ".", "AuthUrl", ",", "\"", "\"", ")", "{", "AuthVersion", "=", "2", "\n", "}", "else", "if", "strings", ".", "Contains", "(", "c", ".", "AuthUrl", ",", "\"", "\"", ")", "{", "AuthVersion", "=", "1", "\n", "}", "else", "{", "return", "nil", ",", "newErrorf", "(", "500", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "switch", "AuthVersion", "{", "case", "1", ":", "return", "&", "v1Auth", "{", "}", ",", "nil", "\n", "case", "2", ":", "return", "&", "v2Auth", "{", "// Guess as to whether using API key or", "// password it will try both eventually so", "// this is just an optimization.", "useApiKey", ":", "len", "(", "c", ".", "ApiKey", ")", ">=", "32", ",", "}", ",", "nil", "\n", "case", "3", ":", "return", "&", "v3Auth", "{", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "newErrorf", "(", "500", ",", "\"", "\"", ",", "AuthVersion", ")", "\n", "}" ]
// newAuth - create a new Authenticator from the AuthUrl // // A hint for AuthVersion can be provided
[ "newAuth", "-", "create", "a", "new", "Authenticator", "from", "the", "AuthUrl", "A", "hint", "for", "AuthVersion", "can", "be", "provided" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L54-L81
6,168
ncw/swift
auth.go
Request
func (auth *v1Auth) Request(c *Connection) (*http.Request, error) { req, err := http.NewRequest("GET", c.AuthUrl, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", c.UserAgent) req.Header.Set("X-Auth-Key", c.ApiKey) req.Header.Set("X-Auth-User", c.UserName) return req, nil }
go
func (auth *v1Auth) Request(c *Connection) (*http.Request, error) { req, err := http.NewRequest("GET", c.AuthUrl, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", c.UserAgent) req.Header.Set("X-Auth-Key", c.ApiKey) req.Header.Set("X-Auth-User", c.UserName) return req, nil }
[ "func", "(", "auth", "*", "v1Auth", ")", "Request", "(", "c", "*", "Connection", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "c", ".", "AuthUrl", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "c", ".", "UserAgent", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "c", ".", "ApiKey", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "c", ".", "UserName", ")", "\n", "return", "req", ",", "nil", "\n", "}" ]
// v1 Authentication - make request
[ "v1", "Authentication", "-", "make", "request" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L91-L100
6,169
ncw/swift
auth.go
Response
func (auth *v1Auth) Response(resp *http.Response) error { auth.Headers = resp.Header return nil }
go
func (auth *v1Auth) Response(resp *http.Response) error { auth.Headers = resp.Header return nil }
[ "func", "(", "auth", "*", "v1Auth", ")", "Response", "(", "resp", "*", "http", ".", "Response", ")", "error", "{", "auth", ".", "Headers", "=", "resp", ".", "Header", "\n", "return", "nil", "\n", "}" ]
// v1 Authentication - read response
[ "v1", "Authentication", "-", "read", "response" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L103-L106
6,170
ncw/swift
auth.go
StorageUrl
func (auth *v1Auth) StorageUrl(Internal bool) string { storageUrl := auth.Headers.Get("X-Storage-Url") if Internal { newUrl, err := url.Parse(storageUrl) if err != nil { return storageUrl } newUrl.Host = "snet-" + newUrl.Host storageUrl = newUrl.String() } return storageUrl }
go
func (auth *v1Auth) StorageUrl(Internal bool) string { storageUrl := auth.Headers.Get("X-Storage-Url") if Internal { newUrl, err := url.Parse(storageUrl) if err != nil { return storageUrl } newUrl.Host = "snet-" + newUrl.Host storageUrl = newUrl.String() } return storageUrl }
[ "func", "(", "auth", "*", "v1Auth", ")", "StorageUrl", "(", "Internal", "bool", ")", "string", "{", "storageUrl", ":=", "auth", ".", "Headers", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "Internal", "{", "newUrl", ",", "err", ":=", "url", ".", "Parse", "(", "storageUrl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "storageUrl", "\n", "}", "\n", "newUrl", ".", "Host", "=", "\"", "\"", "+", "newUrl", ".", "Host", "\n", "storageUrl", "=", "newUrl", ".", "String", "(", ")", "\n", "}", "\n", "return", "storageUrl", "\n", "}" ]
// v1 Authentication - read storage url
[ "v1", "Authentication", "-", "read", "storage", "url" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L109-L120
6,171
ncw/swift
auth.go
Request
func (auth *v2Auth) Request(c *Connection) (*http.Request, error) { auth.Region = c.Region // Toggle useApiKey if not first run and not OK yet if auth.notFirst && !auth.useApiKeyOk { auth.useApiKey = !auth.useApiKey } auth.notFirst = true // Create a V2 auth request for the body of the connection var v2i interface{} if !auth.useApiKey { // Normal swift authentication v2 := v2AuthRequest{} v2.Auth.PasswordCredentials.UserName = c.UserName v2.Auth.PasswordCredentials.Password = c.ApiKey v2.Auth.Tenant = c.Tenant v2.Auth.TenantId = c.TenantId v2i = v2 } else { // Rackspace special with API Key v2 := v2AuthRequestRackspace{} v2.Auth.ApiKeyCredentials.UserName = c.UserName v2.Auth.ApiKeyCredentials.ApiKey = c.ApiKey v2.Auth.Tenant = c.Tenant v2.Auth.TenantId = c.TenantId v2i = v2 } body, err := json.Marshal(v2i) if err != nil { return nil, err } url := c.AuthUrl if !strings.HasSuffix(url, "/") { url += "/" } url += "tokens" req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", c.UserAgent) return req, nil }
go
func (auth *v2Auth) Request(c *Connection) (*http.Request, error) { auth.Region = c.Region // Toggle useApiKey if not first run and not OK yet if auth.notFirst && !auth.useApiKeyOk { auth.useApiKey = !auth.useApiKey } auth.notFirst = true // Create a V2 auth request for the body of the connection var v2i interface{} if !auth.useApiKey { // Normal swift authentication v2 := v2AuthRequest{} v2.Auth.PasswordCredentials.UserName = c.UserName v2.Auth.PasswordCredentials.Password = c.ApiKey v2.Auth.Tenant = c.Tenant v2.Auth.TenantId = c.TenantId v2i = v2 } else { // Rackspace special with API Key v2 := v2AuthRequestRackspace{} v2.Auth.ApiKeyCredentials.UserName = c.UserName v2.Auth.ApiKeyCredentials.ApiKey = c.ApiKey v2.Auth.Tenant = c.Tenant v2.Auth.TenantId = c.TenantId v2i = v2 } body, err := json.Marshal(v2i) if err != nil { return nil, err } url := c.AuthUrl if !strings.HasSuffix(url, "/") { url += "/" } url += "tokens" req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", c.UserAgent) return req, nil }
[ "func", "(", "auth", "*", "v2Auth", ")", "Request", "(", "c", "*", "Connection", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "auth", ".", "Region", "=", "c", ".", "Region", "\n", "// Toggle useApiKey if not first run and not OK yet", "if", "auth", ".", "notFirst", "&&", "!", "auth", ".", "useApiKeyOk", "{", "auth", ".", "useApiKey", "=", "!", "auth", ".", "useApiKey", "\n", "}", "\n", "auth", ".", "notFirst", "=", "true", "\n", "// Create a V2 auth request for the body of the connection", "var", "v2i", "interface", "{", "}", "\n", "if", "!", "auth", ".", "useApiKey", "{", "// Normal swift authentication", "v2", ":=", "v2AuthRequest", "{", "}", "\n", "v2", ".", "Auth", ".", "PasswordCredentials", ".", "UserName", "=", "c", ".", "UserName", "\n", "v2", ".", "Auth", ".", "PasswordCredentials", ".", "Password", "=", "c", ".", "ApiKey", "\n", "v2", ".", "Auth", ".", "Tenant", "=", "c", ".", "Tenant", "\n", "v2", ".", "Auth", ".", "TenantId", "=", "c", ".", "TenantId", "\n", "v2i", "=", "v2", "\n", "}", "else", "{", "// Rackspace special with API Key", "v2", ":=", "v2AuthRequestRackspace", "{", "}", "\n", "v2", ".", "Auth", ".", "ApiKeyCredentials", ".", "UserName", "=", "c", ".", "UserName", "\n", "v2", ".", "Auth", ".", "ApiKeyCredentials", ".", "ApiKey", "=", "c", ".", "ApiKey", "\n", "v2", ".", "Auth", ".", "Tenant", "=", "c", ".", "Tenant", "\n", "v2", ".", "Auth", ".", "TenantId", "=", "c", ".", "TenantId", "\n", "v2i", "=", "v2", "\n", "}", "\n", "body", ",", "err", ":=", "json", ".", "Marshal", "(", "v2i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "url", ":=", "c", ".", "AuthUrl", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "url", ",", "\"", "\"", ")", "{", "url", "+=", "\"", "\"", "\n", "}", "\n", "url", "+=", "\"", "\"", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "bytes", ".", "NewBuffer", "(", "body", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "c", ".", "UserAgent", ")", "\n", "return", "req", ",", "nil", "\n", "}" ]
// v2 Authentication - make request
[ "v2", "Authentication", "-", "make", "request" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L144-L186
6,172
ncw/swift
auth.go
Response
func (auth *v2Auth) Response(resp *http.Response) error { auth.Auth = new(v2AuthResponse) err := readJson(resp, auth.Auth) // If successfully read Auth then no need to toggle useApiKey any more if err == nil { auth.useApiKeyOk = true } return err }
go
func (auth *v2Auth) Response(resp *http.Response) error { auth.Auth = new(v2AuthResponse) err := readJson(resp, auth.Auth) // If successfully read Auth then no need to toggle useApiKey any more if err == nil { auth.useApiKeyOk = true } return err }
[ "func", "(", "auth", "*", "v2Auth", ")", "Response", "(", "resp", "*", "http", ".", "Response", ")", "error", "{", "auth", ".", "Auth", "=", "new", "(", "v2AuthResponse", ")", "\n", "err", ":=", "readJson", "(", "resp", ",", "auth", ".", "Auth", ")", "\n", "// If successfully read Auth then no need to toggle useApiKey any more", "if", "err", "==", "nil", "{", "auth", ".", "useApiKeyOk", "=", "true", "\n", "}", "\n", "return", "err", "\n", "}" ]
// v2 Authentication - read response
[ "v2", "Authentication", "-", "read", "response" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L189-L197
6,173
ncw/swift
auth.go
endpointUrl
func (auth *v2Auth) endpointUrl(Type string, endpointType EndpointType) string { for _, catalog := range auth.Auth.Access.ServiceCatalog { if catalog.Type == Type { for _, endpoint := range catalog.Endpoints { if auth.Region == "" || (auth.Region == endpoint.Region) { switch endpointType { case EndpointTypeInternal: return endpoint.InternalUrl case EndpointTypePublic: return endpoint.PublicUrl case EndpointTypeAdmin: return endpoint.AdminUrl default: return "" } } } } } return "" }
go
func (auth *v2Auth) endpointUrl(Type string, endpointType EndpointType) string { for _, catalog := range auth.Auth.Access.ServiceCatalog { if catalog.Type == Type { for _, endpoint := range catalog.Endpoints { if auth.Region == "" || (auth.Region == endpoint.Region) { switch endpointType { case EndpointTypeInternal: return endpoint.InternalUrl case EndpointTypePublic: return endpoint.PublicUrl case EndpointTypeAdmin: return endpoint.AdminUrl default: return "" } } } } } return "" }
[ "func", "(", "auth", "*", "v2Auth", ")", "endpointUrl", "(", "Type", "string", ",", "endpointType", "EndpointType", ")", "string", "{", "for", "_", ",", "catalog", ":=", "range", "auth", ".", "Auth", ".", "Access", ".", "ServiceCatalog", "{", "if", "catalog", ".", "Type", "==", "Type", "{", "for", "_", ",", "endpoint", ":=", "range", "catalog", ".", "Endpoints", "{", "if", "auth", ".", "Region", "==", "\"", "\"", "||", "(", "auth", ".", "Region", "==", "endpoint", ".", "Region", ")", "{", "switch", "endpointType", "{", "case", "EndpointTypeInternal", ":", "return", "endpoint", ".", "InternalUrl", "\n", "case", "EndpointTypePublic", ":", "return", "endpoint", ".", "PublicUrl", "\n", "case", "EndpointTypeAdmin", ":", "return", "endpoint", ".", "AdminUrl", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Finds the Endpoint Url of "type" from the v2AuthResponse using the // Region if set or defaulting to the first one if not // // Returns "" if not found
[ "Finds", "the", "Endpoint", "Url", "of", "type", "from", "the", "v2AuthResponse", "using", "the", "Region", "if", "set", "or", "defaulting", "to", "the", "first", "one", "if", "not", "Returns", "if", "not", "found" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L203-L223
6,174
ncw/swift
auth.go
Expires
func (auth *v2Auth) Expires() time.Time { t, err := time.Parse(time.RFC3339, auth.Auth.Access.Token.Expires) if err != nil { return time.Time{} // return Zero if not parsed } return t }
go
func (auth *v2Auth) Expires() time.Time { t, err := time.Parse(time.RFC3339, auth.Auth.Access.Token.Expires) if err != nil { return time.Time{} // return Zero if not parsed } return t }
[ "func", "(", "auth", "*", "v2Auth", ")", "Expires", "(", ")", "time", ".", "Time", "{", "t", ",", "err", ":=", "time", ".", "Parse", "(", "time", ".", "RFC3339", ",", "auth", ".", "Auth", ".", "Access", ".", "Token", ".", "Expires", ")", "\n", "if", "err", "!=", "nil", "{", "return", "time", ".", "Time", "{", "}", "// return Zero if not parsed", "\n", "}", "\n", "return", "t", "\n", "}" ]
// v2 Authentication - read expires
[ "v2", "Authentication", "-", "read", "expires" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/auth.go#L250-L256
6,175
ncw/swift
timeout_reader.go
newTimeoutReader
func newTimeoutReader(reader io.ReadCloser, timeout time.Duration, cancel func()) *timeoutReader { return &timeoutReader{ reader: reader, timeout: timeout, cancel: cancel, } }
go
func newTimeoutReader(reader io.ReadCloser, timeout time.Duration, cancel func()) *timeoutReader { return &timeoutReader{ reader: reader, timeout: timeout, cancel: cancel, } }
[ "func", "newTimeoutReader", "(", "reader", "io", ".", "ReadCloser", ",", "timeout", "time", ".", "Duration", ",", "cancel", "func", "(", ")", ")", "*", "timeoutReader", "{", "return", "&", "timeoutReader", "{", "reader", ":", "reader", ",", "timeout", ":", "timeout", ",", "cancel", ":", "cancel", ",", "}", "\n", "}" ]
// Returns a wrapper around the reader which obeys an idle // timeout. The cancel function is called if the timeout happens
[ "Returns", "a", "wrapper", "around", "the", "reader", "which", "obeys", "an", "idle", "timeout", ".", "The", "cancel", "function", "is", "called", "if", "the", "timeout", "happens" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/timeout_reader.go#L17-L23
6,176
ncw/swift
watchdog_reader.go
newWatchdogReader
func newWatchdogReader(reader io.Reader, timeout time.Duration, timer *time.Timer) *watchdogReader { return &watchdogReader{ timeout: timeout, reader: reader, timer: timer, chunkSize: watchdogChunkSize, } }
go
func newWatchdogReader(reader io.Reader, timeout time.Duration, timer *time.Timer) *watchdogReader { return &watchdogReader{ timeout: timeout, reader: reader, timer: timer, chunkSize: watchdogChunkSize, } }
[ "func", "newWatchdogReader", "(", "reader", "io", ".", "Reader", ",", "timeout", "time", ".", "Duration", ",", "timer", "*", "time", ".", "Timer", ")", "*", "watchdogReader", "{", "return", "&", "watchdogReader", "{", "timeout", ":", "timeout", ",", "reader", ":", "reader", ",", "timer", ":", "timer", ",", "chunkSize", ":", "watchdogChunkSize", ",", "}", "\n", "}" ]
// Returns a new reader which will kick the watchdog timer whenever data is read
[ "Returns", "a", "new", "reader", "which", "will", "kick", "the", "watchdog", "timer", "whenever", "data", "is", "read" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/watchdog_reader.go#L19-L26
6,177
ncw/swift
slo.go
StaticLargeObjectCreateFile
func (c *Connection) StaticLargeObjectCreateFile(opts *LargeObjectOpts) (LargeObjectFile, error) { info, err := c.cachedQueryInfo() if err != nil || !info.SupportsSLO() { return nil, SLONotSupported } realMinChunkSize := info.SLOMinSegmentSize() if realMinChunkSize > opts.MinChunkSize { opts.MinChunkSize = realMinChunkSize } lo, err := c.largeObjectCreate(opts) if err != nil { return nil, err } return withBuffer(opts, &StaticLargeObjectCreateFile{ largeObjectCreateFile: *lo, }), nil }
go
func (c *Connection) StaticLargeObjectCreateFile(opts *LargeObjectOpts) (LargeObjectFile, error) { info, err := c.cachedQueryInfo() if err != nil || !info.SupportsSLO() { return nil, SLONotSupported } realMinChunkSize := info.SLOMinSegmentSize() if realMinChunkSize > opts.MinChunkSize { opts.MinChunkSize = realMinChunkSize } lo, err := c.largeObjectCreate(opts) if err != nil { return nil, err } return withBuffer(opts, &StaticLargeObjectCreateFile{ largeObjectCreateFile: *lo, }), nil }
[ "func", "(", "c", "*", "Connection", ")", "StaticLargeObjectCreateFile", "(", "opts", "*", "LargeObjectOpts", ")", "(", "LargeObjectFile", ",", "error", ")", "{", "info", ",", "err", ":=", "c", ".", "cachedQueryInfo", "(", ")", "\n", "if", "err", "!=", "nil", "||", "!", "info", ".", "SupportsSLO", "(", ")", "{", "return", "nil", ",", "SLONotSupported", "\n", "}", "\n", "realMinChunkSize", ":=", "info", ".", "SLOMinSegmentSize", "(", ")", "\n", "if", "realMinChunkSize", ">", "opts", ".", "MinChunkSize", "{", "opts", ".", "MinChunkSize", "=", "realMinChunkSize", "\n", "}", "\n", "lo", ",", "err", ":=", "c", ".", "largeObjectCreate", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "withBuffer", "(", "opts", ",", "&", "StaticLargeObjectCreateFile", "{", "largeObjectCreateFile", ":", "*", "lo", ",", "}", ")", ",", "nil", "\n", "}" ]
// StaticLargeObjectCreateFile creates a static large object returning // an object which satisfies io.Writer, io.Seeker, io.Closer and // io.ReaderFrom. The flags are as passed to the largeObjectCreate // method.
[ "StaticLargeObjectCreateFile", "creates", "a", "static", "large", "object", "returning", "an", "object", "which", "satisfies", "io", ".", "Writer", "io", ".", "Seeker", "io", ".", "Closer", "and", "io", ".", "ReaderFrom", ".", "The", "flags", "are", "as", "passed", "to", "the", "largeObjectCreate", "method", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/slo.go#L40-L56
6,178
ncw/swift
slo.go
StaticLargeObjectCreate
func (c *Connection) StaticLargeObjectCreate(opts *LargeObjectOpts) (LargeObjectFile, error) { opts.Flags = os.O_TRUNC | os.O_CREATE return c.StaticLargeObjectCreateFile(opts) }
go
func (c *Connection) StaticLargeObjectCreate(opts *LargeObjectOpts) (LargeObjectFile, error) { opts.Flags = os.O_TRUNC | os.O_CREATE return c.StaticLargeObjectCreateFile(opts) }
[ "func", "(", "c", "*", "Connection", ")", "StaticLargeObjectCreate", "(", "opts", "*", "LargeObjectOpts", ")", "(", "LargeObjectFile", ",", "error", ")", "{", "opts", ".", "Flags", "=", "os", ".", "O_TRUNC", "|", "os", ".", "O_CREATE", "\n", "return", "c", ".", "StaticLargeObjectCreateFile", "(", "opts", ")", "\n", "}" ]
// StaticLargeObjectCreate creates or truncates an existing static // large object returning a writeable object. This sets opts.Flags to // an appropriate value before calling StaticLargeObjectCreateFile
[ "StaticLargeObjectCreate", "creates", "or", "truncates", "an", "existing", "static", "large", "object", "returning", "a", "writeable", "object", ".", "This", "sets", "opts", ".", "Flags", "to", "an", "appropriate", "value", "before", "calling", "StaticLargeObjectCreateFile" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/slo.go#L61-L64
6,179
ncw/swift
slo.go
StaticLargeObjectDelete
func (c *Connection) StaticLargeObjectDelete(container string, path string) error { info, err := c.cachedQueryInfo() if err != nil || !info.SupportsSLO() { return SLONotSupported } return c.LargeObjectDelete(container, path) }
go
func (c *Connection) StaticLargeObjectDelete(container string, path string) error { info, err := c.cachedQueryInfo() if err != nil || !info.SupportsSLO() { return SLONotSupported } return c.LargeObjectDelete(container, path) }
[ "func", "(", "c", "*", "Connection", ")", "StaticLargeObjectDelete", "(", "container", "string", ",", "path", "string", ")", "error", "{", "info", ",", "err", ":=", "c", ".", "cachedQueryInfo", "(", ")", "\n", "if", "err", "!=", "nil", "||", "!", "info", ".", "SupportsSLO", "(", ")", "{", "return", "SLONotSupported", "\n", "}", "\n", "return", "c", ".", "LargeObjectDelete", "(", "container", ",", "path", ")", "\n", "}" ]
// StaticLargeObjectDelete deletes a static large object and all of its segments.
[ "StaticLargeObjectDelete", "deletes", "a", "static", "large", "object", "and", "all", "of", "its", "segments", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/slo.go#L67-L73
6,180
ncw/swift
slo.go
StaticLargeObjectMove
func (c *Connection) StaticLargeObjectMove(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string) error { swiftInfo, err := c.cachedQueryInfo() if err != nil || !swiftInfo.SupportsSLO() { return SLONotSupported } info, headers, err := c.Object(srcContainer, srcObjectName) if err != nil { return err } container, segments, err := c.getAllSegments(srcContainer, srcObjectName, headers) if err != nil { return err } //copy only metadata during move (other headers might not be safe for copying) headers = headers.ObjectMetadata().ObjectHeaders() if err := c.createSLOManifest(dstContainer, dstObjectName, info.ContentType, container, segments, headers); err != nil { return err } if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { return err } return nil }
go
func (c *Connection) StaticLargeObjectMove(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string) error { swiftInfo, err := c.cachedQueryInfo() if err != nil || !swiftInfo.SupportsSLO() { return SLONotSupported } info, headers, err := c.Object(srcContainer, srcObjectName) if err != nil { return err } container, segments, err := c.getAllSegments(srcContainer, srcObjectName, headers) if err != nil { return err } //copy only metadata during move (other headers might not be safe for copying) headers = headers.ObjectMetadata().ObjectHeaders() if err := c.createSLOManifest(dstContainer, dstObjectName, info.ContentType, container, segments, headers); err != nil { return err } if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Connection", ")", "StaticLargeObjectMove", "(", "srcContainer", "string", ",", "srcObjectName", "string", ",", "dstContainer", "string", ",", "dstObjectName", "string", ")", "error", "{", "swiftInfo", ",", "err", ":=", "c", ".", "cachedQueryInfo", "(", ")", "\n", "if", "err", "!=", "nil", "||", "!", "swiftInfo", ".", "SupportsSLO", "(", ")", "{", "return", "SLONotSupported", "\n", "}", "\n", "info", ",", "headers", ",", "err", ":=", "c", ".", "Object", "(", "srcContainer", ",", "srcObjectName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "container", ",", "segments", ",", "err", ":=", "c", ".", "getAllSegments", "(", "srcContainer", ",", "srcObjectName", ",", "headers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "//copy only metadata during move (other headers might not be safe for copying)", "headers", "=", "headers", ".", "ObjectMetadata", "(", ")", ".", "ObjectHeaders", "(", ")", "\n\n", "if", "err", ":=", "c", ".", "createSLOManifest", "(", "dstContainer", ",", "dstObjectName", ",", "info", ".", "ContentType", ",", "container", ",", "segments", ",", "headers", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "ObjectDelete", "(", "srcContainer", ",", "srcObjectName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// StaticLargeObjectMove moves a static large object from srcContainer, srcObjectName to dstContainer, dstObjectName
[ "StaticLargeObjectMove", "moves", "a", "static", "large", "object", "from", "srcContainer", "srcObjectName", "to", "dstContainer", "dstObjectName" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/slo.go#L76-L103
6,181
ncw/swift
slo.go
createSLOManifest
func (c *Connection) createSLOManifest(container string, path string, contentType string, segmentContainer string, segments []Object, h Headers) error { sloSegments := make([]swiftSegment, len(segments)) for i, segment := range segments { sloSegments[i].Path = fmt.Sprintf("%s/%s", segmentContainer, segment.Name) sloSegments[i].Etag = segment.Hash sloSegments[i].Size = segment.Bytes } content, err := json.Marshal(sloSegments) if err != nil { return err } values := url.Values{} values.Set("multipart-manifest", "put") if _, err := c.objectPut(container, path, bytes.NewBuffer(content), false, "", contentType, h, values); err != nil { return err } return nil }
go
func (c *Connection) createSLOManifest(container string, path string, contentType string, segmentContainer string, segments []Object, h Headers) error { sloSegments := make([]swiftSegment, len(segments)) for i, segment := range segments { sloSegments[i].Path = fmt.Sprintf("%s/%s", segmentContainer, segment.Name) sloSegments[i].Etag = segment.Hash sloSegments[i].Size = segment.Bytes } content, err := json.Marshal(sloSegments) if err != nil { return err } values := url.Values{} values.Set("multipart-manifest", "put") if _, err := c.objectPut(container, path, bytes.NewBuffer(content), false, "", contentType, h, values); err != nil { return err } return nil }
[ "func", "(", "c", "*", "Connection", ")", "createSLOManifest", "(", "container", "string", ",", "path", "string", ",", "contentType", "string", ",", "segmentContainer", "string", ",", "segments", "[", "]", "Object", ",", "h", "Headers", ")", "error", "{", "sloSegments", ":=", "make", "(", "[", "]", "swiftSegment", ",", "len", "(", "segments", ")", ")", "\n", "for", "i", ",", "segment", ":=", "range", "segments", "{", "sloSegments", "[", "i", "]", ".", "Path", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "segmentContainer", ",", "segment", ".", "Name", ")", "\n", "sloSegments", "[", "i", "]", ".", "Etag", "=", "segment", ".", "Hash", "\n", "sloSegments", "[", "i", "]", ".", "Size", "=", "segment", ".", "Bytes", "\n", "}", "\n\n", "content", ",", "err", ":=", "json", ".", "Marshal", "(", "sloSegments", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "values", ":=", "url", ".", "Values", "{", "}", "\n", "values", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "_", ",", "err", ":=", "c", ".", "objectPut", "(", "container", ",", "path", ",", "bytes", ".", "NewBuffer", "(", "content", ")", ",", "false", ",", "\"", "\"", ",", "contentType", ",", "h", ",", "values", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// createSLOManifest creates a static large object manifest
[ "createSLOManifest", "creates", "a", "static", "large", "object", "manifest" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/slo.go#L106-L126
6,182
ncw/swift
rs/rs.go
manage
func (c *RsConnection) manage(p swift.RequestOpts) (resp *http.Response, headers swift.Headers, err error) { p.OnReAuth = func() (string, error) { if c.cdnUrl == "" { c.cdnUrl = c.Auth.CdnUrl() } if c.cdnUrl == "" { return "", errors.New("The X-CDN-Management-Url does not exist on the authenticated platform") } return c.cdnUrl, nil } if c.Authenticated() { _, err = p.OnReAuth() if err != nil { return nil, nil, err } } return c.Connection.Call(c.cdnUrl, p) }
go
func (c *RsConnection) manage(p swift.RequestOpts) (resp *http.Response, headers swift.Headers, err error) { p.OnReAuth = func() (string, error) { if c.cdnUrl == "" { c.cdnUrl = c.Auth.CdnUrl() } if c.cdnUrl == "" { return "", errors.New("The X-CDN-Management-Url does not exist on the authenticated platform") } return c.cdnUrl, nil } if c.Authenticated() { _, err = p.OnReAuth() if err != nil { return nil, nil, err } } return c.Connection.Call(c.cdnUrl, p) }
[ "func", "(", "c", "*", "RsConnection", ")", "manage", "(", "p", "swift", ".", "RequestOpts", ")", "(", "resp", "*", "http", ".", "Response", ",", "headers", "swift", ".", "Headers", ",", "err", "error", ")", "{", "p", ".", "OnReAuth", "=", "func", "(", ")", "(", "string", ",", "error", ")", "{", "if", "c", ".", "cdnUrl", "==", "\"", "\"", "{", "c", ".", "cdnUrl", "=", "c", ".", "Auth", ".", "CdnUrl", "(", ")", "\n", "}", "\n", "if", "c", ".", "cdnUrl", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "cdnUrl", ",", "nil", "\n", "}", "\n", "if", "c", ".", "Authenticated", "(", ")", "{", "_", ",", "err", "=", "p", ".", "OnReAuth", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "c", ".", "Connection", ".", "Call", "(", "c", ".", "cdnUrl", ",", "p", ")", "\n", "}" ]
// manage is similar to the swift storage method, but uses the CDN Management URL for CDN specific calls.
[ "manage", "is", "similar", "to", "the", "swift", "storage", "method", "but", "uses", "the", "CDN", "Management", "URL", "for", "CDN", "specific", "calls", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/rs/rs.go#L19-L36
6,183
ncw/swift
rs/rs.go
ContainerCDNDisable
func (c *RsConnection) ContainerCDNDisable(container string) error { h := swift.Headers{"X-CDN-Enabled": "false"} _, _, err := c.manage(swift.RequestOpts{ Container: container, Operation: "PUT", ErrorMap: swift.ContainerErrorMap, NoResponse: true, Headers: h, }) return err }
go
func (c *RsConnection) ContainerCDNDisable(container string) error { h := swift.Headers{"X-CDN-Enabled": "false"} _, _, err := c.manage(swift.RequestOpts{ Container: container, Operation: "PUT", ErrorMap: swift.ContainerErrorMap, NoResponse: true, Headers: h, }) return err }
[ "func", "(", "c", "*", "RsConnection", ")", "ContainerCDNDisable", "(", "container", "string", ")", "error", "{", "h", ":=", "swift", ".", "Headers", "{", "\"", "\"", ":", "\"", "\"", "}", "\n\n", "_", ",", "_", ",", "err", ":=", "c", ".", "manage", "(", "swift", ".", "RequestOpts", "{", "Container", ":", "container", ",", "Operation", ":", "\"", "\"", ",", "ErrorMap", ":", "swift", ".", "ContainerErrorMap", ",", "NoResponse", ":", "true", ",", "Headers", ":", "h", ",", "}", ")", "\n", "return", "err", "\n", "}" ]
// ContainerCDNDisable disables CDN access to a container.
[ "ContainerCDNDisable", "disables", "CDN", "access", "to", "a", "container", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/rs/rs.go#L60-L71
6,184
ncw/swift
compatibility_1_1.go
cancelRequest
func cancelRequest(transport http.RoundTripper, req *http.Request) { if tr, ok := transport.(interface { CancelRequest(*http.Request) }); ok { tr.CancelRequest(req) } }
go
func cancelRequest(transport http.RoundTripper, req *http.Request) { if tr, ok := transport.(interface { CancelRequest(*http.Request) }); ok { tr.CancelRequest(req) } }
[ "func", "cancelRequest", "(", "transport", "http", ".", "RoundTripper", ",", "req", "*", "http", ".", "Request", ")", "{", "if", "tr", ",", "ok", ":=", "transport", ".", "(", "interface", "{", "CancelRequest", "(", "*", "http", ".", "Request", ")", "\n", "}", ")", ";", "ok", "{", "tr", ".", "CancelRequest", "(", "req", ")", "\n", "}", "\n", "}" ]
// Cancel the request
[ "Cancel", "the", "request" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/compatibility_1_1.go#L13-L19
6,185
ncw/swift
compatibility_1_1.go
resetTimer
func resetTimer(t *time.Timer, d time.Duration) { t.Reset(d) }
go
func resetTimer(t *time.Timer, d time.Duration) { t.Reset(d) }
[ "func", "resetTimer", "(", "t", "*", "time", ".", "Timer", ",", "d", "time", ".", "Duration", ")", "{", "t", ".", "Reset", "(", "d", ")", "\n", "}" ]
// Reset a timer
[ "Reset", "a", "timer" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/compatibility_1_1.go#L22-L24
6,186
ncw/swift
largeobjects.go
largeObjectCreate
func (c *Connection) largeObjectCreate(opts *LargeObjectOpts) (*largeObjectCreateFile, error) { var ( segmentPath string segmentContainer string segments []Object currentLength int64 err error ) if opts.SegmentPrefix != "" { segmentPath = opts.SegmentPrefix } else if segmentPath, err = swiftSegmentPath(opts.ObjectName); err != nil { return nil, err } if info, headers, err := c.Object(opts.Container, opts.ObjectName); err == nil { if opts.Flags&os.O_TRUNC != 0 { c.LargeObjectDelete(opts.Container, opts.ObjectName) } else { currentLength = info.Bytes if headers.IsLargeObject() { segmentContainer, segments, err = c.getAllSegments(opts.Container, opts.ObjectName, headers) if err != nil { return nil, err } if len(segments) > 0 { segmentPath = gopath.Dir(segments[0].Name) } } else { if err = c.ObjectMove(opts.Container, opts.ObjectName, opts.Container, getSegment(segmentPath, 1)); err != nil { return nil, err } segments = append(segments, info) } } } else if err != ObjectNotFound { return nil, err } // segmentContainer is not empty when the manifest already existed if segmentContainer == "" { if opts.SegmentContainer != "" { segmentContainer = opts.SegmentContainer } else { segmentContainer = opts.Container + "_segments" } } file := &largeObjectCreateFile{ conn: c, checkHash: opts.CheckHash, container: opts.Container, objectName: opts.ObjectName, chunkSize: opts.ChunkSize, minChunkSize: opts.MinChunkSize, headers: opts.Headers, segmentContainer: segmentContainer, prefix: segmentPath, segments: segments, currentLength: currentLength, } if file.chunkSize == 0 { file.chunkSize = 10 * 1024 * 1024 } if file.minChunkSize > file.chunkSize { file.chunkSize = file.minChunkSize } if opts.Flags&os.O_APPEND != 0 { file.filePos = currentLength } return file, nil }
go
func (c *Connection) largeObjectCreate(opts *LargeObjectOpts) (*largeObjectCreateFile, error) { var ( segmentPath string segmentContainer string segments []Object currentLength int64 err error ) if opts.SegmentPrefix != "" { segmentPath = opts.SegmentPrefix } else if segmentPath, err = swiftSegmentPath(opts.ObjectName); err != nil { return nil, err } if info, headers, err := c.Object(opts.Container, opts.ObjectName); err == nil { if opts.Flags&os.O_TRUNC != 0 { c.LargeObjectDelete(opts.Container, opts.ObjectName) } else { currentLength = info.Bytes if headers.IsLargeObject() { segmentContainer, segments, err = c.getAllSegments(opts.Container, opts.ObjectName, headers) if err != nil { return nil, err } if len(segments) > 0 { segmentPath = gopath.Dir(segments[0].Name) } } else { if err = c.ObjectMove(opts.Container, opts.ObjectName, opts.Container, getSegment(segmentPath, 1)); err != nil { return nil, err } segments = append(segments, info) } } } else if err != ObjectNotFound { return nil, err } // segmentContainer is not empty when the manifest already existed if segmentContainer == "" { if opts.SegmentContainer != "" { segmentContainer = opts.SegmentContainer } else { segmentContainer = opts.Container + "_segments" } } file := &largeObjectCreateFile{ conn: c, checkHash: opts.CheckHash, container: opts.Container, objectName: opts.ObjectName, chunkSize: opts.ChunkSize, minChunkSize: opts.MinChunkSize, headers: opts.Headers, segmentContainer: segmentContainer, prefix: segmentPath, segments: segments, currentLength: currentLength, } if file.chunkSize == 0 { file.chunkSize = 10 * 1024 * 1024 } if file.minChunkSize > file.chunkSize { file.chunkSize = file.minChunkSize } if opts.Flags&os.O_APPEND != 0 { file.filePos = currentLength } return file, nil }
[ "func", "(", "c", "*", "Connection", ")", "largeObjectCreate", "(", "opts", "*", "LargeObjectOpts", ")", "(", "*", "largeObjectCreateFile", ",", "error", ")", "{", "var", "(", "segmentPath", "string", "\n", "segmentContainer", "string", "\n", "segments", "[", "]", "Object", "\n", "currentLength", "int64", "\n", "err", "error", "\n", ")", "\n\n", "if", "opts", ".", "SegmentPrefix", "!=", "\"", "\"", "{", "segmentPath", "=", "opts", ".", "SegmentPrefix", "\n", "}", "else", "if", "segmentPath", ",", "err", "=", "swiftSegmentPath", "(", "opts", ".", "ObjectName", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "info", ",", "headers", ",", "err", ":=", "c", ".", "Object", "(", "opts", ".", "Container", ",", "opts", ".", "ObjectName", ")", ";", "err", "==", "nil", "{", "if", "opts", ".", "Flags", "&", "os", ".", "O_TRUNC", "!=", "0", "{", "c", ".", "LargeObjectDelete", "(", "opts", ".", "Container", ",", "opts", ".", "ObjectName", ")", "\n", "}", "else", "{", "currentLength", "=", "info", ".", "Bytes", "\n", "if", "headers", ".", "IsLargeObject", "(", ")", "{", "segmentContainer", ",", "segments", ",", "err", "=", "c", ".", "getAllSegments", "(", "opts", ".", "Container", ",", "opts", ".", "ObjectName", ",", "headers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "segments", ")", ">", "0", "{", "segmentPath", "=", "gopath", ".", "Dir", "(", "segments", "[", "0", "]", ".", "Name", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", "=", "c", ".", "ObjectMove", "(", "opts", ".", "Container", ",", "opts", ".", "ObjectName", ",", "opts", ".", "Container", ",", "getSegment", "(", "segmentPath", ",", "1", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "segments", "=", "append", "(", "segments", ",", "info", ")", "\n", "}", "\n", "}", "\n", "}", "else", "if", "err", "!=", "ObjectNotFound", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// segmentContainer is not empty when the manifest already existed", "if", "segmentContainer", "==", "\"", "\"", "{", "if", "opts", ".", "SegmentContainer", "!=", "\"", "\"", "{", "segmentContainer", "=", "opts", ".", "SegmentContainer", "\n", "}", "else", "{", "segmentContainer", "=", "opts", ".", "Container", "+", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "file", ":=", "&", "largeObjectCreateFile", "{", "conn", ":", "c", ",", "checkHash", ":", "opts", ".", "CheckHash", ",", "container", ":", "opts", ".", "Container", ",", "objectName", ":", "opts", ".", "ObjectName", ",", "chunkSize", ":", "opts", ".", "ChunkSize", ",", "minChunkSize", ":", "opts", ".", "MinChunkSize", ",", "headers", ":", "opts", ".", "Headers", ",", "segmentContainer", ":", "segmentContainer", ",", "prefix", ":", "segmentPath", ",", "segments", ":", "segments", ",", "currentLength", ":", "currentLength", ",", "}", "\n\n", "if", "file", ".", "chunkSize", "==", "0", "{", "file", ".", "chunkSize", "=", "10", "*", "1024", "*", "1024", "\n", "}", "\n\n", "if", "file", ".", "minChunkSize", ">", "file", ".", "chunkSize", "{", "file", ".", "chunkSize", "=", "file", ".", "minChunkSize", "\n", "}", "\n\n", "if", "opts", ".", "Flags", "&", "os", ".", "O_APPEND", "!=", "0", "{", "file", ".", "filePos", "=", "currentLength", "\n", "}", "\n\n", "return", "file", ",", "nil", "\n", "}" ]
// largeObjectCreate creates a large object at opts.Container, opts.ObjectName. // // opts.Flags can have the following bits set // os.TRUNC - remove the contents of the large object if it exists // os.APPEND - write at the end of the large object
[ "largeObjectCreate", "creates", "a", "large", "object", "at", "opts", ".", "Container", "opts", ".", "ObjectName", ".", "opts", ".", "Flags", "can", "have", "the", "following", "bits", "set", "os", ".", "TRUNC", "-", "remove", "the", "contents", "of", "the", "large", "object", "if", "it", "exists", "os", ".", "APPEND", "-", "write", "at", "the", "end", "of", "the", "large", "object" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/largeobjects.go#L123-L198
6,187
ncw/swift
largeobjects.go
LargeObjectDelete
func (c *Connection) LargeObjectDelete(container string, objectName string) error { _, headers, err := c.Object(container, objectName) if err != nil { return err } var objects [][]string if headers.IsLargeObject() { segmentContainer, segments, err := c.getAllSegments(container, objectName, headers) if err != nil { return err } for _, obj := range segments { objects = append(objects, []string{segmentContainer, obj.Name}) } } objects = append(objects, []string{container, objectName}) info, err := c.cachedQueryInfo() if err == nil && info.SupportsBulkDelete() && len(objects) > 0 { filenames := make([]string, len(objects)) for i, obj := range objects { filenames[i] = obj[0] + "/" + obj[1] } _, err = c.doBulkDelete(filenames) // Don't fail on ObjectNotFound because eventual consistency // makes this situation normal. if err != nil && err != Forbidden && err != ObjectNotFound { return err } } else { for _, obj := range objects { if err := c.ObjectDelete(obj[0], obj[1]); err != nil { return err } } } return nil }
go
func (c *Connection) LargeObjectDelete(container string, objectName string) error { _, headers, err := c.Object(container, objectName) if err != nil { return err } var objects [][]string if headers.IsLargeObject() { segmentContainer, segments, err := c.getAllSegments(container, objectName, headers) if err != nil { return err } for _, obj := range segments { objects = append(objects, []string{segmentContainer, obj.Name}) } } objects = append(objects, []string{container, objectName}) info, err := c.cachedQueryInfo() if err == nil && info.SupportsBulkDelete() && len(objects) > 0 { filenames := make([]string, len(objects)) for i, obj := range objects { filenames[i] = obj[0] + "/" + obj[1] } _, err = c.doBulkDelete(filenames) // Don't fail on ObjectNotFound because eventual consistency // makes this situation normal. if err != nil && err != Forbidden && err != ObjectNotFound { return err } } else { for _, obj := range objects { if err := c.ObjectDelete(obj[0], obj[1]); err != nil { return err } } } return nil }
[ "func", "(", "c", "*", "Connection", ")", "LargeObjectDelete", "(", "container", "string", ",", "objectName", "string", ")", "error", "{", "_", ",", "headers", ",", "err", ":=", "c", ".", "Object", "(", "container", ",", "objectName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "objects", "[", "]", "[", "]", "string", "\n", "if", "headers", ".", "IsLargeObject", "(", ")", "{", "segmentContainer", ",", "segments", ",", "err", ":=", "c", ".", "getAllSegments", "(", "container", ",", "objectName", ",", "headers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "obj", ":=", "range", "segments", "{", "objects", "=", "append", "(", "objects", ",", "[", "]", "string", "{", "segmentContainer", ",", "obj", ".", "Name", "}", ")", "\n", "}", "\n", "}", "\n", "objects", "=", "append", "(", "objects", ",", "[", "]", "string", "{", "container", ",", "objectName", "}", ")", "\n\n", "info", ",", "err", ":=", "c", ".", "cachedQueryInfo", "(", ")", "\n", "if", "err", "==", "nil", "&&", "info", ".", "SupportsBulkDelete", "(", ")", "&&", "len", "(", "objects", ")", ">", "0", "{", "filenames", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "objects", ")", ")", "\n", "for", "i", ",", "obj", ":=", "range", "objects", "{", "filenames", "[", "i", "]", "=", "obj", "[", "0", "]", "+", "\"", "\"", "+", "obj", "[", "1", "]", "\n", "}", "\n", "_", ",", "err", "=", "c", ".", "doBulkDelete", "(", "filenames", ")", "\n", "// Don't fail on ObjectNotFound because eventual consistency", "// makes this situation normal.", "if", "err", "!=", "nil", "&&", "err", "!=", "Forbidden", "&&", "err", "!=", "ObjectNotFound", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "for", "_", ",", "obj", ":=", "range", "objects", "{", "if", "err", ":=", "c", ".", "ObjectDelete", "(", "obj", "[", "0", "]", ",", "obj", "[", "1", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// LargeObjectDelete deletes the large object named by container, path
[ "LargeObjectDelete", "deletes", "the", "large", "object", "named", "by", "container", "path" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/largeobjects.go#L201-L240
6,188
ncw/swift
largeobjects.go
Seek
func (file *largeObjectCreateFile) Seek(offset int64, whence int) (int64, error) { switch whence { case 0: file.filePos = offset case 1: file.filePos += offset case 2: file.filePos = file.currentLength + offset default: return -1, fmt.Errorf("invalid value for whence") } if file.filePos < 0 { return -1, fmt.Errorf("negative offset") } return file.filePos, nil }
go
func (file *largeObjectCreateFile) Seek(offset int64, whence int) (int64, error) { switch whence { case 0: file.filePos = offset case 1: file.filePos += offset case 2: file.filePos = file.currentLength + offset default: return -1, fmt.Errorf("invalid value for whence") } if file.filePos < 0 { return -1, fmt.Errorf("negative offset") } return file.filePos, nil }
[ "func", "(", "file", "*", "largeObjectCreateFile", ")", "Seek", "(", "offset", "int64", ",", "whence", "int", ")", "(", "int64", ",", "error", ")", "{", "switch", "whence", "{", "case", "0", ":", "file", ".", "filePos", "=", "offset", "\n", "case", "1", ":", "file", ".", "filePos", "+=", "offset", "\n", "case", "2", ":", "file", ".", "filePos", "=", "file", ".", "currentLength", "+", "offset", "\n", "default", ":", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "file", ".", "filePos", "<", "0", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "file", ".", "filePos", ",", "nil", "\n", "}" ]
// Seek sets the offset for the next write operation
[ "Seek", "sets", "the", "offset", "for", "the", "next", "write", "operation" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/largeobjects.go#L257-L272
6,189
ncw/swift
largeobjects.go
Write
func (file *largeObjectCreateFile) Write(buf []byte) (int, error) { var sz int64 var relativeFilePos int writeSegmentIdx := 0 for i, obj := range file.segments { if file.filePos < sz+obj.Bytes || (i == len(file.segments)-1 && file.filePos < sz+file.minChunkSize) { relativeFilePos = int(file.filePos - sz) break } writeSegmentIdx++ sz += obj.Bytes } sizeToWrite := len(buf) for offset := 0; offset < sizeToWrite; { newSegment, n, err := file.writeSegment(buf[offset:], writeSegmentIdx, relativeFilePos) if err != nil { return 0, err } if writeSegmentIdx < len(file.segments) { file.segments[writeSegmentIdx] = *newSegment } else { file.segments = append(file.segments, *newSegment) } offset += n writeSegmentIdx++ relativeFilePos = 0 } file.filePos += int64(sizeToWrite) file.currentLength = 0 for _, obj := range file.segments { file.currentLength += obj.Bytes } return sizeToWrite, nil }
go
func (file *largeObjectCreateFile) Write(buf []byte) (int, error) { var sz int64 var relativeFilePos int writeSegmentIdx := 0 for i, obj := range file.segments { if file.filePos < sz+obj.Bytes || (i == len(file.segments)-1 && file.filePos < sz+file.minChunkSize) { relativeFilePos = int(file.filePos - sz) break } writeSegmentIdx++ sz += obj.Bytes } sizeToWrite := len(buf) for offset := 0; offset < sizeToWrite; { newSegment, n, err := file.writeSegment(buf[offset:], writeSegmentIdx, relativeFilePos) if err != nil { return 0, err } if writeSegmentIdx < len(file.segments) { file.segments[writeSegmentIdx] = *newSegment } else { file.segments = append(file.segments, *newSegment) } offset += n writeSegmentIdx++ relativeFilePos = 0 } file.filePos += int64(sizeToWrite) file.currentLength = 0 for _, obj := range file.segments { file.currentLength += obj.Bytes } return sizeToWrite, nil }
[ "func", "(", "file", "*", "largeObjectCreateFile", ")", "Write", "(", "buf", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "var", "sz", "int64", "\n", "var", "relativeFilePos", "int", "\n", "writeSegmentIdx", ":=", "0", "\n", "for", "i", ",", "obj", ":=", "range", "file", ".", "segments", "{", "if", "file", ".", "filePos", "<", "sz", "+", "obj", ".", "Bytes", "||", "(", "i", "==", "len", "(", "file", ".", "segments", ")", "-", "1", "&&", "file", ".", "filePos", "<", "sz", "+", "file", ".", "minChunkSize", ")", "{", "relativeFilePos", "=", "int", "(", "file", ".", "filePos", "-", "sz", ")", "\n", "break", "\n", "}", "\n", "writeSegmentIdx", "++", "\n", "sz", "+=", "obj", ".", "Bytes", "\n", "}", "\n", "sizeToWrite", ":=", "len", "(", "buf", ")", "\n", "for", "offset", ":=", "0", ";", "offset", "<", "sizeToWrite", ";", "{", "newSegment", ",", "n", ",", "err", ":=", "file", ".", "writeSegment", "(", "buf", "[", "offset", ":", "]", ",", "writeSegmentIdx", ",", "relativeFilePos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "writeSegmentIdx", "<", "len", "(", "file", ".", "segments", ")", "{", "file", ".", "segments", "[", "writeSegmentIdx", "]", "=", "*", "newSegment", "\n", "}", "else", "{", "file", ".", "segments", "=", "append", "(", "file", ".", "segments", ",", "*", "newSegment", ")", "\n", "}", "\n", "offset", "+=", "n", "\n", "writeSegmentIdx", "++", "\n", "relativeFilePos", "=", "0", "\n", "}", "\n", "file", ".", "filePos", "+=", "int64", "(", "sizeToWrite", ")", "\n", "file", ".", "currentLength", "=", "0", "\n", "for", "_", ",", "obj", ":=", "range", "file", ".", "segments", "{", "file", ".", "currentLength", "+=", "obj", ".", "Bytes", "\n", "}", "\n", "return", "sizeToWrite", ",", "nil", "\n", "}" ]
// Write satisfies the io.Writer interface
[ "Write", "satisfies", "the", "io", ".", "Writer", "interface" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/largeobjects.go#L318-L351
6,190
ncw/swift
meta.go
Metadata
func (h Headers) Metadata(metaPrefix string) Metadata { m := Metadata{} metaPrefix = http.CanonicalHeaderKey(metaPrefix) for key, value := range h { if strings.HasPrefix(key, metaPrefix) { metaKey := strings.ToLower(key[len(metaPrefix):]) m[metaKey] = value } } return m }
go
func (h Headers) Metadata(metaPrefix string) Metadata { m := Metadata{} metaPrefix = http.CanonicalHeaderKey(metaPrefix) for key, value := range h { if strings.HasPrefix(key, metaPrefix) { metaKey := strings.ToLower(key[len(metaPrefix):]) m[metaKey] = value } } return m }
[ "func", "(", "h", "Headers", ")", "Metadata", "(", "metaPrefix", "string", ")", "Metadata", "{", "m", ":=", "Metadata", "{", "}", "\n", "metaPrefix", "=", "http", ".", "CanonicalHeaderKey", "(", "metaPrefix", ")", "\n", "for", "key", ",", "value", ":=", "range", "h", "{", "if", "strings", ".", "HasPrefix", "(", "key", ",", "metaPrefix", ")", "{", "metaKey", ":=", "strings", ".", "ToLower", "(", "key", "[", "len", "(", "metaPrefix", ")", ":", "]", ")", "\n", "m", "[", "metaKey", "]", "=", "value", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Metadata gets the Metadata starting with the metaPrefix out of the Headers. // // The keys in the Metadata will be converted to lower case
[ "Metadata", "gets", "the", "Metadata", "starting", "with", "the", "metaPrefix", "out", "of", "the", "Headers", ".", "The", "keys", "in", "the", "Metadata", "will", "be", "converted", "to", "lower", "case" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/meta.go#L19-L29
6,191
ncw/swift
meta.go
nsToFloatString
func nsToFloatString(ns int64) string { if ns < 0 { return "-" + nsToFloatString(-ns) } result := fmt.Sprintf("%010d", ns) split := len(result) - 9 result, decimals := result[:split], result[split:] decimals = strings.TrimRight(decimals, "0") if decimals != "" { result += "." result += decimals } return result }
go
func nsToFloatString(ns int64) string { if ns < 0 { return "-" + nsToFloatString(-ns) } result := fmt.Sprintf("%010d", ns) split := len(result) - 9 result, decimals := result[:split], result[split:] decimals = strings.TrimRight(decimals, "0") if decimals != "" { result += "." result += decimals } return result }
[ "func", "nsToFloatString", "(", "ns", "int64", ")", "string", "{", "if", "ns", "<", "0", "{", "return", "\"", "\"", "+", "nsToFloatString", "(", "-", "ns", ")", "\n", "}", "\n", "result", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ns", ")", "\n", "split", ":=", "len", "(", "result", ")", "-", "9", "\n", "result", ",", "decimals", ":=", "result", "[", ":", "split", "]", ",", "result", "[", "split", ":", "]", "\n", "decimals", "=", "strings", ".", "TrimRight", "(", "decimals", ",", "\"", "\"", ")", "\n", "if", "decimals", "!=", "\"", "\"", "{", "result", "+=", "\"", "\"", "\n", "result", "+=", "decimals", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Turns a number of ns into a floating point string in seconds // // Trims trailing zeros and guaranteed to be perfectly accurate
[ "Turns", "a", "number", "of", "ns", "into", "a", "floating", "point", "string", "in", "seconds", "Trims", "trailing", "zeros", "and", "guaranteed", "to", "be", "perfectly", "accurate" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/meta.go#L84-L97
6,192
ncw/swift
meta.go
floatStringToNs
func floatStringToNs(s string) (int64, error) { const zeros = "000000000" if point := strings.IndexRune(s, '.'); point >= 0 { tail := s[point+1:] if fill := 9 - len(tail); fill < 0 { tail = tail[:9] } else { tail += zeros[:fill] } s = s[:point] + tail } else if len(s) > 0 { // Make sure empty string produces an error s += zeros } return strconv.ParseInt(s, 10, 64) }
go
func floatStringToNs(s string) (int64, error) { const zeros = "000000000" if point := strings.IndexRune(s, '.'); point >= 0 { tail := s[point+1:] if fill := 9 - len(tail); fill < 0 { tail = tail[:9] } else { tail += zeros[:fill] } s = s[:point] + tail } else if len(s) > 0 { // Make sure empty string produces an error s += zeros } return strconv.ParseInt(s, 10, 64) }
[ "func", "floatStringToNs", "(", "s", "string", ")", "(", "int64", ",", "error", ")", "{", "const", "zeros", "=", "\"", "\"", "\n", "if", "point", ":=", "strings", ".", "IndexRune", "(", "s", ",", "'.'", ")", ";", "point", ">=", "0", "{", "tail", ":=", "s", "[", "point", "+", "1", ":", "]", "\n", "if", "fill", ":=", "9", "-", "len", "(", "tail", ")", ";", "fill", "<", "0", "{", "tail", "=", "tail", "[", ":", "9", "]", "\n", "}", "else", "{", "tail", "+=", "zeros", "[", ":", "fill", "]", "\n", "}", "\n", "s", "=", "s", "[", ":", "point", "]", "+", "tail", "\n", "}", "else", "if", "len", "(", "s", ")", ">", "0", "{", "// Make sure empty string produces an error", "s", "+=", "zeros", "\n", "}", "\n", "return", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "64", ")", "\n", "}" ]
// Turns a floating point string in seconds into a ns integer // // Guaranteed to be perfectly accurate
[ "Turns", "a", "floating", "point", "string", "in", "seconds", "into", "a", "ns", "integer", "Guaranteed", "to", "be", "perfectly", "accurate" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/meta.go#L102-L116
6,193
ncw/swift
swift.go
newError
func newError(StatusCode int, Text string) *Error { return &Error{ StatusCode: StatusCode, Text: Text, } }
go
func newError(StatusCode int, Text string) *Error { return &Error{ StatusCode: StatusCode, Text: Text, } }
[ "func", "newError", "(", "StatusCode", "int", ",", "Text", "string", ")", "*", "Error", "{", "return", "&", "Error", "{", "StatusCode", ":", "StatusCode", ",", "Text", ":", "Text", ",", "}", "\n", "}" ]
// newError make a new error from a string.
[ "newError", "make", "a", "new", "error", "from", "a", "string", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/swift.go#L283-L288
6,194
ncw/swift
swift.go
newErrorf
func newErrorf(StatusCode int, Text string, Parameters ...interface{}) *Error { return newError(StatusCode, fmt.Sprintf(Text, Parameters...)) }
go
func newErrorf(StatusCode int, Text string, Parameters ...interface{}) *Error { return newError(StatusCode, fmt.Sprintf(Text, Parameters...)) }
[ "func", "newErrorf", "(", "StatusCode", "int", ",", "Text", "string", ",", "Parameters", "...", "interface", "{", "}", ")", "*", "Error", "{", "return", "newError", "(", "StatusCode", ",", "fmt", ".", "Sprintf", "(", "Text", ",", "Parameters", "...", ")", ")", "\n", "}" ]
// newErrorf makes a new error from sprintf parameters.
[ "newErrorf", "makes", "a", "new", "error", "from", "sprintf", "parameters", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/swift.go#L291-L293
6,195
ncw/swift
swift.go
drainAndClose
func drainAndClose(rd io.ReadCloser, err *error) { if rd == nil { return } _, _ = io.Copy(ioutil.Discard, rd) cerr := rd.Close() if err != nil && *err == nil { *err = cerr } }
go
func drainAndClose(rd io.ReadCloser, err *error) { if rd == nil { return } _, _ = io.Copy(ioutil.Discard, rd) cerr := rd.Close() if err != nil && *err == nil { *err = cerr } }
[ "func", "drainAndClose", "(", "rd", "io", ".", "ReadCloser", ",", "err", "*", "error", ")", "{", "if", "rd", "==", "nil", "{", "return", "\n", "}", "\n\n", "_", ",", "_", "=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "rd", ")", "\n", "cerr", ":=", "rd", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "*", "err", "==", "nil", "{", "*", "err", "=", "cerr", "\n", "}", "\n", "}" ]
// drainAndClose discards all data from rd and closes it. // If an error occurs during Read, it is discarded.
[ "drainAndClose", "discards", "all", "data", "from", "rd", "and", "closes", "it", ".", "If", "an", "error", "occurs", "during", "Read", "it", "is", "discarded", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/swift.go#L353-L363
6,196
ncw/swift
swift.go
parseHeaders
func (c *Connection) parseHeaders(resp *http.Response, errorMap errorMap) error { if errorMap != nil { if err, ok := errorMap[resp.StatusCode]; ok { drainAndClose(resp.Body, nil) return err } } if resp.StatusCode < 200 || resp.StatusCode > 299 { drainAndClose(resp.Body, nil) return newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status) } return nil }
go
func (c *Connection) parseHeaders(resp *http.Response, errorMap errorMap) error { if errorMap != nil { if err, ok := errorMap[resp.StatusCode]; ok { drainAndClose(resp.Body, nil) return err } } if resp.StatusCode < 200 || resp.StatusCode > 299 { drainAndClose(resp.Body, nil) return newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status) } return nil }
[ "func", "(", "c", "*", "Connection", ")", "parseHeaders", "(", "resp", "*", "http", ".", "Response", ",", "errorMap", "errorMap", ")", "error", "{", "if", "errorMap", "!=", "nil", "{", "if", "err", ",", "ok", ":=", "errorMap", "[", "resp", ".", "StatusCode", "]", ";", "ok", "{", "drainAndClose", "(", "resp", ".", "Body", ",", "nil", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "<", "200", "||", "resp", ".", "StatusCode", ">", "299", "{", "drainAndClose", "(", "resp", ".", "Body", ",", "nil", ")", "\n", "return", "newErrorf", "(", "resp", ".", "StatusCode", ",", "\"", "\"", ",", "resp", ".", "StatusCode", ",", "resp", ".", "Status", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// parseHeaders checks a response for errors and translates into // standard errors if necessary. If an error is returned, resp.Body // has been drained and closed.
[ "parseHeaders", "checks", "a", "response", "for", "errors", "and", "translates", "into", "standard", "errors", "if", "necessary", ".", "If", "an", "error", "is", "returned", "resp", ".", "Body", "has", "been", "drained", "and", "closed", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/swift.go#L368-L380
6,197
ncw/swift
swift.go
doTimeoutRequest
func (c *Connection) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) { // Do the request in the background so we can check the timeout type result struct { resp *http.Response err error } done := make(chan result, 1) go func() { resp, err := c.client.Do(req) done <- result{resp, err} }() // Wait for the read or the timeout select { case r := <-done: return r.resp, r.err case <-timer.C: // Kill the connection on timeout so we don't leak sockets or goroutines cancelRequest(c.Transport, req) return nil, TimeoutError } panic("unreachable") // For Go 1.0 }
go
func (c *Connection) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) { // Do the request in the background so we can check the timeout type result struct { resp *http.Response err error } done := make(chan result, 1) go func() { resp, err := c.client.Do(req) done <- result{resp, err} }() // Wait for the read or the timeout select { case r := <-done: return r.resp, r.err case <-timer.C: // Kill the connection on timeout so we don't leak sockets or goroutines cancelRequest(c.Transport, req) return nil, TimeoutError } panic("unreachable") // For Go 1.0 }
[ "func", "(", "c", "*", "Connection", ")", "doTimeoutRequest", "(", "timer", "*", "time", ".", "Timer", ",", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "// Do the request in the background so we can check the timeout", "type", "result", "struct", "{", "resp", "*", "http", ".", "Response", "\n", "err", "error", "\n", "}", "\n", "done", ":=", "make", "(", "chan", "result", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "resp", ",", "err", ":=", "c", ".", "client", ".", "Do", "(", "req", ")", "\n", "done", "<-", "result", "{", "resp", ",", "err", "}", "\n", "}", "(", ")", "\n", "// Wait for the read or the timeout", "select", "{", "case", "r", ":=", "<-", "done", ":", "return", "r", ".", "resp", ",", "r", ".", "err", "\n", "case", "<-", "timer", ".", "C", ":", "// Kill the connection on timeout so we don't leak sockets or goroutines", "cancelRequest", "(", "c", ".", "Transport", ",", "req", ")", "\n", "return", "nil", ",", "TimeoutError", "\n", "}", "\n", "panic", "(", "\"", "\"", ")", "// For Go 1.0", "\n", "}" ]
// Does an http request using the running timer passed in
[ "Does", "an", "http", "request", "using", "the", "running", "timer", "passed", "in" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/swift.go#L398-L419
6,198
ncw/swift
swift.go
setDefaults
func (c *Connection) setDefaults() { if c.UserAgent == "" { c.UserAgent = DefaultUserAgent } if c.Retries == 0 { c.Retries = DefaultRetries } if c.ConnectTimeout == 0 { c.ConnectTimeout = 10 * time.Second } if c.Timeout == 0 { c.Timeout = 60 * time.Second } if c.Transport == nil { t := &http.Transport{ // TLSClientConfig: &tls.Config{RootCAs: pool}, // DisableCompression: true, Proxy: http.ProxyFromEnvironment, // Half of linux's default open files limit (1024). MaxIdleConnsPerHost: 512, } SetExpectContinueTimeout(t, 5*time.Second) c.Transport = t } if c.client == nil { c.client = &http.Client{ // CheckRedirect: redirectPolicyFunc, Transport: c.Transport, } } }
go
func (c *Connection) setDefaults() { if c.UserAgent == "" { c.UserAgent = DefaultUserAgent } if c.Retries == 0 { c.Retries = DefaultRetries } if c.ConnectTimeout == 0 { c.ConnectTimeout = 10 * time.Second } if c.Timeout == 0 { c.Timeout = 60 * time.Second } if c.Transport == nil { t := &http.Transport{ // TLSClientConfig: &tls.Config{RootCAs: pool}, // DisableCompression: true, Proxy: http.ProxyFromEnvironment, // Half of linux's default open files limit (1024). MaxIdleConnsPerHost: 512, } SetExpectContinueTimeout(t, 5*time.Second) c.Transport = t } if c.client == nil { c.client = &http.Client{ // CheckRedirect: redirectPolicyFunc, Transport: c.Transport, } } }
[ "func", "(", "c", "*", "Connection", ")", "setDefaults", "(", ")", "{", "if", "c", ".", "UserAgent", "==", "\"", "\"", "{", "c", ".", "UserAgent", "=", "DefaultUserAgent", "\n", "}", "\n", "if", "c", ".", "Retries", "==", "0", "{", "c", ".", "Retries", "=", "DefaultRetries", "\n", "}", "\n", "if", "c", ".", "ConnectTimeout", "==", "0", "{", "c", ".", "ConnectTimeout", "=", "10", "*", "time", ".", "Second", "\n", "}", "\n", "if", "c", ".", "Timeout", "==", "0", "{", "c", ".", "Timeout", "=", "60", "*", "time", ".", "Second", "\n", "}", "\n", "if", "c", ".", "Transport", "==", "nil", "{", "t", ":=", "&", "http", ".", "Transport", "{", "//\t\tTLSClientConfig: &tls.Config{RootCAs: pool},", "//\t\tDisableCompression: true,", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "// Half of linux's default open files limit (1024).", "MaxIdleConnsPerHost", ":", "512", ",", "}", "\n", "SetExpectContinueTimeout", "(", "t", ",", "5", "*", "time", ".", "Second", ")", "\n", "c", ".", "Transport", "=", "t", "\n", "}", "\n", "if", "c", ".", "client", "==", "nil", "{", "c", ".", "client", "=", "&", "http", ".", "Client", "{", "//\t\tCheckRedirect: redirectPolicyFunc,", "Transport", ":", "c", ".", "Transport", ",", "}", "\n", "}", "\n", "}" ]
// Set defaults for any unset values // // Call with authLock held
[ "Set", "defaults", "for", "any", "unset", "values", "Call", "with", "authLock", "held" ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/swift.go#L424-L454
6,199
ncw/swift
swift.go
Authenticate
func (c *Connection) Authenticate() (err error) { c.authLock.Lock() defer c.authLock.Unlock() return c.authenticate() }
go
func (c *Connection) Authenticate() (err error) { c.authLock.Lock() defer c.authLock.Unlock() return c.authenticate() }
[ "func", "(", "c", "*", "Connection", ")", "Authenticate", "(", ")", "(", "err", "error", ")", "{", "c", ".", "authLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "authLock", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "authenticate", "(", ")", "\n", "}" ]
// Authenticate connects to the Swift server. // // If you don't call it before calling one of the connection methods // then it will be called for you on the first access.
[ "Authenticate", "connects", "to", "the", "Swift", "server", ".", "If", "you", "don", "t", "call", "it", "before", "calling", "one", "of", "the", "connection", "methods", "then", "it", "will", "be", "called", "for", "you", "on", "the", "first", "access", "." ]
753d2090bb62619675997bd87a8e3af423a00f2d
https://github.com/ncw/swift/blob/753d2090bb62619675997bd87a8e3af423a00f2d/swift.go#L460-L464