id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
10,100
aerospike/aerospike-client-go
internal/atomic/int.go
CompareAndSet
func (ai *AtomicInt) CompareAndSet(expect int, update int) bool { res := atomic.CompareAndSwapInt64(&ai.val, int64(expect), int64(update)) return res }
go
func (ai *AtomicInt) CompareAndSet(expect int, update int) bool { res := atomic.CompareAndSwapInt64(&ai.val, int64(expect), int64(update)) return res }
[ "func", "(", "ai", "*", "AtomicInt", ")", "CompareAndSet", "(", "expect", "int", ",", "update", "int", ")", "bool", "{", "res", ":=", "atomic", ".", "CompareAndSwapInt64", "(", "&", "ai", ".", "val", ",", "int64", "(", "expect", ")", ",", "int64", "(...
// CompareAndSet atomically sets the value to the given updated value if the current value == expected value. // Returns true if the expectation was met
[ "CompareAndSet", "atomically", "sets", "the", "value", "to", "the", "given", "updated", "value", "if", "the", "current", "value", "==", "expected", "value", ".", "Returns", "true", "if", "the", "expectation", "was", "met" ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L40-L43
10,101
aerospike/aerospike-client-go
internal/atomic/int.go
DecrementAndGet
func (ai *AtomicInt) DecrementAndGet() int { res := int(atomic.AddInt64(&ai.val, -1)) return res }
go
func (ai *AtomicInt) DecrementAndGet() int { res := int(atomic.AddInt64(&ai.val, -1)) return res }
[ "func", "(", "ai", "*", "AtomicInt", ")", "DecrementAndGet", "(", ")", "int", "{", "res", ":=", "int", "(", "atomic", ".", "AddInt64", "(", "&", "ai", ".", "val", ",", "-", "1", ")", ")", "\n", "return", "res", "\n", "}" ]
// DecrementAndGet atomically decrements current value by one and returns the result.
[ "DecrementAndGet", "atomically", "decrements", "current", "value", "by", "one", "and", "returns", "the", "result", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L46-L49
10,102
aerospike/aerospike-client-go
internal/atomic/int.go
Get
func (ai *AtomicInt) Get() int { res := int(atomic.LoadInt64(&ai.val)) return res }
go
func (ai *AtomicInt) Get() int { res := int(atomic.LoadInt64(&ai.val)) return res }
[ "func", "(", "ai", "*", "AtomicInt", ")", "Get", "(", ")", "int", "{", "res", ":=", "int", "(", "atomic", ".", "LoadInt64", "(", "&", "ai", ".", "val", ")", ")", "\n", "return", "res", "\n", "}" ]
// Get atomically retrieves the current value.
[ "Get", "atomically", "retrieves", "the", "current", "value", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L52-L55
10,103
aerospike/aerospike-client-go
internal/atomic/int.go
GetAndAdd
func (ai *AtomicInt) GetAndAdd(delta int) int { newVal := atomic.AddInt64(&ai.val, int64(delta)) res := int(newVal - int64(delta)) return res }
go
func (ai *AtomicInt) GetAndAdd(delta int) int { newVal := atomic.AddInt64(&ai.val, int64(delta)) res := int(newVal - int64(delta)) return res }
[ "func", "(", "ai", "*", "AtomicInt", ")", "GetAndAdd", "(", "delta", "int", ")", "int", "{", "newVal", ":=", "atomic", ".", "AddInt64", "(", "&", "ai", ".", "val", ",", "int64", "(", "delta", ")", ")", "\n", "res", ":=", "int", "(", "newVal", "-"...
// GetAndAdd atomically adds the given delta to the current value and returns the result.
[ "GetAndAdd", "atomically", "adds", "the", "given", "delta", "to", "the", "current", "value", "and", "returns", "the", "result", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L58-L62
10,104
aerospike/aerospike-client-go
internal/atomic/int.go
GetAndDecrement
func (ai *AtomicInt) GetAndDecrement() int { newVal := atomic.AddInt64(&ai.val, -1) res := int(newVal + 1) return res }
go
func (ai *AtomicInt) GetAndDecrement() int { newVal := atomic.AddInt64(&ai.val, -1) res := int(newVal + 1) return res }
[ "func", "(", "ai", "*", "AtomicInt", ")", "GetAndDecrement", "(", ")", "int", "{", "newVal", ":=", "atomic", ".", "AddInt64", "(", "&", "ai", ".", "val", ",", "-", "1", ")", "\n", "res", ":=", "int", "(", "newVal", "+", "1", ")", "\n", "return", ...
// GetAndDecrement atomically decrements the current value by one and returns the result.
[ "GetAndDecrement", "atomically", "decrements", "the", "current", "value", "by", "one", "and", "returns", "the", "result", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L65-L69
10,105
aerospike/aerospike-client-go
internal/atomic/int.go
GetAndSet
func (ai *AtomicInt) GetAndSet(newValue int) int { res := int(atomic.SwapInt64(&ai.val, int64(newValue))) return res }
go
func (ai *AtomicInt) GetAndSet(newValue int) int { res := int(atomic.SwapInt64(&ai.val, int64(newValue))) return res }
[ "func", "(", "ai", "*", "AtomicInt", ")", "GetAndSet", "(", "newValue", "int", ")", "int", "{", "res", ":=", "int", "(", "atomic", ".", "SwapInt64", "(", "&", "ai", ".", "val", ",", "int64", "(", "newValue", ")", ")", ")", "\n", "return", "res", ...
// GetAndSet atomically sets current value to the given value and returns the old value.
[ "GetAndSet", "atomically", "sets", "current", "value", "to", "the", "given", "value", "and", "returns", "the", "old", "value", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L79-L82
10,106
aerospike/aerospike-client-go
internal/atomic/int.go
IncrementAndGet
func (ai *AtomicInt) IncrementAndGet() int { res := int(atomic.AddInt64(&ai.val, 1)) return res }
go
func (ai *AtomicInt) IncrementAndGet() int { res := int(atomic.AddInt64(&ai.val, 1)) return res }
[ "func", "(", "ai", "*", "AtomicInt", ")", "IncrementAndGet", "(", ")", "int", "{", "res", ":=", "int", "(", "atomic", ".", "AddInt64", "(", "&", "ai", ".", "val", ",", "1", ")", ")", "\n", "return", "res", "\n", "}" ]
// IncrementAndGet atomically increments current value by one and returns the result.
[ "IncrementAndGet", "atomically", "increments", "current", "value", "by", "one", "and", "returns", "the", "result", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L85-L88
10,107
aerospike/aerospike-client-go
internal/atomic/int.go
Set
func (ai *AtomicInt) Set(newValue int) { atomic.StoreInt64(&ai.val, int64(newValue)) }
go
func (ai *AtomicInt) Set(newValue int) { atomic.StoreInt64(&ai.val, int64(newValue)) }
[ "func", "(", "ai", "*", "AtomicInt", ")", "Set", "(", "newValue", "int", ")", "{", "atomic", ".", "StoreInt64", "(", "&", "ai", ".", "val", ",", "int64", "(", "newValue", ")", ")", "\n", "}" ]
// Set atomically sets current value to the given value.
[ "Set", "atomically", "sets", "current", "value", "to", "the", "given", "value", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/internal/atomic/int.go#L91-L93
10,108
aerospike/aerospike-client-go
filter.go
NewEqualFilter
func NewEqualFilter(binName string, value interface{}) *Filter { val := NewValue(value) return newFilter(binName, ICT_DEFAULT, val.GetType(), val, val) }
go
func NewEqualFilter(binName string, value interface{}) *Filter { val := NewValue(value) return newFilter(binName, ICT_DEFAULT, val.GetType(), val, val) }
[ "func", "NewEqualFilter", "(", "binName", "string", ",", "value", "interface", "{", "}", ")", "*", "Filter", "{", "val", ":=", "NewValue", "(", "value", ")", "\n", "return", "newFilter", "(", "binName", ",", "ICT_DEFAULT", ",", "val", ".", "GetType", "("...
// NewEqualFilter creates a new equality filter instance for query.
[ "NewEqualFilter", "creates", "a", "new", "equality", "filter", "instance", "for", "query", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L33-L36
10,109
aerospike/aerospike-client-go
filter.go
NewRangeFilter
func NewRangeFilter(binName string, begin int64, end int64) *Filter { vBegin, vEnd := NewValue(begin), NewValue(end) return newFilter(binName, ICT_DEFAULT, vBegin.GetType(), vBegin, vEnd) }
go
func NewRangeFilter(binName string, begin int64, end int64) *Filter { vBegin, vEnd := NewValue(begin), NewValue(end) return newFilter(binName, ICT_DEFAULT, vBegin.GetType(), vBegin, vEnd) }
[ "func", "NewRangeFilter", "(", "binName", "string", ",", "begin", "int64", ",", "end", "int64", ")", "*", "Filter", "{", "vBegin", ",", "vEnd", ":=", "NewValue", "(", "begin", ")", ",", "NewValue", "(", "end", ")", "\n", "return", "newFilter", "(", "bi...
// NewRangeFilter creates a range filter for query. // Range arguments must be int64 values. // String ranges are not supported.
[ "NewRangeFilter", "creates", "a", "range", "filter", "for", "query", ".", "Range", "arguments", "must", "be", "int64", "values", ".", "String", "ranges", "are", "not", "supported", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L41-L44
10,110
aerospike/aerospike-client-go
filter.go
NewContainsFilter
func NewContainsFilter(binName string, indexCollectionType IndexCollectionType, value interface{}) *Filter { v := NewValue(value) return newFilter(binName, indexCollectionType, v.GetType(), v, v) }
go
func NewContainsFilter(binName string, indexCollectionType IndexCollectionType, value interface{}) *Filter { v := NewValue(value) return newFilter(binName, indexCollectionType, v.GetType(), v, v) }
[ "func", "NewContainsFilter", "(", "binName", "string", ",", "indexCollectionType", "IndexCollectionType", ",", "value", "interface", "{", "}", ")", "*", "Filter", "{", "v", ":=", "NewValue", "(", "value", ")", "\n", "return", "newFilter", "(", "binName", ",", ...
// NewContainsFilter creates a contains filter for query on collection index.
[ "NewContainsFilter", "creates", "a", "contains", "filter", "for", "query", "on", "collection", "index", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L47-L50
10,111
aerospike/aerospike-client-go
filter.go
NewContainsRangeFilter
func NewContainsRangeFilter(binName string, indexCollectionType IndexCollectionType, begin, end int64) *Filter { vBegin, vEnd := NewValue(begin), NewValue(end) return newFilter(binName, indexCollectionType, vBegin.GetType(), vBegin, vEnd) }
go
func NewContainsRangeFilter(binName string, indexCollectionType IndexCollectionType, begin, end int64) *Filter { vBegin, vEnd := NewValue(begin), NewValue(end) return newFilter(binName, indexCollectionType, vBegin.GetType(), vBegin, vEnd) }
[ "func", "NewContainsRangeFilter", "(", "binName", "string", ",", "indexCollectionType", "IndexCollectionType", ",", "begin", ",", "end", "int64", ")", "*", "Filter", "{", "vBegin", ",", "vEnd", ":=", "NewValue", "(", "begin", ")", ",", "NewValue", "(", "end", ...
// NewContainsRangeFilter creates a contains filter for query on ranges of data in a collection index.
[ "NewContainsRangeFilter", "creates", "a", "contains", "filter", "for", "query", "on", "ranges", "of", "data", "in", "a", "collection", "index", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L53-L56
10,112
aerospike/aerospike-client-go
filter.go
NewGeoWithinRegionFilter
func NewGeoWithinRegionFilter(binName, region string) *Filter { v := NewStringValue(region) return newFilter(binName, ICT_DEFAULT, ParticleType.GEOJSON, v, v) }
go
func NewGeoWithinRegionFilter(binName, region string) *Filter { v := NewStringValue(region) return newFilter(binName, ICT_DEFAULT, ParticleType.GEOJSON, v, v) }
[ "func", "NewGeoWithinRegionFilter", "(", "binName", ",", "region", "string", ")", "*", "Filter", "{", "v", ":=", "NewStringValue", "(", "region", ")", "\n", "return", "newFilter", "(", "binName", ",", "ICT_DEFAULT", ",", "ParticleType", ".", "GEOJSON", ",", ...
// NewGeoWithinRegionFilter creates a geospatial "within region" filter for query. // Argument must be a valid GeoJSON region.
[ "NewGeoWithinRegionFilter", "creates", "a", "geospatial", "within", "region", "filter", "for", "query", ".", "Argument", "must", "be", "a", "valid", "GeoJSON", "region", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L60-L63
10,113
aerospike/aerospike-client-go
filter.go
NewGeoWithinRegionForCollectionFilter
func NewGeoWithinRegionForCollectionFilter(binName string, collectionType IndexCollectionType, region string) *Filter { v := NewStringValue(region) return newFilter(binName, collectionType, ParticleType.GEOJSON, v, v) }
go
func NewGeoWithinRegionForCollectionFilter(binName string, collectionType IndexCollectionType, region string) *Filter { v := NewStringValue(region) return newFilter(binName, collectionType, ParticleType.GEOJSON, v, v) }
[ "func", "NewGeoWithinRegionForCollectionFilter", "(", "binName", "string", ",", "collectionType", "IndexCollectionType", ",", "region", "string", ")", "*", "Filter", "{", "v", ":=", "NewStringValue", "(", "region", ")", "\n", "return", "newFilter", "(", "binName", ...
// NewGeoWithinRegionForCollectionFilter creates a geospatial "within region" filter for query on collection index. // Argument must be a valid GeoJSON region.
[ "NewGeoWithinRegionForCollectionFilter", "creates", "a", "geospatial", "within", "region", "filter", "for", "query", "on", "collection", "index", ".", "Argument", "must", "be", "a", "valid", "GeoJSON", "region", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L67-L70
10,114
aerospike/aerospike-client-go
filter.go
NewGeoRegionsContainingPointFilter
func NewGeoRegionsContainingPointFilter(binName, point string) *Filter { v := NewStringValue(point) return newFilter(binName, ICT_DEFAULT, ParticleType.GEOJSON, v, v) }
go
func NewGeoRegionsContainingPointFilter(binName, point string) *Filter { v := NewStringValue(point) return newFilter(binName, ICT_DEFAULT, ParticleType.GEOJSON, v, v) }
[ "func", "NewGeoRegionsContainingPointFilter", "(", "binName", ",", "point", "string", ")", "*", "Filter", "{", "v", ":=", "NewStringValue", "(", "point", ")", "\n", "return", "newFilter", "(", "binName", ",", "ICT_DEFAULT", ",", "ParticleType", ".", "GEOJSON", ...
// NewGeoRegionsContainingPointFilter creates a geospatial "containing point" filter for query. // Argument must be a valid GeoJSON point.
[ "NewGeoRegionsContainingPointFilter", "creates", "a", "geospatial", "containing", "point", "filter", "for", "query", ".", "Argument", "must", "be", "a", "valid", "GeoJSON", "point", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L74-L77
10,115
aerospike/aerospike-client-go
filter.go
NewGeoRegionsContainingPointForCollectionFilter
func NewGeoRegionsContainingPointForCollectionFilter(binName string, collectionType IndexCollectionType, point string) *Filter { v := NewStringValue(point) return newFilter(binName, collectionType, ParticleType.GEOJSON, v, v) }
go
func NewGeoRegionsContainingPointForCollectionFilter(binName string, collectionType IndexCollectionType, point string) *Filter { v := NewStringValue(point) return newFilter(binName, collectionType, ParticleType.GEOJSON, v, v) }
[ "func", "NewGeoRegionsContainingPointForCollectionFilter", "(", "binName", "string", ",", "collectionType", "IndexCollectionType", ",", "point", "string", ")", "*", "Filter", "{", "v", ":=", "NewStringValue", "(", "point", ")", "\n", "return", "newFilter", "(", "bin...
// NewGeoRegionsContainingPointForCollectionFilter creates a geospatial "containing point" filter for query on collection index. // Argument must be a valid GeoJSON point.
[ "NewGeoRegionsContainingPointForCollectionFilter", "creates", "a", "geospatial", "containing", "point", "filter", "for", "query", "on", "collection", "index", ".", "Argument", "must", "be", "a", "valid", "GeoJSON", "point", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L81-L84
10,116
aerospike/aerospike-client-go
filter.go
newFilter
func newFilter(name string, indexCollectionType IndexCollectionType, valueParticleType int, begin Value, end Value) *Filter { return &Filter{ name: name, idxType: indexCollectionType, valueParticleType: valueParticleType, begin: begin, end: end, } }
go
func newFilter(name string, indexCollectionType IndexCollectionType, valueParticleType int, begin Value, end Value) *Filter { return &Filter{ name: name, idxType: indexCollectionType, valueParticleType: valueParticleType, begin: begin, end: end, } }
[ "func", "newFilter", "(", "name", "string", ",", "indexCollectionType", "IndexCollectionType", ",", "valueParticleType", "int", ",", "begin", "Value", ",", "end", "Value", ")", "*", "Filter", "{", "return", "&", "Filter", "{", "name", ":", "name", ",", "idxT...
// Create a filter for query. // Range arguments must be longs or integers which can be cast to longs. // String ranges are not supported.
[ "Create", "a", "filter", "for", "query", ".", "Range", "arguments", "must", "be", "longs", "or", "integers", "which", "can", "be", "cast", "to", "longs", ".", "String", "ranges", "are", "not", "supported", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/filter.go#L103-L111
10,117
aerospike/aerospike-client-go
batch_command_get.go
parseKey
func (cmd *batchCommandGet) parseKey(fieldCount int) error { // var digest [20]byte // var namespace, setName string // var userKey Value var err error for i := 0; i < fieldCount; i++ { if err = cmd.readBytes(4); err != nil { return err } fieldlen := int(Buffer.BytesToUint32(cmd.dataBuffer, 0)) if err = cmd.readBytes(fieldlen); err != nil { return err } fieldtype := FieldType(cmd.dataBuffer[0]) size := fieldlen - 1 switch fieldtype { case DIGEST_RIPE: copy(cmd.key.digest[:], cmd.dataBuffer[1:size+1]) case NAMESPACE: cmd.key.namespace = string(cmd.dataBuffer[1 : size+1]) case TABLE: cmd.key.setName = string(cmd.dataBuffer[1 : size+1]) case KEY: if cmd.key.userKey, err = bytesToKeyValue(int(cmd.dataBuffer[1]), cmd.dataBuffer, 2, size-1); err != nil { return err } } } return nil }
go
func (cmd *batchCommandGet) parseKey(fieldCount int) error { // var digest [20]byte // var namespace, setName string // var userKey Value var err error for i := 0; i < fieldCount; i++ { if err = cmd.readBytes(4); err != nil { return err } fieldlen := int(Buffer.BytesToUint32(cmd.dataBuffer, 0)) if err = cmd.readBytes(fieldlen); err != nil { return err } fieldtype := FieldType(cmd.dataBuffer[0]) size := fieldlen - 1 switch fieldtype { case DIGEST_RIPE: copy(cmd.key.digest[:], cmd.dataBuffer[1:size+1]) case NAMESPACE: cmd.key.namespace = string(cmd.dataBuffer[1 : size+1]) case TABLE: cmd.key.setName = string(cmd.dataBuffer[1 : size+1]) case KEY: if cmd.key.userKey, err = bytesToKeyValue(int(cmd.dataBuffer[1]), cmd.dataBuffer, 2, size-1); err != nil { return err } } } return nil }
[ "func", "(", "cmd", "*", "batchCommandGet", ")", "parseKey", "(", "fieldCount", "int", ")", "error", "{", "// var digest [20]byte", "// var namespace, setName string", "// var userKey Value", "var", "err", "error", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "...
// On batch operations the key values are not returned from the server // So we reuse the Key on the batch Object
[ "On", "batch", "operations", "the", "key", "values", "are", "not", "returned", "from", "the", "server", "So", "we", "reuse", "the", "Key", "on", "the", "batch", "Object" ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/batch_command_get.go#L102-L136
10,118
aerospike/aerospike-client-go
batch_command_get.go
parseRecord
func (cmd *batchCommandGet) parseRecord(key *Key, opCount int, generation, expiration uint32) (*Record, error) { bins := make(BinMap, opCount) for i := 0; i < opCount; i++ { if err := cmd.readBytes(8); err != nil { return nil, err } opSize := int(Buffer.BytesToUint32(cmd.dataBuffer, 0)) particleType := int(cmd.dataBuffer[5]) nameSize := int(cmd.dataBuffer[7]) if err := cmd.readBytes(nameSize); err != nil { return nil, err } name := string(cmd.dataBuffer[:nameSize]) particleBytesSize := opSize - (4 + nameSize) if err := cmd.readBytes(particleBytesSize); err != nil { return nil, err } value, err := bytesToParticle(particleType, cmd.dataBuffer, 0, particleBytesSize) if err != nil { return nil, err } bins[name] = value } return newRecord(cmd.node, key, bins, generation, expiration), nil }
go
func (cmd *batchCommandGet) parseRecord(key *Key, opCount int, generation, expiration uint32) (*Record, error) { bins := make(BinMap, opCount) for i := 0; i < opCount; i++ { if err := cmd.readBytes(8); err != nil { return nil, err } opSize := int(Buffer.BytesToUint32(cmd.dataBuffer, 0)) particleType := int(cmd.dataBuffer[5]) nameSize := int(cmd.dataBuffer[7]) if err := cmd.readBytes(nameSize); err != nil { return nil, err } name := string(cmd.dataBuffer[:nameSize]) particleBytesSize := opSize - (4 + nameSize) if err := cmd.readBytes(particleBytesSize); err != nil { return nil, err } value, err := bytesToParticle(particleType, cmd.dataBuffer, 0, particleBytesSize) if err != nil { return nil, err } bins[name] = value } return newRecord(cmd.node, key, bins, generation, expiration), nil }
[ "func", "(", "cmd", "*", "batchCommandGet", ")", "parseRecord", "(", "key", "*", "Key", ",", "opCount", "int", ",", "generation", ",", "expiration", "uint32", ")", "(", "*", "Record", ",", "error", ")", "{", "bins", ":=", "make", "(", "BinMap", ",", ...
// Parses the given byte buffer and populate the result object. // Returns the number of bytes that were parsed from the given buffer.
[ "Parses", "the", "given", "byte", "buffer", "and", "populate", "the", "result", "object", ".", "Returns", "the", "number", "of", "bytes", "that", "were", "parsed", "from", "the", "given", "buffer", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/batch_command_get.go#L214-L243
10,119
aerospike/aerospike-client-go
examples/expire.go
expireExample
func expireExample(client *as.Client) { key, _ := as.NewKey(*shared.Namespace, *shared.Set, "expirekey ") bin := as.NewBin("expirebin", "expirevalue") log.Printf("Put: namespace=%s set=%s key=%s bin=%s value=%s expiration=2", key.Namespace(), key.SetName(), key.Value(), bin.Name, bin.Value) // Specify that record expires 2 seconds after it's written. writePolicy := as.NewWritePolicy(0, 2) client.PutBins(writePolicy, key, bin) // Read the record before it expires, showing it is there. log.Printf("Get: namespace=%s set=%s key=%s", key.Namespace(), key.SetName(), key.Value()) record, err := client.Get(shared.Policy, key, bin.Name) shared.PanicOnError(err) if record == nil { log.Fatalf( "Failed to get record: namespace=%s set=%s key=%s", key.Namespace(), key.SetName(), key.Value()) } received := record.Bins[bin.Name] expected := bin.Value.String() if received == expected { log.Printf("Get record successful: namespace=%s set=%s key=%s bin=%s value=%s", key.Namespace(), key.SetName(), key.Value(), bin.Name, received) } else { log.Fatalf("Expire record mismatch: Expected %s. Received %s.", expected, received) } // Read the record after it expires, showing it's gone. log.Printf("Sleeping for 3 seconds ...") time.Sleep(3 * time.Second) record, err = client.Get(shared.Policy, key, bin.Name) shared.PanicOnError(err) if record == nil { log.Printf("Expiry of record successful. Record not found.") } else { log.Fatalf("Found record when it should have expired.") } }
go
func expireExample(client *as.Client) { key, _ := as.NewKey(*shared.Namespace, *shared.Set, "expirekey ") bin := as.NewBin("expirebin", "expirevalue") log.Printf("Put: namespace=%s set=%s key=%s bin=%s value=%s expiration=2", key.Namespace(), key.SetName(), key.Value(), bin.Name, bin.Value) // Specify that record expires 2 seconds after it's written. writePolicy := as.NewWritePolicy(0, 2) client.PutBins(writePolicy, key, bin) // Read the record before it expires, showing it is there. log.Printf("Get: namespace=%s set=%s key=%s", key.Namespace(), key.SetName(), key.Value()) record, err := client.Get(shared.Policy, key, bin.Name) shared.PanicOnError(err) if record == nil { log.Fatalf( "Failed to get record: namespace=%s set=%s key=%s", key.Namespace(), key.SetName(), key.Value()) } received := record.Bins[bin.Name] expected := bin.Value.String() if received == expected { log.Printf("Get record successful: namespace=%s set=%s key=%s bin=%s value=%s", key.Namespace(), key.SetName(), key.Value(), bin.Name, received) } else { log.Fatalf("Expire record mismatch: Expected %s. Received %s.", expected, received) } // Read the record after it expires, showing it's gone. log.Printf("Sleeping for 3 seconds ...") time.Sleep(3 * time.Second) record, err = client.Get(shared.Policy, key, bin.Name) shared.PanicOnError(err) if record == nil { log.Printf("Expiry of record successful. Record not found.") } else { log.Fatalf("Found record when it should have expired.") } }
[ "func", "expireExample", "(", "client", "*", "as", ".", "Client", ")", "{", "key", ",", "_", ":=", "as", ".", "NewKey", "(", "*", "shared", ".", "Namespace", ",", "*", "shared", ".", "Set", ",", "\"", "\"", ")", "\n", "bin", ":=", "as", ".", "N...
/** * Write and twice read an expiration record. */
[ "Write", "and", "twice", "read", "an", "expiration", "record", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/examples/expire.go#L39-L82
10,120
aerospike/aerospike-client-go
task.go
onComplete
func (btsk *baseTask) onComplete(ifc Task) chan error { ch := make(chan error, 1) // goroutine will loop every <interval> until IsDone() returns true or error go func() { // always close the channel on return defer close(ch) var interval = 100 * time.Millisecond for { select { case <-time.After(interval): done, err := ifc.IsDone() // Every 5 failed retries increase the interval if btsk.retries.IncrementAndGet()%5 == 0 { interval *= 2 println(interval) if interval > 5*time.Second { interval = 5 * time.Second } } if err != nil { ae, ok := err.(AerospikeError) if ok && ae.ResultCode() == TIMEOUT { ae.MarkInDoubt() } ch <- ae return } else if done { ch <- nil return } } // select } // for }() return ch }
go
func (btsk *baseTask) onComplete(ifc Task) chan error { ch := make(chan error, 1) // goroutine will loop every <interval> until IsDone() returns true or error go func() { // always close the channel on return defer close(ch) var interval = 100 * time.Millisecond for { select { case <-time.After(interval): done, err := ifc.IsDone() // Every 5 failed retries increase the interval if btsk.retries.IncrementAndGet()%5 == 0 { interval *= 2 println(interval) if interval > 5*time.Second { interval = 5 * time.Second } } if err != nil { ae, ok := err.(AerospikeError) if ok && ae.ResultCode() == TIMEOUT { ae.MarkInDoubt() } ch <- ae return } else if done { ch <- nil return } } // select } // for }() return ch }
[ "func", "(", "btsk", "*", "baseTask", ")", "onComplete", "(", "ifc", "Task", ")", "chan", "error", "{", "ch", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n\n", "// goroutine will loop every <interval> until IsDone() returns true or error", "go", "func", ...
// Wait for asynchronous task to complete using default sleep interval.
[ "Wait", "for", "asynchronous", "task", "to", "complete", "using", "default", "sleep", "interval", "." ]
f257953b1650505cf4c357fcc4f032d160ebb07e
https://github.com/aerospike/aerospike-client-go/blob/f257953b1650505cf4c357fcc4f032d160ebb07e/task.go#L46-L85
10,121
ipfs/go-ds-badger
datastore.go
NewTransaction
func (d *Datastore) NewTransaction(readOnly bool) (ds.Txn, error) { d.closeLk.RLock() defer d.closeLk.RUnlock() if d.closed { return nil, ErrClosed } return &txn{d, d.DB.NewTransaction(!readOnly), false}, nil }
go
func (d *Datastore) NewTransaction(readOnly bool) (ds.Txn, error) { d.closeLk.RLock() defer d.closeLk.RUnlock() if d.closed { return nil, ErrClosed } return &txn{d, d.DB.NewTransaction(!readOnly), false}, nil }
[ "func", "(", "d", "*", "Datastore", ")", "NewTransaction", "(", "readOnly", "bool", ")", "(", "ds", ".", "Txn", ",", "error", ")", "{", "d", ".", "closeLk", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "closeLk", ".", "RUnlock", "(", ")", "\n...
// NewTransaction starts a new transaction. The resulting transaction object // can be mutated without incurring changes to the underlying Datastore until // the transaction is Committed.
[ "NewTransaction", "starts", "a", "new", "transaction", ".", "The", "resulting", "transaction", "object", "can", "be", "mutated", "without", "incurring", "changes", "to", "the", "underlying", "Datastore", "until", "the", "transaction", "is", "Committed", "." ]
7fe0af0808f565d460fa8d3851a5808d77f72628
https://github.com/ipfs/go-ds-badger/blob/7fe0af0808f565d460fa8d3851a5808d77f72628/datastore.go#L103-L111
10,122
ipfs/go-ds-badger
datastore.go
newImplicitTransaction
func (d *Datastore) newImplicitTransaction(readOnly bool) *txn { return &txn{d, d.DB.NewTransaction(!readOnly), true} }
go
func (d *Datastore) newImplicitTransaction(readOnly bool) *txn { return &txn{d, d.DB.NewTransaction(!readOnly), true} }
[ "func", "(", "d", "*", "Datastore", ")", "newImplicitTransaction", "(", "readOnly", "bool", ")", "*", "txn", "{", "return", "&", "txn", "{", "d", ",", "d", ".", "DB", ".", "NewTransaction", "(", "!", "readOnly", ")", ",", "true", "}", "\n", "}" ]
// newImplicitTransaction creates a transaction marked as 'implicit'. // Implicit transactions are created by Datastore methods performing single operations.
[ "newImplicitTransaction", "creates", "a", "transaction", "marked", "as", "implicit", ".", "Implicit", "transactions", "are", "created", "by", "Datastore", "methods", "performing", "single", "operations", "." ]
7fe0af0808f565d460fa8d3851a5808d77f72628
https://github.com/ipfs/go-ds-badger/blob/7fe0af0808f565d460fa8d3851a5808d77f72628/datastore.go#L115-L117
10,123
ipfs/go-ds-badger
datastore.go
DiskUsage
func (d *Datastore) DiskUsage() (uint64, error) { d.closeLk.RLock() defer d.closeLk.RUnlock() if d.closed { return 0, ErrClosed } lsm, vlog := d.DB.Size() return uint64(lsm + vlog), nil }
go
func (d *Datastore) DiskUsage() (uint64, error) { d.closeLk.RLock() defer d.closeLk.RUnlock() if d.closed { return 0, ErrClosed } lsm, vlog := d.DB.Size() return uint64(lsm + vlog), nil }
[ "func", "(", "d", "*", "Datastore", ")", "DiskUsage", "(", ")", "(", "uint64", ",", "error", ")", "{", "d", ".", "closeLk", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "closeLk", ".", "RUnlock", "(", ")", "\n", "if", "d", ".", "closed", "{...
// DiskUsage implements the PersistentDatastore interface. // It returns the sum of lsm and value log files sizes in bytes.
[ "DiskUsage", "implements", "the", "PersistentDatastore", "interface", ".", "It", "returns", "the", "sum", "of", "lsm", "and", "value", "log", "files", "sizes", "in", "bytes", "." ]
7fe0af0808f565d460fa8d3851a5808d77f72628
https://github.com/ipfs/go-ds-badger/blob/7fe0af0808f565d460fa8d3851a5808d77f72628/datastore.go#L250-L258
10,124
ipfs/go-ds-badger
datastore.go
Close
func (t *txn) Close() error { t.ds.closeLk.RLock() defer t.ds.closeLk.RUnlock() if t.ds.closed { return ErrClosed } return t.close() }
go
func (t *txn) Close() error { t.ds.closeLk.RLock() defer t.ds.closeLk.RUnlock() if t.ds.closed { return ErrClosed } return t.close() }
[ "func", "(", "t", "*", "txn", ")", "Close", "(", ")", "error", "{", "t", ".", "ds", ".", "closeLk", ".", "RLock", "(", ")", "\n", "defer", "t", ".", "ds", ".", "closeLk", ".", "RUnlock", "(", ")", "\n", "if", "t", ".", "ds", ".", "closed", ...
// Alias to commit
[ "Alias", "to", "commit" ]
7fe0af0808f565d460fa8d3851a5808d77f72628
https://github.com/ipfs/go-ds-badger/blob/7fe0af0808f565d460fa8d3851a5808d77f72628/datastore.go#L583-L590
10,125
jcuga/golongpoll
priority_queue.go
updatePriority
func (pq *priorityQueue) updatePriority(item *expiringBuffer, priority int64) { item.priority = priority // NOTE: fix is a slightly more efficient version of calling Remove() and // then Push() heap.Fix(pq, item.index) }
go
func (pq *priorityQueue) updatePriority(item *expiringBuffer, priority int64) { item.priority = priority // NOTE: fix is a slightly more efficient version of calling Remove() and // then Push() heap.Fix(pq, item.index) }
[ "func", "(", "pq", "*", "priorityQueue", ")", "updatePriority", "(", "item", "*", "expiringBuffer", ",", "priority", "int64", ")", "{", "item", ".", "priority", "=", "priority", "\n", "// NOTE: fix is a slightly more efficient version of calling Remove() and", "// then ...
// update modifies the priority of an item and updates the heap accordingly
[ "update", "modifies", "the", "priority", "of", "an", "item", "and", "updates", "the", "heap", "accordingly" ]
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/priority_queue.go#L70-L75
10,126
jcuga/golongpoll
priority_queue.go
peakTopPriority
func (pq *priorityQueue) peakTopPriority() (int64, error) { if len(*pq) > 0 { return (*pq)[0].priority, nil } else { return -1, fmt.Errorf("PriorityQueue is empty. No top priority.") } }
go
func (pq *priorityQueue) peakTopPriority() (int64, error) { if len(*pq) > 0 { return (*pq)[0].priority, nil } else { return -1, fmt.Errorf("PriorityQueue is empty. No top priority.") } }
[ "func", "(", "pq", "*", "priorityQueue", ")", "peakTopPriority", "(", ")", "(", "int64", ",", "error", ")", "{", "if", "len", "(", "*", "pq", ")", ">", "0", "{", "return", "(", "*", "pq", ")", "[", "0", "]", ".", "priority", ",", "nil", "\n", ...
// get the priority of the heap's top item.
[ "get", "the", "priority", "of", "the", "heap", "s", "top", "item", "." ]
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/priority_queue.go#L78-L84
10,127
jcuga/golongpoll
examples/advanced/advanced.go
getEventSubscriptionHandler
func getEventSubscriptionHandler(manager *golongpoll.LongpollManager) func(w http.ResponseWriter, r *http.Request) { // Creates closure that captures the LongpollManager // Wraps the manager.SubscriptionHandler with a layer of dummy access control validation return func(w http.ResponseWriter, r *http.Request) { category := r.URL.Query().Get("category") user := r.URL.Query().Get("user") // NOTE: real user authentication should be used in the real world! // Dummy user access control in the event the client is requesting // a user's private activity stream: if category == "larry_actions" && user != "larry" { w.WriteHeader(http.StatusForbidden) w.Write([]byte("You're not Larry.")) return } if category == "moe_actions" && user != "moe" { w.WriteHeader(http.StatusForbidden) w.Write([]byte("You're not Moe.")) return } if category == "curly_actions" && user != "curly" { w.WriteHeader(http.StatusForbidden) w.Write([]byte("You're not Curly.")) return } // Only allow supported subscription categories: if category != "public_actions" && category != "larry_actions" && category != "moe_actions" && category != "curly_actions" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Subscription channel does not exist.")) return } // Client is either requesting the public stream, or a private // stream that they're allowed to see. // Go ahead and let the subscription happen: manager.SubscriptionHandler(w, r) } }
go
func getEventSubscriptionHandler(manager *golongpoll.LongpollManager) func(w http.ResponseWriter, r *http.Request) { // Creates closure that captures the LongpollManager // Wraps the manager.SubscriptionHandler with a layer of dummy access control validation return func(w http.ResponseWriter, r *http.Request) { category := r.URL.Query().Get("category") user := r.URL.Query().Get("user") // NOTE: real user authentication should be used in the real world! // Dummy user access control in the event the client is requesting // a user's private activity stream: if category == "larry_actions" && user != "larry" { w.WriteHeader(http.StatusForbidden) w.Write([]byte("You're not Larry.")) return } if category == "moe_actions" && user != "moe" { w.WriteHeader(http.StatusForbidden) w.Write([]byte("You're not Moe.")) return } if category == "curly_actions" && user != "curly" { w.WriteHeader(http.StatusForbidden) w.Write([]byte("You're not Curly.")) return } // Only allow supported subscription categories: if category != "public_actions" && category != "larry_actions" && category != "moe_actions" && category != "curly_actions" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Subscription channel does not exist.")) return } // Client is either requesting the public stream, or a private // stream that they're allowed to see. // Go ahead and let the subscription happen: manager.SubscriptionHandler(w, r) } }
[ "func", "getEventSubscriptionHandler", "(", "manager", "*", "golongpoll", ".", "LongpollManager", ")", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Creates closure that captures the LongpollManager", "// Wraps t...
// Creates a closure function that is used as an http handler for browsers to // subscribe to events via longpolling. // Notice how we're wrapping LongpollManager.SubscriptionHandler in order to // add our own logic and validation.
[ "Creates", "a", "closure", "function", "that", "is", "used", "as", "an", "http", "handler", "for", "browsers", "to", "subscribe", "to", "events", "via", "longpolling", ".", "Notice", "how", "we", "re", "wrapping", "LongpollManager", ".", "SubscriptionHandler", ...
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/examples/advanced/advanced.go#L121-L160
10,128
jcuga/golongpoll
events.go
QueueEvent
func (eb *eventBuffer) QueueEvent(event *lpEvent) error { if event == nil { return errors.New("event was nil") } // Cull our buffer if we're at max capacity if eb.List.Len() >= eb.MaxBufferSize { oldestEvent := eb.List.Back() if oldestEvent != nil { eb.List.Remove(oldestEvent) } } // Add event to front of our list eb.List.PushFront(event) // Update oldestEventTime with the time of our least recent event (at back) // keeping track of this allows for more efficient event TTL expiration purges if lastElement := eb.List.Back(); lastElement != nil { lastEvent, ok := lastElement.Value.(*lpEvent) if !ok { return fmt.Errorf("Found non-event type in event buffer.") } eb.oldestEventTime = lastEvent.Timestamp } return nil }
go
func (eb *eventBuffer) QueueEvent(event *lpEvent) error { if event == nil { return errors.New("event was nil") } // Cull our buffer if we're at max capacity if eb.List.Len() >= eb.MaxBufferSize { oldestEvent := eb.List.Back() if oldestEvent != nil { eb.List.Remove(oldestEvent) } } // Add event to front of our list eb.List.PushFront(event) // Update oldestEventTime with the time of our least recent event (at back) // keeping track of this allows for more efficient event TTL expiration purges if lastElement := eb.List.Back(); lastElement != nil { lastEvent, ok := lastElement.Value.(*lpEvent) if !ok { return fmt.Errorf("Found non-event type in event buffer.") } eb.oldestEventTime = lastEvent.Timestamp } return nil }
[ "func", "(", "eb", "*", "eventBuffer", ")", "QueueEvent", "(", "event", "*", "lpEvent", ")", "error", "{", "if", "event", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// Cull our buffer if we're at max capacity"...
// QueueEvent adds a new longpoll Event to the front of our buffer and removes // the oldest event from the back of the buffer if we're already at maximum // capacity.
[ "QueueEvent", "adds", "a", "new", "longpoll", "Event", "to", "the", "front", "of", "our", "buffer", "and", "removes", "the", "oldest", "event", "from", "the", "back", "of", "the", "buffer", "if", "we", "re", "already", "at", "maximum", "capacity", "." ]
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/events.go#L51-L74
10,129
jcuga/golongpoll
longpoll.go
getLongPollSubscriptionHandler
func getLongPollSubscriptionHandler(maxTimeoutSeconds int, subscriptionRequests chan clientSubscription, clientTimeouts chan<- clientCategoryPair, loggingEnabled bool) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { timeout, err := strconv.Atoi(r.URL.Query().Get("timeout")) if loggingEnabled { log.Println("Handling HTTP request at ", r.URL) } // We are going to return json no matter what: w.Header().Set("Content-Type", "application/json") // Don't cache response: w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1. w.Header().Set("Pragma", "no-cache") // HTTP 1.0. w.Header().Set("Expires", "0") // Proxies. if err != nil || timeout > maxTimeoutSeconds || timeout < 1 { if loggingEnabled { log.Printf("Error: Invalid timeout param. Must be 1-%d. Got: %q.\n", maxTimeoutSeconds, r.URL.Query().Get("timeout")) } io.WriteString(w, fmt.Sprintf("{\"error\": \"Invalid timeout arg. Must be 1-%d.\"}", maxTimeoutSeconds)) return } category := r.URL.Query().Get("category") if len(category) == 0 || len(category) > 1024 { if loggingEnabled { log.Printf("Error: Invalid subscription category, must be 1-1024 characters long.\n") } io.WriteString(w, "{\"error\": \"Invalid subscription category, must be 1-1024 characters long.\"}") return } // Default to only looking for current events lastEventTime := time.Now() // since_time is string of milliseconds since epoch lastEventTimeParam := r.URL.Query().Get("since_time") if len(lastEventTimeParam) > 0 { // Client is requesting any event from given timestamp // parse time var parseError error lastEventTime, parseError = millisecondStringToTime(lastEventTimeParam) if parseError != nil { if loggingEnabled { log.Printf("Error parsing last_event_time arg. Parm Value: %s, Error: %s.\n", lastEventTimeParam, err) } io.WriteString(w, "{\"error\": \"Invalid last_event_time arg.\"}") return } } subscription, err := newclientSubscription(category, lastEventTime) if err != nil { if loggingEnabled { log.Printf("Error creating new Subscription: %s.\n", err) } io.WriteString(w, "{\"error\": \"Error creating new Subscription.\"}") return } subscriptionRequests <- *subscription // Listens for connection close and un-register subscription in the // event that a client crashes or the connection goes down. We don't // need to wait around to fulfill a subscription if no one is going to // receive it disconnectNotify := w.(http.CloseNotifier).CloseNotify() select { case <-time.After(time.Duration(timeout) * time.Second): // Lets the subscription manager know it can discard this request's // channel. clientTimeouts <- subscription.clientCategoryPair timeout_resp := makeTimeoutResponse(time.Now()) if jsonData, err := json.Marshal(timeout_resp); err == nil { io.WriteString(w, string(jsonData)) } else { io.WriteString(w, "{\"error\": \"json marshaller failed\"}") } case events := <-subscription.Events: // Consume event. Subscription manager will automatically discard // this client's channel upon sending event // NOTE: event is actually []Event if jsonData, err := json.Marshal(eventResponse{&events}); err == nil { io.WriteString(w, string(jsonData)) } else { io.WriteString(w, "{\"error\": \"json marshaller failed\"}") } case <-disconnectNotify: // Client connection closed before any events occurred and before // the timeout was exceeded. Tell manager to forget about this // client. clientTimeouts <- subscription.clientCategoryPair } } }
go
func getLongPollSubscriptionHandler(maxTimeoutSeconds int, subscriptionRequests chan clientSubscription, clientTimeouts chan<- clientCategoryPair, loggingEnabled bool) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { timeout, err := strconv.Atoi(r.URL.Query().Get("timeout")) if loggingEnabled { log.Println("Handling HTTP request at ", r.URL) } // We are going to return json no matter what: w.Header().Set("Content-Type", "application/json") // Don't cache response: w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1. w.Header().Set("Pragma", "no-cache") // HTTP 1.0. w.Header().Set("Expires", "0") // Proxies. if err != nil || timeout > maxTimeoutSeconds || timeout < 1 { if loggingEnabled { log.Printf("Error: Invalid timeout param. Must be 1-%d. Got: %q.\n", maxTimeoutSeconds, r.URL.Query().Get("timeout")) } io.WriteString(w, fmt.Sprintf("{\"error\": \"Invalid timeout arg. Must be 1-%d.\"}", maxTimeoutSeconds)) return } category := r.URL.Query().Get("category") if len(category) == 0 || len(category) > 1024 { if loggingEnabled { log.Printf("Error: Invalid subscription category, must be 1-1024 characters long.\n") } io.WriteString(w, "{\"error\": \"Invalid subscription category, must be 1-1024 characters long.\"}") return } // Default to only looking for current events lastEventTime := time.Now() // since_time is string of milliseconds since epoch lastEventTimeParam := r.URL.Query().Get("since_time") if len(lastEventTimeParam) > 0 { // Client is requesting any event from given timestamp // parse time var parseError error lastEventTime, parseError = millisecondStringToTime(lastEventTimeParam) if parseError != nil { if loggingEnabled { log.Printf("Error parsing last_event_time arg. Parm Value: %s, Error: %s.\n", lastEventTimeParam, err) } io.WriteString(w, "{\"error\": \"Invalid last_event_time arg.\"}") return } } subscription, err := newclientSubscription(category, lastEventTime) if err != nil { if loggingEnabled { log.Printf("Error creating new Subscription: %s.\n", err) } io.WriteString(w, "{\"error\": \"Error creating new Subscription.\"}") return } subscriptionRequests <- *subscription // Listens for connection close and un-register subscription in the // event that a client crashes or the connection goes down. We don't // need to wait around to fulfill a subscription if no one is going to // receive it disconnectNotify := w.(http.CloseNotifier).CloseNotify() select { case <-time.After(time.Duration(timeout) * time.Second): // Lets the subscription manager know it can discard this request's // channel. clientTimeouts <- subscription.clientCategoryPair timeout_resp := makeTimeoutResponse(time.Now()) if jsonData, err := json.Marshal(timeout_resp); err == nil { io.WriteString(w, string(jsonData)) } else { io.WriteString(w, "{\"error\": \"json marshaller failed\"}") } case events := <-subscription.Events: // Consume event. Subscription manager will automatically discard // this client's channel upon sending event // NOTE: event is actually []Event if jsonData, err := json.Marshal(eventResponse{&events}); err == nil { io.WriteString(w, string(jsonData)) } else { io.WriteString(w, "{\"error\": \"json marshaller failed\"}") } case <-disconnectNotify: // Client connection closed before any events occurred and before // the timeout was exceeded. Tell manager to forget about this // client. clientTimeouts <- subscription.clientCategoryPair } } }
[ "func", "getLongPollSubscriptionHandler", "(", "maxTimeoutSeconds", "int", ",", "subscriptionRequests", "chan", "clientSubscription", ",", "clientTimeouts", "chan", "<-", "clientCategoryPair", ",", "loggingEnabled", "bool", ")", "func", "(", "w", "http", ".", "ResponseW...
// get web handler that has closure around sub chanel and clientTimeout channnel
[ "get", "web", "handler", "that", "has", "closure", "around", "sub", "chanel", "and", "clientTimeout", "channnel" ]
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/longpoll.go#L213-L301
10,130
jcuga/golongpoll
longpoll.go
run
func (sm *subscriptionManager) run() error { if sm.LoggingEnabled { log.Println("SubscriptionManager: Starting run.") } for { // NOTE: we check to see if its time to purge old buffers whenever // something happens or a period of inactivity has occurred. // An alternative would be to have another goroutine with a // select case time.After() but then you'd have concurrency issues // with access to the sm.SubEventBuffer and sm.bufferPriorityQueue objs // So instead of introducing mutexes we have this uglier manual time check calls select { case newClient := <-sm.clientSubscriptions: sm.handleNewClient(&newClient) sm.seeIfTimeToPurgeStaleCategories() case disconnected := <-sm.ClientTimeouts: sm.handleClientDisconnect(&disconnected) sm.seeIfTimeToPurgeStaleCategories() case event := <-sm.Events: sm.handleNewEvent(&event) sm.seeIfTimeToPurgeStaleCategories() case <-time.After(time.Duration(5) * time.Second): sm.seeIfTimeToPurgeStaleCategories() case _ = <-sm.Quit: if sm.LoggingEnabled { log.Println("SubscriptionManager: received quit signal, stopping.") } // break out of our infinite loop/select return nil } } }
go
func (sm *subscriptionManager) run() error { if sm.LoggingEnabled { log.Println("SubscriptionManager: Starting run.") } for { // NOTE: we check to see if its time to purge old buffers whenever // something happens or a period of inactivity has occurred. // An alternative would be to have another goroutine with a // select case time.After() but then you'd have concurrency issues // with access to the sm.SubEventBuffer and sm.bufferPriorityQueue objs // So instead of introducing mutexes we have this uglier manual time check calls select { case newClient := <-sm.clientSubscriptions: sm.handleNewClient(&newClient) sm.seeIfTimeToPurgeStaleCategories() case disconnected := <-sm.ClientTimeouts: sm.handleClientDisconnect(&disconnected) sm.seeIfTimeToPurgeStaleCategories() case event := <-sm.Events: sm.handleNewEvent(&event) sm.seeIfTimeToPurgeStaleCategories() case <-time.After(time.Duration(5) * time.Second): sm.seeIfTimeToPurgeStaleCategories() case _ = <-sm.Quit: if sm.LoggingEnabled { log.Println("SubscriptionManager: received quit signal, stopping.") } // break out of our infinite loop/select return nil } } }
[ "func", "(", "sm", "*", "subscriptionManager", ")", "run", "(", ")", "error", "{", "if", "sm", ".", "LoggingEnabled", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "{", "// NOTE: we check to see if its time to purge old buffers when...
// This should be fired off in its own goroutine
[ "This", "should", "be", "fired", "off", "in", "its", "own", "goroutine" ]
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/longpoll.go#L350-L381
10,131
jcuga/golongpoll
go-client/glpclient/client.go
Start
func (c *Client) Start() { u := c.url if c.LoggingEnabled { log.Println("Now observing changes on", u.String()) } atomic.AddUint64(&(c.runID), 1) currentRunID := atomic.LoadUint64(&(c.runID)) go func(runID uint64, u *url.URL) { since := time.Now().Unix() * 1000 for { pr, err := c.fetchEvents(since) if err != nil { if c.LoggingEnabled { log.Println(err) log.Printf("Reattempting to connect to %s in %d seconds", u.String(), c.Reattempt) } time.Sleep(c.Reattempt) continue } // We check that its still the same runID as when this goroutine was started clientRunID := atomic.LoadUint64(&(c.runID)) if clientRunID != runID { if c.LoggingEnabled { log.Printf("Client on URL %s has been stopped, not sending events", u.String()) } return } if len(pr.Events) > 0 { if c.LoggingEnabled { log.Println("Got", len(pr.Events), "event(s) from URL", u.String()) } for _, event := range pr.Events { since = event.Timestamp c.EventsChan <- event } } else { // Only push timestamp forward if its greater than the last we checked if pr.Timestamp > since { since = pr.Timestamp } } } }(currentRunID, u) }
go
func (c *Client) Start() { u := c.url if c.LoggingEnabled { log.Println("Now observing changes on", u.String()) } atomic.AddUint64(&(c.runID), 1) currentRunID := atomic.LoadUint64(&(c.runID)) go func(runID uint64, u *url.URL) { since := time.Now().Unix() * 1000 for { pr, err := c.fetchEvents(since) if err != nil { if c.LoggingEnabled { log.Println(err) log.Printf("Reattempting to connect to %s in %d seconds", u.String(), c.Reattempt) } time.Sleep(c.Reattempt) continue } // We check that its still the same runID as when this goroutine was started clientRunID := atomic.LoadUint64(&(c.runID)) if clientRunID != runID { if c.LoggingEnabled { log.Printf("Client on URL %s has been stopped, not sending events", u.String()) } return } if len(pr.Events) > 0 { if c.LoggingEnabled { log.Println("Got", len(pr.Events), "event(s) from URL", u.String()) } for _, event := range pr.Events { since = event.Timestamp c.EventsChan <- event } } else { // Only push timestamp forward if its greater than the last we checked if pr.Timestamp > since { since = pr.Timestamp } } } }(currentRunID, u) }
[ "func", "(", "c", "*", "Client", ")", "Start", "(", ")", "{", "u", ":=", "c", ".", "url", "\n", "if", "c", ".", "LoggingEnabled", "{", "log", ".", "Println", "(", "\"", "\"", ",", "u", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "atomic"...
// Start the polling of the events on the URL defined in the client // Will send the events in the EventsChan of the client
[ "Start", "the", "polling", "of", "the", "events", "on", "the", "URL", "defined", "in", "the", "client", "Will", "send", "the", "events", "in", "the", "EventsChan", "of", "the", "client" ]
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/go-client/glpclient/client.go#L72-L120
10,132
jcuga/golongpoll
go-client/glpclient/client.go
fetchEvents
func (c Client) fetchEvents(since int64) (PollResponse, error) { u := c.url if c.LoggingEnabled { log.Println("Checking for changes events since", since, "on URL", u.String()) } query := u.Query() query.Set("category", c.category) query.Set("since_time", fmt.Sprintf("%d", since)) query.Set("timeout", fmt.Sprintf("%d", c.Timeout)) u.RawQuery = query.Encode() req, _ := http.NewRequest("GET", u.String(), nil) if c.BasicAuthUsername != "" && c.BasicAuthPassword != "" { req.SetBasicAuth(c.BasicAuthUsername, c.BasicAuthPassword) } resp, err := c.HttpClient.Do(req) if err != nil { msg := fmt.Sprintf("Error while connecting to %s to observe changes. Error was: %s", u, err) return PollResponse{}, errors.New(msg) } if resp.StatusCode != http.StatusOK { msg := fmt.Sprintf("Wrong status code received from longpoll server: %d", resp.StatusCode) return PollResponse{}, errors.New(msg) } decoder := json.NewDecoder(resp.Body) defer resp.Body.Close() var pr PollResponse err = decoder.Decode(&pr) if err != nil { if c.LoggingEnabled { log.Println("Error while decoding poll response: %s", err) } return PollResponse{}, err } return pr, nil }
go
func (c Client) fetchEvents(since int64) (PollResponse, error) { u := c.url if c.LoggingEnabled { log.Println("Checking for changes events since", since, "on URL", u.String()) } query := u.Query() query.Set("category", c.category) query.Set("since_time", fmt.Sprintf("%d", since)) query.Set("timeout", fmt.Sprintf("%d", c.Timeout)) u.RawQuery = query.Encode() req, _ := http.NewRequest("GET", u.String(), nil) if c.BasicAuthUsername != "" && c.BasicAuthPassword != "" { req.SetBasicAuth(c.BasicAuthUsername, c.BasicAuthPassword) } resp, err := c.HttpClient.Do(req) if err != nil { msg := fmt.Sprintf("Error while connecting to %s to observe changes. Error was: %s", u, err) return PollResponse{}, errors.New(msg) } if resp.StatusCode != http.StatusOK { msg := fmt.Sprintf("Wrong status code received from longpoll server: %d", resp.StatusCode) return PollResponse{}, errors.New(msg) } decoder := json.NewDecoder(resp.Body) defer resp.Body.Close() var pr PollResponse err = decoder.Decode(&pr) if err != nil { if c.LoggingEnabled { log.Println("Error while decoding poll response: %s", err) } return PollResponse{}, err } return pr, nil }
[ "func", "(", "c", "Client", ")", "fetchEvents", "(", "since", "int64", ")", "(", "PollResponse", ",", "error", ")", "{", "u", ":=", "c", ".", "url", "\n", "if", "c", ".", "LoggingEnabled", "{", "log", ".", "Println", "(", "\"", "\"", ",", "since", ...
// Call the longpoll server to get the events since a specific timestamp
[ "Call", "the", "longpoll", "server", "to", "get", "the", "events", "since", "a", "specific", "timestamp" ]
939e3befd837556f948f5deff4f387c07cfe9df8
https://github.com/jcuga/golongpoll/blob/939e3befd837556f948f5deff4f387c07cfe9df8/go-client/glpclient/client.go#L128-L169
10,133
sethvargo/go-password
password/generate.go
NewGenerator
func NewGenerator(i *GeneratorInput) (*Generator, error) { if i == nil { i = new(GeneratorInput) } g := &Generator{ lowerLetters: i.LowerLetters, upperLetters: i.UpperLetters, digits: i.Digits, symbols: i.Symbols, } if g.lowerLetters == "" { g.lowerLetters = LowerLetters } if g.upperLetters == "" { g.upperLetters = UpperLetters } if g.digits == "" { g.digits = Digits } if g.symbols == "" { g.symbols = Symbols } return g, nil }
go
func NewGenerator(i *GeneratorInput) (*Generator, error) { if i == nil { i = new(GeneratorInput) } g := &Generator{ lowerLetters: i.LowerLetters, upperLetters: i.UpperLetters, digits: i.Digits, symbols: i.Symbols, } if g.lowerLetters == "" { g.lowerLetters = LowerLetters } if g.upperLetters == "" { g.upperLetters = UpperLetters } if g.digits == "" { g.digits = Digits } if g.symbols == "" { g.symbols = Symbols } return g, nil }
[ "func", "NewGenerator", "(", "i", "*", "GeneratorInput", ")", "(", "*", "Generator", ",", "error", ")", "{", "if", "i", "==", "nil", "{", "i", "=", "new", "(", "GeneratorInput", ")", "\n", "}", "\n\n", "g", ":=", "&", "Generator", "{", "lowerLetters"...
// NewGenerator creates a new Generator from the specified configuration. If no // input is given, all the default values are used. This function is safe for // concurrent use.
[ "NewGenerator", "creates", "a", "new", "Generator", "from", "the", "specified", "configuration", ".", "If", "no", "input", "is", "given", "all", "the", "default", "values", "are", "used", ".", "This", "function", "is", "safe", "for", "concurrent", "use", "."...
68ac5879751a7105834296859f8c1bf70b064675
https://github.com/sethvargo/go-password/blob/68ac5879751a7105834296859f8c1bf70b064675/password/generate.go#L72-L101
10,134
sethvargo/go-password
password/generate.go
Generate
func (g *Generator) Generate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) (string, error) { letters := g.lowerLetters if !noUpper { letters += g.upperLetters } chars := length - numDigits - numSymbols if chars < 0 { return "", ErrExceedsTotalLength } if !allowRepeat && chars > len(letters) { return "", ErrLettersExceedsAvailable } if !allowRepeat && numDigits > len(g.digits) { return "", ErrDigitsExceedsAvailable } if !allowRepeat && numSymbols > len(g.symbols) { return "", ErrSymbolsExceedsAvailable } var result string // Characters for i := 0; i < chars; i++ { ch, err := randomElement(letters) if err != nil { return "", err } if !allowRepeat && strings.Contains(result, ch) { i-- continue } result, err = randomInsert(result, ch) if err != nil { return "", err } } // Digits for i := 0; i < numDigits; i++ { d, err := randomElement(g.digits) if err != nil { return "", err } if !allowRepeat && strings.Contains(result, d) { i-- continue } result, err = randomInsert(result, d) if err != nil { return "", err } } // Symbols for i := 0; i < numSymbols; i++ { sym, err := randomElement(g.symbols) if err != nil { return "", err } if !allowRepeat && strings.Contains(result, sym) { i-- continue } result, err = randomInsert(result, sym) if err != nil { return "", err } } return result, nil }
go
func (g *Generator) Generate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) (string, error) { letters := g.lowerLetters if !noUpper { letters += g.upperLetters } chars := length - numDigits - numSymbols if chars < 0 { return "", ErrExceedsTotalLength } if !allowRepeat && chars > len(letters) { return "", ErrLettersExceedsAvailable } if !allowRepeat && numDigits > len(g.digits) { return "", ErrDigitsExceedsAvailable } if !allowRepeat && numSymbols > len(g.symbols) { return "", ErrSymbolsExceedsAvailable } var result string // Characters for i := 0; i < chars; i++ { ch, err := randomElement(letters) if err != nil { return "", err } if !allowRepeat && strings.Contains(result, ch) { i-- continue } result, err = randomInsert(result, ch) if err != nil { return "", err } } // Digits for i := 0; i < numDigits; i++ { d, err := randomElement(g.digits) if err != nil { return "", err } if !allowRepeat && strings.Contains(result, d) { i-- continue } result, err = randomInsert(result, d) if err != nil { return "", err } } // Symbols for i := 0; i < numSymbols; i++ { sym, err := randomElement(g.symbols) if err != nil { return "", err } if !allowRepeat && strings.Contains(result, sym) { i-- continue } result, err = randomInsert(result, sym) if err != nil { return "", err } } return result, nil }
[ "func", "(", "g", "*", "Generator", ")", "Generate", "(", "length", ",", "numDigits", ",", "numSymbols", "int", ",", "noUpper", ",", "allowRepeat", "bool", ")", "(", "string", ",", "error", ")", "{", "letters", ":=", "g", ".", "lowerLetters", "\n", "if...
// Generate generates a password with the given requirements. length is the // total number of characters in the password. numDigits is the number of digits // to include in the result. numSymbols is the number of symbols to include in // the result. noUpper excludes uppercase letters from the results. allowRepeat // allows characters to repeat. // // The algorithm is fast, but it's not designed to be performant; it favors // entropy over speed. This function is safe for concurrent use.
[ "Generate", "generates", "a", "password", "with", "the", "given", "requirements", ".", "length", "is", "the", "total", "number", "of", "characters", "in", "the", "password", ".", "numDigits", "is", "the", "number", "of", "digits", "to", "include", "in", "the...
68ac5879751a7105834296859f8c1bf70b064675
https://github.com/sethvargo/go-password/blob/68ac5879751a7105834296859f8c1bf70b064675/password/generate.go#L111-L191
10,135
sethvargo/go-password
password/generate.go
MustGenerate
func (g *Generator) MustGenerate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) string { res, err := g.Generate(length, numDigits, numSymbols, noUpper, allowRepeat) if err != nil { panic(err) } return res }
go
func (g *Generator) MustGenerate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) string { res, err := g.Generate(length, numDigits, numSymbols, noUpper, allowRepeat) if err != nil { panic(err) } return res }
[ "func", "(", "g", "*", "Generator", ")", "MustGenerate", "(", "length", ",", "numDigits", ",", "numSymbols", "int", ",", "noUpper", ",", "allowRepeat", "bool", ")", "string", "{", "res", ",", "err", ":=", "g", ".", "Generate", "(", "length", ",", "numD...
// MustGenerate is the same as Generate, but panics on error.
[ "MustGenerate", "is", "the", "same", "as", "Generate", "but", "panics", "on", "error", "." ]
68ac5879751a7105834296859f8c1bf70b064675
https://github.com/sethvargo/go-password/blob/68ac5879751a7105834296859f8c1bf70b064675/password/generate.go#L194-L200
10,136
sethvargo/go-password
password/generate.go
Generate
func Generate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) (string, error) { gen, err := NewGenerator(nil) if err != nil { return "", err } return gen.Generate(length, numDigits, numSymbols, noUpper, allowRepeat) }
go
func Generate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) (string, error) { gen, err := NewGenerator(nil) if err != nil { return "", err } return gen.Generate(length, numDigits, numSymbols, noUpper, allowRepeat) }
[ "func", "Generate", "(", "length", ",", "numDigits", ",", "numSymbols", "int", ",", "noUpper", ",", "allowRepeat", "bool", ")", "(", "string", ",", "error", ")", "{", "gen", ",", "err", ":=", "NewGenerator", "(", "nil", ")", "\n", "if", "err", "!=", ...
// Generate is the package shortcut for Generator.Generate.
[ "Generate", "is", "the", "package", "shortcut", "for", "Generator", ".", "Generate", "." ]
68ac5879751a7105834296859f8c1bf70b064675
https://github.com/sethvargo/go-password/blob/68ac5879751a7105834296859f8c1bf70b064675/password/generate.go#L203-L210
10,137
sethvargo/go-password
password/generate.go
randomInsert
func randomInsert(s, val string) (string, error) { if s == "" { return val, nil } n, err := rand.Int(rand.Reader, big.NewInt(int64(len(s)+1))) if err != nil { return "", err } i := n.Int64() return s[0:i] + val + s[i:len(s)], nil }
go
func randomInsert(s, val string) (string, error) { if s == "" { return val, nil } n, err := rand.Int(rand.Reader, big.NewInt(int64(len(s)+1))) if err != nil { return "", err } i := n.Int64() return s[0:i] + val + s[i:len(s)], nil }
[ "func", "randomInsert", "(", "s", ",", "val", "string", ")", "(", "string", ",", "error", ")", "{", "if", "s", "==", "\"", "\"", "{", "return", "val", ",", "nil", "\n", "}", "\n\n", "n", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", ...
// randomInsert randomly inserts the given value into the given string.
[ "randomInsert", "randomly", "inserts", "the", "given", "value", "into", "the", "given", "string", "." ]
68ac5879751a7105834296859f8c1bf70b064675
https://github.com/sethvargo/go-password/blob/68ac5879751a7105834296859f8c1bf70b064675/password/generate.go#L222-L233
10,138
sethvargo/go-password
password/generate.go
randomElement
func randomElement(s string) (string, error) { n, err := rand.Int(rand.Reader, big.NewInt(int64(len(s)))) if err != nil { return "", err } return string(s[n.Int64()]), nil }
go
func randomElement(s string) (string, error) { n, err := rand.Int(rand.Reader, big.NewInt(int64(len(s)))) if err != nil { return "", err } return string(s[n.Int64()]), nil }
[ "func", "randomElement", "(", "s", "string", ")", "(", "string", ",", "error", ")", "{", "n", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "big", ".", "NewInt", "(", "int64", "(", "len", "(", "s", ")", ")", ")", ")", ...
// randomElement extracts a random element from the given string.
[ "randomElement", "extracts", "a", "random", "element", "from", "the", "given", "string", "." ]
68ac5879751a7105834296859f8c1bf70b064675
https://github.com/sethvargo/go-password/blob/68ac5879751a7105834296859f8c1bf70b064675/password/generate.go#L236-L242
10,139
harlow/kinesis-consumer
examples/consumer/cp-dynamo/main.go
init
func init() { sock, err := net.Listen("tcp", "localhost:8080") if err != nil { log.Printf("net listen error: %v", err) } go func() { fmt.Println("Metrics available at http://localhost:8080/debug/vars") http.Serve(sock, nil) }() }
go
func init() { sock, err := net.Listen("tcp", "localhost:8080") if err != nil { log.Printf("net listen error: %v", err) } go func() { fmt.Println("Metrics available at http://localhost:8080/debug/vars") http.Serve(sock, nil) }() }
[ "func", "init", "(", ")", "{", "sock", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "go", "func"...
// kick off a server for exposing scan metrics
[ "kick", "off", "a", "server", "for", "exposing", "scan", "metrics" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/examples/consumer/cp-dynamo/main.go#L26-L35
10,140
harlow/kinesis-consumer
examples/consumer/cp-dynamo/main.go
ShouldRetry
func (r *MyRetryer) ShouldRetry(err error) bool { if awsErr, ok := err.(awserr.Error); ok { switch awsErr.Code() { case dynamodb.ErrCodeProvisionedThroughputExceededException, dynamodb.ErrCodeLimitExceededException: return true default: return false } } return false }
go
func (r *MyRetryer) ShouldRetry(err error) bool { if awsErr, ok := err.(awserr.Error); ok { switch awsErr.Code() { case dynamodb.ErrCodeProvisionedThroughputExceededException, dynamodb.ErrCodeLimitExceededException: return true default: return false } } return false }
[ "func", "(", "r", "*", "MyRetryer", ")", "ShouldRetry", "(", "err", "error", ")", "bool", "{", "if", "awsErr", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "{", "switch", "awsErr", ".", "Code", "(", ")", "{", "case", ...
// ShouldRetry implements custom logic for when a checkpont should retry
[ "ShouldRetry", "implements", "custom", "logic", "for", "when", "a", "checkpont", "should", "retry" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/examples/consumer/cp-dynamo/main.go#L125-L135
10,141
harlow/kinesis-consumer
broker.go
start
func (b *broker) start(ctx context.Context) { b.findNewShards() ticker := time.NewTicker(30 * time.Second) // Note: while ticker is a rather naive approach to this problem, // it actually simplies a few things. i.e. If we miss a new shard while // AWS is resharding we'll pick it up max 30 seconds later. // It might be worth refactoring this flow to allow the consumer to // to notify the broker when a shard is closed. However, shards don't // necessarily close at the same time, so we could potentially get a // thundering heard of notifications from the consumer. for { select { case <-ctx.Done(): ticker.Stop() return case <-ticker.C: b.findNewShards() } } }
go
func (b *broker) start(ctx context.Context) { b.findNewShards() ticker := time.NewTicker(30 * time.Second) // Note: while ticker is a rather naive approach to this problem, // it actually simplies a few things. i.e. If we miss a new shard while // AWS is resharding we'll pick it up max 30 seconds later. // It might be worth refactoring this flow to allow the consumer to // to notify the broker when a shard is closed. However, shards don't // necessarily close at the same time, so we could potentially get a // thundering heard of notifications from the consumer. for { select { case <-ctx.Done(): ticker.Stop() return case <-ticker.C: b.findNewShards() } } }
[ "func", "(", "b", "*", "broker", ")", "start", "(", "ctx", "context", ".", "Context", ")", "{", "b", ".", "findNewShards", "(", ")", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "30", "*", "time", ".", "Second", ")", "\n\n", "// Note: while t...
// start is a blocking operation which will loop and attempt to find new // shards on a regular cadence.
[ "start", "is", "a", "blocking", "operation", "which", "will", "loop", "and", "attempt", "to", "find", "new", "shards", "on", "a", "regular", "cadence", "." ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/broker.go#L43-L65
10,142
harlow/kinesis-consumer
broker.go
findNewShards
func (b *broker) findNewShards() { b.shardMu.Lock() defer b.shardMu.Unlock() b.logger.Log("[BROKER]", "fetching shards") shards, err := b.listShards() if err != nil { b.logger.Log("[BROKER]", err) return } for _, shard := range shards { if _, ok := b.shards[*shard.ShardId]; ok { continue } b.shards[*shard.ShardId] = shard b.shardc <- shard } }
go
func (b *broker) findNewShards() { b.shardMu.Lock() defer b.shardMu.Unlock() b.logger.Log("[BROKER]", "fetching shards") shards, err := b.listShards() if err != nil { b.logger.Log("[BROKER]", err) return } for _, shard := range shards { if _, ok := b.shards[*shard.ShardId]; ok { continue } b.shards[*shard.ShardId] = shard b.shardc <- shard } }
[ "func", "(", "b", "*", "broker", ")", "findNewShards", "(", ")", "{", "b", ".", "shardMu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "shardMu", ".", "Unlock", "(", ")", "\n\n", "b", ".", "logger", ".", "Log", "(", "\"", "\"", ",", "\"", ...
// findNewShards pulls the list of shards from the Kinesis API // and uses a local cache to determine if we are already processing // a particular shard.
[ "findNewShards", "pulls", "the", "list", "of", "shards", "from", "the", "Kinesis", "API", "and", "uses", "a", "local", "cache", "to", "determine", "if", "we", "are", "already", "processing", "a", "particular", "shard", "." ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/broker.go#L70-L89
10,143
harlow/kinesis-consumer
broker.go
listShards
func (b *broker) listShards() ([]*kinesis.Shard, error) { var ss []*kinesis.Shard var listShardsInput = &kinesis.ListShardsInput{ StreamName: aws.String(b.streamName), } for { resp, err := b.client.ListShards(listShardsInput) if err != nil { return nil, fmt.Errorf("ListShards error: %v", err) } ss = append(ss, resp.Shards...) if resp.NextToken == nil { return ss, nil } listShardsInput = &kinesis.ListShardsInput{ NextToken: resp.NextToken, StreamName: aws.String(b.streamName), } } }
go
func (b *broker) listShards() ([]*kinesis.Shard, error) { var ss []*kinesis.Shard var listShardsInput = &kinesis.ListShardsInput{ StreamName: aws.String(b.streamName), } for { resp, err := b.client.ListShards(listShardsInput) if err != nil { return nil, fmt.Errorf("ListShards error: %v", err) } ss = append(ss, resp.Shards...) if resp.NextToken == nil { return ss, nil } listShardsInput = &kinesis.ListShardsInput{ NextToken: resp.NextToken, StreamName: aws.String(b.streamName), } } }
[ "func", "(", "b", "*", "broker", ")", "listShards", "(", ")", "(", "[", "]", "*", "kinesis", ".", "Shard", ",", "error", ")", "{", "var", "ss", "[", "]", "*", "kinesis", ".", "Shard", "\n", "var", "listShardsInput", "=", "&", "kinesis", ".", "Lis...
// listShards pulls a list of shard IDs from the kinesis api
[ "listShards", "pulls", "a", "list", "of", "shard", "IDs", "from", "the", "kinesis", "api" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/broker.go#L92-L114
10,144
harlow/kinesis-consumer
checkpoint/ddb/ddb.go
WithMaxInterval
func WithMaxInterval(maxInterval time.Duration) Option { return func(c *Checkpoint) { c.maxInterval = maxInterval } }
go
func WithMaxInterval(maxInterval time.Duration) Option { return func(c *Checkpoint) { c.maxInterval = maxInterval } }
[ "func", "WithMaxInterval", "(", "maxInterval", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "c", "*", "Checkpoint", ")", "{", "c", ".", "maxInterval", "=", "maxInterval", "\n", "}", "\n", "}" ]
// WithMaxInterval sets the flush interval
[ "WithMaxInterval", "sets", "the", "flush", "interval" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/ddb/ddb.go#L20-L24
10,145
harlow/kinesis-consumer
checkpoint/ddb/ddb.go
WithDynamoClient
func WithDynamoClient(svc dynamodbiface.DynamoDBAPI) Option { return func(c *Checkpoint) { c.client = svc } }
go
func WithDynamoClient(svc dynamodbiface.DynamoDBAPI) Option { return func(c *Checkpoint) { c.client = svc } }
[ "func", "WithDynamoClient", "(", "svc", "dynamodbiface", ".", "DynamoDBAPI", ")", "Option", "{", "return", "func", "(", "c", "*", "Checkpoint", ")", "{", "c", ".", "client", "=", "svc", "\n", "}", "\n", "}" ]
// WithDynamoClient sets the dynamoDb client
[ "WithDynamoClient", "sets", "the", "dynamoDb", "client" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/ddb/ddb.go#L27-L31
10,146
harlow/kinesis-consumer
checkpoint/ddb/ddb.go
New
func New(appName, tableName string, opts ...Option) (*Checkpoint, error) { client := dynamodb.New(session.New(aws.NewConfig())) ck := &Checkpoint{ tableName: tableName, appName: appName, client: client, maxInterval: time.Duration(1 * time.Minute), done: make(chan struct{}), mu: &sync.Mutex{}, checkpoints: map[key]string{}, retryer: &DefaultRetryer{}, } for _, opt := range opts { opt(ck) } go ck.loop() return ck, nil }
go
func New(appName, tableName string, opts ...Option) (*Checkpoint, error) { client := dynamodb.New(session.New(aws.NewConfig())) ck := &Checkpoint{ tableName: tableName, appName: appName, client: client, maxInterval: time.Duration(1 * time.Minute), done: make(chan struct{}), mu: &sync.Mutex{}, checkpoints: map[key]string{}, retryer: &DefaultRetryer{}, } for _, opt := range opts { opt(ck) } go ck.loop() return ck, nil }
[ "func", "New", "(", "appName", ",", "tableName", "string", ",", "opts", "...", "Option", ")", "(", "*", "Checkpoint", ",", "error", ")", "{", "client", ":=", "dynamodb", ".", "New", "(", "session", ".", "New", "(", "aws", ".", "NewConfig", "(", ")", ...
// New returns a checkpoint that uses DynamoDB for underlying storage
[ "New", "returns", "a", "checkpoint", "that", "uses", "DynamoDB", "for", "underlying", "storage" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/ddb/ddb.go#L41-L62
10,147
harlow/kinesis-consumer
options.go
WithClient
func WithClient(client kinesisiface.KinesisAPI) Option { return func(c *Consumer) { c.client = client } }
go
func WithClient(client kinesisiface.KinesisAPI) Option { return func(c *Consumer) { c.client = client } }
[ "func", "WithClient", "(", "client", "kinesisiface", ".", "KinesisAPI", ")", "Option", "{", "return", "func", "(", "c", "*", "Consumer", ")", "{", "c", ".", "client", "=", "client", "\n", "}", "\n", "}" ]
// WithClient overrides the default client
[ "WithClient", "overrides", "the", "default", "client" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/options.go#L30-L34
10,148
harlow/kinesis-consumer
consumer.go
New
func New(streamName string, opts ...Option) (*Consumer, error) { if streamName == "" { return nil, fmt.Errorf("must provide stream name") } // new consumer with no-op checkpoint, counter, and logger c := &Consumer{ streamName: streamName, initialShardIteratorType: kinesis.ShardIteratorTypeLatest, checkpoint: &noopCheckpoint{}, counter: &noopCounter{}, logger: &noopLogger{ logger: log.New(ioutil.Discard, "", log.LstdFlags), }, } // override defaults for _, opt := range opts { opt(c) } // default client if none provided if c.client == nil { newSession, err := session.NewSession(aws.NewConfig()) if err != nil { return nil, err } c.client = kinesis.New(newSession) } return c, nil }
go
func New(streamName string, opts ...Option) (*Consumer, error) { if streamName == "" { return nil, fmt.Errorf("must provide stream name") } // new consumer with no-op checkpoint, counter, and logger c := &Consumer{ streamName: streamName, initialShardIteratorType: kinesis.ShardIteratorTypeLatest, checkpoint: &noopCheckpoint{}, counter: &noopCounter{}, logger: &noopLogger{ logger: log.New(ioutil.Discard, "", log.LstdFlags), }, } // override defaults for _, opt := range opts { opt(c) } // default client if none provided if c.client == nil { newSession, err := session.NewSession(aws.NewConfig()) if err != nil { return nil, err } c.client = kinesis.New(newSession) } return c, nil }
[ "func", "New", "(", "streamName", "string", ",", "opts", "...", "Option", ")", "(", "*", "Consumer", ",", "error", ")", "{", "if", "streamName", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "...
// New creates a kinesis consumer with default settings. Use Option to override // any of the optional attributes.
[ "New", "creates", "a", "kinesis", "consumer", "with", "default", "settings", ".", "Use", "Option", "to", "override", "any", "of", "the", "optional", "attributes", "." ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/consumer.go#L21-L52
10,149
harlow/kinesis-consumer
consumer.go
Scan
func (c *Consumer) Scan(ctx context.Context, fn ScanFunc) error { var ( errc = make(chan error, 1) shardc = make(chan *kinesis.Shard, 1) broker = newBroker(c.client, c.streamName, shardc, c.logger) ) ctx, cancel := context.WithCancel(ctx) defer cancel() go broker.start(ctx) go func() { <-ctx.Done() close(shardc) }() // process each of the shards for shard := range shardc { go func(shardID string) { if err := c.ScanShard(ctx, shardID, fn); err != nil { select { case errc <- fmt.Errorf("shard %s error: %v", shardID, err): // first error to occur cancel() default: // error has already occured } } }(aws.StringValue(shard.ShardId)) } close(errc) return <-errc }
go
func (c *Consumer) Scan(ctx context.Context, fn ScanFunc) error { var ( errc = make(chan error, 1) shardc = make(chan *kinesis.Shard, 1) broker = newBroker(c.client, c.streamName, shardc, c.logger) ) ctx, cancel := context.WithCancel(ctx) defer cancel() go broker.start(ctx) go func() { <-ctx.Done() close(shardc) }() // process each of the shards for shard := range shardc { go func(shardID string) { if err := c.ScanShard(ctx, shardID, fn); err != nil { select { case errc <- fmt.Errorf("shard %s error: %v", shardID, err): // first error to occur cancel() default: // error has already occured } } }(aws.StringValue(shard.ShardId)) } close(errc) return <-errc }
[ "func", "(", "c", "*", "Consumer", ")", "Scan", "(", "ctx", "context", ".", "Context", ",", "fn", "ScanFunc", ")", "error", "{", "var", "(", "errc", "=", "make", "(", "chan", "error", ",", "1", ")", "\n", "shardc", "=", "make", "(", "chan", "*", ...
// Scan launches a goroutine to process each of the shards in the stream. The ScanFunc // is passed through to each of the goroutines and called with each message pulled from // the stream.
[ "Scan", "launches", "a", "goroutine", "to", "process", "each", "of", "the", "shards", "in", "the", "stream", ".", "The", "ScanFunc", "is", "passed", "through", "to", "each", "of", "the", "goroutines", "and", "called", "with", "each", "message", "pulled", "...
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/consumer.go#L80-L115
10,150
harlow/kinesis-consumer
consumer.go
ScanShard
func (c *Consumer) ScanShard(ctx context.Context, shardID string, fn ScanFunc) error { // get last seq number from checkpoint lastSeqNum, err := c.checkpoint.Get(c.streamName, shardID) if err != nil { return fmt.Errorf("get checkpoint error: %v", err) } // get shard iterator shardIterator, err := c.getShardIterator(c.streamName, shardID, lastSeqNum) if err != nil { return fmt.Errorf("get shard iterator error: %v", err) } c.logger.Log("[START]\t", shardID, lastSeqNum) defer func() { c.logger.Log("[STOP]\t", shardID) }() for { select { case <-ctx.Done(): return nil default: resp, err := c.client.GetRecords(&kinesis.GetRecordsInput{ ShardIterator: shardIterator, }) // attempt to recover from GetRecords error by getting new shard iterator if err != nil { shardIterator, err = c.getShardIterator(c.streamName, shardID, lastSeqNum) if err != nil { return fmt.Errorf("get shard iterator error: %v", err) } continue } // loop over records, call callback func for _, r := range resp.Records { select { case <-ctx.Done(): return nil default: err := fn(r) if err != nil && err != SkipCheckpoint { return err } if err != SkipCheckpoint { if err := c.checkpoint.Set(c.streamName, shardID, *r.SequenceNumber); err != nil { return err } } c.counter.Add("records", 1) lastSeqNum = *r.SequenceNumber } } if isShardClosed(resp.NextShardIterator, shardIterator) { c.logger.Log("[CLOSED]\t", shardID) return nil } shardIterator = resp.NextShardIterator } } }
go
func (c *Consumer) ScanShard(ctx context.Context, shardID string, fn ScanFunc) error { // get last seq number from checkpoint lastSeqNum, err := c.checkpoint.Get(c.streamName, shardID) if err != nil { return fmt.Errorf("get checkpoint error: %v", err) } // get shard iterator shardIterator, err := c.getShardIterator(c.streamName, shardID, lastSeqNum) if err != nil { return fmt.Errorf("get shard iterator error: %v", err) } c.logger.Log("[START]\t", shardID, lastSeqNum) defer func() { c.logger.Log("[STOP]\t", shardID) }() for { select { case <-ctx.Done(): return nil default: resp, err := c.client.GetRecords(&kinesis.GetRecordsInput{ ShardIterator: shardIterator, }) // attempt to recover from GetRecords error by getting new shard iterator if err != nil { shardIterator, err = c.getShardIterator(c.streamName, shardID, lastSeqNum) if err != nil { return fmt.Errorf("get shard iterator error: %v", err) } continue } // loop over records, call callback func for _, r := range resp.Records { select { case <-ctx.Done(): return nil default: err := fn(r) if err != nil && err != SkipCheckpoint { return err } if err != SkipCheckpoint { if err := c.checkpoint.Set(c.streamName, shardID, *r.SequenceNumber); err != nil { return err } } c.counter.Add("records", 1) lastSeqNum = *r.SequenceNumber } } if isShardClosed(resp.NextShardIterator, shardIterator) { c.logger.Log("[CLOSED]\t", shardID) return nil } shardIterator = resp.NextShardIterator } } }
[ "func", "(", "c", "*", "Consumer", ")", "ScanShard", "(", "ctx", "context", ".", "Context", ",", "shardID", "string", ",", "fn", "ScanFunc", ")", "error", "{", "// get last seq number from checkpoint", "lastSeqNum", ",", "err", ":=", "c", ".", "checkpoint", ...
// ScanShard loops over records on a specific shard, calls the callback func // for each record and checkpoints the progress of scan.
[ "ScanShard", "loops", "over", "records", "on", "a", "specific", "shard", "calls", "the", "callback", "func", "for", "each", "record", "and", "checkpoints", "the", "progress", "of", "scan", "." ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/consumer.go#L119-L185
10,151
harlow/kinesis-consumer
checkpoint/redis/redis.go
New
func New(appName string) (*Checkpoint, error) { addr := os.Getenv("REDIS_URL") if addr == "" { addr = localhost } client := redis.NewClient(&redis.Options{Addr: addr}) // verify we can ping server _, err := client.Ping().Result() if err != nil { return nil, err } return &Checkpoint{ appName: appName, client: client, }, nil }
go
func New(appName string) (*Checkpoint, error) { addr := os.Getenv("REDIS_URL") if addr == "" { addr = localhost } client := redis.NewClient(&redis.Options{Addr: addr}) // verify we can ping server _, err := client.Ping().Result() if err != nil { return nil, err } return &Checkpoint{ appName: appName, client: client, }, nil }
[ "func", "New", "(", "appName", "string", ")", "(", "*", "Checkpoint", ",", "error", ")", "{", "addr", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "addr", "==", "\"", "\"", "{", "addr", "=", "localhost", "\n", "}", "\n\n", "client...
// New returns a checkpoint that uses Redis for underlying storage
[ "New", "returns", "a", "checkpoint", "that", "uses", "Redis", "for", "underlying", "storage" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/redis/redis.go#L13-L31
10,152
harlow/kinesis-consumer
checkpoint/redis/redis.go
Get
func (c *Checkpoint) Get(streamName, shardID string) (string, error) { val, _ := c.client.Get(c.key(streamName, shardID)).Result() return val, nil }
go
func (c *Checkpoint) Get(streamName, shardID string) (string, error) { val, _ := c.client.Get(c.key(streamName, shardID)).Result() return val, nil }
[ "func", "(", "c", "*", "Checkpoint", ")", "Get", "(", "streamName", ",", "shardID", "string", ")", "(", "string", ",", "error", ")", "{", "val", ",", "_", ":=", "c", ".", "client", ".", "Get", "(", "c", ".", "key", "(", "streamName", ",", "shardI...
// Get fetches the checkpoint for a particular Shard.
[ "Get", "fetches", "the", "checkpoint", "for", "a", "particular", "Shard", "." ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/redis/redis.go#L40-L43
10,153
harlow/kinesis-consumer
checkpoint/redis/redis.go
key
func (c *Checkpoint) key(streamName, shardID string) string { return fmt.Sprintf("%v:checkpoint:%v:%v", c.appName, streamName, shardID) }
go
func (c *Checkpoint) key(streamName, shardID string) string { return fmt.Sprintf("%v:checkpoint:%v:%v", c.appName, streamName, shardID) }
[ "func", "(", "c", "*", "Checkpoint", ")", "key", "(", "streamName", ",", "shardID", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "appName", ",", "streamName", ",", "shardID", ")", "\n", "}" ]
// key generates a unique Redis key for storage of Checkpoint.
[ "key", "generates", "a", "unique", "Redis", "key", "for", "storage", "of", "Checkpoint", "." ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/redis/redis.go#L59-L61
10,154
harlow/kinesis-consumer
checkpoint/postgres/postgres.go
New
func New(appName, tableName, connectionStr string, opts ...Option) (*Checkpoint, error) { if appName == "" { return nil, errors.New("application name not defined") } if tableName == "" { return nil, errors.New("table name not defined") } conn, err := sql.Open("postgres", connectionStr) if err != nil { return nil, err } ck := &Checkpoint{ conn: conn, appName: appName, tableName: tableName, done: make(chan struct{}), maxInterval: 1 * time.Minute, mu: new(sync.Mutex), checkpoints: map[key]string{}, } for _, opt := range opts { opt(ck) } go ck.loop() return ck, nil }
go
func New(appName, tableName, connectionStr string, opts ...Option) (*Checkpoint, error) { if appName == "" { return nil, errors.New("application name not defined") } if tableName == "" { return nil, errors.New("table name not defined") } conn, err := sql.Open("postgres", connectionStr) if err != nil { return nil, err } ck := &Checkpoint{ conn: conn, appName: appName, tableName: tableName, done: make(chan struct{}), maxInterval: 1 * time.Minute, mu: new(sync.Mutex), checkpoints: map[key]string{}, } for _, opt := range opts { opt(ck) } go ck.loop() return ck, nil }
[ "func", "New", "(", "appName", ",", "tableName", ",", "connectionStr", "string", ",", "opts", "...", "Option", ")", "(", "*", "Checkpoint", ",", "error", ")", "{", "if", "appName", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(...
// New returns a checkpoint that uses PostgresDB for underlying storage // Using connectionStr turn it more flexible to use specific db configs
[ "New", "returns", "a", "checkpoint", "that", "uses", "PostgresDB", "for", "underlying", "storage", "Using", "connectionStr", "turn", "it", "more", "flexible", "to", "use", "specific", "db", "configs" ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/postgres/postgres.go#L41-L73
10,155
harlow/kinesis-consumer
checkpoint/postgres/postgres.go
Shutdown
func (c *Checkpoint) Shutdown() error { defer c.conn.Close() c.done <- struct{}{} return c.save() }
go
func (c *Checkpoint) Shutdown() error { defer c.conn.Close() c.done <- struct{}{} return c.save() }
[ "func", "(", "c", "*", "Checkpoint", ")", "Shutdown", "(", ")", "error", "{", "defer", "c", ".", "conn", ".", "Close", "(", ")", "\n\n", "c", ".", "done", "<-", "struct", "{", "}", "{", "}", "\n\n", "return", "c", ".", "save", "(", ")", "\n", ...
// Shutdown the checkpoint. Save any in-flight data.
[ "Shutdown", "the", "checkpoint", ".", "Save", "any", "in", "-", "flight", "data", "." ]
b48acfa5d47ba3615bfa39bc681deb18cf16cea1
https://github.com/harlow/kinesis-consumer/blob/b48acfa5d47ba3615bfa39bc681deb18cf16cea1/checkpoint/postgres/postgres.go#L121-L127
10,156
fatih/set
set_nots.go
newNonTS
func newNonTS() *SetNonTS { s := &SetNonTS{} s.m = make(map[interface{}]struct{}) // Ensure interface compliance var _ Interface = s return s }
go
func newNonTS() *SetNonTS { s := &SetNonTS{} s.m = make(map[interface{}]struct{}) // Ensure interface compliance var _ Interface = s return s }
[ "func", "newNonTS", "(", ")", "*", "SetNonTS", "{", "s", ":=", "&", "SetNonTS", "{", "}", "\n", "s", ".", "m", "=", "make", "(", "map", "[", "interface", "{", "}", "]", "struct", "{", "}", ")", "\n\n", "// Ensure interface compliance", "var", "_", ...
// NewNonTS creates and initializes a new non-threadsafe Set.
[ "NewNonTS", "creates", "and", "initializes", "a", "new", "non", "-", "threadsafe", "Set", "." ]
2c768e3c5489976167bfc42b5c7c92ca783f4389
https://github.com/fatih/set/blob/2c768e3c5489976167bfc42b5c7c92ca783f4389/set_nots.go#L19-L27
10,157
fatih/set
set_nots.go
IsEqual
func (s *set) IsEqual(t Interface) bool { // Force locking only if given set is threadsafe. if conv, ok := t.(*Set); ok { conv.l.RLock() defer conv.l.RUnlock() } // return false if they are no the same size if sameSize := len(s.m) == t.Size(); !sameSize { return false } equal := true t.Each(func(item interface{}) bool { _, equal = s.m[item] return equal // if false, Each() will end }) return equal }
go
func (s *set) IsEqual(t Interface) bool { // Force locking only if given set is threadsafe. if conv, ok := t.(*Set); ok { conv.l.RLock() defer conv.l.RUnlock() } // return false if they are no the same size if sameSize := len(s.m) == t.Size(); !sameSize { return false } equal := true t.Each(func(item interface{}) bool { _, equal = s.m[item] return equal // if false, Each() will end }) return equal }
[ "func", "(", "s", "*", "set", ")", "IsEqual", "(", "t", "Interface", ")", "bool", "{", "// Force locking only if given set is threadsafe.", "if", "conv", ",", "ok", ":=", "t", ".", "(", "*", "Set", ")", ";", "ok", "{", "conv", ".", "l", ".", "RLock", ...
// IsEqual test whether s and t are the same in size and have the same items.
[ "IsEqual", "test", "whether", "s", "and", "t", "are", "the", "same", "in", "size", "and", "have", "the", "same", "items", "." ]
2c768e3c5489976167bfc42b5c7c92ca783f4389
https://github.com/fatih/set/blob/2c768e3c5489976167bfc42b5c7c92ca783f4389/set_nots.go#L96-L115
10,158
fatih/set
set_nots.go
String
func (s *set) String() string { t := make([]string, 0, len(s.List())) for _, item := range s.List() { t = append(t, fmt.Sprintf("%v", item)) } return fmt.Sprintf("[%s]", strings.Join(t, ", ")) }
go
func (s *set) String() string { t := make([]string, 0, len(s.List())) for _, item := range s.List() { t = append(t, fmt.Sprintf("%v", item)) } return fmt.Sprintf("[%s]", strings.Join(t, ", ")) }
[ "func", "(", "s", "*", "set", ")", "String", "(", ")", "string", "{", "t", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "s", ".", "List", "(", ")", ")", ")", "\n", "for", "_", ",", "item", ":=", "range", "s", ".", "Li...
// String returns a string representation of s
[ "String", "returns", "a", "string", "representation", "of", "s" ]
2c768e3c5489976167bfc42b5c7c92ca783f4389
https://github.com/fatih/set/blob/2c768e3c5489976167bfc42b5c7c92ca783f4389/set_nots.go#L155-L162
10,159
fatih/set
set.go
Intersection
func Intersection(set1, set2 Interface, sets ...Interface) Interface { all := Union(set1, set2, sets...) result := Union(set1, set2, sets...) all.Each(func(item interface{}) bool { if !set1.Has(item) || !set2.Has(item) { result.Remove(item) } for _, set := range sets { if !set.Has(item) { result.Remove(item) } } return true }) return result }
go
func Intersection(set1, set2 Interface, sets ...Interface) Interface { all := Union(set1, set2, sets...) result := Union(set1, set2, sets...) all.Each(func(item interface{}) bool { if !set1.Has(item) || !set2.Has(item) { result.Remove(item) } for _, set := range sets { if !set.Has(item) { result.Remove(item) } } return true }) return result }
[ "func", "Intersection", "(", "set1", ",", "set2", "Interface", ",", "sets", "...", "Interface", ")", "Interface", "{", "all", ":=", "Union", "(", "set1", ",", "set2", ",", "sets", "...", ")", "\n", "result", ":=", "Union", "(", "set1", ",", "set2", "...
// Intersection returns a new set which contains items that only exist in all given sets.
[ "Intersection", "returns", "a", "new", "set", "which", "contains", "items", "that", "only", "exist", "in", "all", "given", "sets", "." ]
2c768e3c5489976167bfc42b5c7c92ca783f4389
https://github.com/fatih/set/blob/2c768e3c5489976167bfc42b5c7c92ca783f4389/set.go#L93-L110
10,160
fatih/set
set.go
SymmetricDifference
func SymmetricDifference(s Interface, t Interface) Interface { u := Difference(s, t) v := Difference(t, s) return Union(u, v) }
go
func SymmetricDifference(s Interface, t Interface) Interface { u := Difference(s, t) v := Difference(t, s) return Union(u, v) }
[ "func", "SymmetricDifference", "(", "s", "Interface", ",", "t", "Interface", ")", "Interface", "{", "u", ":=", "Difference", "(", "s", ",", "t", ")", "\n", "v", ":=", "Difference", "(", "t", ",", "s", ")", "\n", "return", "Union", "(", "u", ",", "v...
// SymmetricDifference returns a new set which s is the difference of items which are in // one of either, but not in both.
[ "SymmetricDifference", "returns", "a", "new", "set", "which", "s", "is", "the", "difference", "of", "items", "which", "are", "in", "one", "of", "either", "but", "not", "in", "both", "." ]
2c768e3c5489976167bfc42b5c7c92ca783f4389
https://github.com/fatih/set/blob/2c768e3c5489976167bfc42b5c7c92ca783f4389/set.go#L114-L118
10,161
fatih/set
set.go
StringSlice
func StringSlice(s Interface) []string { slice := make([]string, 0) for _, item := range s.List() { v, ok := item.(string) if !ok { continue } slice = append(slice, v) } return slice }
go
func StringSlice(s Interface) []string { slice := make([]string, 0) for _, item := range s.List() { v, ok := item.(string) if !ok { continue } slice = append(slice, v) } return slice }
[ "func", "StringSlice", "(", "s", "Interface", ")", "[", "]", "string", "{", "slice", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "for", "_", ",", "item", ":=", "range", "s", ".", "List", "(", ")", "{", "v", ",", "ok", ":=", "i...
// StringSlice is a helper function that returns a slice of strings of s. If // the set contains mixed types of items only items of type string are returned.
[ "StringSlice", "is", "a", "helper", "function", "that", "returns", "a", "slice", "of", "strings", "of", "s", ".", "If", "the", "set", "contains", "mixed", "types", "of", "items", "only", "items", "of", "type", "string", "are", "returned", "." ]
2c768e3c5489976167bfc42b5c7c92ca783f4389
https://github.com/fatih/set/blob/2c768e3c5489976167bfc42b5c7c92ca783f4389/set.go#L122-L133
10,162
fatih/set
set.go
IntSlice
func IntSlice(s Interface) []int { slice := make([]int, 0) for _, item := range s.List() { v, ok := item.(int) if !ok { continue } slice = append(slice, v) } return slice }
go
func IntSlice(s Interface) []int { slice := make([]int, 0) for _, item := range s.List() { v, ok := item.(int) if !ok { continue } slice = append(slice, v) } return slice }
[ "func", "IntSlice", "(", "s", "Interface", ")", "[", "]", "int", "{", "slice", ":=", "make", "(", "[", "]", "int", ",", "0", ")", "\n", "for", "_", ",", "item", ":=", "range", "s", ".", "List", "(", ")", "{", "v", ",", "ok", ":=", "item", "...
// IntSlice is a helper function that returns a slice of ints of s. If // the set contains mixed types of items only items of type int are returned.
[ "IntSlice", "is", "a", "helper", "function", "that", "returns", "a", "slice", "of", "ints", "of", "s", ".", "If", "the", "set", "contains", "mixed", "types", "of", "items", "only", "items", "of", "type", "int", "are", "returned", "." ]
2c768e3c5489976167bfc42b5c7c92ca783f4389
https://github.com/fatih/set/blob/2c768e3c5489976167bfc42b5c7c92ca783f4389/set.go#L137-L148
10,163
zalando/gin-oauth2
zalando/zalando.go
RequestTeamInfo
func RequestTeamInfo(tc *ginoauth2.TokenContainer, uri string) ([]byte, error) { var uv = make(url.Values) uv.Set("member", tc.Scopes["uid"].(string)) info_url := uri + "?" + uv.Encode() client := &http.Client{Transport: &ginoauth2.Transport} req, err := http.NewRequest("GET", info_url, nil) if err != nil { return nil, err } req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tc.Token.AccessToken)) resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) }
go
func RequestTeamInfo(tc *ginoauth2.TokenContainer, uri string) ([]byte, error) { var uv = make(url.Values) uv.Set("member", tc.Scopes["uid"].(string)) info_url := uri + "?" + uv.Encode() client := &http.Client{Transport: &ginoauth2.Transport} req, err := http.NewRequest("GET", info_url, nil) if err != nil { return nil, err } req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tc.Token.AccessToken)) resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) }
[ "func", "RequestTeamInfo", "(", "tc", "*", "ginoauth2", ".", "TokenContainer", ",", "uri", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "uv", "=", "make", "(", "url", ".", "Values", ")", "\n", "uv", ".", "Set", "(", "\"", ...
// RequestTeamInfo is a function that returns team information for a // given token.
[ "RequestTeamInfo", "is", "a", "function", "that", "returns", "team", "information", "for", "a", "given", "token", "." ]
405fac2d081c9faee4b56aabae642685a5335ee7
https://github.com/zalando/gin-oauth2/blob/405fac2d081c9faee4b56aabae642685a5335ee7/zalando/zalando.go#L49-L67
10,164
zalando/gin-oauth2
zalando/zalando.go
GroupCheck
func GroupCheck(at []AccessTuple) func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { ats := at return func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { blob, err := RequestTeamInfo(tc, TeamAPI) if err != nil { glog.Errorf("[Gin-OAuth] failed to get team info, caused by: %s", err) return false } var data []TeamInfo err = json.Unmarshal(blob, &data) if err != nil { glog.Errorf("[Gin-OAuth] JSON.Unmarshal failed, caused by: %s", err) return false } granted := false for _, teamInfo := range data { for idx := range ats { at := ats[idx] if teamInfo.Id == at.Uid { granted = true glog.Infof("[Gin-OAuth] Grant access to %s as team member of \"%s\"\n", tc.Scopes["uid"].(string), teamInfo.Id) } if teamInfo.Type == "official" { ctx.Set("uid", tc.Scopes["uid"].(string)) ctx.Set("team", teamInfo.Id) } } } return granted } }
go
func GroupCheck(at []AccessTuple) func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { ats := at return func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { blob, err := RequestTeamInfo(tc, TeamAPI) if err != nil { glog.Errorf("[Gin-OAuth] failed to get team info, caused by: %s", err) return false } var data []TeamInfo err = json.Unmarshal(blob, &data) if err != nil { glog.Errorf("[Gin-OAuth] JSON.Unmarshal failed, caused by: %s", err) return false } granted := false for _, teamInfo := range data { for idx := range ats { at := ats[idx] if teamInfo.Id == at.Uid { granted = true glog.Infof("[Gin-OAuth] Grant access to %s as team member of \"%s\"\n", tc.Scopes["uid"].(string), teamInfo.Id) } if teamInfo.Type == "official" { ctx.Set("uid", tc.Scopes["uid"].(string)) ctx.Set("team", teamInfo.Id) } } } return granted } }
[ "func", "GroupCheck", "(", "at", "[", "]", "AccessTuple", ")", "func", "(", "tc", "*", "ginoauth2", ".", "TokenContainer", ",", "ctx", "*", "gin", ".", "Context", ")", "bool", "{", "ats", ":=", "at", "\n", "return", "func", "(", "tc", "*", "ginoauth2...
// GroupCheck is an authorization function that checks, if the Token // was issued for an employee of a specified team. The given // TokenContainer must be valid. As side effect it sets "uid" and // "team" in the gin.Context to the "official" team.
[ "GroupCheck", "is", "an", "authorization", "function", "that", "checks", "if", "the", "Token", "was", "issued", "for", "an", "employee", "of", "a", "specified", "team", ".", "The", "given", "TokenContainer", "must", "be", "valid", ".", "As", "side", "effect"...
405fac2d081c9faee4b56aabae642685a5335ee7
https://github.com/zalando/gin-oauth2/blob/405fac2d081c9faee4b56aabae642685a5335ee7/zalando/zalando.go#L73-L103
10,165
zalando/gin-oauth2
zalando/zalando.go
ScopeCheck
func ScopeCheck(name string, scopes ...string) func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { glog.Infof("ScopeCheck %s configured to grant access for scopes: %v", name, scopes) configuredScopes := scopes return func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { scopesFromToken := make([]string, 0) for _, s := range configuredScopes { if cur, ok := tc.Scopes[s]; ok { glog.V(2).Infof("Found configured scope %s", s) scopesFromToken = append(scopesFromToken, s) ctx.Set(s, cur) // set value from token of configured scope to the context, which you can use in your application. } } //Getting the uid for identification of the service calling if cur, ok := tc.Scopes["uid"]; ok { ctx.Set("uid", cur) } return len(scopesFromToken) > 0 } }
go
func ScopeCheck(name string, scopes ...string) func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { glog.Infof("ScopeCheck %s configured to grant access for scopes: %v", name, scopes) configuredScopes := scopes return func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool { scopesFromToken := make([]string, 0) for _, s := range configuredScopes { if cur, ok := tc.Scopes[s]; ok { glog.V(2).Infof("Found configured scope %s", s) scopesFromToken = append(scopesFromToken, s) ctx.Set(s, cur) // set value from token of configured scope to the context, which you can use in your application. } } //Getting the uid for identification of the service calling if cur, ok := tc.Scopes["uid"]; ok { ctx.Set("uid", cur) } return len(scopesFromToken) > 0 } }
[ "func", "ScopeCheck", "(", "name", "string", ",", "scopes", "...", "string", ")", "func", "(", "tc", "*", "ginoauth2", ".", "TokenContainer", ",", "ctx", "*", "gin", ".", "Context", ")", "bool", "{", "glog", ".", "Infof", "(", "\"", "\"", ",", "name"...
// ScopeCheck does an OR check of scopes given from token of the // request to all provided scopes. If one of provided scopes is in the // Scopes of the token it grants access to the resource.
[ "ScopeCheck", "does", "an", "OR", "check", "of", "scopes", "given", "from", "token", "of", "the", "request", "to", "all", "provided", "scopes", ".", "If", "one", "of", "provided", "scopes", "is", "in", "the", "Scopes", "of", "the", "token", "it", "grants...
405fac2d081c9faee4b56aabae642685a5335ee7
https://github.com/zalando/gin-oauth2/blob/405fac2d081c9faee4b56aabae642685a5335ee7/zalando/zalando.go#L128-L146
10,166
zalando/gin-oauth2
ginoauth2.go
Valid
func (t *TokenContainer) Valid() bool { if t.Token == nil { return false } return t.Token.Valid() }
go
func (t *TokenContainer) Valid() bool { if t.Token == nil { return false } return t.Token.Valid() }
[ "func", "(", "t", "*", "TokenContainer", ")", "Valid", "(", ")", "bool", "{", "if", "t", ".", "Token", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "t", ".", "Token", ".", "Valid", "(", ")", "\n", "}" ]
// // TokenContainer // // Validates that the AccessToken within TokenContainer is not expired and not empty.
[ "TokenContainer", "Validates", "that", "the", "AccessToken", "within", "TokenContainer", "is", "not", "expired", "and", "not", "empty", "." ]
405fac2d081c9faee4b56aabae642685a5335ee7
https://github.com/zalando/gin-oauth2/blob/405fac2d081c9faee4b56aabae642685a5335ee7/ginoauth2.go#L209-L214
10,167
zalando/gin-oauth2
google/google.go
Setup
func Setup(redirectURL, credFile string, scopes []string, secret []byte) { store = sessions.NewCookieStore(secret) var c Credentials file, err := ioutil.ReadFile(credFile) if err != nil { glog.Fatalf("[Gin-OAuth] File error: %v\n", err) } json.Unmarshal(file, &c) conf = &oauth2.Config{ ClientID: c.ClientID, ClientSecret: c.ClientSecret, RedirectURL: redirectURL, Scopes: scopes, Endpoint: google.Endpoint, } }
go
func Setup(redirectURL, credFile string, scopes []string, secret []byte) { store = sessions.NewCookieStore(secret) var c Credentials file, err := ioutil.ReadFile(credFile) if err != nil { glog.Fatalf("[Gin-OAuth] File error: %v\n", err) } json.Unmarshal(file, &c) conf = &oauth2.Config{ ClientID: c.ClientID, ClientSecret: c.ClientSecret, RedirectURL: redirectURL, Scopes: scopes, Endpoint: google.Endpoint, } }
[ "func", "Setup", "(", "redirectURL", ",", "credFile", "string", ",", "scopes", "[", "]", "string", ",", "secret", "[", "]", "byte", ")", "{", "store", "=", "sessions", ".", "NewCookieStore", "(", "secret", ")", "\n", "var", "c", "Credentials", "\n", "f...
// Setup the authorization path
[ "Setup", "the", "authorization", "path" ]
405fac2d081c9faee4b56aabae642685a5335ee7
https://github.com/zalando/gin-oauth2/blob/405fac2d081c9faee4b56aabae642685a5335ee7/google/google.go#L54-L70
10,168
blang/vfs
prefixfs/prefixfs.go
Create
func Create(root vfs.Filesystem, prefix string) *FS { return &FS{root, prefix} }
go
func Create(root vfs.Filesystem, prefix string) *FS { return &FS{root, prefix} }
[ "func", "Create", "(", "root", "vfs", ".", "Filesystem", ",", "prefix", "string", ")", "*", "FS", "{", "return", "&", "FS", "{", "root", ",", "prefix", "}", "\n", "}" ]
// Create returns a file system that prefixes all paths and forwards to root.
[ "Create", "returns", "a", "file", "system", "that", "prefixes", "all", "paths", "and", "forwards", "to", "root", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L18-L20
10,169
blang/vfs
prefixfs/prefixfs.go
PrefixPath
func (fs *FS) PrefixPath(path string) string { return fs.Prefix + string(fs.PathSeparator()) + path }
go
func (fs *FS) PrefixPath(path string) string { return fs.Prefix + string(fs.PathSeparator()) + path }
[ "func", "(", "fs", "*", "FS", ")", "PrefixPath", "(", "path", "string", ")", "string", "{", "return", "fs", ".", "Prefix", "+", "string", "(", "fs", ".", "PathSeparator", "(", ")", ")", "+", "path", "\n", "}" ]
// PrefixPath returns path with the prefix prefixed.
[ "PrefixPath", "returns", "path", "with", "the", "prefix", "prefixed", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L23-L25
10,170
blang/vfs
prefixfs/prefixfs.go
OpenFile
func (fs *FS) OpenFile(name string, flag int, perm os.FileMode) (vfs.File, error) { return fs.Filesystem.OpenFile(fs.PrefixPath(name), flag, perm) }
go
func (fs *FS) OpenFile(name string, flag int, perm os.FileMode) (vfs.File, error) { return fs.Filesystem.OpenFile(fs.PrefixPath(name), flag, perm) }
[ "func", "(", "fs", "*", "FS", ")", "OpenFile", "(", "name", "string", ",", "flag", "int", ",", "perm", "os", ".", "FileMode", ")", "(", "vfs", ".", "File", ",", "error", ")", "{", "return", "fs", ".", "Filesystem", ".", "OpenFile", "(", "fs", "."...
// OpenFile implements vfs.Filesystem.
[ "OpenFile", "implements", "vfs", ".", "Filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L31-L33
10,171
blang/vfs
prefixfs/prefixfs.go
Remove
func (fs *FS) Remove(name string) error { return fs.Filesystem.Remove(fs.PrefixPath(name)) }
go
func (fs *FS) Remove(name string) error { return fs.Filesystem.Remove(fs.PrefixPath(name)) }
[ "func", "(", "fs", "*", "FS", ")", "Remove", "(", "name", "string", ")", "error", "{", "return", "fs", ".", "Filesystem", ".", "Remove", "(", "fs", ".", "PrefixPath", "(", "name", ")", ")", "\n", "}" ]
// Remove implements vfs.Filesystem.
[ "Remove", "implements", "vfs", ".", "Filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L36-L38
10,172
blang/vfs
prefixfs/prefixfs.go
Rename
func (fs *FS) Rename(oldpath, newpath string) error { return fs.Filesystem.Rename(fs.PrefixPath(oldpath), fs.PrefixPath(newpath)) }
go
func (fs *FS) Rename(oldpath, newpath string) error { return fs.Filesystem.Rename(fs.PrefixPath(oldpath), fs.PrefixPath(newpath)) }
[ "func", "(", "fs", "*", "FS", ")", "Rename", "(", "oldpath", ",", "newpath", "string", ")", "error", "{", "return", "fs", ".", "Filesystem", ".", "Rename", "(", "fs", ".", "PrefixPath", "(", "oldpath", ")", ",", "fs", ".", "PrefixPath", "(", "newpath...
// Rename implements vfs.Filesystem.
[ "Rename", "implements", "vfs", ".", "Filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L41-L43
10,173
blang/vfs
prefixfs/prefixfs.go
Mkdir
func (fs *FS) Mkdir(name string, perm os.FileMode) error { return fs.Filesystem.Mkdir(fs.PrefixPath(name), perm) }
go
func (fs *FS) Mkdir(name string, perm os.FileMode) error { return fs.Filesystem.Mkdir(fs.PrefixPath(name), perm) }
[ "func", "(", "fs", "*", "FS", ")", "Mkdir", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "error", "{", "return", "fs", ".", "Filesystem", ".", "Mkdir", "(", "fs", ".", "PrefixPath", "(", "name", ")", ",", "perm", ")", "\n", "}"...
// Mkdir implements vfs.Filesystem.
[ "Mkdir", "implements", "vfs", ".", "Filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L46-L48
10,174
blang/vfs
prefixfs/prefixfs.go
Stat
func (fs *FS) Stat(name string) (os.FileInfo, error) { return fs.Filesystem.Stat(fs.PrefixPath(name)) }
go
func (fs *FS) Stat(name string) (os.FileInfo, error) { return fs.Filesystem.Stat(fs.PrefixPath(name)) }
[ "func", "(", "fs", "*", "FS", ")", "Stat", "(", "name", "string", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "return", "fs", ".", "Filesystem", ".", "Stat", "(", "fs", ".", "PrefixPath", "(", "name", ")", ")", "\n", "}" ]
// Stat implements vfs.Filesystem.
[ "Stat", "implements", "vfs", ".", "Filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L51-L53
10,175
blang/vfs
prefixfs/prefixfs.go
ReadDir
func (fs *FS) ReadDir(path string) ([]os.FileInfo, error) { return fs.Filesystem.ReadDir(fs.PrefixPath(path)) }
go
func (fs *FS) ReadDir(path string) ([]os.FileInfo, error) { return fs.Filesystem.ReadDir(fs.PrefixPath(path)) }
[ "func", "(", "fs", "*", "FS", ")", "ReadDir", "(", "path", "string", ")", "(", "[", "]", "os", ".", "FileInfo", ",", "error", ")", "{", "return", "fs", ".", "Filesystem", ".", "ReadDir", "(", "fs", ".", "PrefixPath", "(", "path", ")", ")", "\n", ...
// ReadDir implements vfs.Filesystem.
[ "ReadDir", "implements", "vfs", ".", "Filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/prefixfs/prefixfs.go#L61-L63
10,176
blang/vfs
memfs/memfile.go
NewMemFile
func NewMemFile(name string, rwMutex *sync.RWMutex, buf *[]byte) *MemFile { return &MemFile{ Buffer: NewBuffer(buf), mutex: rwMutex, name: name, } }
go
func NewMemFile(name string, rwMutex *sync.RWMutex, buf *[]byte) *MemFile { return &MemFile{ Buffer: NewBuffer(buf), mutex: rwMutex, name: name, } }
[ "func", "NewMemFile", "(", "name", "string", ",", "rwMutex", "*", "sync", ".", "RWMutex", ",", "buf", "*", "[", "]", "byte", ")", "*", "MemFile", "{", "return", "&", "MemFile", "{", "Buffer", ":", "NewBuffer", "(", "buf", ")", ",", "mutex", ":", "r...
// NewMemFile creates a Buffer which byte slice is safe from concurrent access, // the file itself is not thread-safe. // // This means multiple files can work safely on the same byte slice, // but multiple go routines working on the same file may corrupt the internal pointer structure.
[ "NewMemFile", "creates", "a", "Buffer", "which", "byte", "slice", "is", "safe", "from", "concurrent", "access", "the", "file", "itself", "is", "not", "thread", "-", "safe", ".", "This", "means", "multiple", "files", "can", "work", "safely", "on", "the", "s...
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/memfs/memfile.go#L19-L25
10,177
blang/vfs
memfs/memfile.go
Truncate
func (b MemFile) Truncate(size int64) (err error) { b.mutex.Lock() err = b.Buffer.Truncate(size) b.mutex.Unlock() return }
go
func (b MemFile) Truncate(size int64) (err error) { b.mutex.Lock() err = b.Buffer.Truncate(size) b.mutex.Unlock() return }
[ "func", "(", "b", "MemFile", ")", "Truncate", "(", "size", "int64", ")", "(", "err", "error", ")", "{", "b", ".", "mutex", ".", "Lock", "(", ")", "\n", "err", "=", "b", ".", "Buffer", ".", "Truncate", "(", "size", ")", "\n", "b", ".", "mutex", ...
// Truncate changes the size of the file
[ "Truncate", "changes", "the", "size", "of", "the", "file" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/memfs/memfile.go#L38-L43
10,178
blang/vfs
ioutil.go
ReadFile
func ReadFile(fs Filesystem, filename string) ([]byte, error) { f, err := fs.OpenFile(filename, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() // It's a good but not certain bet that FileInfo will tell us exactly how // much to read, so let's try it but be prepared for the answer to be wrong. var n int64 if fi, err := fs.Stat(filename); err == nil { if size := fi.Size(); size < 1e9 { n = size } } // As initial capacity for readAll, use n + a little extra in case Size is // zero, and to avoid another allocation after Read has filled the buffer. // The readAll call will read into its allocated internal buffer cheaply. If // the size was wrong, we'll either waste some space off the end or // reallocate as needed, but in the overwhelmingly common case we'll get it // just right. return readAll(f, n+bytes.MinRead) }
go
func ReadFile(fs Filesystem, filename string) ([]byte, error) { f, err := fs.OpenFile(filename, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() // It's a good but not certain bet that FileInfo will tell us exactly how // much to read, so let's try it but be prepared for the answer to be wrong. var n int64 if fi, err := fs.Stat(filename); err == nil { if size := fi.Size(); size < 1e9 { n = size } } // As initial capacity for readAll, use n + a little extra in case Size is // zero, and to avoid another allocation after Read has filled the buffer. // The readAll call will read into its allocated internal buffer cheaply. If // the size was wrong, we'll either waste some space off the end or // reallocate as needed, but in the overwhelmingly common case we'll get it // just right. return readAll(f, n+bytes.MinRead) }
[ "func", "ReadFile", "(", "fs", "Filesystem", ",", "filename", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "f", ",", "err", ":=", "fs", ".", "OpenFile", "(", "filename", ",", "os", ".", "O_RDONLY", ",", "0", ")", "\n", "if", "err...
// ReadFile reads the file named by filename and returns the contents. A // successful call returns err == nil, not err == EOF. Because ReadFile reads // the whole file, it does not treat an EOF from Read as an error to be // reported. // // This is a port of the stdlib ioutil.ReadFile function.
[ "ReadFile", "reads", "the", "file", "named", "by", "filename", "and", "returns", "the", "contents", ".", "A", "successful", "call", "returns", "err", "==", "nil", "not", "err", "==", "EOF", ".", "Because", "ReadFile", "reads", "the", "whole", "file", "it",...
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/ioutil.go#L35-L58
10,179
blang/vfs
readonly.go
Mkdir
func (fs RoFS) Mkdir(name string, perm os.FileMode) error { return ErrReadOnly }
go
func (fs RoFS) Mkdir(name string, perm os.FileMode) error { return ErrReadOnly }
[ "func", "(", "fs", "RoFS", ")", "Mkdir", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "error", "{", "return", "ErrReadOnly", "\n", "}" ]
// Mkdir is disabled and returns ErrorReadOnly
[ "Mkdir", "is", "disabled", "and", "returns", "ErrorReadOnly" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/readonly.go#L43-L45
10,180
blang/vfs
memfs/memfs.go
Create
func Create() *MemFS { root := &fileInfo{ name: "/", dir: true, } return &MemFS{ root: root, wd: root, lock: &sync.RWMutex{}, } }
go
func Create() *MemFS { root := &fileInfo{ name: "/", dir: true, } return &MemFS{ root: root, wd: root, lock: &sync.RWMutex{}, } }
[ "func", "Create", "(", ")", "*", "MemFS", "{", "root", ":=", "&", "fileInfo", "{", "name", ":", "\"", "\"", ",", "dir", ":", "true", ",", "}", "\n", "return", "&", "MemFS", "{", "root", ":", "root", ",", "wd", ":", "root", ",", "lock", ":", "...
// Create a new MemFS filesystem which entirely resides in memory
[ "Create", "a", "new", "MemFS", "filesystem", "which", "entirely", "resides", "in", "memory" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/memfs/memfs.go#L35-L45
10,181
blang/vfs
memfs/memfs.go
Mkdir
func (fs *MemFS) Mkdir(name string, perm os.FileMode) error { fs.lock.Lock() defer fs.lock.Unlock() name = filepath.Clean(name) base := filepath.Base(name) parent, fi, err := fs.fileInfo(name) if err != nil { return &os.PathError{"mkdir", name, err} } if fi != nil { return &os.PathError{"mkdir", name, fmt.Errorf("Directory %q already exists", name)} } fi = &fileInfo{ name: base, dir: true, mode: perm, parent: parent, modTime: time.Now(), fs: fs, } parent.childs[base] = fi return nil }
go
func (fs *MemFS) Mkdir(name string, perm os.FileMode) error { fs.lock.Lock() defer fs.lock.Unlock() name = filepath.Clean(name) base := filepath.Base(name) parent, fi, err := fs.fileInfo(name) if err != nil { return &os.PathError{"mkdir", name, err} } if fi != nil { return &os.PathError{"mkdir", name, fmt.Errorf("Directory %q already exists", name)} } fi = &fileInfo{ name: base, dir: true, mode: perm, parent: parent, modTime: time.Now(), fs: fs, } parent.childs[base] = fi return nil }
[ "func", "(", "fs", "*", "MemFS", ")", "Mkdir", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "error", "{", "fs", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "fs", ".", "lock", ".", "Unlock", "(", ")", "\n", "name", "=",...
// Mkdir creates a new directory with given permissions
[ "Mkdir", "creates", "a", "new", "directory", "with", "given", "permissions" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/memfs/memfs.go#L108-L131
10,182
blang/vfs
memfs/memfs.go
Write
func (f *roFile) Write(p []byte) (n int, err error) { return 0, ErrReadOnly }
go
func (f *roFile) Write(p []byte) (n int, err error) { return 0, ErrReadOnly }
[ "func", "(", "f", "*", "roFile", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "0", ",", "ErrReadOnly", "\n", "}" ]
// Write is disabled and returns ErrorReadOnly
[ "Write", "is", "disabled", "and", "returns", "ErrorReadOnly" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/memfs/memfs.go#L287-L289
10,183
blang/vfs
memfs/memfs.go
Read
func (f *woFile) Read(p []byte) (n int, err error) { return 0, ErrWriteOnly }
go
func (f *woFile) Read(p []byte) (n int, err error) { return 0, ErrWriteOnly }
[ "func", "(", "f", "*", "woFile", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "0", ",", "ErrWriteOnly", "\n", "}" ]
// Read is disabled and returns ErrorWroteOnly
[ "Read", "is", "disabled", "and", "returns", "ErrorWroteOnly" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/memfs/memfs.go#L297-L299
10,184
blang/vfs
memfs/buffer.go
makeSlice
func makeSlice(n int) (b []byte, err error) { // If the make fails, give a known error. defer func() { if recover() != nil { b = nil err = ErrTooLarge return } }() b = make([]byte, n) return }
go
func makeSlice(n int) (b []byte, err error) { // If the make fails, give a known error. defer func() { if recover() != nil { b = nil err = ErrTooLarge return } }() b = make([]byte, n) return }
[ "func", "makeSlice", "(", "n", "int", ")", "(", "b", "[", "]", "byte", ",", "err", "error", ")", "{", "// If the make fails, give a known error.", "defer", "func", "(", ")", "{", "if", "recover", "(", ")", "!=", "nil", "{", "b", "=", "nil", "\n", "er...
// makeSlice allocates a slice of size n. If the allocation fails, it panics // with ErrTooLarge.
[ "makeSlice", "allocates", "a", "slice", "of", "size", "n", ".", "If", "the", "allocation", "fails", "it", "panics", "with", "ErrTooLarge", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/memfs/buffer.go#L166-L177
10,185
blang/vfs
dummy.go
OpenFile
func (fs DummyFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { return nil, fs.err }
go
func (fs DummyFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { return nil, fs.err }
[ "func", "(", "fs", "DummyFS", ")", "OpenFile", "(", "name", "string", ",", "flag", "int", ",", "perm", "os", ".", "FileMode", ")", "(", "File", ",", "error", ")", "{", "return", "nil", ",", "fs", ".", "err", "\n", "}" ]
// OpenFile returns dummy error
[ "OpenFile", "returns", "dummy", "error" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/dummy.go#L25-L27
10,186
blang/vfs
dummy.go
Mkdir
func (fs DummyFS) Mkdir(name string, perm os.FileMode) error { return fs.err }
go
func (fs DummyFS) Mkdir(name string, perm os.FileMode) error { return fs.err }
[ "func", "(", "fs", "DummyFS", ")", "Mkdir", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "error", "{", "return", "fs", ".", "err", "\n", "}" ]
// Mkdir returns dummy error
[ "Mkdir", "returns", "dummy", "error" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/dummy.go#L40-L42
10,187
blang/vfs
dummy.go
Stat
func (fs DummyFS) Stat(name string) (os.FileInfo, error) { return nil, fs.err }
go
func (fs DummyFS) Stat(name string) (os.FileInfo, error) { return nil, fs.err }
[ "func", "(", "fs", "DummyFS", ")", "Stat", "(", "name", "string", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "return", "nil", ",", "fs", ".", "err", "\n", "}" ]
// Stat returns dummy error
[ "Stat", "returns", "dummy", "error" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/dummy.go#L45-L47
10,188
blang/vfs
dummy.go
ReadDir
func (fs DummyFS) ReadDir(path string) ([]os.FileInfo, error) { return nil, fs.err }
go
func (fs DummyFS) ReadDir(path string) ([]os.FileInfo, error) { return nil, fs.err }
[ "func", "(", "fs", "DummyFS", ")", "ReadDir", "(", "path", "string", ")", "(", "[", "]", "os", ".", "FileInfo", ",", "error", ")", "{", "return", "nil", ",", "fs", ".", "err", "\n", "}" ]
// ReadDir returns dummy error
[ "ReadDir", "returns", "dummy", "error" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/dummy.go#L55-L57
10,189
blang/vfs
dummy.go
Write
func (f DumFile) Write(p []byte) (n int, err error) { return 0, f.err }
go
func (f DumFile) Write(p []byte) (n int, err error) { return 0, f.err }
[ "func", "(", "f", "DumFile", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "0", ",", "f", ".", "err", "\n", "}" ]
// Write returns dummy error
[ "Write", "returns", "dummy", "error" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/dummy.go#L100-L102
10,190
blang/vfs
dummy.go
ReadAt
func (f DumFile) ReadAt(p []byte, off int64) (n int, err error) { return 0, f.err }
go
func (f DumFile) ReadAt(p []byte, off int64) (n int, err error) { return 0, f.err }
[ "func", "(", "f", "DumFile", ")", "ReadAt", "(", "p", "[", "]", "byte", ",", "off", "int64", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "0", ",", "f", ".", "err", "\n", "}" ]
// ReadAt returns dummy error
[ "ReadAt", "returns", "dummy", "error" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/dummy.go#L110-L112
10,191
blang/vfs
dummy.go
Seek
func (f DumFile) Seek(offset int64, whence int) (int64, error) { return 0, f.err }
go
func (f DumFile) Seek(offset int64, whence int) (int64, error) { return 0, f.err }
[ "func", "(", "f", "DumFile", ")", "Seek", "(", "offset", "int64", ",", "whence", "int", ")", "(", "int64", ",", "error", ")", "{", "return", "0", ",", "f", ".", "err", "\n", "}" ]
// Seek returns dummy error
[ "Seek", "returns", "dummy", "error" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/dummy.go#L115-L117
10,192
blang/vfs
os.go
OpenFile
func (fs OsFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { return os.OpenFile(name, flag, perm) }
go
func (fs OsFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { return os.OpenFile(name, flag, perm) }
[ "func", "(", "fs", "OsFS", ")", "OpenFile", "(", "name", "string", ",", "flag", "int", ",", "perm", "os", ".", "FileMode", ")", "(", "File", ",", "error", ")", "{", "return", "os", ".", "OpenFile", "(", "name", ",", "flag", ",", "perm", ")", "\n"...
// OpenFile wraps os.OpenFile
[ "OpenFile", "wraps", "os", ".", "OpenFile" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/os.go#L22-L24
10,193
blang/vfs
os.go
Mkdir
func (fs OsFS) Mkdir(name string, perm os.FileMode) error { return os.Mkdir(name, perm) }
go
func (fs OsFS) Mkdir(name string, perm os.FileMode) error { return os.Mkdir(name, perm) }
[ "func", "(", "fs", "OsFS", ")", "Mkdir", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "error", "{", "return", "os", ".", "Mkdir", "(", "name", ",", "perm", ")", "\n", "}" ]
// Mkdir wraps os.Mkdir
[ "Mkdir", "wraps", "os", ".", "Mkdir" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/os.go#L32-L34
10,194
blang/vfs
os.go
Rename
func (fs OsFS) Rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) }
go
func (fs OsFS) Rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) }
[ "func", "(", "fs", "OsFS", ")", "Rename", "(", "oldpath", ",", "newpath", "string", ")", "error", "{", "return", "os", ".", "Rename", "(", "oldpath", ",", "newpath", ")", "\n", "}" ]
// Rename wraps os.Rename
[ "Rename", "wraps", "os", ".", "Rename" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/os.go#L37-L39
10,195
blang/vfs
os.go
ReadDir
func (fs OsFS) ReadDir(path string) ([]os.FileInfo, error) { return ioutil.ReadDir(path) }
go
func (fs OsFS) ReadDir(path string) ([]os.FileInfo, error) { return ioutil.ReadDir(path) }
[ "func", "(", "fs", "OsFS", ")", "ReadDir", "(", "path", "string", ")", "(", "[", "]", "os", ".", "FileInfo", ",", "error", ")", "{", "return", "ioutil", ".", "ReadDir", "(", "path", ")", "\n", "}" ]
// ReadDir wraps ioutil.ReadDir
[ "ReadDir", "wraps", "ioutil", ".", "ReadDir" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/os.go#L52-L54
10,196
blang/vfs
mountfs/mountfs.go
Create
func Create(rootFS vfs.Filesystem) *MountFS { return &MountFS{ rootFS: rootFS, mounts: make(map[string]vfs.Filesystem), parents: make(map[string][]string), } }
go
func Create(rootFS vfs.Filesystem) *MountFS { return &MountFS{ rootFS: rootFS, mounts: make(map[string]vfs.Filesystem), parents: make(map[string][]string), } }
[ "func", "Create", "(", "rootFS", "vfs", ".", "Filesystem", ")", "*", "MountFS", "{", "return", "&", "MountFS", "{", "rootFS", ":", "rootFS", ",", "mounts", ":", "make", "(", "map", "[", "string", "]", "vfs", ".", "Filesystem", ")", ",", "parents", ":...
// Create a new MountFS based on a root filesystem.
[ "Create", "a", "new", "MountFS", "based", "on", "a", "root", "filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/mountfs/mountfs.go#L16-L22
10,197
blang/vfs
mountfs/mountfs.go
findMount
func findMount(path string, mounts map[string]vfs.Filesystem, fallback vfs.Filesystem, pathSeparator string) (vfs.Filesystem, string) { path = filepath.Clean(path) segs := vfs.SplitPath(path, pathSeparator) l := len(segs) for i := l; i > 0; i-- { mountPath := strings.Join(segs[0:i], pathSeparator) if fs, ok := mounts[mountPath]; ok { return fs, "/" + strings.Join(segs[i:l], pathSeparator) } } return fallback, path }
go
func findMount(path string, mounts map[string]vfs.Filesystem, fallback vfs.Filesystem, pathSeparator string) (vfs.Filesystem, string) { path = filepath.Clean(path) segs := vfs.SplitPath(path, pathSeparator) l := len(segs) for i := l; i > 0; i-- { mountPath := strings.Join(segs[0:i], pathSeparator) if fs, ok := mounts[mountPath]; ok { return fs, "/" + strings.Join(segs[i:l], pathSeparator) } } return fallback, path }
[ "func", "findMount", "(", "path", "string", ",", "mounts", "map", "[", "string", "]", "vfs", ".", "Filesystem", ",", "fallback", "vfs", ".", "Filesystem", ",", "pathSeparator", "string", ")", "(", "vfs", ".", "Filesystem", ",", "string", ")", "{", "path"...
// findMount finds a valid mountpoint for the given path. // It returns the corresponding filesystem and the path inside of this filesystem.
[ "findMount", "finds", "a", "valid", "mountpoint", "for", "the", "given", "path", ".", "It", "returns", "the", "corresponding", "filesystem", "and", "the", "path", "inside", "of", "this", "filesystem", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/mountfs/mountfs.go#L75-L86
10,198
blang/vfs
mountfs/mountfs.go
Remove
func (fs MountFS) Remove(name string) error { mount, innerPath := findMount(name, fs.mounts, fs.rootFS, string(fs.PathSeparator())) return mount.Remove(innerPath) }
go
func (fs MountFS) Remove(name string) error { mount, innerPath := findMount(name, fs.mounts, fs.rootFS, string(fs.PathSeparator())) return mount.Remove(innerPath) }
[ "func", "(", "fs", "MountFS", ")", "Remove", "(", "name", "string", ")", "error", "{", "mount", ",", "innerPath", ":=", "findMount", "(", "name", ",", "fs", ".", "mounts", ",", "fs", ".", "rootFS", ",", "string", "(", "fs", ".", "PathSeparator", "(",...
// Remove removes a file or directory
[ "Remove", "removes", "a", "file", "or", "directory" ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/mountfs/mountfs.go#L108-L111
10,199
blang/vfs
mountfs/mountfs.go
Rename
func (fs MountFS) Rename(oldpath, newpath string) error { oldMount, oldInnerPath := findMount(oldpath, fs.mounts, fs.rootFS, string(fs.PathSeparator())) newMount, newInnerPath := findMount(newpath, fs.mounts, fs.rootFS, string(fs.PathSeparator())) if oldMount != newMount { return ErrBoundary } return oldMount.Rename(oldInnerPath, newInnerPath) }
go
func (fs MountFS) Rename(oldpath, newpath string) error { oldMount, oldInnerPath := findMount(oldpath, fs.mounts, fs.rootFS, string(fs.PathSeparator())) newMount, newInnerPath := findMount(newpath, fs.mounts, fs.rootFS, string(fs.PathSeparator())) if oldMount != newMount { return ErrBoundary } return oldMount.Rename(oldInnerPath, newInnerPath) }
[ "func", "(", "fs", "MountFS", ")", "Rename", "(", "oldpath", ",", "newpath", "string", ")", "error", "{", "oldMount", ",", "oldInnerPath", ":=", "findMount", "(", "oldpath", ",", "fs", ".", "mounts", ",", "fs", ".", "rootFS", ",", "string", "(", "fs", ...
// Rename renames a file. // Renames across filesystems are not allowed.
[ "Rename", "renames", "a", "file", ".", "Renames", "across", "filesystems", "are", "not", "allowed", "." ]
2c3e2278e174a74f31ff8bf6f47b43ecb358a870
https://github.com/blang/vfs/blob/2c3e2278e174a74f31ff8bf6f47b43ecb358a870/mountfs/mountfs.go#L115-L122