repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
go-redsync/redsync
redsync.go
NewMutex
func (r *Redsync) NewMutex(name string, options ...Option) *Mutex { m := &Mutex{ name: name, expiry: 8 * time.Second, tries: 32, delayFunc: func(tries int) time.Duration { return 500 * time.Millisecond }, genValueFunc: genValue, factor: 0.01, quorum: len(r.pools)/2 + 1, pools: r.pools, } for _, o := range options { o.Apply(m) } return m }
go
func (r *Redsync) NewMutex(name string, options ...Option) *Mutex { m := &Mutex{ name: name, expiry: 8 * time.Second, tries: 32, delayFunc: func(tries int) time.Duration { return 500 * time.Millisecond }, genValueFunc: genValue, factor: 0.01, quorum: len(r.pools)/2 + 1, pools: r.pools, } for _, o := range options { o.Apply(m) } return m }
[ "func", "(", "r", "*", "Redsync", ")", "NewMutex", "(", "name", "string", ",", "options", "...", "Option", ")", "*", "Mutex", "{", "m", ":=", "&", "Mutex", "{", "name", ":", "name", ",", "expiry", ":", "8", "*", "time", ".", "Second", ",", "tries...
// NewMutex returns a new distributed mutex with given name.
[ "NewMutex", "returns", "a", "new", "distributed", "mutex", "with", "given", "name", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/redsync.go#L18-L33
train
go-redsync/redsync
redsync.go
SetExpiry
func SetExpiry(expiry time.Duration) Option { return OptionFunc(func(m *Mutex) { m.expiry = expiry }) }
go
func SetExpiry(expiry time.Duration) Option { return OptionFunc(func(m *Mutex) { m.expiry = expiry }) }
[ "func", "SetExpiry", "(", "expiry", "time", ".", "Duration", ")", "Option", "{", "return", "OptionFunc", "(", "func", "(", "m", "*", "Mutex", ")", "{", "m", ".", "expiry", "=", "expiry", "\n", "}", ")", "\n", "}" ]
// SetExpiry can be used to set the expiry of a mutex to the given value.
[ "SetExpiry", "can", "be", "used", "to", "set", "the", "expiry", "of", "a", "mutex", "to", "the", "given", "value", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/redsync.go#L49-L53
train
go-redsync/redsync
redsync.go
SetTries
func SetTries(tries int) Option { return OptionFunc(func(m *Mutex) { m.tries = tries }) }
go
func SetTries(tries int) Option { return OptionFunc(func(m *Mutex) { m.tries = tries }) }
[ "func", "SetTries", "(", "tries", "int", ")", "Option", "{", "return", "OptionFunc", "(", "func", "(", "m", "*", "Mutex", ")", "{", "m", ".", "tries", "=", "tries", "\n", "}", ")", "\n", "}" ]
// SetTries can be used to set the number of times lock acquire is attempted.
[ "SetTries", "can", "be", "used", "to", "set", "the", "number", "of", "times", "lock", "acquire", "is", "attempted", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/redsync.go#L56-L60
train
go-redsync/redsync
redsync.go
SetRetryDelay
func SetRetryDelay(delay time.Duration) Option { return OptionFunc(func(m *Mutex) { m.delayFunc = func(tries int) time.Duration { return delay } }) }
go
func SetRetryDelay(delay time.Duration) Option { return OptionFunc(func(m *Mutex) { m.delayFunc = func(tries int) time.Duration { return delay } }) }
[ "func", "SetRetryDelay", "(", "delay", "time", ".", "Duration", ")", "Option", "{", "return", "OptionFunc", "(", "func", "(", "m", "*", "Mutex", ")", "{", "m", ".", "delayFunc", "=", "func", "(", "tries", "int", ")", "time", ".", "Duration", "{", "re...
// SetRetryDelay can be used to set the amount of time to wait between retries.
[ "SetRetryDelay", "can", "be", "used", "to", "set", "the", "amount", "of", "time", "to", "wait", "between", "retries", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/redsync.go#L63-L69
train
go-redsync/redsync
redsync.go
SetRetryDelayFunc
func SetRetryDelayFunc(delayFunc DelayFunc) Option { return OptionFunc(func(m *Mutex) { m.delayFunc = delayFunc }) }
go
func SetRetryDelayFunc(delayFunc DelayFunc) Option { return OptionFunc(func(m *Mutex) { m.delayFunc = delayFunc }) }
[ "func", "SetRetryDelayFunc", "(", "delayFunc", "DelayFunc", ")", "Option", "{", "return", "OptionFunc", "(", "func", "(", "m", "*", "Mutex", ")", "{", "m", ".", "delayFunc", "=", "delayFunc", "\n", "}", ")", "\n", "}" ]
// SetRetryDelayFunc can be used to override default delay behavior.
[ "SetRetryDelayFunc", "can", "be", "used", "to", "override", "default", "delay", "behavior", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/redsync.go#L72-L76
train
go-redsync/redsync
redsync.go
SetDriftFactor
func SetDriftFactor(factor float64) Option { return OptionFunc(func(m *Mutex) { m.factor = factor }) }
go
func SetDriftFactor(factor float64) Option { return OptionFunc(func(m *Mutex) { m.factor = factor }) }
[ "func", "SetDriftFactor", "(", "factor", "float64", ")", "Option", "{", "return", "OptionFunc", "(", "func", "(", "m", "*", "Mutex", ")", "{", "m", ".", "factor", "=", "factor", "\n", "}", ")", "\n", "}" ]
// SetDriftFactor can be used to set the clock drift factor.
[ "SetDriftFactor", "can", "be", "used", "to", "set", "the", "clock", "drift", "factor", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/redsync.go#L79-L83
train
go-redsync/redsync
redsync.go
SetGenValueFunc
func SetGenValueFunc(genValueFunc func() (string, error)) Option { return OptionFunc(func(m *Mutex) { m.genValueFunc = genValueFunc }) }
go
func SetGenValueFunc(genValueFunc func() (string, error)) Option { return OptionFunc(func(m *Mutex) { m.genValueFunc = genValueFunc }) }
[ "func", "SetGenValueFunc", "(", "genValueFunc", "func", "(", ")", "(", "string", ",", "error", ")", ")", "Option", "{", "return", "OptionFunc", "(", "func", "(", "m", "*", "Mutex", ")", "{", "m", ".", "genValueFunc", "=", "genValueFunc", "\n", "}", ")"...
// SetGenValueFunc can be used to set the custom value generator.
[ "SetGenValueFunc", "can", "be", "used", "to", "set", "the", "custom", "value", "generator", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/redsync.go#L86-L90
train
go-redsync/redsync
mutex.go
Unlock
func (m *Mutex) Unlock() bool { n := m.actOnPoolsAsync(func(pool Pool) bool { return m.release(pool, m.value) }) return n >= m.quorum }
go
func (m *Mutex) Unlock() bool { n := m.actOnPoolsAsync(func(pool Pool) bool { return m.release(pool, m.value) }) return n >= m.quorum }
[ "func", "(", "m", "*", "Mutex", ")", "Unlock", "(", ")", "bool", "{", "n", ":=", "m", ".", "actOnPoolsAsync", "(", "func", "(", "pool", "Pool", ")", "bool", "{", "return", "m", ".", "release", "(", "pool", ",", "m", ".", "value", ")", "\n", "}"...
// Unlock unlocks m and returns the status of unlock.
[ "Unlock", "unlocks", "m", "and", "returns", "the", "status", "of", "unlock", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/mutex.go#L66-L71
train
go-redsync/redsync
mutex.go
Extend
func (m *Mutex) Extend() bool { n := m.actOnPoolsAsync(func(pool Pool) bool { return m.touch(pool, m.value, int(m.expiry/time.Millisecond)) }) return n >= m.quorum }
go
func (m *Mutex) Extend() bool { n := m.actOnPoolsAsync(func(pool Pool) bool { return m.touch(pool, m.value, int(m.expiry/time.Millisecond)) }) return n >= m.quorum }
[ "func", "(", "m", "*", "Mutex", ")", "Extend", "(", ")", "bool", "{", "n", ":=", "m", ".", "actOnPoolsAsync", "(", "func", "(", "pool", "Pool", ")", "bool", "{", "return", "m", ".", "touch", "(", "pool", ",", "m", ".", "value", ",", "int", "(",...
// Extend resets the mutex's expiry and returns the status of expiry extension.
[ "Extend", "resets", "the", "mutex", "s", "expiry", "and", "returns", "the", "status", "of", "expiry", "extension", "." ]
aba0a125bc554b826ae0f194e00af531c967bcd6
https://github.com/go-redsync/redsync/blob/aba0a125bc554b826ae0f194e00af531c967bcd6/mutex.go#L74-L79
train
cesanta/docker_auth
auth_server/authn/tokendb.go
NewTokenDB
func NewTokenDB(file string) (TokenDB, error) { db, err := leveldb.OpenFile(file, nil) return &TokenDBImpl{ DB: db, }, err }
go
func NewTokenDB(file string) (TokenDB, error) { db, err := leveldb.OpenFile(file, nil) return &TokenDBImpl{ DB: db, }, err }
[ "func", "NewTokenDB", "(", "file", "string", ")", "(", "TokenDB", ",", "error", ")", "{", "db", ",", "err", ":=", "leveldb", ".", "OpenFile", "(", "file", ",", "nil", ")", "\n", "return", "&", "TokenDBImpl", "{", "DB", ":", "db", ",", "}", ",", "...
// NewTokenDB returns a new TokenDB structure
[ "NewTokenDB", "returns", "a", "new", "TokenDB", "structure" ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authn/tokendb.go#L77-L82
train
cesanta/docker_auth
auth_server/authz/acl_mongo.go
NewACLMongoAuthorizer
func NewACLMongoAuthorizer(c *ACLMongoConfig) (Authorizer, error) { // Attempt to create new MongoDB session. session, err := mgo_session.New(c.MongoConfig) if err != nil { return nil, err } authorizer := &aclMongoAuthorizer{ config: c, session: session, updateTicker: time.NewTicker(c.CacheTTL), } // Initially fetch the ACL from MongoDB if err := authorizer.updateACLCache(); err != nil { return nil, err } go authorizer.continuouslyUpdateACLCache() return authorizer, nil }
go
func NewACLMongoAuthorizer(c *ACLMongoConfig) (Authorizer, error) { // Attempt to create new MongoDB session. session, err := mgo_session.New(c.MongoConfig) if err != nil { return nil, err } authorizer := &aclMongoAuthorizer{ config: c, session: session, updateTicker: time.NewTicker(c.CacheTTL), } // Initially fetch the ACL from MongoDB if err := authorizer.updateACLCache(); err != nil { return nil, err } go authorizer.continuouslyUpdateACLCache() return authorizer, nil }
[ "func", "NewACLMongoAuthorizer", "(", "c", "*", "ACLMongoConfig", ")", "(", "Authorizer", ",", "error", ")", "{", "// Attempt to create new MongoDB session.", "session", ",", "err", ":=", "mgo_session", ".", "New", "(", "c", ".", "MongoConfig", ")", "\n", "if", ...
// NewACLMongoAuthorizer creates a new ACL MongoDB authorizer
[ "NewACLMongoAuthorizer", "creates", "a", "new", "ACL", "MongoDB", "authorizer" ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authz/acl_mongo.go#L40-L61
train
cesanta/docker_auth
auth_server/authz/acl_mongo.go
continuouslyUpdateACLCache
func (ma *aclMongoAuthorizer) continuouslyUpdateACLCache() { var tick time.Time for ; true; tick = <-ma.updateTicker.C { aclAge := time.Now().Sub(ma.lastCacheUpdate) glog.V(2).Infof("Updating ACL at %s (ACL age: %s. CacheTTL: %s)", tick, aclAge, ma.config.CacheTTL) for true { err := ma.updateACLCache() if err == nil { break } else if err == io.EOF { glog.Warningf("EOF error received from Mongo. Retrying connection") time.Sleep(time.Second) continue } else { glog.Errorf("Failed to update ACL. ERROR: %s", err) glog.Warningf("Using stale ACL (Age: %s, TTL: %s)", aclAge, ma.config.CacheTTL) break } } } }
go
func (ma *aclMongoAuthorizer) continuouslyUpdateACLCache() { var tick time.Time for ; true; tick = <-ma.updateTicker.C { aclAge := time.Now().Sub(ma.lastCacheUpdate) glog.V(2).Infof("Updating ACL at %s (ACL age: %s. CacheTTL: %s)", tick, aclAge, ma.config.CacheTTL) for true { err := ma.updateACLCache() if err == nil { break } else if err == io.EOF { glog.Warningf("EOF error received from Mongo. Retrying connection") time.Sleep(time.Second) continue } else { glog.Errorf("Failed to update ACL. ERROR: %s", err) glog.Warningf("Using stale ACL (Age: %s, TTL: %s)", aclAge, ma.config.CacheTTL) break } } } }
[ "func", "(", "ma", "*", "aclMongoAuthorizer", ")", "continuouslyUpdateACLCache", "(", ")", "{", "var", "tick", "time", ".", "Time", "\n", "for", ";", "true", ";", "tick", "=", "<-", "ma", ".", "updateTicker", ".", "C", "{", "aclAge", ":=", "time", ".",...
// continuouslyUpdateACLCache checks if the ACL cache has expired and depending // on the the result it updates the cache with the ACL from the MongoDB server. // The ACL will be stored inside the static authorizer instance which we use // to minimize duplication of code and maximize reuse of existing code.
[ "continuouslyUpdateACLCache", "checks", "if", "the", "ACL", "cache", "has", "expired", "and", "depending", "on", "the", "the", "result", "it", "updates", "the", "cache", "with", "the", "ACL", "from", "the", "MongoDB", "server", ".", "The", "ACL", "will", "be...
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authz/acl_mongo.go#L112-L133
train
cesanta/docker_auth
auth_server/mgo_session/mgo_session.go
Validate
func (c *Config) Validate(configKey string) error { if len(c.DialInfo.Addrs) == 0 { return fmt.Errorf("At least one element in %s.dial_info.addrs is required", configKey) } if c.DialInfo.Timeout == 0 { c.DialInfo.Timeout = 10 * time.Second } if c.DialInfo.Database == "" { return fmt.Errorf("%s.dial_info.database is required", configKey) } return nil }
go
func (c *Config) Validate(configKey string) error { if len(c.DialInfo.Addrs) == 0 { return fmt.Errorf("At least one element in %s.dial_info.addrs is required", configKey) } if c.DialInfo.Timeout == 0 { c.DialInfo.Timeout = 10 * time.Second } if c.DialInfo.Database == "" { return fmt.Errorf("%s.dial_info.database is required", configKey) } return nil }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", "configKey", "string", ")", "error", "{", "if", "len", "(", "c", ".", "DialInfo", ".", "Addrs", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "configKey", ")", "\...
// Validate ensures the most common fields inside the mgo.DialInfo portion of // a Config are set correctly as well as other fields inside the // Config itself.
[ "Validate", "ensures", "the", "most", "common", "fields", "inside", "the", "mgo", ".", "DialInfo", "portion", "of", "a", "Config", "are", "set", "correctly", "as", "well", "as", "other", "fields", "inside", "the", "Config", "itself", "." ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/mgo_session/mgo_session.go#L41-L52
train
cesanta/docker_auth
auth_server/authz/acl.go
NewACLAuthorizer
func NewACLAuthorizer(acl ACL) (Authorizer, error) { if err := ValidateACL(acl); err != nil { return nil, err } glog.V(1).Infof("Created ACL Authorizer with %d entries", len(acl)) return &aclAuthorizer{acl: acl}, nil }
go
func NewACLAuthorizer(acl ACL) (Authorizer, error) { if err := ValidateACL(acl); err != nil { return nil, err } glog.V(1).Infof("Created ACL Authorizer with %d entries", len(acl)) return &aclAuthorizer{acl: acl}, nil }
[ "func", "NewACLAuthorizer", "(", "acl", "ACL", ")", "(", "Authorizer", ",", "error", ")", "{", "if", "err", ":=", "ValidateACL", "(", "acl", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "glog", ".", "V", "(", "...
// NewACLAuthorizer Creates a new static authorizer with ACL that have been read from the config file
[ "NewACLAuthorizer", "Creates", "a", "new", "static", "authorizer", "with", "ACL", "that", "have", "been", "read", "from", "the", "config", "file" ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authz/acl.go#L104-L110
train
cesanta/docker_auth
auth_server/authn/ldap_auth.go
ldapSearch
func (la *LDAPAuth) ldapSearch(l *ldap.Conn, baseDN *string, filter *string, attrs *[]string) (string, map[string][]string, error) { if l == nil { return "", nil, fmt.Errorf("No ldap connection!") } glog.V(2).Infof("Searching...basedDN:%s, filter:%s", *baseDN, *filter) searchRequest := ldap.NewSearchRequest( *baseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, *filter, *attrs, nil) sr, err := l.Search(searchRequest) if err != nil { return "", nil, err } if len(sr.Entries) == 0 { return "", nil, nil // User does not exist } else if len(sr.Entries) > 1 { return "", nil, fmt.Errorf("Too many entries returned.") } attributes := make(map[string][]string) var entryDn string for _, entry := range sr.Entries { entryDn = entry.DN if len(*attrs) == 0 { glog.V(2).Infof("Entry DN = %s", entryDn) } else { for _, attr := range *attrs { values := entry.GetAttributeValues(attr) glog.V(2).Infof("Entry %s = %s", attr, strings.Join(values, "\n")) attributes[attr] = values } } } return entryDn, attributes, nil }
go
func (la *LDAPAuth) ldapSearch(l *ldap.Conn, baseDN *string, filter *string, attrs *[]string) (string, map[string][]string, error) { if l == nil { return "", nil, fmt.Errorf("No ldap connection!") } glog.V(2).Infof("Searching...basedDN:%s, filter:%s", *baseDN, *filter) searchRequest := ldap.NewSearchRequest( *baseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, *filter, *attrs, nil) sr, err := l.Search(searchRequest) if err != nil { return "", nil, err } if len(sr.Entries) == 0 { return "", nil, nil // User does not exist } else if len(sr.Entries) > 1 { return "", nil, fmt.Errorf("Too many entries returned.") } attributes := make(map[string][]string) var entryDn string for _, entry := range sr.Entries { entryDn = entry.DN if len(*attrs) == 0 { glog.V(2).Infof("Entry DN = %s", entryDn) } else { for _, attr := range *attrs { values := entry.GetAttributeValues(attr) glog.V(2).Infof("Entry %s = %s", attr, strings.Join(values, "\n")) attributes[attr] = values } } } return entryDn, attributes, nil }
[ "func", "(", "la", "*", "LDAPAuth", ")", "ldapSearch", "(", "l", "*", "ldap", ".", "Conn", ",", "baseDN", "*", "string", ",", "filter", "*", "string", ",", "attrs", "*", "[", "]", "string", ")", "(", "string", ",", "map", "[", "string", "]", "[",...
//ldap search and return required attributes' value from searched entries //default return entry's DN value if you leave attrs array empty
[ "ldap", "search", "and", "return", "required", "attributes", "value", "from", "searched", "entries", "default", "return", "entry", "s", "DN", "value", "if", "you", "leave", "attrs", "array", "empty" ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authn/ldap_auth.go#L204-L242
train
cesanta/docker_auth
auth_server/authn/github_auth.go
removeSubstringsFromString
func removeSubstringsFromString(sourceStr string, stringsToStrip []string) string { theNewString := sourceStr for _, i := range stringsToStrip { theNewString = strings.Replace(theNewString, i, "", -1) } return theNewString }
go
func removeSubstringsFromString(sourceStr string, stringsToStrip []string) string { theNewString := sourceStr for _, i := range stringsToStrip { theNewString = strings.Replace(theNewString, i, "", -1) } return theNewString }
[ "func", "removeSubstringsFromString", "(", "sourceStr", "string", ",", "stringsToStrip", "[", "]", "string", ")", "string", "{", "theNewString", ":=", "sourceStr", "\n", "for", "_", ",", "i", ":=", "range", "stringsToStrip", "{", "theNewString", "=", "strings", ...
// removeSubstringsFromString removes all occurences of stringsToStrip from sourceStr //
[ "removeSubstringsFromString", "removes", "all", "occurences", "of", "stringsToStrip", "from", "sourceStr" ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authn/github_auth.go#L123-L129
train
cesanta/docker_auth
auth_server/authn/tokendb_gcs.go
GetValue
func (db *gcsTokenDB) GetValue(user string) (*TokenDBValue, error) { rd, err := db.gcs.Bucket(db.bucket).Object(user).NewReader(context.Background()) if err == storage.ErrObjectNotExist { return nil, nil } if err != nil { return nil, fmt.Errorf("could not retrieved token for user '%s' due: %v", user, err) } defer rd.Close() var dbv TokenDBValue if err := json.NewDecoder(rd).Decode(&dbv); err != nil { glog.Errorf("bad DB value for %q: %v", user, err) return nil, fmt.Errorf("could not read token for user '%s' due: %v", user, err) } return &dbv, nil }
go
func (db *gcsTokenDB) GetValue(user string) (*TokenDBValue, error) { rd, err := db.gcs.Bucket(db.bucket).Object(user).NewReader(context.Background()) if err == storage.ErrObjectNotExist { return nil, nil } if err != nil { return nil, fmt.Errorf("could not retrieved token for user '%s' due: %v", user, err) } defer rd.Close() var dbv TokenDBValue if err := json.NewDecoder(rd).Decode(&dbv); err != nil { glog.Errorf("bad DB value for %q: %v", user, err) return nil, fmt.Errorf("could not read token for user '%s' due: %v", user, err) } return &dbv, nil }
[ "func", "(", "db", "*", "gcsTokenDB", ")", "GetValue", "(", "user", "string", ")", "(", "*", "TokenDBValue", ",", "error", ")", "{", "rd", ",", "err", ":=", "db", ".", "gcs", ".", "Bucket", "(", "db", ".", "bucket", ")", ".", "Object", "(", "user...
// GetValue gets token value associated with the provided user. Each user // in the bucket is having it's own file for tokens and it's recomanded bucket // to not be shared with other apps
[ "GetValue", "gets", "token", "value", "associated", "with", "the", "provided", "user", ".", "Each", "user", "in", "the", "bucket", "is", "having", "it", "s", "own", "file", "for", "tokens", "and", "it", "s", "recomanded", "bucket", "to", "not", "be", "sh...
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authn/tokendb_gcs.go#L48-L65
train
cesanta/docker_auth
auth_server/authn/tokendb_gcs.go
StoreToken
func (db *gcsTokenDB) StoreToken(user string, v *TokenDBValue, updatePassword bool) (dp string, err error) { if updatePassword { dp = uniuri.New() dph, _ := bcrypt.GenerateFromPassword([]byte(dp), bcrypt.DefaultCost) v.DockerPassword = string(dph) } wr := db.gcs.Bucket(db.bucket).Object(user).NewWriter(context.Background()) if err := json.NewEncoder(wr).Encode(v); err != nil { glog.Errorf("failed to set token data for %s: %s", user, err) return "", fmt.Errorf("failed to set token data for %s due: %v", user, err) } err = wr.Close() return }
go
func (db *gcsTokenDB) StoreToken(user string, v *TokenDBValue, updatePassword bool) (dp string, err error) { if updatePassword { dp = uniuri.New() dph, _ := bcrypt.GenerateFromPassword([]byte(dp), bcrypt.DefaultCost) v.DockerPassword = string(dph) } wr := db.gcs.Bucket(db.bucket).Object(user).NewWriter(context.Background()) if err := json.NewEncoder(wr).Encode(v); err != nil { glog.Errorf("failed to set token data for %s: %s", user, err) return "", fmt.Errorf("failed to set token data for %s due: %v", user, err) } err = wr.Close() return }
[ "func", "(", "db", "*", "gcsTokenDB", ")", "StoreToken", "(", "user", "string", ",", "v", "*", "TokenDBValue", ",", "updatePassword", "bool", ")", "(", "dp", "string", ",", "err", "error", ")", "{", "if", "updatePassword", "{", "dp", "=", "uniuri", "."...
// StoreToken stores token in the GCS file in a JSON format. Note that separate file is // used for each user
[ "StoreToken", "stores", "token", "in", "the", "GCS", "file", "in", "a", "JSON", "format", ".", "Note", "that", "separate", "file", "is", "used", "for", "each", "user" ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authn/tokendb_gcs.go#L69-L85
train
cesanta/docker_auth
auth_server/authn/tokendb_gcs.go
DeleteToken
func (db *gcsTokenDB) DeleteToken(user string) error { ctx := context.Background() err := db.gcs.Bucket(db.bucket).Object(user).Delete(ctx) if err == storage.ErrObjectNotExist { return nil } return err }
go
func (db *gcsTokenDB) DeleteToken(user string) error { ctx := context.Background() err := db.gcs.Bucket(db.bucket).Object(user).Delete(ctx) if err == storage.ErrObjectNotExist { return nil } return err }
[ "func", "(", "db", "*", "gcsTokenDB", ")", "DeleteToken", "(", "user", "string", ")", "error", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "err", ":=", "db", ".", "gcs", ".", "Bucket", "(", "db", ".", "bucket", ")", ".", "Object...
// DeleteToken deletes the GCS file that is associated with the provided user.
[ "DeleteToken", "deletes", "the", "GCS", "file", "that", "is", "associated", "with", "the", "provided", "user", "." ]
b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf
https://github.com/cesanta/docker_auth/blob/b89dec9a4f0098fb0f71d9b94e44d1710c1fe5cf/auth_server/authn/tokendb_gcs.go#L109-L116
train
square/certstrap
depot/depot.go
NewFileDepot
func NewFileDepot(dir string) (*FileDepot, error) { dirpath, err := filepath.Abs(dir) if err != nil { return nil, err } return &FileDepot{dirpath}, nil }
go
func NewFileDepot(dir string) (*FileDepot, error) { dirpath, err := filepath.Abs(dir) if err != nil { return nil, err } return &FileDepot{dirpath}, nil }
[ "func", "NewFileDepot", "(", "dir", "string", ")", "(", "*", "FileDepot", ",", "error", ")", "{", "dirpath", ",", "err", ":=", "filepath", ".", "Abs", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "...
// NewFileDepot creates a new Depot at the specified path
[ "NewFileDepot", "creates", "a", "new", "Depot", "at", "the", "specified", "path" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/depot.go#L60-L67
train
square/certstrap
depot/depot.go
Put
func (d *FileDepot) Put(tag *Tag, data []byte) error { if data == nil { return errors.New("data is nil") } if err := os.MkdirAll(d.dirPath, 0755); err != nil { return err } name := d.path(tag.name) perm := tag.perm file, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm) if err != nil { return err } if _, err := file.Write(data); err != nil { file.Close() os.Remove(name) return err } file.Close() return nil }
go
func (d *FileDepot) Put(tag *Tag, data []byte) error { if data == nil { return errors.New("data is nil") } if err := os.MkdirAll(d.dirPath, 0755); err != nil { return err } name := d.path(tag.name) perm := tag.perm file, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm) if err != nil { return err } if _, err := file.Write(data); err != nil { file.Close() os.Remove(name) return err } file.Close() return nil }
[ "func", "(", "d", "*", "FileDepot", ")", "Put", "(", "tag", "*", "Tag", ",", "data", "[", "]", "byte", ")", "error", "{", "if", "data", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":...
// Put inserts the data into the file specified by the tag
[ "Put", "inserts", "the", "data", "into", "the", "file", "specified", "by", "the", "tag" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/depot.go#L74-L99
train
square/certstrap
depot/depot.go
Check
func (d *FileDepot) Check(tag *Tag) bool { name := d.path(tag.name) if fi, err := os.Stat(name); err == nil && ^fi.Mode()&tag.perm == 0 { return true } return false }
go
func (d *FileDepot) Check(tag *Tag) bool { name := d.path(tag.name) if fi, err := os.Stat(name); err == nil && ^fi.Mode()&tag.perm == 0 { return true } return false }
[ "func", "(", "d", "*", "FileDepot", ")", "Check", "(", "tag", "*", "Tag", ")", "bool", "{", "name", ":=", "d", ".", "path", "(", "tag", ".", "name", ")", "\n", "if", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "name", ")", ";", "err", "...
// Check returns whether the file at the tag location exists and has the correct permissions
[ "Check", "returns", "whether", "the", "file", "at", "the", "tag", "location", "exists", "and", "has", "the", "correct", "permissions" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/depot.go#L102-L108
train
square/certstrap
depot/depot.go
Get
func (d *FileDepot) Get(tag *Tag) ([]byte, error) { if err := d.check(tag); err != nil { return nil, err } return ioutil.ReadFile(d.path(tag.name)) }
go
func (d *FileDepot) Get(tag *Tag) ([]byte, error) { if err := d.check(tag); err != nil { return nil, err } return ioutil.ReadFile(d.path(tag.name)) }
[ "func", "(", "d", "*", "FileDepot", ")", "Get", "(", "tag", "*", "Tag", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "err", ":=", "d", ".", "check", "(", "tag", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\...
// Get reads the file specified by the tag
[ "Get", "reads", "the", "file", "specified", "by", "the", "tag" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/depot.go#L123-L128
train
square/certstrap
depot/depot.go
Delete
func (d *FileDepot) Delete(tag *Tag) error { return os.Remove(d.path(tag.name)) }
go
func (d *FileDepot) Delete(tag *Tag) error { return os.Remove(d.path(tag.name)) }
[ "func", "(", "d", "*", "FileDepot", ")", "Delete", "(", "tag", "*", "Tag", ")", "error", "{", "return", "os", ".", "Remove", "(", "d", ".", "path", "(", "tag", ".", "name", ")", ")", "\n", "}" ]
// Delete removes the file specified by the tag
[ "Delete", "removes", "the", "file", "specified", "by", "the", "tag" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/depot.go#L131-L133
train
square/certstrap
depot/depot.go
List
func (d *FileDepot) List() []*Tag { var tags = make([]*Tag, 0) filepath.Walk(d.dirPath, func(path string, info os.FileInfo, err error) error { if err != nil { return nil } if info.IsDir() { return nil } rel, err := filepath.Rel(d.dirPath, path) if err != nil { return nil } if rel != info.Name() { return nil } tags = append(tags, &Tag{info.Name(), info.Mode()}) return nil }) return tags }
go
func (d *FileDepot) List() []*Tag { var tags = make([]*Tag, 0) filepath.Walk(d.dirPath, func(path string, info os.FileInfo, err error) error { if err != nil { return nil } if info.IsDir() { return nil } rel, err := filepath.Rel(d.dirPath, path) if err != nil { return nil } if rel != info.Name() { return nil } tags = append(tags, &Tag{info.Name(), info.Mode()}) return nil }) return tags }
[ "func", "(", "d", "*", "FileDepot", ")", "List", "(", ")", "[", "]", "*", "Tag", "{", "var", "tags", "=", "make", "(", "[", "]", "*", "Tag", ",", "0", ")", "\n\n", "filepath", ".", "Walk", "(", "d", ".", "dirPath", ",", "func", "(", "path", ...
// List returns all tags in the specified depot
[ "List", "returns", "all", "tags", "in", "the", "specified", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/depot.go#L136-L158
train
square/certstrap
depot/depot.go
GetFile
func (d *FileDepot) GetFile(tag *Tag) (*File, error) { if err := d.check(tag); err != nil { return nil, err } fi, err := os.Stat(d.path(tag.name)) if err != nil { return nil, err } b, err := ioutil.ReadFile(d.path(tag.name)) return &File{fi, b}, err }
go
func (d *FileDepot) GetFile(tag *Tag) (*File, error) { if err := d.check(tag); err != nil { return nil, err } fi, err := os.Stat(d.path(tag.name)) if err != nil { return nil, err } b, err := ioutil.ReadFile(d.path(tag.name)) return &File{fi, b}, err }
[ "func", "(", "d", "*", "FileDepot", ")", "GetFile", "(", "tag", "*", "Tag", ")", "(", "*", "File", ",", "error", ")", "{", "if", "err", ":=", "d", ".", "check", "(", "tag", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n",...
// GetFile returns the File at the specified tag in the given depot
[ "GetFile", "returns", "the", "File", "at", "the", "specified", "tag", "in", "the", "given", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/depot.go#L167-L177
train
square/certstrap
cmd/revoke.go
NewRevokeCommand
func NewRevokeCommand() cli.Command { return cli.Command{ Name: "revoke", Usage: "Revoke certificate", Description: "Add certificate to the CA's CRL.", Flags: []cli.Flag{ cli.StringFlag{ Name: "CN", Usage: "Common Name (CN) of certificate to revoke", }, cli.StringFlag{ Name: "CA", Usage: "Name of CA under which certificate was issued", }, }, Action: new(revokeCommand).run, } }
go
func NewRevokeCommand() cli.Command { return cli.Command{ Name: "revoke", Usage: "Revoke certificate", Description: "Add certificate to the CA's CRL.", Flags: []cli.Flag{ cli.StringFlag{ Name: "CN", Usage: "Common Name (CN) of certificate to revoke", }, cli.StringFlag{ Name: "CA", Usage: "Name of CA under which certificate was issued", }, }, Action: new(revokeCommand).run, } }
[ "func", "NewRevokeCommand", "(", ")", "cli", ".", "Command", "{", "return", "cli", ".", "Command", "{", "Name", ":", "\"", "\"", ",", "Usage", ":", "\"", "\"", ",", "Description", ":", "\"", "\"", ",", "Flags", ":", "[", "]", "cli", ".", "Flag", ...
// NewRevokeCommand revokes the given certificate by adding it to the CA's CRL.
[ "NewRevokeCommand", "revokes", "the", "given", "certificate", "by", "adding", "it", "to", "the", "CA", "s", "CRL", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/cmd/revoke.go#L23-L40
train
square/certstrap
cmd/sign.go
NewSignCommand
func NewSignCommand() cli.Command { return cli.Command{ Name: "sign", Usage: "Sign certificate request", Description: "Sign certificate request with CA, and generate certificate for the host.", Flags: []cli.Flag{ cli.StringFlag{ Name: "passphrase", Usage: "Passphrase to decrypt private-key PEM block of CA", }, cli.IntFlag{ Name: "years", Hidden: true, }, cli.StringFlag{ Name: "expires", Value: "2 years", Usage: "How long until the certificate expires (example: 1 year 2 days 3 months 4 hours)", }, cli.StringFlag{ Name: "CA", Usage: "Name of CA to issue cert with", }, cli.BoolFlag{ Name: "stdout", Usage: "Print certificate to stdout in addition to saving file", }, cli.BoolFlag{ Name: "intermediate", Usage: "Whether generated certificate should be a intermediate", }, }, Action: newSignAction, } }
go
func NewSignCommand() cli.Command { return cli.Command{ Name: "sign", Usage: "Sign certificate request", Description: "Sign certificate request with CA, and generate certificate for the host.", Flags: []cli.Flag{ cli.StringFlag{ Name: "passphrase", Usage: "Passphrase to decrypt private-key PEM block of CA", }, cli.IntFlag{ Name: "years", Hidden: true, }, cli.StringFlag{ Name: "expires", Value: "2 years", Usage: "How long until the certificate expires (example: 1 year 2 days 3 months 4 hours)", }, cli.StringFlag{ Name: "CA", Usage: "Name of CA to issue cert with", }, cli.BoolFlag{ Name: "stdout", Usage: "Print certificate to stdout in addition to saving file", }, cli.BoolFlag{ Name: "intermediate", Usage: "Whether generated certificate should be a intermediate", }, }, Action: newSignAction, } }
[ "func", "NewSignCommand", "(", ")", "cli", ".", "Command", "{", "return", "cli", ".", "Command", "{", "Name", ":", "\"", "\"", ",", "Usage", ":", "\"", "\"", ",", "Description", ":", "\"", "\"", ",", "Flags", ":", "[", "]", "cli", ".", "Flag", "{...
// NewSignCommand sets up a "sign" command to sign a CSR with a given CA for a new certificate
[ "NewSignCommand", "sets", "up", "a", "sign", "command", "to", "sign", "a", "CSR", "with", "a", "given", "CA", "for", "a", "new", "certificate" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/cmd/sign.go#L31-L65
train
square/certstrap
pkix/crl.go
NewCertificateRevocationListFromPEM
func NewCertificateRevocationListFromPEM(data []byte) (*CertificateRevocationList, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if pemBlock.Type != crlPEMBlockType || len(pemBlock.Headers) != 0 { return nil, errors.New("unmatched type or headers") } return &CertificateRevocationList{derBytes: pemBlock.Bytes}, nil }
go
func NewCertificateRevocationListFromPEM(data []byte) (*CertificateRevocationList, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if pemBlock.Type != crlPEMBlockType || len(pemBlock.Headers) != 0 { return nil, errors.New("unmatched type or headers") } return &CertificateRevocationList{derBytes: pemBlock.Bytes}, nil }
[ "func", "NewCertificateRevocationListFromPEM", "(", "data", "[", "]", "byte", ")", "(", "*", "CertificateRevocationList", ",", "error", ")", "{", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "data", ")", "\n", "if", "pemBlock", "==", "nil", "{", ...
// NewCertificateRevocationListFromPEM inits CertificateRevocationList from PEM-format bytes
[ "NewCertificateRevocationListFromPEM", "inits", "CertificateRevocationList", "from", "PEM", "-", "format", "bytes" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/crl.go#L62-L71
train
square/certstrap
pkix/cert.go
NewCertificateFromPEM
func NewCertificateFromPEM(data []byte) (c *Certificate, err error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { err = errors.New("cannot find the next PEM formatted block") return } if pemBlock.Type != certificatePEMBlockType || len(pemBlock.Headers) != 0 { err = errors.New("unmatched type or headers") return } c = &Certificate{derBytes: pemBlock.Bytes} return }
go
func NewCertificateFromPEM(data []byte) (c *Certificate, err error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { err = errors.New("cannot find the next PEM formatted block") return } if pemBlock.Type != certificatePEMBlockType || len(pemBlock.Headers) != 0 { err = errors.New("unmatched type or headers") return } c = &Certificate{derBytes: pemBlock.Bytes} return }
[ "func", "NewCertificateFromPEM", "(", "data", "[", "]", "byte", ")", "(", "c", "*", "Certificate", ",", "err", "error", ")", "{", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "data", ")", "\n", "if", "pemBlock", "==", "nil", "{", "err", "...
// NewCertificateFromPEM inits Certificate from PEM-format bytes // data should contain at most one certificate
[ "NewCertificateFromPEM", "inits", "Certificate", "from", "PEM", "-", "format", "bytes", "data", "should", "contain", "at", "most", "one", "certificate" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L48-L60
train
square/certstrap
pkix/cert.go
buildX509Certificate
func (c *Certificate) buildX509Certificate() error { if c.crt != nil { return nil } crts, err := x509.ParseCertificates(c.derBytes) if err != nil { return err } if len(crts) != 1 { return errors.New("unsupported multiple certificates in a block") } c.crt = crts[0] return nil }
go
func (c *Certificate) buildX509Certificate() error { if c.crt != nil { return nil } crts, err := x509.ParseCertificates(c.derBytes) if err != nil { return err } if len(crts) != 1 { return errors.New("unsupported multiple certificates in a block") } c.crt = crts[0] return nil }
[ "func", "(", "c", "*", "Certificate", ")", "buildX509Certificate", "(", ")", "error", "{", "if", "c", ".", "crt", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "crts", ",", "err", ":=", "x509", ".", "ParseCertificates", "(", "c", ".", "derByt...
// build crt field if needed
[ "build", "crt", "field", "if", "needed" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L63-L77
train
square/certstrap
pkix/cert.go
GetRawCertificate
func (c *Certificate) GetRawCertificate() (*x509.Certificate, error) { if err := c.buildX509Certificate(); err != nil { return nil, err } return c.crt, nil }
go
func (c *Certificate) GetRawCertificate() (*x509.Certificate, error) { if err := c.buildX509Certificate(); err != nil { return nil, err } return c.crt, nil }
[ "func", "(", "c", "*", "Certificate", ")", "GetRawCertificate", "(", ")", "(", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "buildX509Certificate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",",...
// GetRawCertificate returns a copy of this certificate as an x509.Certificate
[ "GetRawCertificate", "returns", "a", "copy", "of", "this", "certificate", "as", "an", "x509", ".", "Certificate" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L80-L85
train
square/certstrap
pkix/cert.go
GetExpirationDuration
func (c *Certificate) GetExpirationDuration() time.Duration { if err := c.buildX509Certificate(); err != nil { return time.Unix(0, 0).Sub(time.Now()) } return c.crt.NotAfter.Sub(time.Now()) }
go
func (c *Certificate) GetExpirationDuration() time.Duration { if err := c.buildX509Certificate(); err != nil { return time.Unix(0, 0).Sub(time.Now()) } return c.crt.NotAfter.Sub(time.Now()) }
[ "func", "(", "c", "*", "Certificate", ")", "GetExpirationDuration", "(", ")", "time", ".", "Duration", "{", "if", "err", ":=", "c", ".", "buildX509Certificate", "(", ")", ";", "err", "!=", "nil", "{", "return", "time", ".", "Unix", "(", "0", ",", "0"...
// GetExpirationDuration gets time duration before expiration
[ "GetExpirationDuration", "gets", "time", "duration", "before", "expiration" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L88-L93
train
square/certstrap
pkix/cert.go
CheckAuthority
func (c *Certificate) CheckAuthority() error { if err := c.buildX509Certificate(); err != nil { return err } return c.crt.CheckSignatureFrom(c.crt) }
go
func (c *Certificate) CheckAuthority() error { if err := c.buildX509Certificate(); err != nil { return err } return c.crt.CheckSignatureFrom(c.crt) }
[ "func", "(", "c", "*", "Certificate", ")", "CheckAuthority", "(", ")", "error", "{", "if", "err", ":=", "c", ".", "buildX509Certificate", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "crt", ".", "Che...
// CheckAuthority checks the authority of certificate against itself. // It only ensures that certificate is self-explanatory, and // cannot promise the validity and security.
[ "CheckAuthority", "checks", "the", "authority", "of", "certificate", "against", "itself", ".", "It", "only", "ensures", "that", "certificate", "is", "self", "-", "explanatory", "and", "cannot", "promise", "the", "validity", "and", "security", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L98-L103
train
square/certstrap
pkix/cert.go
Export
func (c *Certificate) Export() ([]byte, error) { pemBlock := &pem.Block{ Type: certificatePEMBlockType, Headers: nil, Bytes: c.derBytes, } buf := new(bytes.Buffer) if err := pem.Encode(buf, pemBlock); err != nil { return nil, err } return buf.Bytes(), nil }
go
func (c *Certificate) Export() ([]byte, error) { pemBlock := &pem.Block{ Type: certificatePEMBlockType, Headers: nil, Bytes: c.derBytes, } buf := new(bytes.Buffer) if err := pem.Encode(buf, pemBlock); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "c", "*", "Certificate", ")", "Export", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "pemBlock", ":=", "&", "pem", ".", "Block", "{", "Type", ":", "certificatePEMBlockType", ",", "Headers", ":", "nil", ",", "Bytes", ":", "c...
// Export returns PEM-format bytes
[ "Export", "returns", "PEM", "-", "format", "bytes" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L151-L163
train
square/certstrap
pkix/cert_auth.go
CreateCertificateAuthority
func CreateCertificateAuthority(key *Key, organizationalUnit string, expiry time.Time, organization string, country string, province string, locality string, commonName string) (*Certificate, error) { subjectKeyID, err := GenerateSubjectKeyID(key.Public) if err != nil { return nil, err } authTemplate.SubjectKeyId = subjectKeyID authTemplate.NotAfter = expiry if len(country) > 0 { authTemplate.Subject.Country = []string{country} } if len(province) > 0 { authTemplate.Subject.Province = []string{province} } if len(locality) > 0 { authTemplate.Subject.Locality = []string{locality} } if len(organization) > 0 { authTemplate.Subject.Organization = []string{organization} } if len(organizationalUnit) > 0 { authTemplate.Subject.OrganizationalUnit = []string{organizationalUnit} } if len(commonName) > 0 { authTemplate.Subject.CommonName = commonName } crtBytes, err := x509.CreateCertificate(rand.Reader, &authTemplate, &authTemplate, key.Public, key.Private) if err != nil { return nil, err } return NewCertificateFromDER(crtBytes), nil }
go
func CreateCertificateAuthority(key *Key, organizationalUnit string, expiry time.Time, organization string, country string, province string, locality string, commonName string) (*Certificate, error) { subjectKeyID, err := GenerateSubjectKeyID(key.Public) if err != nil { return nil, err } authTemplate.SubjectKeyId = subjectKeyID authTemplate.NotAfter = expiry if len(country) > 0 { authTemplate.Subject.Country = []string{country} } if len(province) > 0 { authTemplate.Subject.Province = []string{province} } if len(locality) > 0 { authTemplate.Subject.Locality = []string{locality} } if len(organization) > 0 { authTemplate.Subject.Organization = []string{organization} } if len(organizationalUnit) > 0 { authTemplate.Subject.OrganizationalUnit = []string{organizationalUnit} } if len(commonName) > 0 { authTemplate.Subject.CommonName = commonName } crtBytes, err := x509.CreateCertificate(rand.Reader, &authTemplate, &authTemplate, key.Public, key.Private) if err != nil { return nil, err } return NewCertificateFromDER(crtBytes), nil }
[ "func", "CreateCertificateAuthority", "(", "key", "*", "Key", ",", "organizationalUnit", "string", ",", "expiry", "time", ".", "Time", ",", "organization", "string", ",", "country", "string", ",", "province", "string", ",", "locality", "string", ",", "commonName...
// CreateCertificateAuthority creates Certificate Authority using existing key. // CertificateAuthorityInfo returned is the extra infomation required by Certificate Authority.
[ "CreateCertificateAuthority", "creates", "Certificate", "Authority", "using", "existing", "key", ".", "CertificateAuthorityInfo", "returned", "is", "the", "extra", "infomation", "required", "by", "Certificate", "Authority", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert_auth.go#L80-L112
train
square/certstrap
pkix/cert_auth.go
CreateIntermediateCertificateAuthority
func CreateIntermediateCertificateAuthority(crtAuth *Certificate, keyAuth *Key, csr *CertificateSigningRequest, proposedExpiry time.Time) (*Certificate, error) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, err } authTemplate.SerialNumber.Set(serialNumber) authTemplate.MaxPathLenZero = false rawCsr, err := csr.GetRawCertificateSigningRequest() if err != nil { return nil, err } authTemplate.RawSubject = rawCsr.RawSubject caExpiry := time.Now().Add(crtAuth.GetExpirationDuration()) // ensure cert doesn't expire after issuer if caExpiry.Before(proposedExpiry) { authTemplate.NotAfter = caExpiry } else { authTemplate.NotAfter = proposedExpiry } authTemplate.SubjectKeyId, err = GenerateSubjectKeyID(rawCsr.PublicKey) if err != nil { return nil, err } authTemplate.IPAddresses = rawCsr.IPAddresses authTemplate.DNSNames = rawCsr.DNSNames authTemplate.URIs = rawCsr.URIs rawCrtAuth, err := crtAuth.GetRawCertificate() if err != nil { return nil, err } crtOutBytes, err := x509.CreateCertificate(rand.Reader, &authTemplate, rawCrtAuth, rawCsr.PublicKey, keyAuth.Private) if err != nil { return nil, err } return NewCertificateFromDER(crtOutBytes), nil }
go
func CreateIntermediateCertificateAuthority(crtAuth *Certificate, keyAuth *Key, csr *CertificateSigningRequest, proposedExpiry time.Time) (*Certificate, error) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, err } authTemplate.SerialNumber.Set(serialNumber) authTemplate.MaxPathLenZero = false rawCsr, err := csr.GetRawCertificateSigningRequest() if err != nil { return nil, err } authTemplate.RawSubject = rawCsr.RawSubject caExpiry := time.Now().Add(crtAuth.GetExpirationDuration()) // ensure cert doesn't expire after issuer if caExpiry.Before(proposedExpiry) { authTemplate.NotAfter = caExpiry } else { authTemplate.NotAfter = proposedExpiry } authTemplate.SubjectKeyId, err = GenerateSubjectKeyID(rawCsr.PublicKey) if err != nil { return nil, err } authTemplate.IPAddresses = rawCsr.IPAddresses authTemplate.DNSNames = rawCsr.DNSNames authTemplate.URIs = rawCsr.URIs rawCrtAuth, err := crtAuth.GetRawCertificate() if err != nil { return nil, err } crtOutBytes, err := x509.CreateCertificate(rand.Reader, &authTemplate, rawCrtAuth, rawCsr.PublicKey, keyAuth.Private) if err != nil { return nil, err } return NewCertificateFromDER(crtOutBytes), nil }
[ "func", "CreateIntermediateCertificateAuthority", "(", "crtAuth", "*", "Certificate", ",", "keyAuth", "*", "Key", ",", "csr", "*", "CertificateSigningRequest", ",", "proposedExpiry", "time", ".", "Time", ")", "(", "*", "Certificate", ",", "error", ")", "{", "ser...
// CreateIntermediateCertificateAuthority creates an intermediate // CA certificate signed by the given authority.
[ "CreateIntermediateCertificateAuthority", "creates", "an", "intermediate", "CA", "certificate", "signed", "by", "the", "given", "authority", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert_auth.go#L116-L160
train
square/certstrap
depot/pkix.go
GetNameFromCrtTag
func GetNameFromCrtTag(tag *Tag) string { name := strings.TrimSuffix(tag.name, crtSuffix) if name == tag.name { return "" } return name }
go
func GetNameFromCrtTag(tag *Tag) string { name := strings.TrimSuffix(tag.name, crtSuffix) if name == tag.name { return "" } return name }
[ "func", "GetNameFromCrtTag", "(", "tag", "*", "Tag", ")", "string", "{", "name", ":=", "strings", ".", "TrimSuffix", "(", "tag", ".", "name", ",", "crtSuffix", ")", "\n", "if", "name", "==", "tag", ".", "name", "{", "return", "\"", "\"", "\n", "}", ...
// GetNameFromCrtTag returns the host name from a certificate file tag
[ "GetNameFromCrtTag", "returns", "the", "host", "name", "from", "a", "certificate", "file", "tag" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L59-L65
train
square/certstrap
depot/pkix.go
PutCertificate
func PutCertificate(d Depot, name string, crt *pkix.Certificate) error { b, err := crt.Export() if err != nil { return err } return d.Put(CrtTag(name), b) }
go
func PutCertificate(d Depot, name string, crt *pkix.Certificate) error { b, err := crt.Export() if err != nil { return err } return d.Put(CrtTag(name), b) }
[ "func", "PutCertificate", "(", "d", "Depot", ",", "name", "string", ",", "crt", "*", "pkix", ".", "Certificate", ")", "error", "{", "b", ",", "err", ":=", "crt", ".", "Export", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", ...
// PutCertificate creates a certificate file for a given CA name in the depot
[ "PutCertificate", "creates", "a", "certificate", "file", "for", "a", "given", "CA", "name", "in", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L68-L74
train
square/certstrap
depot/pkix.go
CheckCertificate
func CheckCertificate(d Depot, name string) bool { return d.Check(CrtTag(name)) }
go
func CheckCertificate(d Depot, name string) bool { return d.Check(CrtTag(name)) }
[ "func", "CheckCertificate", "(", "d", "Depot", ",", "name", "string", ")", "bool", "{", "return", "d", ".", "Check", "(", "CrtTag", "(", "name", ")", ")", "\n", "}" ]
// CheckCertificate checks the depot for existence of a certificate file for a given CA name
[ "CheckCertificate", "checks", "the", "depot", "for", "existence", "of", "a", "certificate", "file", "for", "a", "given", "CA", "name" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L77-L79
train
square/certstrap
depot/pkix.go
GetCertificate
func GetCertificate(d Depot, name string) (crt *pkix.Certificate, err error) { b, err := d.Get(CrtTag(name)) if err != nil { return nil, err } return pkix.NewCertificateFromPEM(b) }
go
func GetCertificate(d Depot, name string) (crt *pkix.Certificate, err error) { b, err := d.Get(CrtTag(name)) if err != nil { return nil, err } return pkix.NewCertificateFromPEM(b) }
[ "func", "GetCertificate", "(", "d", "Depot", ",", "name", "string", ")", "(", "crt", "*", "pkix", ".", "Certificate", ",", "err", "error", ")", "{", "b", ",", "err", ":=", "d", ".", "Get", "(", "CrtTag", "(", "name", ")", ")", "\n", "if", "err", ...
// GetCertificate retrieves a certificate file for a given name from the depot
[ "GetCertificate", "retrieves", "a", "certificate", "file", "for", "a", "given", "name", "from", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L82-L88
train
square/certstrap
depot/pkix.go
DeleteCertificate
func DeleteCertificate(d Depot, name string) error { return d.Delete(CrtTag(name)) }
go
func DeleteCertificate(d Depot, name string) error { return d.Delete(CrtTag(name)) }
[ "func", "DeleteCertificate", "(", "d", "Depot", ",", "name", "string", ")", "error", "{", "return", "d", ".", "Delete", "(", "CrtTag", "(", "name", ")", ")", "\n", "}" ]
// DeleteCertificate removes a certificate file for a given name from the depot
[ "DeleteCertificate", "removes", "a", "certificate", "file", "for", "a", "given", "name", "from", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L91-L93
train
square/certstrap
depot/pkix.go
PutCertificateSigningRequest
func PutCertificateSigningRequest(d Depot, name string, csr *pkix.CertificateSigningRequest) error { b, err := csr.Export() if err != nil { return err } return d.Put(CsrTag(name), b) }
go
func PutCertificateSigningRequest(d Depot, name string, csr *pkix.CertificateSigningRequest) error { b, err := csr.Export() if err != nil { return err } return d.Put(CsrTag(name), b) }
[ "func", "PutCertificateSigningRequest", "(", "d", "Depot", ",", "name", "string", ",", "csr", "*", "pkix", ".", "CertificateSigningRequest", ")", "error", "{", "b", ",", "err", ":=", "csr", ".", "Export", "(", ")", "\n", "if", "err", "!=", "nil", "{", ...
// PutCertificateSigningRequest creates a certificate signing request file for a given name and csr in the depot
[ "PutCertificateSigningRequest", "creates", "a", "certificate", "signing", "request", "file", "for", "a", "given", "name", "and", "csr", "in", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L96-L102
train
square/certstrap
depot/pkix.go
CheckCertificateSigningRequest
func CheckCertificateSigningRequest(d Depot, name string) bool { return d.Check(CsrTag(name)) }
go
func CheckCertificateSigningRequest(d Depot, name string) bool { return d.Check(CsrTag(name)) }
[ "func", "CheckCertificateSigningRequest", "(", "d", "Depot", ",", "name", "string", ")", "bool", "{", "return", "d", ".", "Check", "(", "CsrTag", "(", "name", ")", ")", "\n", "}" ]
// CheckCertificateSigningRequest checks the depot for existence of a certificate signing request file for a given host name
[ "CheckCertificateSigningRequest", "checks", "the", "depot", "for", "existence", "of", "a", "certificate", "signing", "request", "file", "for", "a", "given", "host", "name" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L105-L107
train
square/certstrap
depot/pkix.go
GetCertificateSigningRequest
func GetCertificateSigningRequest(d Depot, name string) (crt *pkix.CertificateSigningRequest, err error) { b, err := d.Get(CsrTag(name)) if err != nil { return nil, err } return pkix.NewCertificateSigningRequestFromPEM(b) }
go
func GetCertificateSigningRequest(d Depot, name string) (crt *pkix.CertificateSigningRequest, err error) { b, err := d.Get(CsrTag(name)) if err != nil { return nil, err } return pkix.NewCertificateSigningRequestFromPEM(b) }
[ "func", "GetCertificateSigningRequest", "(", "d", "Depot", ",", "name", "string", ")", "(", "crt", "*", "pkix", ".", "CertificateSigningRequest", ",", "err", "error", ")", "{", "b", ",", "err", ":=", "d", ".", "Get", "(", "CsrTag", "(", "name", ")", ")...
// GetCertificateSigningRequest retrieves a certificate signing request file for a given host name from the depot
[ "GetCertificateSigningRequest", "retrieves", "a", "certificate", "signing", "request", "file", "for", "a", "given", "host", "name", "from", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L110-L116
train
square/certstrap
depot/pkix.go
DeleteCertificateSigningRequest
func DeleteCertificateSigningRequest(d Depot, name string) error { return d.Delete(CsrTag(name)) }
go
func DeleteCertificateSigningRequest(d Depot, name string) error { return d.Delete(CsrTag(name)) }
[ "func", "DeleteCertificateSigningRequest", "(", "d", "Depot", ",", "name", "string", ")", "error", "{", "return", "d", ".", "Delete", "(", "CsrTag", "(", "name", ")", ")", "\n", "}" ]
// DeleteCertificateSigningRequest removes a certificate signing request file for a given host name from the depot
[ "DeleteCertificateSigningRequest", "removes", "a", "certificate", "signing", "request", "file", "for", "a", "given", "host", "name", "from", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L119-L121
train
square/certstrap
depot/pkix.go
PutPrivateKey
func PutPrivateKey(d Depot, name string, key *pkix.Key) error { b, err := key.ExportPrivate() if err != nil { return err } return d.Put(PrivKeyTag(name), b) }
go
func PutPrivateKey(d Depot, name string, key *pkix.Key) error { b, err := key.ExportPrivate() if err != nil { return err } return d.Put(PrivKeyTag(name), b) }
[ "func", "PutPrivateKey", "(", "d", "Depot", ",", "name", "string", ",", "key", "*", "pkix", ".", "Key", ")", "error", "{", "b", ",", "err", ":=", "key", ".", "ExportPrivate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "...
// PutPrivateKey creates a private key file for a given name in the depot
[ "PutPrivateKey", "creates", "a", "private", "key", "file", "for", "a", "given", "name", "in", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L124-L130
train
square/certstrap
depot/pkix.go
CheckPrivateKey
func CheckPrivateKey(d Depot, name string) bool { return d.Check(PrivKeyTag(name)) }
go
func CheckPrivateKey(d Depot, name string) bool { return d.Check(PrivKeyTag(name)) }
[ "func", "CheckPrivateKey", "(", "d", "Depot", ",", "name", "string", ")", "bool", "{", "return", "d", ".", "Check", "(", "PrivKeyTag", "(", "name", ")", ")", "\n", "}" ]
// CheckPrivateKey checks the depot for existence of a private key file for a given name
[ "CheckPrivateKey", "checks", "the", "depot", "for", "existence", "of", "a", "private", "key", "file", "for", "a", "given", "name" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L133-L135
train
square/certstrap
depot/pkix.go
GetPrivateKey
func GetPrivateKey(d Depot, name string) (key *pkix.Key, err error) { b, err := d.Get(PrivKeyTag(name)) if err != nil { return nil, err } return pkix.NewKeyFromPrivateKeyPEM(b) }
go
func GetPrivateKey(d Depot, name string) (key *pkix.Key, err error) { b, err := d.Get(PrivKeyTag(name)) if err != nil { return nil, err } return pkix.NewKeyFromPrivateKeyPEM(b) }
[ "func", "GetPrivateKey", "(", "d", "Depot", ",", "name", "string", ")", "(", "key", "*", "pkix", ".", "Key", ",", "err", "error", ")", "{", "b", ",", "err", ":=", "d", ".", "Get", "(", "PrivKeyTag", "(", "name", ")", ")", "\n", "if", "err", "!=...
// GetPrivateKey retrieves a private key file for a given name from the depot
[ "GetPrivateKey", "retrieves", "a", "private", "key", "file", "for", "a", "given", "name", "from", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L138-L144
train
square/certstrap
depot/pkix.go
PutEncryptedPrivateKey
func PutEncryptedPrivateKey(d Depot, name string, key *pkix.Key, passphrase []byte) error { b, err := key.ExportEncryptedPrivate(passphrase) if err != nil { return err } return d.Put(PrivKeyTag(name), b) }
go
func PutEncryptedPrivateKey(d Depot, name string, key *pkix.Key, passphrase []byte) error { b, err := key.ExportEncryptedPrivate(passphrase) if err != nil { return err } return d.Put(PrivKeyTag(name), b) }
[ "func", "PutEncryptedPrivateKey", "(", "d", "Depot", ",", "name", "string", ",", "key", "*", "pkix", ".", "Key", ",", "passphrase", "[", "]", "byte", ")", "error", "{", "b", ",", "err", ":=", "key", ".", "ExportEncryptedPrivate", "(", "passphrase", ")", ...
// PutEncryptedPrivateKey creates an encrypted private key file for a given name in the depot
[ "PutEncryptedPrivateKey", "creates", "an", "encrypted", "private", "key", "file", "for", "a", "given", "name", "in", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L147-L153
train
square/certstrap
depot/pkix.go
GetEncryptedPrivateKey
func GetEncryptedPrivateKey(d Depot, name string, passphrase []byte) (key *pkix.Key, err error) { b, err := d.Get(PrivKeyTag(name)) if err != nil { return nil, err } return pkix.NewKeyFromEncryptedPrivateKeyPEM(b, passphrase) }
go
func GetEncryptedPrivateKey(d Depot, name string, passphrase []byte) (key *pkix.Key, err error) { b, err := d.Get(PrivKeyTag(name)) if err != nil { return nil, err } return pkix.NewKeyFromEncryptedPrivateKeyPEM(b, passphrase) }
[ "func", "GetEncryptedPrivateKey", "(", "d", "Depot", ",", "name", "string", ",", "passphrase", "[", "]", "byte", ")", "(", "key", "*", "pkix", ".", "Key", ",", "err", "error", ")", "{", "b", ",", "err", ":=", "d", ".", "Get", "(", "PrivKeyTag", "("...
// GetEncryptedPrivateKey retrieves an encrypted private key file for a given name from the depot
[ "GetEncryptedPrivateKey", "retrieves", "an", "encrypted", "private", "key", "file", "for", "a", "given", "name", "from", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L156-L162
train
square/certstrap
depot/pkix.go
PutCertificateRevocationList
func PutCertificateRevocationList(d Depot, name string, crl *pkix.CertificateRevocationList) error { b, err := crl.Export() if err != nil { return err } return d.Put(CrlTag(name), b) }
go
func PutCertificateRevocationList(d Depot, name string, crl *pkix.CertificateRevocationList) error { b, err := crl.Export() if err != nil { return err } return d.Put(CrlTag(name), b) }
[ "func", "PutCertificateRevocationList", "(", "d", "Depot", ",", "name", "string", ",", "crl", "*", "pkix", ".", "CertificateRevocationList", ")", "error", "{", "b", ",", "err", ":=", "crl", ".", "Export", "(", ")", "\n", "if", "err", "!=", "nil", "{", ...
// PutCertificateRevocationList creates a CRL file for a given name and ca in the depot
[ "PutCertificateRevocationList", "creates", "a", "CRL", "file", "for", "a", "given", "name", "and", "ca", "in", "the", "depot" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L165-L171
train
square/certstrap
depot/pkix.go
GetCertificateRevocationList
func GetCertificateRevocationList(d Depot, name string) (*pkix.CertificateRevocationList, error) { b, err := d.Get(CrlTag(name)) if err != nil { return nil, err } return pkix.NewCertificateRevocationListFromPEM(b) }
go
func GetCertificateRevocationList(d Depot, name string) (*pkix.CertificateRevocationList, error) { b, err := d.Get(CrlTag(name)) if err != nil { return nil, err } return pkix.NewCertificateRevocationListFromPEM(b) }
[ "func", "GetCertificateRevocationList", "(", "d", "Depot", ",", "name", "string", ")", "(", "*", "pkix", ".", "CertificateRevocationList", ",", "error", ")", "{", "b", ",", "err", ":=", "d", ".", "Get", "(", "CrlTag", "(", "name", ")", ")", "\n", "if",...
//GetCertificateRevocationList gets a CRL file for a given name and ca in the depot.
[ "GetCertificateRevocationList", "gets", "a", "CRL", "file", "for", "a", "given", "name", "and", "ca", "in", "the", "depot", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/depot/pkix.go#L174-L180
train
square/certstrap
cmd/init.go
NewInitCommand
func NewInitCommand() cli.Command { return cli.Command{ Name: "init", Usage: "Create Certificate Authority", Description: "Create Certificate Authority, including certificate, key and extra information file.", Flags: []cli.Flag{ cli.StringFlag{ Name: "passphrase", Usage: "Passphrase to encrypt private key PEM block", }, cli.IntFlag{ Name: "key-bits", Value: 4096, Usage: "Size (in bits) of RSA keypair to generate (example: 4096)", }, cli.IntFlag{ Name: "years", Hidden: true, }, cli.StringFlag{ Name: "expires", Value: "18 months", Usage: "How long until the certificate expires (example: 1 year 2 days 3 months 4 hours)", }, cli.StringFlag{ Name: "organization, o", Usage: "Sets the Organization (O) field of the certificate", }, cli.StringFlag{ Name: "organizational-unit, ou", Usage: "Sets the Organizational Unit (OU) field of the certificate", }, cli.StringFlag{ Name: "country, c", Usage: "Sets the Country (C) field of the certificate", }, cli.StringFlag{ Name: "common-name, cn", Usage: "Sets the Common Name (CN) field of the certificate", }, cli.StringFlag{ Name: "province, st", Usage: "Sets the State/Province (ST) field of the certificate", }, cli.StringFlag{ Name: "locality, l", Usage: "Sets the Locality (L) field of the certificate", }, cli.StringFlag{ Name: "key", Usage: "Path to private key PEM file (if blank, will generate new key pair)", }, cli.BoolFlag{ Name: "stdout", Usage: "Print certificate to stdout in addition to saving file", }, }, Action: initAction, } }
go
func NewInitCommand() cli.Command { return cli.Command{ Name: "init", Usage: "Create Certificate Authority", Description: "Create Certificate Authority, including certificate, key and extra information file.", Flags: []cli.Flag{ cli.StringFlag{ Name: "passphrase", Usage: "Passphrase to encrypt private key PEM block", }, cli.IntFlag{ Name: "key-bits", Value: 4096, Usage: "Size (in bits) of RSA keypair to generate (example: 4096)", }, cli.IntFlag{ Name: "years", Hidden: true, }, cli.StringFlag{ Name: "expires", Value: "18 months", Usage: "How long until the certificate expires (example: 1 year 2 days 3 months 4 hours)", }, cli.StringFlag{ Name: "organization, o", Usage: "Sets the Organization (O) field of the certificate", }, cli.StringFlag{ Name: "organizational-unit, ou", Usage: "Sets the Organizational Unit (OU) field of the certificate", }, cli.StringFlag{ Name: "country, c", Usage: "Sets the Country (C) field of the certificate", }, cli.StringFlag{ Name: "common-name, cn", Usage: "Sets the Common Name (CN) field of the certificate", }, cli.StringFlag{ Name: "province, st", Usage: "Sets the State/Province (ST) field of the certificate", }, cli.StringFlag{ Name: "locality, l", Usage: "Sets the Locality (L) field of the certificate", }, cli.StringFlag{ Name: "key", Usage: "Path to private key PEM file (if blank, will generate new key pair)", }, cli.BoolFlag{ Name: "stdout", Usage: "Print certificate to stdout in addition to saving file", }, }, Action: initAction, } }
[ "func", "NewInitCommand", "(", ")", "cli", ".", "Command", "{", "return", "cli", ".", "Command", "{", "Name", ":", "\"", "\"", ",", "Usage", ":", "\"", "\"", ",", "Description", ":", "\"", "\"", ",", "Flags", ":", "[", "]", "cli", ".", "Flag", "{...
// NewInitCommand sets up an "init" command to initialize a new CA
[ "NewInitCommand", "sets", "up", "an", "init", "command", "to", "initialize", "a", "new", "CA" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/cmd/init.go#L32-L91
train
square/certstrap
pkix/cert_info.go
NewCertificateAuthorityInfoFromJSON
func NewCertificateAuthorityInfoFromJSON(data []byte) (*CertificateAuthorityInfo, error) { i := big.NewInt(0) if err := i.UnmarshalJSON(data); err != nil { return nil, err } return &CertificateAuthorityInfo{i}, nil }
go
func NewCertificateAuthorityInfoFromJSON(data []byte) (*CertificateAuthorityInfo, error) { i := big.NewInt(0) if err := i.UnmarshalJSON(data); err != nil { return nil, err } return &CertificateAuthorityInfo{i}, nil }
[ "func", "NewCertificateAuthorityInfoFromJSON", "(", "data", "[", "]", "byte", ")", "(", "*", "CertificateAuthorityInfo", ",", "error", ")", "{", "i", ":=", "big", ".", "NewInt", "(", "0", ")", "\n\n", "if", "err", ":=", "i", ".", "UnmarshalJSON", "(", "d...
// NewCertificateAuthorityInfoFromJSON creates a new CertifaceAuthorityInfo with the given JSON information
[ "NewCertificateAuthorityInfoFromJSON", "creates", "a", "new", "CertifaceAuthorityInfo", "with", "the", "given", "JSON", "information" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert_info.go#L37-L45
train
square/certstrap
pkix/cert_info.go
IncSerialNumber
func (n *CertificateAuthorityInfo) IncSerialNumber() { n.SerialNumber.Add(n.SerialNumber, big.NewInt(1)) }
go
func (n *CertificateAuthorityInfo) IncSerialNumber() { n.SerialNumber.Add(n.SerialNumber, big.NewInt(1)) }
[ "func", "(", "n", "*", "CertificateAuthorityInfo", ")", "IncSerialNumber", "(", ")", "{", "n", ".", "SerialNumber", ".", "Add", "(", "n", ".", "SerialNumber", ",", "big", ".", "NewInt", "(", "1", ")", ")", "\n", "}" ]
// IncSerialNumber increments the given CA Info's serial number
[ "IncSerialNumber", "increments", "the", "given", "CA", "Info", "s", "serial", "number" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert_info.go#L48-L50
train
square/certstrap
pkix/key.go
CreateRSAKey
func CreateRSAKey(rsaBits int) (*Key, error) { priv, err := rsa.GenerateKey(rand.Reader, rsaBits) if err != nil { return nil, err } return NewKey(&priv.PublicKey, priv), nil }
go
func CreateRSAKey(rsaBits int) (*Key, error) { priv, err := rsa.GenerateKey(rand.Reader, rsaBits) if err != nil { return nil, err } return NewKey(&priv.PublicKey, priv), nil }
[ "func", "CreateRSAKey", "(", "rsaBits", "int", ")", "(", "*", "Key", ",", "error", ")", "{", "priv", ",", "err", ":=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "rsaBits", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil",...
// CreateRSAKey creates a new Key using RSA algorithm
[ "CreateRSAKey", "creates", "a", "new", "Key", "using", "RSA", "algorithm" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/key.go#L38-L45
train
square/certstrap
pkix/key.go
NewKey
func NewKey(pub crypto.PublicKey, priv crypto.PrivateKey) *Key { return &Key{Public: pub, Private: priv} }
go
func NewKey(pub crypto.PublicKey, priv crypto.PrivateKey) *Key { return &Key{Public: pub, Private: priv} }
[ "func", "NewKey", "(", "pub", "crypto", ".", "PublicKey", ",", "priv", "crypto", ".", "PrivateKey", ")", "*", "Key", "{", "return", "&", "Key", "{", "Public", ":", "pub", ",", "Private", ":", "priv", "}", "\n", "}" ]
// NewKey returns a new public-private keypair Key type
[ "NewKey", "returns", "a", "new", "public", "-", "private", "keypair", "Key", "type" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/key.go#L54-L56
train
square/certstrap
pkix/key.go
NewKeyFromPrivateKeyPEM
func NewKeyFromPrivateKeyPEM(data []byte) (*Key, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if pemBlock.Type != rsaPrivateKeyPEMBlockType || len(pemBlock.Headers) != 0 { return nil, errors.New("unmatched type or headers") } priv, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes) if err != nil { return nil, err } return NewKey(&priv.PublicKey, priv), nil }
go
func NewKeyFromPrivateKeyPEM(data []byte) (*Key, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if pemBlock.Type != rsaPrivateKeyPEMBlockType || len(pemBlock.Headers) != 0 { return nil, errors.New("unmatched type or headers") } priv, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes) if err != nil { return nil, err } return NewKey(&priv.PublicKey, priv), nil }
[ "func", "NewKeyFromPrivateKeyPEM", "(", "data", "[", "]", "byte", ")", "(", "*", "Key", ",", "error", ")", "{", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "data", ")", "\n", "if", "pemBlock", "==", "nil", "{", "return", "nil", ",", "err...
// NewKeyFromPrivateKeyPEM inits Key from PEM-format rsa private key bytes
[ "NewKeyFromPrivateKeyPEM", "inits", "Key", "from", "PEM", "-", "format", "rsa", "private", "key", "bytes" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/key.go#L59-L74
train
square/certstrap
pkix/key.go
NewKeyFromEncryptedPrivateKeyPEM
func NewKeyFromEncryptedPrivateKeyPEM(data []byte, password []byte) (*Key, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if pemBlock.Type != rsaPrivateKeyPEMBlockType { return nil, errors.New("unmatched type or headers") } b, err := x509.DecryptPEMBlock(pemBlock, password) if err != nil { return nil, err } priv, err := x509.ParsePKCS1PrivateKey(b) if err != nil { return nil, err } return NewKey(&priv.PublicKey, priv), nil }
go
func NewKeyFromEncryptedPrivateKeyPEM(data []byte, password []byte) (*Key, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if pemBlock.Type != rsaPrivateKeyPEMBlockType { return nil, errors.New("unmatched type or headers") } b, err := x509.DecryptPEMBlock(pemBlock, password) if err != nil { return nil, err } priv, err := x509.ParsePKCS1PrivateKey(b) if err != nil { return nil, err } return NewKey(&priv.PublicKey, priv), nil }
[ "func", "NewKeyFromEncryptedPrivateKeyPEM", "(", "data", "[", "]", "byte", ",", "password", "[", "]", "byte", ")", "(", "*", "Key", ",", "error", ")", "{", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "data", ")", "\n", "if", "pemBlock", "=...
// NewKeyFromEncryptedPrivateKeyPEM inits Key from encrypted PEM-format rsa private key bytes
[ "NewKeyFromEncryptedPrivateKeyPEM", "inits", "Key", "from", "encrypted", "PEM", "-", "format", "rsa", "private", "key", "bytes" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/key.go#L77-L97
train
square/certstrap
pkix/key.go
ExportPrivate
func (k *Key) ExportPrivate() ([]byte, error) { var privPEMBlock *pem.Block switch priv := k.Private.(type) { case *rsa.PrivateKey: privBytes := x509.MarshalPKCS1PrivateKey(priv) privPEMBlock = &pem.Block{ Type: rsaPrivateKeyPEMBlockType, Bytes: privBytes, } default: return nil, errors.New("only RSA private key is supported") } buf := new(bytes.Buffer) if err := pem.Encode(buf, privPEMBlock); err != nil { return nil, err } return buf.Bytes(), nil }
go
func (k *Key) ExportPrivate() ([]byte, error) { var privPEMBlock *pem.Block switch priv := k.Private.(type) { case *rsa.PrivateKey: privBytes := x509.MarshalPKCS1PrivateKey(priv) privPEMBlock = &pem.Block{ Type: rsaPrivateKeyPEMBlockType, Bytes: privBytes, } default: return nil, errors.New("only RSA private key is supported") } buf := new(bytes.Buffer) if err := pem.Encode(buf, privPEMBlock); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "k", "*", "Key", ")", "ExportPrivate", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "privPEMBlock", "*", "pem", ".", "Block", "\n", "switch", "priv", ":=", "k", ".", "Private", ".", "(", "type", ")", "{", "case", ...
// ExportPrivate exports PEM-format private key
[ "ExportPrivate", "exports", "PEM", "-", "format", "private", "key" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/key.go#L100-L118
train
square/certstrap
pkix/key.go
ExportEncryptedPrivate
func (k *Key) ExportEncryptedPrivate(password []byte) ([]byte, error) { var privBytes []byte switch priv := k.Private.(type) { case *rsa.PrivateKey: privBytes = x509.MarshalPKCS1PrivateKey(priv) default: return nil, errors.New("only RSA private key is supported") } privPEMBlock, err := x509.EncryptPEMBlock(rand.Reader, rsaPrivateKeyPEMBlockType, privBytes, password, x509.PEMCipher3DES) if err != nil { return nil, err } buf := new(bytes.Buffer) if err := pem.Encode(buf, privPEMBlock); err != nil { return nil, err } return buf.Bytes(), nil }
go
func (k *Key) ExportEncryptedPrivate(password []byte) ([]byte, error) { var privBytes []byte switch priv := k.Private.(type) { case *rsa.PrivateKey: privBytes = x509.MarshalPKCS1PrivateKey(priv) default: return nil, errors.New("only RSA private key is supported") } privPEMBlock, err := x509.EncryptPEMBlock(rand.Reader, rsaPrivateKeyPEMBlockType, privBytes, password, x509.PEMCipher3DES) if err != nil { return nil, err } buf := new(bytes.Buffer) if err := pem.Encode(buf, privPEMBlock); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "k", "*", "Key", ")", "ExportEncryptedPrivate", "(", "password", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "privBytes", "[", "]", "byte", "\n", "switch", "priv", ":=", "k", ".", "Private", ".", "(", ...
// ExportEncryptedPrivate exports encrypted PEM-format private key
[ "ExportEncryptedPrivate", "exports", "encrypted", "PEM", "-", "format", "private", "key" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/key.go#L121-L140
train
square/certstrap
pkix/key.go
GenerateSubjectKeyID
func GenerateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) { var pubBytes []byte var err error switch pub := pub.(type) { case *rsa.PublicKey: pubBytes, err = asn1.Marshal(rsaPublicKey{ N: pub.N, E: pub.E, }) if err != nil { return nil, err } default: return nil, errors.New("only RSA public key is supported") } hash := sha1.Sum(pubBytes) return hash[:], nil }
go
func GenerateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) { var pubBytes []byte var err error switch pub := pub.(type) { case *rsa.PublicKey: pubBytes, err = asn1.Marshal(rsaPublicKey{ N: pub.N, E: pub.E, }) if err != nil { return nil, err } default: return nil, errors.New("only RSA public key is supported") } hash := sha1.Sum(pubBytes) return hash[:], nil }
[ "func", "GenerateSubjectKeyID", "(", "pub", "crypto", ".", "PublicKey", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "pubBytes", "[", "]", "byte", "\n", "var", "err", "error", "\n", "switch", "pub", ":=", "pub", ".", "(", "type", ")", ...
// GenerateSubjectKeyID generates SubjectKeyId used in Certificate // Id is 160-bit SHA-1 hash of the value of the BIT STRING subjectPublicKey
[ "GenerateSubjectKeyID", "generates", "SubjectKeyId", "used", "in", "Certificate", "Id", "is", "160", "-", "bit", "SHA", "-", "1", "hash", "of", "the", "value", "of", "the", "BIT", "STRING", "subjectPublicKey" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/key.go#L150-L169
train
square/certstrap
pkix/csr.go
ParseAndValidateIPs
func ParseAndValidateIPs(ipList string) (res []net.IP, err error) { // IP list can potentially be a blank string, "" if len(ipList) > 0 { ips := strings.Split(ipList, ",") for _, ip := range ips { parsedIP := net.ParseIP(ip) if parsedIP == nil { return nil, fmt.Errorf("Invalid IP address: %s", ip) } res = append(res, parsedIP) } } return }
go
func ParseAndValidateIPs(ipList string) (res []net.IP, err error) { // IP list can potentially be a blank string, "" if len(ipList) > 0 { ips := strings.Split(ipList, ",") for _, ip := range ips { parsedIP := net.ParseIP(ip) if parsedIP == nil { return nil, fmt.Errorf("Invalid IP address: %s", ip) } res = append(res, parsedIP) } } return }
[ "func", "ParseAndValidateIPs", "(", "ipList", "string", ")", "(", "res", "[", "]", "net", ".", "IP", ",", "err", "error", ")", "{", "// IP list can potentially be a blank string, \"\"", "if", "len", "(", "ipList", ")", ">", "0", "{", "ips", ":=", "strings", ...
// ParseAndValidateIPs parses a comma-delimited list of IP addresses into an array of IP addresses
[ "ParseAndValidateIPs", "parses", "a", "comma", "-", "delimited", "list", "of", "IP", "addresses", "into", "an", "array", "of", "IP", "addresses" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L58-L71
train
square/certstrap
pkix/csr.go
ParseAndValidateURIs
func ParseAndValidateURIs(uriList string) (res []*url.URL, err error) { if len(uriList) > 0 { uris := strings.Split(uriList, ",") for _, uri := range uris { parsedURI, err := url.Parse(uri) if err != nil { parsedURI = nil } if parsedURI == nil { return nil, fmt.Errorf("Invalid URI: %s", uri) } if !parsedURI.IsAbs() { return nil, fmt.Errorf("Invalid URI: %s", uri) } res = append(res, parsedURI) } } return }
go
func ParseAndValidateURIs(uriList string) (res []*url.URL, err error) { if len(uriList) > 0 { uris := strings.Split(uriList, ",") for _, uri := range uris { parsedURI, err := url.Parse(uri) if err != nil { parsedURI = nil } if parsedURI == nil { return nil, fmt.Errorf("Invalid URI: %s", uri) } if !parsedURI.IsAbs() { return nil, fmt.Errorf("Invalid URI: %s", uri) } res = append(res, parsedURI) } } return }
[ "func", "ParseAndValidateURIs", "(", "uriList", "string", ")", "(", "res", "[", "]", "*", "url", ".", "URL", ",", "err", "error", ")", "{", "if", "len", "(", "uriList", ")", ">", "0", "{", "uris", ":=", "strings", ".", "Split", "(", "uriList", ",",...
// ParseAndValidateURIs parses a comma-delimited list of URIs into an array of url.URLs
[ "ParseAndValidateURIs", "parses", "a", "comma", "-", "delimited", "list", "of", "URIs", "into", "an", "array", "of", "url", ".", "URLs" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L74-L92
train
square/certstrap
pkix/csr.go
CreateCertificateSigningRequest
func CreateCertificateSigningRequest(key *Key, organizationalUnit string, ipList []net.IP, domainList []string, uriList []*url.URL, organization string, country string, province string, locality string, commonName string) (*CertificateSigningRequest, error) { csrPkixName.CommonName = commonName if len(organizationalUnit) > 0 { csrPkixName.OrganizationalUnit = []string{organizationalUnit} } if len(organization) > 0 { csrPkixName.Organization = []string{organization} } if len(country) > 0 { csrPkixName.Country = []string{country} } if len(province) > 0 { csrPkixName.Province = []string{province} } if len(locality) > 0 { csrPkixName.Locality = []string{locality} } csrTemplate := &x509.CertificateRequest{ Subject: csrPkixName, IPAddresses: ipList, DNSNames: domainList, URIs: uriList, } csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, key.Private) if err != nil { return nil, err } return NewCertificateSigningRequestFromDER(csrBytes), nil }
go
func CreateCertificateSigningRequest(key *Key, organizationalUnit string, ipList []net.IP, domainList []string, uriList []*url.URL, organization string, country string, province string, locality string, commonName string) (*CertificateSigningRequest, error) { csrPkixName.CommonName = commonName if len(organizationalUnit) > 0 { csrPkixName.OrganizationalUnit = []string{organizationalUnit} } if len(organization) > 0 { csrPkixName.Organization = []string{organization} } if len(country) > 0 { csrPkixName.Country = []string{country} } if len(province) > 0 { csrPkixName.Province = []string{province} } if len(locality) > 0 { csrPkixName.Locality = []string{locality} } csrTemplate := &x509.CertificateRequest{ Subject: csrPkixName, IPAddresses: ipList, DNSNames: domainList, URIs: uriList, } csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, key.Private) if err != nil { return nil, err } return NewCertificateSigningRequestFromDER(csrBytes), nil }
[ "func", "CreateCertificateSigningRequest", "(", "key", "*", "Key", ",", "organizationalUnit", "string", ",", "ipList", "[", "]", "net", ".", "IP", ",", "domainList", "[", "]", "string", ",", "uriList", "[", "]", "*", "url", ".", "URL", ",", "organization",...
// CreateCertificateSigningRequest sets up a request to create a csr file with the given parameters
[ "CreateCertificateSigningRequest", "sets", "up", "a", "request", "to", "create", "a", "csr", "file", "with", "the", "given", "parameters" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L95-L126
train
square/certstrap
pkix/csr.go
NewCertificateSigningRequestFromPEM
func NewCertificateSigningRequestFromPEM(data []byte) (*CertificateSigningRequest, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if (pemBlock.Type != csrPEMBlockType && pemBlock.Type != oldCsrPEMBlockType) || len(pemBlock.Headers) != 0 { return nil, errors.New("unmatched type or headers") } return &CertificateSigningRequest{derBytes: pemBlock.Bytes}, nil }
go
func NewCertificateSigningRequestFromPEM(data []byte) (*CertificateSigningRequest, error) { pemBlock, _ := pem.Decode(data) if pemBlock == nil { return nil, errors.New("cannot find the next PEM formatted block") } if (pemBlock.Type != csrPEMBlockType && pemBlock.Type != oldCsrPEMBlockType) || len(pemBlock.Headers) != 0 { return nil, errors.New("unmatched type or headers") } return &CertificateSigningRequest{derBytes: pemBlock.Bytes}, nil }
[ "func", "NewCertificateSigningRequestFromPEM", "(", "data", "[", "]", "byte", ")", "(", "*", "CertificateSigningRequest", ",", "error", ")", "{", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "data", ")", "\n", "if", "pemBlock", "==", "nil", "{", ...
// NewCertificateSigningRequestFromPEM inits CertificateSigningRequest from PEM-format bytes // data should contain at most one certificate
[ "NewCertificateSigningRequestFromPEM", "inits", "CertificateSigningRequest", "from", "PEM", "-", "format", "bytes", "data", "should", "contain", "at", "most", "one", "certificate" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L143-L152
train
square/certstrap
pkix/csr.go
buildPKCS10CertificateSigningRequest
func (c *CertificateSigningRequest) buildPKCS10CertificateSigningRequest() error { if c.cr != nil { return nil } var err error c.cr, err = x509.ParseCertificateRequest(c.derBytes) if err != nil { return err } return nil }
go
func (c *CertificateSigningRequest) buildPKCS10CertificateSigningRequest() error { if c.cr != nil { return nil } var err error c.cr, err = x509.ParseCertificateRequest(c.derBytes) if err != nil { return err } return nil }
[ "func", "(", "c", "*", "CertificateSigningRequest", ")", "buildPKCS10CertificateSigningRequest", "(", ")", "error", "{", "if", "c", ".", "cr", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "err", "error", "\n", "c", ".", "cr", ",", "err", ...
// build cr field if needed
[ "build", "cr", "field", "if", "needed" ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L155-L166
train
square/certstrap
pkix/csr.go
GetRawCertificateSigningRequest
func (c *CertificateSigningRequest) GetRawCertificateSigningRequest() (*x509.CertificateRequest, error) { if err := c.buildPKCS10CertificateSigningRequest(); err != nil { return nil, err } return c.cr, nil }
go
func (c *CertificateSigningRequest) GetRawCertificateSigningRequest() (*x509.CertificateRequest, error) { if err := c.buildPKCS10CertificateSigningRequest(); err != nil { return nil, err } return c.cr, nil }
[ "func", "(", "c", "*", "CertificateSigningRequest", ")", "GetRawCertificateSigningRequest", "(", ")", "(", "*", "x509", ".", "CertificateRequest", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "buildPKCS10CertificateSigningRequest", "(", ")", ";", "err", ...
// GetRawCertificateSigningRequest returns a copy of this certificate request as an x509.CertificateRequest.
[ "GetRawCertificateSigningRequest", "returns", "a", "copy", "of", "this", "certificate", "request", "as", "an", "x509", ".", "CertificateRequest", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L169-L174
train
square/certstrap
pkix/csr.go
CheckSignature
func (c *CertificateSigningRequest) CheckSignature() error { if err := c.buildPKCS10CertificateSigningRequest(); err != nil { return err } return checkSignature(c.cr, c.cr.SignatureAlgorithm, c.cr.RawTBSCertificateRequest, c.cr.Signature) }
go
func (c *CertificateSigningRequest) CheckSignature() error { if err := c.buildPKCS10CertificateSigningRequest(); err != nil { return err } return checkSignature(c.cr, c.cr.SignatureAlgorithm, c.cr.RawTBSCertificateRequest, c.cr.Signature) }
[ "func", "(", "c", "*", "CertificateSigningRequest", ")", "CheckSignature", "(", ")", "error", "{", "if", "err", ":=", "c", ".", "buildPKCS10CertificateSigningRequest", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "che...
// CheckSignature verifies that the signature is a valid signature // using the public key in CertificateSigningRequest.
[ "CheckSignature", "verifies", "that", "the", "signature", "is", "a", "valid", "signature", "using", "the", "public", "key", "in", "CertificateSigningRequest", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L178-L183
train
square/certstrap
pkix/csr.go
checkSignature
func checkSignature(csr *x509.CertificateRequest, algo x509.SignatureAlgorithm, signed, signature []byte) error { var hashType crypto.Hash switch algo { case x509.SHA1WithRSA, x509.ECDSAWithSHA1: hashType = crypto.SHA1 case x509.SHA256WithRSA, x509.ECDSAWithSHA256: hashType = crypto.SHA256 case x509.SHA384WithRSA, x509.ECDSAWithSHA384: hashType = crypto.SHA384 case x509.SHA512WithRSA, x509.ECDSAWithSHA512: hashType = crypto.SHA512 default: return x509.ErrUnsupportedAlgorithm } if !hashType.Available() { return x509.ErrUnsupportedAlgorithm } h := hashType.New() h.Write(signed) digest := h.Sum(nil) switch pub := csr.PublicKey.(type) { case *rsa.PublicKey: return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) case *ecdsa.PublicKey: ecdsaSig := new(struct{ R, S *big.Int }) if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { return err } if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { return errors.New("x509: ECDSA signature contained zero or negative values") } if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { return errors.New("x509: ECDSA verification failure") } return nil } return x509.ErrUnsupportedAlgorithm }
go
func checkSignature(csr *x509.CertificateRequest, algo x509.SignatureAlgorithm, signed, signature []byte) error { var hashType crypto.Hash switch algo { case x509.SHA1WithRSA, x509.ECDSAWithSHA1: hashType = crypto.SHA1 case x509.SHA256WithRSA, x509.ECDSAWithSHA256: hashType = crypto.SHA256 case x509.SHA384WithRSA, x509.ECDSAWithSHA384: hashType = crypto.SHA384 case x509.SHA512WithRSA, x509.ECDSAWithSHA512: hashType = crypto.SHA512 default: return x509.ErrUnsupportedAlgorithm } if !hashType.Available() { return x509.ErrUnsupportedAlgorithm } h := hashType.New() h.Write(signed) digest := h.Sum(nil) switch pub := csr.PublicKey.(type) { case *rsa.PublicKey: return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) case *ecdsa.PublicKey: ecdsaSig := new(struct{ R, S *big.Int }) if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { return err } if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { return errors.New("x509: ECDSA signature contained zero or negative values") } if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { return errors.New("x509: ECDSA verification failure") } return nil } return x509.ErrUnsupportedAlgorithm }
[ "func", "checkSignature", "(", "csr", "*", "x509", ".", "CertificateRequest", ",", "algo", "x509", ".", "SignatureAlgorithm", ",", "signed", ",", "signature", "[", "]", "byte", ")", "error", "{", "var", "hashType", "crypto", ".", "Hash", "\n", "switch", "a...
// checkSignature verifies a signature made by the key on a CSR, such // as on the CSR itself.
[ "checkSignature", "verifies", "a", "signature", "made", "by", "the", "key", "on", "a", "CSR", "such", "as", "on", "the", "CSR", "itself", "." ]
350df15b3713d535548735ea754726228b00c742
https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L187-L224
train
rylio/ytdl
video_info.go
GetVideoInfo
func GetVideoInfo(value interface{}) (*VideoInfo, error) { switch t := value.(type) { case *url.URL: return GetVideoInfoFromURL(t) case string: u, err := url.ParseRequestURI(t) if err != nil { return GetVideoInfoFromID(t) } if u.Host == "youtu.be" { return GetVideoInfoFromShortURL(u) } return GetVideoInfoFromURL(u) default: return nil, fmt.Errorf("Identifier type must be a string, *url.URL, or []byte") } }
go
func GetVideoInfo(value interface{}) (*VideoInfo, error) { switch t := value.(type) { case *url.URL: return GetVideoInfoFromURL(t) case string: u, err := url.ParseRequestURI(t) if err != nil { return GetVideoInfoFromID(t) } if u.Host == "youtu.be" { return GetVideoInfoFromShortURL(u) } return GetVideoInfoFromURL(u) default: return nil, fmt.Errorf("Identifier type must be a string, *url.URL, or []byte") } }
[ "func", "GetVideoInfo", "(", "value", "interface", "{", "}", ")", "(", "*", "VideoInfo", ",", "error", ")", "{", "switch", "t", ":=", "value", ".", "(", "type", ")", "{", "case", "*", "url", ".", "URL", ":", "return", "GetVideoInfoFromURL", "(", "t",...
// GetVideoInfo fetches info from a url string, url object, or a url string
[ "GetVideoInfo", "fetches", "info", "from", "a", "url", "string", "url", "object", "or", "a", "url", "string" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/video_info.go#L51-L67
train
rylio/ytdl
video_info.go
GetVideoInfoFromURL
func GetVideoInfoFromURL(u *url.URL) (*VideoInfo, error) { videoID := u.Query().Get("v") if len(videoID) == 0 { return nil, fmt.Errorf("Invalid youtube url, no video id") } return GetVideoInfoFromID(videoID) }
go
func GetVideoInfoFromURL(u *url.URL) (*VideoInfo, error) { videoID := u.Query().Get("v") if len(videoID) == 0 { return nil, fmt.Errorf("Invalid youtube url, no video id") } return GetVideoInfoFromID(videoID) }
[ "func", "GetVideoInfoFromURL", "(", "u", "*", "url", ".", "URL", ")", "(", "*", "VideoInfo", ",", "error", ")", "{", "videoID", ":=", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "len", "(", "videoID", ")", "==", "...
// GetVideoInfoFromURL fetches video info from a youtube url
[ "GetVideoInfoFromURL", "fetches", "video", "info", "from", "a", "youtube", "url" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/video_info.go#L70-L76
train
rylio/ytdl
video_info.go
GetVideoInfoFromShortURL
func GetVideoInfoFromShortURL(u *url.URL) (*VideoInfo, error) { if len(u.Path) >= 1 { if path := u.Path[1:]; path != "" { return GetVideoInfoFromID(path) } } return nil, errors.New("Could not parse short URL") }
go
func GetVideoInfoFromShortURL(u *url.URL) (*VideoInfo, error) { if len(u.Path) >= 1 { if path := u.Path[1:]; path != "" { return GetVideoInfoFromID(path) } } return nil, errors.New("Could not parse short URL") }
[ "func", "GetVideoInfoFromShortURL", "(", "u", "*", "url", ".", "URL", ")", "(", "*", "VideoInfo", ",", "error", ")", "{", "if", "len", "(", "u", ".", "Path", ")", ">=", "1", "{", "if", "path", ":=", "u", ".", "Path", "[", "1", ":", "]", ";", ...
// GetVideoInfoFromShortURL fetches video info from a short youtube url
[ "GetVideoInfoFromShortURL", "fetches", "video", "info", "from", "a", "short", "youtube", "url" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/video_info.go#L79-L86
train
rylio/ytdl
video_info.go
GetVideoInfoFromID
func GetVideoInfoFromID(id string) (*VideoInfo, error) { u, _ := url.ParseRequestURI(youtubeBaseURL) values := u.Query() values.Set("v", id) u.RawQuery = values.Encode() resp, err := http.Get(u.String()) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, fmt.Errorf("Invalid status code: %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return getVideoInfoFromHTML(id, body) }
go
func GetVideoInfoFromID(id string) (*VideoInfo, error) { u, _ := url.ParseRequestURI(youtubeBaseURL) values := u.Query() values.Set("v", id) u.RawQuery = values.Encode() resp, err := http.Get(u.String()) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, fmt.Errorf("Invalid status code: %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return getVideoInfoFromHTML(id, body) }
[ "func", "GetVideoInfoFromID", "(", "id", "string", ")", "(", "*", "VideoInfo", ",", "error", ")", "{", "u", ",", "_", ":=", "url", ".", "ParseRequestURI", "(", "youtubeBaseURL", ")", "\n", "values", ":=", "u", ".", "Query", "(", ")", "\n", "values", ...
// GetVideoInfoFromID fetches video info from a youtube video id
[ "GetVideoInfoFromID", "fetches", "video", "info", "from", "a", "youtube", "video", "id" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/video_info.go#L89-L108
train
rylio/ytdl
video_info.go
GetDownloadURL
func (info *VideoInfo) GetDownloadURL(format Format) (*url.URL, error) { return getDownloadURL(format, info.htmlPlayerFile) }
go
func (info *VideoInfo) GetDownloadURL(format Format) (*url.URL, error) { return getDownloadURL(format, info.htmlPlayerFile) }
[ "func", "(", "info", "*", "VideoInfo", ")", "GetDownloadURL", "(", "format", "Format", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "return", "getDownloadURL", "(", "format", ",", "info", ".", "htmlPlayerFile", ")", "\n", "}" ]
// GetDownloadURL gets the download url for a format
[ "GetDownloadURL", "gets", "the", "download", "url", "for", "a", "format" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/video_info.go#L111-L113
train
rylio/ytdl
video_info.go
GetThumbnailURL
func (info *VideoInfo) GetThumbnailURL(quality ThumbnailQuality) *url.URL { u, _ := url.Parse(fmt.Sprintf("http://img.youtube.com/vi/%s/%s.jpg", info.ID, quality)) return u }
go
func (info *VideoInfo) GetThumbnailURL(quality ThumbnailQuality) *url.URL { u, _ := url.Parse(fmt.Sprintf("http://img.youtube.com/vi/%s/%s.jpg", info.ID, quality)) return u }
[ "func", "(", "info", "*", "VideoInfo", ")", "GetThumbnailURL", "(", "quality", "ThumbnailQuality", ")", "*", "url", ".", "URL", "{", "u", ",", "_", ":=", "url", ".", "Parse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "info", ".", "ID", ",",...
// GetThumbnailURL returns a url for the thumbnail image // with the given quality
[ "GetThumbnailURL", "returns", "a", "url", "for", "the", "thumbnail", "image", "with", "the", "given", "quality" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/video_info.go#L117-L121
train
rylio/ytdl
video_info.go
Download
func (info *VideoInfo) Download(format Format, dest io.Writer) error { u, err := info.GetDownloadURL(format) if err != nil { return err } resp, err := http.Get(u.String()) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { return fmt.Errorf("Invalid status code: %d", resp.StatusCode) } _, err = io.Copy(dest, resp.Body) return err }
go
func (info *VideoInfo) Download(format Format, dest io.Writer) error { u, err := info.GetDownloadURL(format) if err != nil { return err } resp, err := http.Get(u.String()) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { return fmt.Errorf("Invalid status code: %d", resp.StatusCode) } _, err = io.Copy(dest, resp.Body) return err }
[ "func", "(", "info", "*", "VideoInfo", ")", "Download", "(", "format", "Format", ",", "dest", "io", ".", "Writer", ")", "error", "{", "u", ",", "err", ":=", "info", ".", "GetDownloadURL", "(", "format", ")", "\n", "if", "err", "!=", "nil", "{", "re...
// Download is a convenience method to download a format to an io.Writer
[ "Download", "is", "a", "convenience", "method", "to", "download", "a", "format", "to", "an", "io", ".", "Writer" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/video_info.go#L124-L139
train
rylio/ytdl
format.go
ValueForKey
func (f Format) ValueForKey(key FormatKey) interface{} { switch key { case FormatItagKey: return f.Itag case FormatExtensionKey: return f.Extension case FormatResolutionKey: return f.Resolution case FormatVideoEncodingKey: return f.VideoEncoding case FormatAudioEncodingKey: return f.AudioEncoding case FormatAudioBitrateKey: return f.AudioBitrate default: if f.meta != nil { return f.meta[string(key)] } return nil } }
go
func (f Format) ValueForKey(key FormatKey) interface{} { switch key { case FormatItagKey: return f.Itag case FormatExtensionKey: return f.Extension case FormatResolutionKey: return f.Resolution case FormatVideoEncodingKey: return f.VideoEncoding case FormatAudioEncodingKey: return f.AudioEncoding case FormatAudioBitrateKey: return f.AudioBitrate default: if f.meta != nil { return f.meta[string(key)] } return nil } }
[ "func", "(", "f", "Format", ")", "ValueForKey", "(", "key", "FormatKey", ")", "interface", "{", "}", "{", "switch", "key", "{", "case", "FormatItagKey", ":", "return", "f", ".", "Itag", "\n", "case", "FormatExtensionKey", ":", "return", "f", ".", "Extens...
// ValueForKey gets the format value for a format key, used for filtering
[ "ValueForKey", "gets", "the", "format", "value", "for", "a", "format", "key", "used", "for", "filtering" ]
1f14ef2e151a8f8a1af2f318f518f26ff0980b31
https://github.com/rylio/ytdl/blob/1f14ef2e151a8f8a1af2f318f518f26ff0980b31/format.go#L39-L59
train
mmcdole/gofeed
translator.go
Translate
func (t *DefaultRSSTranslator) Translate(feed interface{}) (*Feed, error) { rss, found := feed.(*rss.Feed) if !found { return nil, fmt.Errorf("Feed did not match expected type of *rss.Feed") } result := &Feed{} result.Title = t.translateFeedTitle(rss) result.Description = t.translateFeedDescription(rss) result.Link = t.translateFeedLink(rss) result.FeedLink = t.translateFeedFeedLink(rss) result.Updated = t.translateFeedUpdated(rss) result.UpdatedParsed = t.translateFeedUpdatedParsed(rss) result.Published = t.translateFeedPublished(rss) result.PublishedParsed = t.translateFeedPublishedParsed(rss) result.Author = t.translateFeedAuthor(rss) result.Language = t.translateFeedLanguage(rss) result.Image = t.translateFeedImage(rss) result.Copyright = t.translateFeedCopyright(rss) result.Generator = t.translateFeedGenerator(rss) result.Categories = t.translateFeedCategories(rss) result.Items = t.translateFeedItems(rss) result.ITunesExt = rss.ITunesExt result.DublinCoreExt = rss.DublinCoreExt result.Extensions = rss.Extensions result.FeedVersion = rss.Version result.FeedType = "rss" return result, nil }
go
func (t *DefaultRSSTranslator) Translate(feed interface{}) (*Feed, error) { rss, found := feed.(*rss.Feed) if !found { return nil, fmt.Errorf("Feed did not match expected type of *rss.Feed") } result := &Feed{} result.Title = t.translateFeedTitle(rss) result.Description = t.translateFeedDescription(rss) result.Link = t.translateFeedLink(rss) result.FeedLink = t.translateFeedFeedLink(rss) result.Updated = t.translateFeedUpdated(rss) result.UpdatedParsed = t.translateFeedUpdatedParsed(rss) result.Published = t.translateFeedPublished(rss) result.PublishedParsed = t.translateFeedPublishedParsed(rss) result.Author = t.translateFeedAuthor(rss) result.Language = t.translateFeedLanguage(rss) result.Image = t.translateFeedImage(rss) result.Copyright = t.translateFeedCopyright(rss) result.Generator = t.translateFeedGenerator(rss) result.Categories = t.translateFeedCategories(rss) result.Items = t.translateFeedItems(rss) result.ITunesExt = rss.ITunesExt result.DublinCoreExt = rss.DublinCoreExt result.Extensions = rss.Extensions result.FeedVersion = rss.Version result.FeedType = "rss" return result, nil }
[ "func", "(", "t", "*", "DefaultRSSTranslator", ")", "Translate", "(", "feed", "interface", "{", "}", ")", "(", "*", "Feed", ",", "error", ")", "{", "rss", ",", "found", ":=", "feed", ".", "(", "*", "rss", ".", "Feed", ")", "\n", "if", "!", "found...
// Translate converts an RSS feed into the universal // feed type.
[ "Translate", "converts", "an", "RSS", "feed", "into", "the", "universal", "feed", "type", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/translator.go#L30-L58
train
mmcdole/gofeed
translator.go
Translate
func (t *DefaultAtomTranslator) Translate(feed interface{}) (*Feed, error) { atom, found := feed.(*atom.Feed) if !found { return nil, fmt.Errorf("Feed did not match expected type of *atom.Feed") } result := &Feed{} result.Title = t.translateFeedTitle(atom) result.Description = t.translateFeedDescription(atom) result.Link = t.translateFeedLink(atom) result.FeedLink = t.translateFeedFeedLink(atom) result.Updated = t.translateFeedUpdated(atom) result.UpdatedParsed = t.translateFeedUpdatedParsed(atom) result.Author = t.translateFeedAuthor(atom) result.Language = t.translateFeedLanguage(atom) result.Image = t.translateFeedImage(atom) result.Copyright = t.translateFeedCopyright(atom) result.Categories = t.translateFeedCategories(atom) result.Generator = t.translateFeedGenerator(atom) result.Items = t.translateFeedItems(atom) result.Extensions = atom.Extensions result.FeedVersion = atom.Version result.FeedType = "atom" return result, nil }
go
func (t *DefaultAtomTranslator) Translate(feed interface{}) (*Feed, error) { atom, found := feed.(*atom.Feed) if !found { return nil, fmt.Errorf("Feed did not match expected type of *atom.Feed") } result := &Feed{} result.Title = t.translateFeedTitle(atom) result.Description = t.translateFeedDescription(atom) result.Link = t.translateFeedLink(atom) result.FeedLink = t.translateFeedFeedLink(atom) result.Updated = t.translateFeedUpdated(atom) result.UpdatedParsed = t.translateFeedUpdatedParsed(atom) result.Author = t.translateFeedAuthor(atom) result.Language = t.translateFeedLanguage(atom) result.Image = t.translateFeedImage(atom) result.Copyright = t.translateFeedCopyright(atom) result.Categories = t.translateFeedCategories(atom) result.Generator = t.translateFeedGenerator(atom) result.Items = t.translateFeedItems(atom) result.Extensions = atom.Extensions result.FeedVersion = atom.Version result.FeedType = "atom" return result, nil }
[ "func", "(", "t", "*", "DefaultAtomTranslator", ")", "Translate", "(", "feed", "interface", "{", "}", ")", "(", "*", "Feed", ",", "error", ")", "{", "atom", ",", "found", ":=", "feed", ".", "(", "*", "atom", ".", "Feed", ")", "\n", "if", "!", "fo...
// Translate converts an Atom feed into the universal // feed type.
[ "Translate", "converts", "an", "Atom", "feed", "into", "the", "universal", "feed", "type", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/translator.go#L440-L464
train
mmcdole/gofeed
internal/shared/xmlsanitizer.go
NewXMLSanitizerReader
func NewXMLSanitizerReader(xml io.Reader) io.Reader { isIllegal := func(r rune) bool { return !(r == 0x09 || r == 0x0A || r == 0x0D || r >= 0x20 && r <= 0xDF77 || r >= 0xE000 && r <= 0xFFFD || r >= 0x10000 && r <= 0x10FFFF) } t := transform.Chain(transform.RemoveFunc(isIllegal)) return transform.NewReader(xml, t) }
go
func NewXMLSanitizerReader(xml io.Reader) io.Reader { isIllegal := func(r rune) bool { return !(r == 0x09 || r == 0x0A || r == 0x0D || r >= 0x20 && r <= 0xDF77 || r >= 0xE000 && r <= 0xFFFD || r >= 0x10000 && r <= 0x10FFFF) } t := transform.Chain(transform.RemoveFunc(isIllegal)) return transform.NewReader(xml, t) }
[ "func", "NewXMLSanitizerReader", "(", "xml", "io", ".", "Reader", ")", "io", ".", "Reader", "{", "isIllegal", ":=", "func", "(", "r", "rune", ")", "bool", "{", "return", "!", "(", "r", "==", "0x09", "||", "r", "==", "0x0A", "||", "r", "==", "0x0D",...
// NewXMLSanitizerReader creates an io.Reader that // wraps another io.Reader and removes illegal xml // characters from the io stream.
[ "NewXMLSanitizerReader", "creates", "an", "io", ".", "Reader", "that", "wraps", "another", "io", ".", "Reader", "and", "removes", "illegal", "xml", "characters", "from", "the", "io", "stream", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/xmlsanitizer.go#L12-L23
train
mmcdole/gofeed
internal/shared/parseutils.go
ParseText
func ParseText(p *xpp.XMLPullParser) (string, error) { var text struct { Type string `xml:"type,attr"` InnerXML string `xml:",innerxml"` } err := p.DecodeElement(&text) if err != nil { return "", err } result := text.InnerXML result = strings.TrimSpace(result) if strings.Contains(result, CDATA_START) { return StripCDATA(result), nil } return DecodeEntities(result) }
go
func ParseText(p *xpp.XMLPullParser) (string, error) { var text struct { Type string `xml:"type,attr"` InnerXML string `xml:",innerxml"` } err := p.DecodeElement(&text) if err != nil { return "", err } result := text.InnerXML result = strings.TrimSpace(result) if strings.Contains(result, CDATA_START) { return StripCDATA(result), nil } return DecodeEntities(result) }
[ "func", "ParseText", "(", "p", "*", "xpp", ".", "XMLPullParser", ")", "(", "string", ",", "error", ")", "{", "var", "text", "struct", "{", "Type", "string", "`xml:\"type,attr\"`", "\n", "InnerXML", "string", "`xml:\",innerxml\"`", "\n", "}", "\n\n", "err", ...
// ParseText is a helper function for parsing the text // from the current element of the XMLPullParser. // This function can handle parsing naked XML text from // an element.
[ "ParseText", "is", "a", "helper", "function", "for", "parsing", "the", "text", "from", "the", "current", "element", "of", "the", "XMLPullParser", ".", "This", "function", "can", "handle", "parsing", "naked", "XML", "text", "from", "an", "element", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/parseutils.go#L31-L50
train
mmcdole/gofeed
internal/shared/parseutils.go
StripCDATA
func StripCDATA(str string) string { buf := bytes.NewBuffer([]byte{}) curr := 0 for curr < len(str) { start := indexAt(str, CDATA_START, curr) if start == -1 { dec, _ := DecodeEntities(str[curr:]) buf.Write([]byte(dec)) return buf.String() } end := indexAt(str, CDATA_END, start) if end == -1 { dec, _ := DecodeEntities(str[curr:]) buf.Write([]byte(dec)) return buf.String() } buf.Write([]byte(str[start+len(CDATA_START) : end])) curr = curr + end + len(CDATA_END) } return buf.String() }
go
func StripCDATA(str string) string { buf := bytes.NewBuffer([]byte{}) curr := 0 for curr < len(str) { start := indexAt(str, CDATA_START, curr) if start == -1 { dec, _ := DecodeEntities(str[curr:]) buf.Write([]byte(dec)) return buf.String() } end := indexAt(str, CDATA_END, start) if end == -1 { dec, _ := DecodeEntities(str[curr:]) buf.Write([]byte(dec)) return buf.String() } buf.Write([]byte(str[start+len(CDATA_START) : end])) curr = curr + end + len(CDATA_END) } return buf.String() }
[ "func", "StripCDATA", "(", "str", "string", ")", "string", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "{", "}", ")", "\n\n", "curr", ":=", "0", "\n\n", "for", "curr", "<", "len", "(", "str", ")", "{", "start", ":=", "inde...
// StripCDATA removes CDATA tags from the string // content outside of CDATA tags is passed via DecodeEntities
[ "StripCDATA", "removes", "CDATA", "tags", "from", "the", "string", "content", "outside", "of", "CDATA", "tags", "is", "passed", "via", "DecodeEntities" ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/parseutils.go#L54-L83
train
mmcdole/gofeed
internal/shared/parseutils.go
DecodeEntities
func DecodeEntities(str string) (string, error) { data := []byte(str) buf := bytes.NewBuffer([]byte{}) for len(data) > 0 { // Find the next entity idx := bytes.IndexByte(data, '&') if idx == -1 { buf.Write(data) break } // Write and skip everything before it buf.Write(data[:idx]) data = data[idx+1:] if len(data) == 0 { return "", TruncatedEntity } // Find the end of the entity end := bytes.IndexByte(data, ';') if end == -1 { return "", TruncatedEntity } if data[0] == '#' { // Numerical character reference var str string base := 10 if len(data) > 1 && data[1] == 'x' { str = string(data[2:end]) base = 16 } else { str = string(data[1:end]) } i, err := strconv.ParseUint(str, base, 32) if err != nil { return "", InvalidNumericReference } buf.WriteRune(rune(i)) } else { // Predefined entity name := string(data[:end]) var c byte switch name { case "lt": c = '<' case "gt": c = '>' case "quot": c = '"' case "apos": c = '\'' case "amp": c = '&' default: return "", fmt.Errorf("unknown predefined "+ "entity &%s;", name) } buf.WriteByte(c) } // Skip the entity data = data[end+1:] } return buf.String(), nil }
go
func DecodeEntities(str string) (string, error) { data := []byte(str) buf := bytes.NewBuffer([]byte{}) for len(data) > 0 { // Find the next entity idx := bytes.IndexByte(data, '&') if idx == -1 { buf.Write(data) break } // Write and skip everything before it buf.Write(data[:idx]) data = data[idx+1:] if len(data) == 0 { return "", TruncatedEntity } // Find the end of the entity end := bytes.IndexByte(data, ';') if end == -1 { return "", TruncatedEntity } if data[0] == '#' { // Numerical character reference var str string base := 10 if len(data) > 1 && data[1] == 'x' { str = string(data[2:end]) base = 16 } else { str = string(data[1:end]) } i, err := strconv.ParseUint(str, base, 32) if err != nil { return "", InvalidNumericReference } buf.WriteRune(rune(i)) } else { // Predefined entity name := string(data[:end]) var c byte switch name { case "lt": c = '<' case "gt": c = '>' case "quot": c = '"' case "apos": c = '\'' case "amp": c = '&' default: return "", fmt.Errorf("unknown predefined "+ "entity &%s;", name) } buf.WriteByte(c) } // Skip the entity data = data[end+1:] } return buf.String(), nil }
[ "func", "DecodeEntities", "(", "str", "string", ")", "(", "string", ",", "error", ")", "{", "data", ":=", "[", "]", "byte", "(", "str", ")", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "{", "}", ")", "\n\n", "for", "len",...
// DecodeEntities decodes escaped XML entities // in a string and returns the unescaped string
[ "DecodeEntities", "decodes", "escaped", "XML", "entities", "in", "a", "string", "and", "returns", "the", "unescaped", "string" ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/parseutils.go#L87-L160
train
mmcdole/gofeed
extensions/itunes.go
NewITunesFeedExtension
func NewITunesFeedExtension(extensions map[string][]Extension) *ITunesFeedExtension { feed := &ITunesFeedExtension{} feed.Author = parseTextExtension("author", extensions) feed.Block = parseTextExtension("block", extensions) feed.Explicit = parseTextExtension("explicit", extensions) feed.Keywords = parseTextExtension("keywords", extensions) feed.Subtitle = parseTextExtension("subtitle", extensions) feed.Summary = parseTextExtension("summary", extensions) feed.Image = parseImage(extensions) feed.Complete = parseTextExtension("complete", extensions) feed.NewFeedURL = parseTextExtension("new-feed-url", extensions) feed.Categories = parseCategories(extensions) feed.Owner = parseOwner(extensions) feed.Type = parseTextExtension("type", extensions) return feed }
go
func NewITunesFeedExtension(extensions map[string][]Extension) *ITunesFeedExtension { feed := &ITunesFeedExtension{} feed.Author = parseTextExtension("author", extensions) feed.Block = parseTextExtension("block", extensions) feed.Explicit = parseTextExtension("explicit", extensions) feed.Keywords = parseTextExtension("keywords", extensions) feed.Subtitle = parseTextExtension("subtitle", extensions) feed.Summary = parseTextExtension("summary", extensions) feed.Image = parseImage(extensions) feed.Complete = parseTextExtension("complete", extensions) feed.NewFeedURL = parseTextExtension("new-feed-url", extensions) feed.Categories = parseCategories(extensions) feed.Owner = parseOwner(extensions) feed.Type = parseTextExtension("type", extensions) return feed }
[ "func", "NewITunesFeedExtension", "(", "extensions", "map", "[", "string", "]", "[", "]", "Extension", ")", "*", "ITunesFeedExtension", "{", "feed", ":=", "&", "ITunesFeedExtension", "{", "}", "\n", "feed", ".", "Author", "=", "parseTextExtension", "(", "\"", ...
// NewITunesFeedExtension creates an ITunesFeedExtension given an // extension map for the "itunes" key.
[ "NewITunesFeedExtension", "creates", "an", "ITunesFeedExtension", "given", "an", "extension", "map", "for", "the", "itunes", "key", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/extensions/itunes.go#L49-L64
train
mmcdole/gofeed
extensions/itunes.go
NewITunesItemExtension
func NewITunesItemExtension(extensions map[string][]Extension) *ITunesItemExtension { entry := &ITunesItemExtension{} entry.Author = parseTextExtension("author", extensions) entry.Block = parseTextExtension("block", extensions) entry.Duration = parseTextExtension("duration", extensions) entry.Explicit = parseTextExtension("explicit", extensions) entry.Subtitle = parseTextExtension("subtitle", extensions) entry.Summary = parseTextExtension("summary", extensions) entry.Keywords = parseTextExtension("keywords", extensions) entry.Image = parseImage(extensions) entry.IsClosedCaptioned = parseTextExtension("isClosedCaptioned", extensions) entry.Order = parseTextExtension("order", extensions) return entry }
go
func NewITunesItemExtension(extensions map[string][]Extension) *ITunesItemExtension { entry := &ITunesItemExtension{} entry.Author = parseTextExtension("author", extensions) entry.Block = parseTextExtension("block", extensions) entry.Duration = parseTextExtension("duration", extensions) entry.Explicit = parseTextExtension("explicit", extensions) entry.Subtitle = parseTextExtension("subtitle", extensions) entry.Summary = parseTextExtension("summary", extensions) entry.Keywords = parseTextExtension("keywords", extensions) entry.Image = parseImage(extensions) entry.IsClosedCaptioned = parseTextExtension("isClosedCaptioned", extensions) entry.Order = parseTextExtension("order", extensions) return entry }
[ "func", "NewITunesItemExtension", "(", "extensions", "map", "[", "string", "]", "[", "]", "Extension", ")", "*", "ITunesItemExtension", "{", "entry", ":=", "&", "ITunesItemExtension", "{", "}", "\n", "entry", ".", "Author", "=", "parseTextExtension", "(", "\""...
// NewITunesItemExtension creates an ITunesItemExtension given an // extension map for the "itunes" key.
[ "NewITunesItemExtension", "creates", "an", "ITunesItemExtension", "given", "an", "extension", "map", "for", "the", "itunes", "key", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/extensions/itunes.go#L68-L81
train
mmcdole/gofeed
internal/shared/xmlbase.go
FindRoot
func (b *XMLBase) FindRoot(p *xpp.XMLPullParser) (event xpp.XMLEventType, err error) { for { event, err = b.NextTag(p) if err != nil { return event, err } if event == xpp.StartTag { break } if event == xpp.EndDocument { return event, fmt.Errorf("Failed to find root node before document end.") } } return }
go
func (b *XMLBase) FindRoot(p *xpp.XMLPullParser) (event xpp.XMLEventType, err error) { for { event, err = b.NextTag(p) if err != nil { return event, err } if event == xpp.StartTag { break } if event == xpp.EndDocument { return event, fmt.Errorf("Failed to find root node before document end.") } } return }
[ "func", "(", "b", "*", "XMLBase", ")", "FindRoot", "(", "p", "*", "xpp", ".", "XMLPullParser", ")", "(", "event", "xpp", ".", "XMLEventType", ",", "err", "error", ")", "{", "for", "{", "event", ",", "err", "=", "b", ".", "NextTag", "(", "p", ")",...
// FindRoot iterates through the tokens of an xml document until // it encounters its first StartTag event. It returns an error // if it reaches EndDocument before finding a tag.
[ "FindRoot", "iterates", "through", "the", "tokens", "of", "an", "xml", "document", "until", "it", "encounters", "its", "first", "StartTag", "event", ".", "It", "returns", "an", "error", "if", "it", "reaches", "EndDocument", "before", "finding", "a", "tag", "...
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/xmlbase.go#L64-L79
train
mmcdole/gofeed
internal/shared/xmlbase.go
pop
func (b *XMLBase) pop() string { url := b.stack.pop() if url != nil { return url.String() } return "" }
go
func (b *XMLBase) pop() string { url := b.stack.pop() if url != nil { return url.String() } return "" }
[ "func", "(", "b", "*", "XMLBase", ")", "pop", "(", ")", "string", "{", "url", ":=", "b", ".", "stack", ".", "pop", "(", ")", "\n", "if", "url", "!=", "nil", "{", "return", "url", ".", "String", "(", ")", "\n", "}", "\n", "return", "\"", "\"",...
// returns the popped base URL
[ "returns", "the", "popped", "base", "URL" ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/xmlbase.go#L155-L161
train
mmcdole/gofeed
internal/shared/xmlbase.go
ResolveURL
func (b *XMLBase) ResolveURL(u string) (string, error) { if b.CurrentBase() == "" { return u, nil } relURL, err := url.Parse(u) if err != nil { return u, err } curr := b.CurrentBaseURL() if curr.Path != "" && u != "" && curr.Path[len(curr.Path)-1] != '/' { // There's no reason someone would use a path in xml:base if they // didn't mean for it to be a directory curr.Path = curr.Path + "/" } absURL := b.CurrentBaseURL().ResolveReference(relURL) return absURL.String(), nil }
go
func (b *XMLBase) ResolveURL(u string) (string, error) { if b.CurrentBase() == "" { return u, nil } relURL, err := url.Parse(u) if err != nil { return u, err } curr := b.CurrentBaseURL() if curr.Path != "" && u != "" && curr.Path[len(curr.Path)-1] != '/' { // There's no reason someone would use a path in xml:base if they // didn't mean for it to be a directory curr.Path = curr.Path + "/" } absURL := b.CurrentBaseURL().ResolveReference(relURL) return absURL.String(), nil }
[ "func", "(", "b", "*", "XMLBase", ")", "ResolveURL", "(", "u", "string", ")", "(", "string", ",", "error", ")", "{", "if", "b", ".", "CurrentBase", "(", ")", "==", "\"", "\"", "{", "return", "u", ",", "nil", "\n", "}", "\n\n", "relURL", ",", "e...
// resolve the given string as a URL relative to current base
[ "resolve", "the", "given", "string", "as", "a", "URL", "relative", "to", "current", "base" ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/xmlbase.go#L175-L192
train
mmcdole/gofeed
internal/shared/xmlbase.go
ResolveHTML
func (b *XMLBase) ResolveHTML(relHTML string) (string, error) { if b.CurrentBase() == "" { return relHTML, nil } htmlReader := strings.NewReader(relHTML) doc, err := html.Parse(htmlReader) if err != nil { return relHTML, err } var visit func(*html.Node) // recursively traverse HTML resolving any relative URIs in attributes visit = func(n *html.Node) { if n.Type == html.ElementNode { for i, a := range n.Attr { if htmlURIAttrs[a.Key] { absVal, err := b.ResolveURL(a.Val) if err == nil { n.Attr[i].Val = absVal } break } } } for c := n.FirstChild; c != nil; c = c.NextSibling { visit(c) } } visit(doc) var w bytes.Buffer err = html.Render(&w, doc) if err != nil { return relHTML, err } // html.Render() always writes a complete html5 document, so strip the html // and body tags absHTML := w.String() absHTML = strings.TrimPrefix(absHTML, "<html><head></head><body>") absHTML = strings.TrimSuffix(absHTML, "</body></html>") return absHTML, err }
go
func (b *XMLBase) ResolveHTML(relHTML string) (string, error) { if b.CurrentBase() == "" { return relHTML, nil } htmlReader := strings.NewReader(relHTML) doc, err := html.Parse(htmlReader) if err != nil { return relHTML, err } var visit func(*html.Node) // recursively traverse HTML resolving any relative URIs in attributes visit = func(n *html.Node) { if n.Type == html.ElementNode { for i, a := range n.Attr { if htmlURIAttrs[a.Key] { absVal, err := b.ResolveURL(a.Val) if err == nil { n.Attr[i].Val = absVal } break } } } for c := n.FirstChild; c != nil; c = c.NextSibling { visit(c) } } visit(doc) var w bytes.Buffer err = html.Render(&w, doc) if err != nil { return relHTML, err } // html.Render() always writes a complete html5 document, so strip the html // and body tags absHTML := w.String() absHTML = strings.TrimPrefix(absHTML, "<html><head></head><body>") absHTML = strings.TrimSuffix(absHTML, "</body></html>") return absHTML, err }
[ "func", "(", "b", "*", "XMLBase", ")", "ResolveHTML", "(", "relHTML", "string", ")", "(", "string", ",", "error", ")", "{", "if", "b", ".", "CurrentBase", "(", ")", "==", "\"", "\"", "{", "return", "relHTML", ",", "nil", "\n", "}", "\n\n", "htmlRea...
// Transforms html by resolving any relative URIs in attributes // if an error occurs during parsing or serialization, then the original string // is returned along with the error.
[ "Transforms", "html", "by", "resolving", "any", "relative", "URIs", "in", "attributes", "if", "an", "error", "occurs", "during", "parsing", "or", "serialization", "then", "the", "original", "string", "is", "returned", "along", "with", "the", "error", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/xmlbase.go#L212-L258
train
mmcdole/gofeed
internal/shared/dateparser.go
ParseDate
func ParseDate(ds string) (t time.Time, err error) { d := strings.TrimSpace(ds) if d == "" { return t, fmt.Errorf("Date string is empty") } for _, f := range dateFormats { if t, err = time.Parse(f, d); err == nil { return } } for _, f := range dateFormatsWithNamedZone { t, err = time.Parse(f, d) if err != nil { continue } // This is a format match! Now try to load the timezone name loc, err := time.LoadLocation(t.Location().String()) if err != nil { // We couldn't load the TZ name. Just use UTC instead... return t, nil } if t, err = time.ParseInLocation(f, ds, loc); err == nil { return t, nil } // This should not be reachable } err = fmt.Errorf("Failed to parse date: %s", ds) return }
go
func ParseDate(ds string) (t time.Time, err error) { d := strings.TrimSpace(ds) if d == "" { return t, fmt.Errorf("Date string is empty") } for _, f := range dateFormats { if t, err = time.Parse(f, d); err == nil { return } } for _, f := range dateFormatsWithNamedZone { t, err = time.Parse(f, d) if err != nil { continue } // This is a format match! Now try to load the timezone name loc, err := time.LoadLocation(t.Location().String()) if err != nil { // We couldn't load the TZ name. Just use UTC instead... return t, nil } if t, err = time.ParseInLocation(f, ds, loc); err == nil { return t, nil } // This should not be reachable } err = fmt.Errorf("Failed to parse date: %s", ds) return }
[ "func", "ParseDate", "(", "ds", "string", ")", "(", "t", "time", ".", "Time", ",", "err", "error", ")", "{", "d", ":=", "strings", ".", "TrimSpace", "(", "ds", ")", "\n", "if", "d", "==", "\"", "\"", "{", "return", "t", ",", "fmt", ".", "Errorf...
// ParseDate parses a given date string using a large // list of commonly found feed date formats.
[ "ParseDate", "parses", "a", "given", "date", "string", "using", "a", "large", "list", "of", "commonly", "found", "feed", "date", "formats", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/dateparser.go#L188-L219
train
mmcdole/gofeed
detector.go
DetectFeedType
func DetectFeedType(feed io.Reader) FeedType { p := xpp.NewXMLPullParser(feed, false, shared.NewReaderLabel) xmlBase := shared.XMLBase{} _, err := xmlBase.FindRoot(p) if err != nil { return FeedTypeUnknown } name := strings.ToLower(p.Name) switch name { case "rdf": return FeedTypeRSS case "rss": return FeedTypeRSS case "feed": return FeedTypeAtom default: return FeedTypeUnknown } }
go
func DetectFeedType(feed io.Reader) FeedType { p := xpp.NewXMLPullParser(feed, false, shared.NewReaderLabel) xmlBase := shared.XMLBase{} _, err := xmlBase.FindRoot(p) if err != nil { return FeedTypeUnknown } name := strings.ToLower(p.Name) switch name { case "rdf": return FeedTypeRSS case "rss": return FeedTypeRSS case "feed": return FeedTypeAtom default: return FeedTypeUnknown } }
[ "func", "DetectFeedType", "(", "feed", "io", ".", "Reader", ")", "FeedType", "{", "p", ":=", "xpp", ".", "NewXMLPullParser", "(", "feed", ",", "false", ",", "shared", ".", "NewReaderLabel", ")", "\n\n", "xmlBase", ":=", "shared", ".", "XMLBase", "{", "}"...
// DetectFeedType attempts to determine the type of feed // by looking for specific xml elements unique to the // various feed types.
[ "DetectFeedType", "attempts", "to", "determine", "the", "type", "of", "feed", "by", "looking", "for", "specific", "xml", "elements", "unique", "to", "the", "various", "feed", "types", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/detector.go#L28-L48
train
mmcdole/gofeed
extensions/dublincore.go
NewDublinCoreExtension
func NewDublinCoreExtension(extensions map[string][]Extension) *DublinCoreExtension { dc := &DublinCoreExtension{} dc.Title = parseTextArrayExtension("title", extensions) dc.Creator = parseTextArrayExtension("creator", extensions) dc.Author = parseTextArrayExtension("author", extensions) dc.Subject = parseTextArrayExtension("subject", extensions) dc.Description = parseTextArrayExtension("description", extensions) dc.Publisher = parseTextArrayExtension("publisher", extensions) dc.Contributor = parseTextArrayExtension("contributor", extensions) dc.Date = parseTextArrayExtension("date", extensions) dc.Type = parseTextArrayExtension("type", extensions) dc.Format = parseTextArrayExtension("format", extensions) dc.Identifier = parseTextArrayExtension("identifier", extensions) dc.Source = parseTextArrayExtension("source", extensions) dc.Language = parseTextArrayExtension("language", extensions) dc.Relation = parseTextArrayExtension("relation", extensions) dc.Coverage = parseTextArrayExtension("coverage", extensions) dc.Rights = parseTextArrayExtension("rights", extensions) return dc }
go
func NewDublinCoreExtension(extensions map[string][]Extension) *DublinCoreExtension { dc := &DublinCoreExtension{} dc.Title = parseTextArrayExtension("title", extensions) dc.Creator = parseTextArrayExtension("creator", extensions) dc.Author = parseTextArrayExtension("author", extensions) dc.Subject = parseTextArrayExtension("subject", extensions) dc.Description = parseTextArrayExtension("description", extensions) dc.Publisher = parseTextArrayExtension("publisher", extensions) dc.Contributor = parseTextArrayExtension("contributor", extensions) dc.Date = parseTextArrayExtension("date", extensions) dc.Type = parseTextArrayExtension("type", extensions) dc.Format = parseTextArrayExtension("format", extensions) dc.Identifier = parseTextArrayExtension("identifier", extensions) dc.Source = parseTextArrayExtension("source", extensions) dc.Language = parseTextArrayExtension("language", extensions) dc.Relation = parseTextArrayExtension("relation", extensions) dc.Coverage = parseTextArrayExtension("coverage", extensions) dc.Rights = parseTextArrayExtension("rights", extensions) return dc }
[ "func", "NewDublinCoreExtension", "(", "extensions", "map", "[", "string", "]", "[", "]", "Extension", ")", "*", "DublinCoreExtension", "{", "dc", ":=", "&", "DublinCoreExtension", "{", "}", "\n", "dc", ".", "Title", "=", "parseTextArrayExtension", "(", "\"", ...
// NewDublinCoreExtension creates a new DublinCoreExtension // given the generic extension map for the "dc" prefix.
[ "NewDublinCoreExtension", "creates", "a", "new", "DublinCoreExtension", "given", "the", "generic", "extension", "map", "for", "the", "dc", "prefix", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/extensions/dublincore.go#L26-L45
train
mmcdole/gofeed
internal/shared/extparser.go
ParseExtension
func ParseExtension(fe ext.Extensions, p *xpp.XMLPullParser) (ext.Extensions, error) { prefix := prefixForNamespace(p.Space, p) result, err := parseExtensionElement(p) if err != nil { return nil, err } // Ensure the extension prefix map exists if _, ok := fe[prefix]; !ok { fe[prefix] = map[string][]ext.Extension{} } // Ensure the extension element slice exists if _, ok := fe[prefix][p.Name]; !ok { fe[prefix][p.Name] = []ext.Extension{} } fe[prefix][p.Name] = append(fe[prefix][p.Name], result) return fe, nil }
go
func ParseExtension(fe ext.Extensions, p *xpp.XMLPullParser) (ext.Extensions, error) { prefix := prefixForNamespace(p.Space, p) result, err := parseExtensionElement(p) if err != nil { return nil, err } // Ensure the extension prefix map exists if _, ok := fe[prefix]; !ok { fe[prefix] = map[string][]ext.Extension{} } // Ensure the extension element slice exists if _, ok := fe[prefix][p.Name]; !ok { fe[prefix][p.Name] = []ext.Extension{} } fe[prefix][p.Name] = append(fe[prefix][p.Name], result) return fe, nil }
[ "func", "ParseExtension", "(", "fe", "ext", ".", "Extensions", ",", "p", "*", "xpp", ".", "XMLPullParser", ")", "(", "ext", ".", "Extensions", ",", "error", ")", "{", "prefix", ":=", "prefixForNamespace", "(", "p", ".", "Space", ",", "p", ")", "\n\n", ...
// ParseExtension parses the current element of the // XMLPullParser as an extension element and updates // the extension map
[ "ParseExtension", "parses", "the", "current", "element", "of", "the", "XMLPullParser", "as", "an", "extension", "element", "and", "updates", "the", "extension", "map" ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/extparser.go#L25-L44
train
mmcdole/gofeed
parser.go
NewParser
func NewParser() *Parser { fp := Parser{ rp: &rss.Parser{}, ap: &atom.Parser{}, } return &fp }
go
func NewParser() *Parser { fp := Parser{ rp: &rss.Parser{}, ap: &atom.Parser{}, } return &fp }
[ "func", "NewParser", "(", ")", "*", "Parser", "{", "fp", ":=", "Parser", "{", "rp", ":", "&", "rss", ".", "Parser", "{", "}", ",", "ap", ":", "&", "atom", ".", "Parser", "{", "}", ",", "}", "\n", "return", "&", "fp", "\n", "}" ]
// NewParser creates a universal feed parser.
[ "NewParser", "creates", "a", "universal", "feed", "parser", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/parser.go#L41-L47
train
mmcdole/gofeed
parser.go
Parse
func (f *Parser) Parse(feed io.Reader) (*Feed, error) { // Wrap the feed io.Reader in a io.TeeReader // so we can capture all the bytes read by the // DetectFeedType function and construct a new // reader with those bytes intact for when we // attempt to parse the feeds. var buf bytes.Buffer tee := io.TeeReader(feed, &buf) feedType := DetectFeedType(tee) // Glue the read bytes from the detect function // back into a new reader r := io.MultiReader(&buf, feed) switch feedType { case FeedTypeAtom: return f.parseAtomFeed(r) case FeedTypeRSS: return f.parseRSSFeed(r) } return nil, ErrFeedTypeNotDetected }
go
func (f *Parser) Parse(feed io.Reader) (*Feed, error) { // Wrap the feed io.Reader in a io.TeeReader // so we can capture all the bytes read by the // DetectFeedType function and construct a new // reader with those bytes intact for when we // attempt to parse the feeds. var buf bytes.Buffer tee := io.TeeReader(feed, &buf) feedType := DetectFeedType(tee) // Glue the read bytes from the detect function // back into a new reader r := io.MultiReader(&buf, feed) switch feedType { case FeedTypeAtom: return f.parseAtomFeed(r) case FeedTypeRSS: return f.parseRSSFeed(r) } return nil, ErrFeedTypeNotDetected }
[ "func", "(", "f", "*", "Parser", ")", "Parse", "(", "feed", "io", ".", "Reader", ")", "(", "*", "Feed", ",", "error", ")", "{", "// Wrap the feed io.Reader in a io.TeeReader", "// so we can capture all the bytes read by the", "// DetectFeedType function and construct a ne...
// Parse parses a RSS or Atom feed into // the universal gofeed.Feed. It takes an // io.Reader which should return the xml content.
[ "Parse", "parses", "a", "RSS", "or", "Atom", "feed", "into", "the", "universal", "gofeed", ".", "Feed", ".", "It", "takes", "an", "io", ".", "Reader", "which", "should", "return", "the", "xml", "content", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/parser.go#L52-L74
train
mmcdole/gofeed
parser.go
ParseURL
func (f *Parser) ParseURL(feedURL string) (feed *Feed, err error) { client := f.httpClient() req, err := http.NewRequest("GET", feedURL, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", "Gofeed/1.0") resp, err := client.Do(req) if err != nil { return nil, err } if resp != nil { defer func() { ce := resp.Body.Close() if ce != nil { err = ce } }() } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, HTTPError{ StatusCode: resp.StatusCode, Status: resp.Status, } } return f.Parse(resp.Body) }
go
func (f *Parser) ParseURL(feedURL string) (feed *Feed, err error) { client := f.httpClient() req, err := http.NewRequest("GET", feedURL, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", "Gofeed/1.0") resp, err := client.Do(req) if err != nil { return nil, err } if resp != nil { defer func() { ce := resp.Body.Close() if ce != nil { err = ce } }() } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, HTTPError{ StatusCode: resp.StatusCode, Status: resp.Status, } } return f.Parse(resp.Body) }
[ "func", "(", "f", "*", "Parser", ")", "ParseURL", "(", "feedURL", "string", ")", "(", "feed", "*", "Feed", ",", "err", "error", ")", "{", "client", ":=", "f", ".", "httpClient", "(", ")", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", ...
// ParseURL fetches the contents of a given url and // attempts to parse the response into the universal feed type.
[ "ParseURL", "fetches", "the", "contents", "of", "a", "given", "url", "and", "attempts", "to", "parse", "the", "response", "into", "the", "universal", "feed", "type", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/parser.go#L78-L109
train
mmcdole/gofeed
parser.go
ParseString
func (f *Parser) ParseString(feed string) (*Feed, error) { return f.Parse(strings.NewReader(feed)) }
go
func (f *Parser) ParseString(feed string) (*Feed, error) { return f.Parse(strings.NewReader(feed)) }
[ "func", "(", "f", "*", "Parser", ")", "ParseString", "(", "feed", "string", ")", "(", "*", "Feed", ",", "error", ")", "{", "return", "f", ".", "Parse", "(", "strings", ".", "NewReader", "(", "feed", ")", ")", "\n", "}" ]
// ParseString parses a feed XML string and into the // universal feed type.
[ "ParseString", "parses", "a", "feed", "XML", "string", "and", "into", "the", "universal", "feed", "type", "." ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/parser.go#L113-L115
train
mmcdole/gofeed
rss/parser.go
Parse
func (rp *Parser) Parse(feed io.Reader) (*Feed, error) { p := xpp.NewXMLPullParser(feed, false, shared.NewReaderLabel) rp.base = &shared.XMLBase{} _, err := rp.base.FindRoot(p) if err != nil { return nil, err } return rp.parseRoot(p) }
go
func (rp *Parser) Parse(feed io.Reader) (*Feed, error) { p := xpp.NewXMLPullParser(feed, false, shared.NewReaderLabel) rp.base = &shared.XMLBase{} _, err := rp.base.FindRoot(p) if err != nil { return nil, err } return rp.parseRoot(p) }
[ "func", "(", "rp", "*", "Parser", ")", "Parse", "(", "feed", "io", ".", "Reader", ")", "(", "*", "Feed", ",", "error", ")", "{", "p", ":=", "xpp", ".", "NewXMLPullParser", "(", "feed", ",", "false", ",", "shared", ".", "NewReaderLabel", ")", "\n", ...
// Parse parses an xml feed into an rss.Feed
[ "Parse", "parses", "an", "xml", "feed", "into", "an", "rss", ".", "Feed" ]
0e68beaf6fdf215bd1fe42a09f6de292c7032359
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/rss/parser.go#L19-L29
train