id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
149,200 | 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",
"{",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"IntFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Hidden",
":",
"true",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Value",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"BoolFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"BoolFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"}",
",",
"Action",
":",
"newSignAction",
",",
"}",
"\n",
"}"
] | // 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 |
149,201 | 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",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"pemBlock",
".",
"Type",
"!=",
"crlPEMBlockType",
"||",
"len",
"(",
"pemBlock",
".",
"Headers",
")",
"!=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"CertificateRevocationList",
"{",
"derBytes",
":",
"pemBlock",
".",
"Bytes",
"}",
",",
"nil",
"\n",
"}"
] | // 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 |
149,202 | 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",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"pemBlock",
".",
"Type",
"!=",
"certificatePEMBlockType",
"||",
"len",
"(",
"pemBlock",
".",
"Headers",
")",
"!=",
"0",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"c",
"=",
"&",
"Certificate",
"{",
"derBytes",
":",
"pemBlock",
".",
"Bytes",
"}",
"\n",
"return",
"\n",
"}"
] | // 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 |
149,203 | 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",
".",
"derBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"crts",
")",
"!=",
"1",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"c",
".",
"crt",
"=",
"crts",
"[",
"0",
"]",
"\n",
"return",
"nil",
"\n",
"}"
] | // build crt field if needed | [
"build",
"crt",
"field",
"if",
"needed"
] | 350df15b3713d535548735ea754726228b00c742 | https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L63-L77 |
149,204 | 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",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"crt",
",",
"nil",
"\n",
"}"
] | // 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 |
149,205 | 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",
")",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"crt",
".",
"NotAfter",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"}"
] | // 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 |
149,206 | 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",
".",
"CheckSignatureFrom",
"(",
"c",
".",
"crt",
")",
"\n",
"}"
] | // 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 |
149,207 | 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",
".",
"derBytes",
",",
"}",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"if",
"err",
":=",
"pem",
".",
"Encode",
"(",
"buf",
",",
"pemBlock",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Export returns PEM-format bytes | [
"Export",
"returns",
"PEM",
"-",
"format",
"bytes"
] | 350df15b3713d535548735ea754726228b00c742 | https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/cert.go#L151-L163 |
149,208 | 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",
"string",
")",
"(",
"*",
"Certificate",
",",
"error",
")",
"{",
"subjectKeyID",
",",
"err",
":=",
"GenerateSubjectKeyID",
"(",
"key",
".",
"Public",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"authTemplate",
".",
"SubjectKeyId",
"=",
"subjectKeyID",
"\n",
"authTemplate",
".",
"NotAfter",
"=",
"expiry",
"\n",
"if",
"len",
"(",
"country",
")",
">",
"0",
"{",
"authTemplate",
".",
"Subject",
".",
"Country",
"=",
"[",
"]",
"string",
"{",
"country",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"province",
")",
">",
"0",
"{",
"authTemplate",
".",
"Subject",
".",
"Province",
"=",
"[",
"]",
"string",
"{",
"province",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"locality",
")",
">",
"0",
"{",
"authTemplate",
".",
"Subject",
".",
"Locality",
"=",
"[",
"]",
"string",
"{",
"locality",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"organization",
")",
">",
"0",
"{",
"authTemplate",
".",
"Subject",
".",
"Organization",
"=",
"[",
"]",
"string",
"{",
"organization",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"organizationalUnit",
")",
">",
"0",
"{",
"authTemplate",
".",
"Subject",
".",
"OrganizationalUnit",
"=",
"[",
"]",
"string",
"{",
"organizationalUnit",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"commonName",
")",
">",
"0",
"{",
"authTemplate",
".",
"Subject",
".",
"CommonName",
"=",
"commonName",
"\n",
"}",
"\n\n",
"crtBytes",
",",
"err",
":=",
"x509",
".",
"CreateCertificate",
"(",
"rand",
".",
"Reader",
",",
"&",
"authTemplate",
",",
"&",
"authTemplate",
",",
"key",
".",
"Public",
",",
"key",
".",
"Private",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NewCertificateFromDER",
"(",
"crtBytes",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,209 | 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",
")",
"{",
"serialNumberLimit",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Lsh",
"(",
"big",
".",
"NewInt",
"(",
"1",
")",
",",
"128",
")",
"\n",
"serialNumber",
",",
"err",
":=",
"rand",
".",
"Int",
"(",
"rand",
".",
"Reader",
",",
"serialNumberLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"authTemplate",
".",
"SerialNumber",
".",
"Set",
"(",
"serialNumber",
")",
"\n",
"authTemplate",
".",
"MaxPathLenZero",
"=",
"false",
"\n\n",
"rawCsr",
",",
"err",
":=",
"csr",
".",
"GetRawCertificateSigningRequest",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"authTemplate",
".",
"RawSubject",
"=",
"rawCsr",
".",
"RawSubject",
"\n\n",
"caExpiry",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"crtAuth",
".",
"GetExpirationDuration",
"(",
")",
")",
"\n",
"// ensure cert doesn't expire after issuer",
"if",
"caExpiry",
".",
"Before",
"(",
"proposedExpiry",
")",
"{",
"authTemplate",
".",
"NotAfter",
"=",
"caExpiry",
"\n",
"}",
"else",
"{",
"authTemplate",
".",
"NotAfter",
"=",
"proposedExpiry",
"\n",
"}",
"\n\n",
"authTemplate",
".",
"SubjectKeyId",
",",
"err",
"=",
"GenerateSubjectKeyID",
"(",
"rawCsr",
".",
"PublicKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"authTemplate",
".",
"IPAddresses",
"=",
"rawCsr",
".",
"IPAddresses",
"\n",
"authTemplate",
".",
"DNSNames",
"=",
"rawCsr",
".",
"DNSNames",
"\n",
"authTemplate",
".",
"URIs",
"=",
"rawCsr",
".",
"URIs",
"\n\n",
"rawCrtAuth",
",",
"err",
":=",
"crtAuth",
".",
"GetRawCertificate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"crtOutBytes",
",",
"err",
":=",
"x509",
".",
"CreateCertificate",
"(",
"rand",
".",
"Reader",
",",
"&",
"authTemplate",
",",
"rawCrtAuth",
",",
"rawCsr",
".",
"PublicKey",
",",
"keyAuth",
".",
"Private",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NewCertificateFromDER",
"(",
"crtOutBytes",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,210 | 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",
"}",
"\n",
"return",
"name",
"\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 |
149,211 | 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",
"}",
"\n",
"return",
"d",
".",
"Put",
"(",
"CrtTag",
"(",
"name",
")",
",",
"b",
")",
"\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 |
149,212 | 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 |
149,213 | 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",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pkix",
".",
"NewCertificateFromPEM",
"(",
"b",
")",
"\n",
"}"
] | // 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 |
149,214 | 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 |
149,215 | 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",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"d",
".",
"Put",
"(",
"CsrTag",
"(",
"name",
")",
",",
"b",
")",
"\n",
"}"
] | // 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 |
149,216 | 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 |
149,217 | 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",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pkix",
".",
"NewCertificateSigningRequestFromPEM",
"(",
"b",
")",
"\n",
"}"
] | // 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 |
149,218 | 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 |
149,219 | 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",
"}",
"\n",
"return",
"d",
".",
"Put",
"(",
"PrivKeyTag",
"(",
"name",
")",
",",
"b",
")",
"\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 |
149,220 | 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 |
149,221 | 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",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pkix",
".",
"NewKeyFromPrivateKeyPEM",
"(",
"b",
")",
"\n",
"}"
] | // 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 |
149,222 | 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"d",
".",
"Put",
"(",
"PrivKeyTag",
"(",
"name",
")",
",",
"b",
")",
"\n",
"}"
] | // 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 |
149,223 | 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",
"(",
"name",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pkix",
".",
"NewKeyFromEncryptedPrivateKeyPEM",
"(",
"b",
",",
"passphrase",
")",
"\n",
"}"
] | // 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 |
149,224 | 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",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"d",
".",
"Put",
"(",
"CrlTag",
"(",
"name",
")",
",",
"b",
")",
"\n",
"}"
] | // 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 |
149,225 | 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",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pkix",
".",
"NewCertificateRevocationListFromPEM",
"(",
"b",
")",
"\n",
"}"
] | //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 |
149,226 | 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",
"{",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"IntFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Value",
":",
"4096",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"IntFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Hidden",
":",
"true",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Value",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"StringFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"cli",
".",
"BoolFlag",
"{",
"Name",
":",
"\"",
"\"",
",",
"Usage",
":",
"\"",
"\"",
",",
"}",
",",
"}",
",",
"Action",
":",
"initAction",
",",
"}",
"\n",
"}"
] | // 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 |
149,227 | 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",
"(",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"CertificateAuthorityInfo",
"{",
"i",
"}",
",",
"nil",
"\n",
"}"
] | // 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 |
149,228 | 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 |
149,229 | 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",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NewKey",
"(",
"&",
"priv",
".",
"PublicKey",
",",
"priv",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,230 | 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 |
149,231 | 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",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"pemBlock",
".",
"Type",
"!=",
"rsaPrivateKeyPEMBlockType",
"||",
"len",
"(",
"pemBlock",
".",
"Headers",
")",
"!=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"priv",
",",
"err",
":=",
"x509",
".",
"ParsePKCS1PrivateKey",
"(",
"pemBlock",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NewKey",
"(",
"&",
"priv",
".",
"PublicKey",
",",
"priv",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,232 | 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",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"pemBlock",
".",
"Type",
"!=",
"rsaPrivateKeyPEMBlockType",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"x509",
".",
"DecryptPEMBlock",
"(",
"pemBlock",
",",
"password",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"priv",
",",
"err",
":=",
"x509",
".",
"ParsePKCS1PrivateKey",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NewKey",
"(",
"&",
"priv",
".",
"PublicKey",
",",
"priv",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,233 | 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",
"*",
"rsa",
".",
"PrivateKey",
":",
"privBytes",
":=",
"x509",
".",
"MarshalPKCS1PrivateKey",
"(",
"priv",
")",
"\n",
"privPEMBlock",
"=",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"rsaPrivateKeyPEMBlockType",
",",
"Bytes",
":",
"privBytes",
",",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"if",
"err",
":=",
"pem",
".",
"Encode",
"(",
"buf",
",",
"privPEMBlock",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,234 | 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",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rsa",
".",
"PrivateKey",
":",
"privBytes",
"=",
"x509",
".",
"MarshalPKCS1PrivateKey",
"(",
"priv",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"privPEMBlock",
",",
"err",
":=",
"x509",
".",
"EncryptPEMBlock",
"(",
"rand",
".",
"Reader",
",",
"rsaPrivateKeyPEMBlockType",
",",
"privBytes",
",",
"password",
",",
"x509",
".",
"PEMCipher3DES",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"if",
"err",
":=",
"pem",
".",
"Encode",
"(",
"buf",
",",
"privPEMBlock",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,235 | 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",
")",
"{",
"case",
"*",
"rsa",
".",
"PublicKey",
":",
"pubBytes",
",",
"err",
"=",
"asn1",
".",
"Marshal",
"(",
"rsaPublicKey",
"{",
"N",
":",
"pub",
".",
"N",
",",
"E",
":",
"pub",
".",
"E",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"hash",
":=",
"sha1",
".",
"Sum",
"(",
"pubBytes",
")",
"\n\n",
"return",
"hash",
"[",
":",
"]",
",",
"nil",
"\n",
"}"
] | // 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 |
149,236 | 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",
".",
"Split",
"(",
"ipList",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"ip",
":=",
"range",
"ips",
"{",
"parsedIP",
":=",
"net",
".",
"ParseIP",
"(",
"ip",
")",
"\n",
"if",
"parsedIP",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ip",
")",
"\n",
"}",
"\n",
"res",
"=",
"append",
"(",
"res",
",",
"parsedIP",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // 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 |
149,237 | 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",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"uri",
":=",
"range",
"uris",
"{",
"parsedURI",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"uri",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"parsedURI",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"parsedURI",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uri",
")",
"\n",
"}",
"\n",
"if",
"!",
"parsedURI",
".",
"IsAbs",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uri",
")",
"\n",
"}",
"\n",
"res",
"=",
"append",
"(",
"res",
",",
"parsedURI",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // 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 |
149,238 | 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",
"string",
",",
"country",
"string",
",",
"province",
"string",
",",
"locality",
"string",
",",
"commonName",
"string",
")",
"(",
"*",
"CertificateSigningRequest",
",",
"error",
")",
"{",
"csrPkixName",
".",
"CommonName",
"=",
"commonName",
"\n\n",
"if",
"len",
"(",
"organizationalUnit",
")",
">",
"0",
"{",
"csrPkixName",
".",
"OrganizationalUnit",
"=",
"[",
"]",
"string",
"{",
"organizationalUnit",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"organization",
")",
">",
"0",
"{",
"csrPkixName",
".",
"Organization",
"=",
"[",
"]",
"string",
"{",
"organization",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"country",
")",
">",
"0",
"{",
"csrPkixName",
".",
"Country",
"=",
"[",
"]",
"string",
"{",
"country",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"province",
")",
">",
"0",
"{",
"csrPkixName",
".",
"Province",
"=",
"[",
"]",
"string",
"{",
"province",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"locality",
")",
">",
"0",
"{",
"csrPkixName",
".",
"Locality",
"=",
"[",
"]",
"string",
"{",
"locality",
"}",
"\n",
"}",
"\n",
"csrTemplate",
":=",
"&",
"x509",
".",
"CertificateRequest",
"{",
"Subject",
":",
"csrPkixName",
",",
"IPAddresses",
":",
"ipList",
",",
"DNSNames",
":",
"domainList",
",",
"URIs",
":",
"uriList",
",",
"}",
"\n\n",
"csrBytes",
",",
"err",
":=",
"x509",
".",
"CreateCertificateRequest",
"(",
"rand",
".",
"Reader",
",",
"csrTemplate",
",",
"key",
".",
"Private",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewCertificateSigningRequestFromDER",
"(",
"csrBytes",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,239 | 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",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"(",
"pemBlock",
".",
"Type",
"!=",
"csrPEMBlockType",
"&&",
"pemBlock",
".",
"Type",
"!=",
"oldCsrPEMBlockType",
")",
"||",
"len",
"(",
"pemBlock",
".",
"Headers",
")",
"!=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"CertificateSigningRequest",
"{",
"derBytes",
":",
"pemBlock",
".",
"Bytes",
"}",
",",
"nil",
"\n",
"}"
] | // 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 |
149,240 | 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",
"=",
"x509",
".",
"ParseCertificateRequest",
"(",
"c",
".",
"derBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // build cr field if needed | [
"build",
"cr",
"field",
"if",
"needed"
] | 350df15b3713d535548735ea754726228b00c742 | https://github.com/square/certstrap/blob/350df15b3713d535548735ea754726228b00c742/pkix/csr.go#L155-L166 |
149,241 | 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",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"cr",
",",
"nil",
"\n",
"}"
] | // 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 |
149,242 | 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",
"checkSignature",
"(",
"c",
".",
"cr",
",",
"c",
".",
"cr",
".",
"SignatureAlgorithm",
",",
"c",
".",
"cr",
".",
"RawTBSCertificateRequest",
",",
"c",
".",
"cr",
".",
"Signature",
")",
"\n",
"}"
] | // 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 |
149,243 | 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",
"algo",
"{",
"case",
"x509",
".",
"SHA1WithRSA",
",",
"x509",
".",
"ECDSAWithSHA1",
":",
"hashType",
"=",
"crypto",
".",
"SHA1",
"\n",
"case",
"x509",
".",
"SHA256WithRSA",
",",
"x509",
".",
"ECDSAWithSHA256",
":",
"hashType",
"=",
"crypto",
".",
"SHA256",
"\n",
"case",
"x509",
".",
"SHA384WithRSA",
",",
"x509",
".",
"ECDSAWithSHA384",
":",
"hashType",
"=",
"crypto",
".",
"SHA384",
"\n",
"case",
"x509",
".",
"SHA512WithRSA",
",",
"x509",
".",
"ECDSAWithSHA512",
":",
"hashType",
"=",
"crypto",
".",
"SHA512",
"\n",
"default",
":",
"return",
"x509",
".",
"ErrUnsupportedAlgorithm",
"\n",
"}",
"\n",
"if",
"!",
"hashType",
".",
"Available",
"(",
")",
"{",
"return",
"x509",
".",
"ErrUnsupportedAlgorithm",
"\n",
"}",
"\n",
"h",
":=",
"hashType",
".",
"New",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"signed",
")",
"\n",
"digest",
":=",
"h",
".",
"Sum",
"(",
"nil",
")",
"\n",
"switch",
"pub",
":=",
"csr",
".",
"PublicKey",
".",
"(",
"type",
")",
"{",
"case",
"*",
"rsa",
".",
"PublicKey",
":",
"return",
"rsa",
".",
"VerifyPKCS1v15",
"(",
"pub",
",",
"hashType",
",",
"digest",
",",
"signature",
")",
"\n",
"case",
"*",
"ecdsa",
".",
"PublicKey",
":",
"ecdsaSig",
":=",
"new",
"(",
"struct",
"{",
"R",
",",
"S",
"*",
"big",
".",
"Int",
"}",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"asn1",
".",
"Unmarshal",
"(",
"signature",
",",
"ecdsaSig",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"ecdsaSig",
".",
"R",
".",
"Sign",
"(",
")",
"<=",
"0",
"||",
"ecdsaSig",
".",
"S",
".",
"Sign",
"(",
")",
"<=",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"ecdsa",
".",
"Verify",
"(",
"pub",
",",
"digest",
",",
"ecdsaSig",
".",
"R",
",",
"ecdsaSig",
".",
"S",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"x509",
".",
"ErrUnsupportedAlgorithm",
"\n",
"}"
] | // 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 |
149,244 | 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",
")",
"\n",
"case",
"string",
":",
"u",
",",
"err",
":=",
"url",
".",
"ParseRequestURI",
"(",
"t",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"GetVideoInfoFromID",
"(",
"t",
")",
"\n",
"}",
"\n",
"if",
"u",
".",
"Host",
"==",
"\"",
"\"",
"{",
"return",
"GetVideoInfoFromShortURL",
"(",
"u",
")",
"\n",
"}",
"\n",
"return",
"GetVideoInfoFromURL",
"(",
"u",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // 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 |
149,245 | 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",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"GetVideoInfoFromID",
"(",
"videoID",
")",
"\n",
"}"
] | // 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 |
149,246 | 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",
":",
"]",
";",
"path",
"!=",
"\"",
"\"",
"{",
"return",
"GetVideoInfoFromID",
"(",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // 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 |
149,247 | 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",
".",
"Set",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"u",
".",
"RawQuery",
"=",
"values",
".",
"Encode",
"(",
")",
"\n\n",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"u",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"getVideoInfoFromHTML",
"(",
"id",
",",
"body",
")",
"\n",
"}"
] | // 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 |
149,248 | 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 |
149,249 | 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",
",",
"quality",
")",
")",
"\n",
"return",
"u",
"\n",
"}"
] | // 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 |
149,250 | 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",
"{",
"return",
"err",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"u",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"<",
"200",
"||",
"resp",
".",
"StatusCode",
">",
"299",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"dest",
",",
"resp",
".",
"Body",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // 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 |
149,251 | 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",
".",
"Extension",
"\n",
"case",
"FormatResolutionKey",
":",
"return",
"f",
".",
"Resolution",
"\n",
"case",
"FormatVideoEncodingKey",
":",
"return",
"f",
".",
"VideoEncoding",
"\n",
"case",
"FormatAudioEncodingKey",
":",
"return",
"f",
".",
"AudioEncoding",
"\n",
"case",
"FormatAudioBitrateKey",
":",
"return",
"f",
".",
"AudioBitrate",
"\n",
"default",
":",
"if",
"f",
".",
"meta",
"!=",
"nil",
"{",
"return",
"f",
".",
"meta",
"[",
"string",
"(",
"key",
")",
"]",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // 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 |
149,252 | 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",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"&",
"Feed",
"{",
"}",
"\n",
"result",
".",
"Title",
"=",
"t",
".",
"translateFeedTitle",
"(",
"rss",
")",
"\n",
"result",
".",
"Description",
"=",
"t",
".",
"translateFeedDescription",
"(",
"rss",
")",
"\n",
"result",
".",
"Link",
"=",
"t",
".",
"translateFeedLink",
"(",
"rss",
")",
"\n",
"result",
".",
"FeedLink",
"=",
"t",
".",
"translateFeedFeedLink",
"(",
"rss",
")",
"\n",
"result",
".",
"Updated",
"=",
"t",
".",
"translateFeedUpdated",
"(",
"rss",
")",
"\n",
"result",
".",
"UpdatedParsed",
"=",
"t",
".",
"translateFeedUpdatedParsed",
"(",
"rss",
")",
"\n",
"result",
".",
"Published",
"=",
"t",
".",
"translateFeedPublished",
"(",
"rss",
")",
"\n",
"result",
".",
"PublishedParsed",
"=",
"t",
".",
"translateFeedPublishedParsed",
"(",
"rss",
")",
"\n",
"result",
".",
"Author",
"=",
"t",
".",
"translateFeedAuthor",
"(",
"rss",
")",
"\n",
"result",
".",
"Language",
"=",
"t",
".",
"translateFeedLanguage",
"(",
"rss",
")",
"\n",
"result",
".",
"Image",
"=",
"t",
".",
"translateFeedImage",
"(",
"rss",
")",
"\n",
"result",
".",
"Copyright",
"=",
"t",
".",
"translateFeedCopyright",
"(",
"rss",
")",
"\n",
"result",
".",
"Generator",
"=",
"t",
".",
"translateFeedGenerator",
"(",
"rss",
")",
"\n",
"result",
".",
"Categories",
"=",
"t",
".",
"translateFeedCategories",
"(",
"rss",
")",
"\n",
"result",
".",
"Items",
"=",
"t",
".",
"translateFeedItems",
"(",
"rss",
")",
"\n",
"result",
".",
"ITunesExt",
"=",
"rss",
".",
"ITunesExt",
"\n",
"result",
".",
"DublinCoreExt",
"=",
"rss",
".",
"DublinCoreExt",
"\n",
"result",
".",
"Extensions",
"=",
"rss",
".",
"Extensions",
"\n",
"result",
".",
"FeedVersion",
"=",
"rss",
".",
"Version",
"\n",
"result",
".",
"FeedType",
"=",
"\"",
"\"",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // 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 |
149,253 | 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",
"!",
"found",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"&",
"Feed",
"{",
"}",
"\n",
"result",
".",
"Title",
"=",
"t",
".",
"translateFeedTitle",
"(",
"atom",
")",
"\n",
"result",
".",
"Description",
"=",
"t",
".",
"translateFeedDescription",
"(",
"atom",
")",
"\n",
"result",
".",
"Link",
"=",
"t",
".",
"translateFeedLink",
"(",
"atom",
")",
"\n",
"result",
".",
"FeedLink",
"=",
"t",
".",
"translateFeedFeedLink",
"(",
"atom",
")",
"\n",
"result",
".",
"Updated",
"=",
"t",
".",
"translateFeedUpdated",
"(",
"atom",
")",
"\n",
"result",
".",
"UpdatedParsed",
"=",
"t",
".",
"translateFeedUpdatedParsed",
"(",
"atom",
")",
"\n",
"result",
".",
"Author",
"=",
"t",
".",
"translateFeedAuthor",
"(",
"atom",
")",
"\n",
"result",
".",
"Language",
"=",
"t",
".",
"translateFeedLanguage",
"(",
"atom",
")",
"\n",
"result",
".",
"Image",
"=",
"t",
".",
"translateFeedImage",
"(",
"atom",
")",
"\n",
"result",
".",
"Copyright",
"=",
"t",
".",
"translateFeedCopyright",
"(",
"atom",
")",
"\n",
"result",
".",
"Categories",
"=",
"t",
".",
"translateFeedCategories",
"(",
"atom",
")",
"\n",
"result",
".",
"Generator",
"=",
"t",
".",
"translateFeedGenerator",
"(",
"atom",
")",
"\n",
"result",
".",
"Items",
"=",
"t",
".",
"translateFeedItems",
"(",
"atom",
")",
"\n",
"result",
".",
"Extensions",
"=",
"atom",
".",
"Extensions",
"\n",
"result",
".",
"FeedVersion",
"=",
"atom",
".",
"Version",
"\n",
"result",
".",
"FeedType",
"=",
"\"",
"\"",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // 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 |
149,254 | 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",
"||",
"r",
">=",
"0x20",
"&&",
"r",
"<=",
"0xDF77",
"||",
"r",
">=",
"0xE000",
"&&",
"r",
"<=",
"0xFFFD",
"||",
"r",
">=",
"0x10000",
"&&",
"r",
"<=",
"0x10FFFF",
")",
"\n",
"}",
"\n",
"t",
":=",
"transform",
".",
"Chain",
"(",
"transform",
".",
"RemoveFunc",
"(",
"isIllegal",
")",
")",
"\n",
"return",
"transform",
".",
"NewReader",
"(",
"xml",
",",
"t",
")",
"\n",
"}"
] | // 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 |
149,255 | 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",
":=",
"p",
".",
"DecodeElement",
"(",
"&",
"text",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"result",
":=",
"text",
".",
"InnerXML",
"\n",
"result",
"=",
"strings",
".",
"TrimSpace",
"(",
"result",
")",
"\n\n",
"if",
"strings",
".",
"Contains",
"(",
"result",
",",
"CDATA_START",
")",
"{",
"return",
"StripCDATA",
"(",
"result",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"DecodeEntities",
"(",
"result",
")",
"\n",
"}"
] | // 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 |
149,256 | 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",
":=",
"indexAt",
"(",
"str",
",",
"CDATA_START",
",",
"curr",
")",
"\n\n",
"if",
"start",
"==",
"-",
"1",
"{",
"dec",
",",
"_",
":=",
"DecodeEntities",
"(",
"str",
"[",
"curr",
":",
"]",
")",
"\n",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"dec",
")",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"end",
":=",
"indexAt",
"(",
"str",
",",
"CDATA_END",
",",
"start",
")",
"\n\n",
"if",
"end",
"==",
"-",
"1",
"{",
"dec",
",",
"_",
":=",
"DecodeEntities",
"(",
"str",
"[",
"curr",
":",
"]",
")",
"\n",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"dec",
")",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"str",
"[",
"start",
"+",
"len",
"(",
"CDATA_START",
")",
":",
"end",
"]",
")",
")",
"\n\n",
"curr",
"=",
"curr",
"+",
"end",
"+",
"len",
"(",
"CDATA_END",
")",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // 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 |
149,257 | 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",
"(",
"data",
")",
">",
"0",
"{",
"// Find the next entity",
"idx",
":=",
"bytes",
".",
"IndexByte",
"(",
"data",
",",
"'&'",
")",
"\n",
"if",
"idx",
"==",
"-",
"1",
"{",
"buf",
".",
"Write",
"(",
"data",
")",
"\n",
"break",
"\n",
"}",
"\n\n",
"// Write and skip everything before it",
"buf",
".",
"Write",
"(",
"data",
"[",
":",
"idx",
"]",
")",
"\n",
"data",
"=",
"data",
"[",
"idx",
"+",
"1",
":",
"]",
"\n\n",
"if",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"TruncatedEntity",
"\n",
"}",
"\n\n",
"// Find the end of the entity",
"end",
":=",
"bytes",
".",
"IndexByte",
"(",
"data",
",",
"';'",
")",
"\n",
"if",
"end",
"==",
"-",
"1",
"{",
"return",
"\"",
"\"",
",",
"TruncatedEntity",
"\n",
"}",
"\n\n",
"if",
"data",
"[",
"0",
"]",
"==",
"'#'",
"{",
"// Numerical character reference",
"var",
"str",
"string",
"\n",
"base",
":=",
"10",
"\n\n",
"if",
"len",
"(",
"data",
")",
">",
"1",
"&&",
"data",
"[",
"1",
"]",
"==",
"'x'",
"{",
"str",
"=",
"string",
"(",
"data",
"[",
"2",
":",
"end",
"]",
")",
"\n",
"base",
"=",
"16",
"\n",
"}",
"else",
"{",
"str",
"=",
"string",
"(",
"data",
"[",
"1",
":",
"end",
"]",
")",
"\n",
"}",
"\n\n",
"i",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"str",
",",
"base",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"InvalidNumericReference",
"\n",
"}",
"\n\n",
"buf",
".",
"WriteRune",
"(",
"rune",
"(",
"i",
")",
")",
"\n",
"}",
"else",
"{",
"// Predefined entity",
"name",
":=",
"string",
"(",
"data",
"[",
":",
"end",
"]",
")",
"\n\n",
"var",
"c",
"byte",
"\n",
"switch",
"name",
"{",
"case",
"\"",
"\"",
":",
"c",
"=",
"'<'",
"\n",
"case",
"\"",
"\"",
":",
"c",
"=",
"'>'",
"\n",
"case",
"\"",
"\"",
":",
"c",
"=",
"'\"'",
"\n",
"case",
"\"",
"\"",
":",
"c",
"=",
"'\\''",
"\n",
"case",
"\"",
"\"",
":",
"c",
"=",
"'&'",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"buf",
".",
"WriteByte",
"(",
"c",
")",
"\n",
"}",
"\n\n",
"// Skip the entity",
"data",
"=",
"data",
"[",
"end",
"+",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,258 | 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",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"Block",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"Explicit",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"Keywords",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"Subtitle",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"Summary",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"Image",
"=",
"parseImage",
"(",
"extensions",
")",
"\n",
"feed",
".",
"Complete",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"NewFeedURL",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"feed",
".",
"Categories",
"=",
"parseCategories",
"(",
"extensions",
")",
"\n",
"feed",
".",
"Owner",
"=",
"parseOwner",
"(",
"extensions",
")",
"\n",
"feed",
".",
"Type",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"return",
"feed",
"\n",
"}"
] | // 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 |
149,259 | 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",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Block",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Duration",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Explicit",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Subtitle",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Summary",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Keywords",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Image",
"=",
"parseImage",
"(",
"extensions",
")",
"\n",
"entry",
".",
"IsClosedCaptioned",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"entry",
".",
"Order",
"=",
"parseTextExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"return",
"entry",
"\n",
"}"
] | // 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 |
149,260 | 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"event",
",",
"err",
"\n",
"}",
"\n",
"if",
"event",
"==",
"xpp",
".",
"StartTag",
"{",
"break",
"\n",
"}",
"\n\n",
"if",
"event",
"==",
"xpp",
".",
"EndDocument",
"{",
"return",
"event",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // 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 |
149,261 | 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",
"\"",
"\"",
"\n",
"}"
] | // returns the popped base URL | [
"returns",
"the",
"popped",
"base",
"URL"
] | 0e68beaf6fdf215bd1fe42a09f6de292c7032359 | https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/xmlbase.go#L155-L161 |
149,262 | 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",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"u",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"u",
",",
"err",
"\n",
"}",
"\n",
"curr",
":=",
"b",
".",
"CurrentBaseURL",
"(",
")",
"\n",
"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",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"absURL",
":=",
"b",
".",
"CurrentBaseURL",
"(",
")",
".",
"ResolveReference",
"(",
"relURL",
")",
"\n",
"return",
"absURL",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // 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 |
149,263 | 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",
"htmlReader",
":=",
"strings",
".",
"NewReader",
"(",
"relHTML",
")",
"\n\n",
"doc",
",",
"err",
":=",
"html",
".",
"Parse",
"(",
"htmlReader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"relHTML",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"visit",
"func",
"(",
"*",
"html",
".",
"Node",
")",
"\n\n",
"// 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",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"n",
".",
"Attr",
"[",
"i",
"]",
".",
"Val",
"=",
"absVal",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"c",
":=",
"n",
".",
"FirstChild",
";",
"c",
"!=",
"nil",
";",
"c",
"=",
"c",
".",
"NextSibling",
"{",
"visit",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"visit",
"(",
"doc",
")",
"\n",
"var",
"w",
"bytes",
".",
"Buffer",
"\n",
"err",
"=",
"html",
".",
"Render",
"(",
"&",
"w",
",",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"relHTML",
",",
"err",
"\n",
"}",
"\n\n",
"// html.Render() always writes a complete html5 document, so strip the html",
"// and body tags",
"absHTML",
":=",
"w",
".",
"String",
"(",
")",
"\n",
"absHTML",
"=",
"strings",
".",
"TrimPrefix",
"(",
"absHTML",
",",
"\"",
"\"",
")",
"\n",
"absHTML",
"=",
"strings",
".",
"TrimSuffix",
"(",
"absHTML",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"absHTML",
",",
"err",
"\n",
"}"
] | // 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 |
149,264 | 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",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"dateFormats",
"{",
"if",
"t",
",",
"err",
"=",
"time",
".",
"Parse",
"(",
"f",
",",
"d",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"dateFormatsWithNamedZone",
"{",
"t",
",",
"err",
"=",
"time",
".",
"Parse",
"(",
"f",
",",
"d",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// This is a format match! Now try to load the timezone name",
"loc",
",",
"err",
":=",
"time",
".",
"LoadLocation",
"(",
"t",
".",
"Location",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// We couldn't load the TZ name. Just use UTC instead...",
"return",
"t",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"t",
",",
"err",
"=",
"time",
".",
"ParseInLocation",
"(",
"f",
",",
"ds",
",",
"loc",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"t",
",",
"nil",
"\n",
"}",
"\n",
"// This should not be reachable",
"}",
"\n\n",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ds",
")",
"\n",
"return",
"\n",
"}"
] | // 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 |
149,265 | 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",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"xmlBase",
".",
"FindRoot",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"FeedTypeUnknown",
"\n",
"}",
"\n\n",
"name",
":=",
"strings",
".",
"ToLower",
"(",
"p",
".",
"Name",
")",
"\n",
"switch",
"name",
"{",
"case",
"\"",
"\"",
":",
"return",
"FeedTypeRSS",
"\n",
"case",
"\"",
"\"",
":",
"return",
"FeedTypeRSS",
"\n",
"case",
"\"",
"\"",
":",
"return",
"FeedTypeAtom",
"\n",
"default",
":",
"return",
"FeedTypeUnknown",
"\n",
"}",
"\n",
"}"
] | // 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 |
149,266 | 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",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Creator",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Author",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Subject",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Description",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Publisher",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Contributor",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Date",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Type",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Format",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Identifier",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Source",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Language",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Relation",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Coverage",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"dc",
".",
"Rights",
"=",
"parseTextArrayExtension",
"(",
"\"",
"\"",
",",
"extensions",
")",
"\n",
"return",
"dc",
"\n",
"}"
] | // 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 |
149,267 | 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",
"result",
",",
"err",
":=",
"parseExtensionElement",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Ensure the extension prefix map exists",
"if",
"_",
",",
"ok",
":=",
"fe",
"[",
"prefix",
"]",
";",
"!",
"ok",
"{",
"fe",
"[",
"prefix",
"]",
"=",
"map",
"[",
"string",
"]",
"[",
"]",
"ext",
".",
"Extension",
"{",
"}",
"\n",
"}",
"\n",
"// Ensure the extension element slice exists",
"if",
"_",
",",
"ok",
":=",
"fe",
"[",
"prefix",
"]",
"[",
"p",
".",
"Name",
"]",
";",
"!",
"ok",
"{",
"fe",
"[",
"prefix",
"]",
"[",
"p",
".",
"Name",
"]",
"=",
"[",
"]",
"ext",
".",
"Extension",
"{",
"}",
"\n",
"}",
"\n\n",
"fe",
"[",
"prefix",
"]",
"[",
"p",
".",
"Name",
"]",
"=",
"append",
"(",
"fe",
"[",
"prefix",
"]",
"[",
"p",
".",
"Name",
"]",
",",
"result",
")",
"\n",
"return",
"fe",
",",
"nil",
"\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 |
149,268 | 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 |
149,269 | 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 new",
"// reader with those bytes intact for when we",
"// attempt to parse the feeds.",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"tee",
":=",
"io",
".",
"TeeReader",
"(",
"feed",
",",
"&",
"buf",
")",
"\n",
"feedType",
":=",
"DetectFeedType",
"(",
"tee",
")",
"\n\n",
"// Glue the read bytes from the detect function",
"// back into a new reader",
"r",
":=",
"io",
".",
"MultiReader",
"(",
"&",
"buf",
",",
"feed",
")",
"\n\n",
"switch",
"feedType",
"{",
"case",
"FeedTypeAtom",
":",
"return",
"f",
".",
"parseAtomFeed",
"(",
"r",
")",
"\n",
"case",
"FeedTypeRSS",
":",
"return",
"f",
".",
"parseRSSFeed",
"(",
"r",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"ErrFeedTypeNotDetected",
"\n",
"}"
] | // 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 |
149,270 | 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",
"(",
"\"",
"\"",
",",
"feedURL",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"resp",
"!=",
"nil",
"{",
"defer",
"func",
"(",
")",
"{",
"ce",
":=",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"ce",
"!=",
"nil",
"{",
"err",
"=",
"ce",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"<",
"200",
"||",
"resp",
".",
"StatusCode",
">=",
"300",
"{",
"return",
"nil",
",",
"HTTPError",
"{",
"StatusCode",
":",
"resp",
".",
"StatusCode",
",",
"Status",
":",
"resp",
".",
"Status",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"f",
".",
"Parse",
"(",
"resp",
".",
"Body",
")",
"\n",
"}"
] | // 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 |
149,271 | 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 |
149,272 | 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",
"rp",
".",
"base",
"=",
"&",
"shared",
".",
"XMLBase",
"{",
"}",
"\n\n",
"_",
",",
"err",
":=",
"rp",
".",
"base",
".",
"FindRoot",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"rp",
".",
"parseRoot",
"(",
"p",
")",
"\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 |
149,273 | vulcand/oxy | forward/rewrite.go | Rewrite | func (rw *HeaderRewriter) Rewrite(req *http.Request) {
if !rw.TrustForwardHeader {
utils.RemoveHeaders(req.Header, XHeaders...)
}
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
clientIP = ipv6fix(clientIP)
// If not websocket, done in http.ReverseProxy
if IsWebsocketRequest(req) {
if prior, ok := req.Header[XForwardedFor]; ok {
req.Header.Set(XForwardedFor, strings.Join(prior, ", ")+", "+clientIP)
} else {
req.Header.Set(XForwardedFor, clientIP)
}
}
if req.Header.Get(XRealIp) == "" {
req.Header.Set(XRealIp, clientIP)
}
}
xfProto := req.Header.Get(XForwardedProto)
if xfProto == "" {
if req.TLS != nil {
req.Header.Set(XForwardedProto, "https")
} else {
req.Header.Set(XForwardedProto, "http")
}
}
if IsWebsocketRequest(req) {
if req.Header.Get(XForwardedProto) == "https" {
req.Header.Set(XForwardedProto, "wss")
} else {
req.Header.Set(XForwardedProto, "ws")
}
}
if xfPort := req.Header.Get(XForwardedPort); xfPort == "" {
req.Header.Set(XForwardedPort, forwardedPort(req))
}
if xfHost := req.Header.Get(XForwardedHost); xfHost == "" && req.Host != "" {
req.Header.Set(XForwardedHost, req.Host)
}
if rw.Hostname != "" {
req.Header.Set(XForwardedServer, rw.Hostname)
}
} | go | func (rw *HeaderRewriter) Rewrite(req *http.Request) {
if !rw.TrustForwardHeader {
utils.RemoveHeaders(req.Header, XHeaders...)
}
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
clientIP = ipv6fix(clientIP)
// If not websocket, done in http.ReverseProxy
if IsWebsocketRequest(req) {
if prior, ok := req.Header[XForwardedFor]; ok {
req.Header.Set(XForwardedFor, strings.Join(prior, ", ")+", "+clientIP)
} else {
req.Header.Set(XForwardedFor, clientIP)
}
}
if req.Header.Get(XRealIp) == "" {
req.Header.Set(XRealIp, clientIP)
}
}
xfProto := req.Header.Get(XForwardedProto)
if xfProto == "" {
if req.TLS != nil {
req.Header.Set(XForwardedProto, "https")
} else {
req.Header.Set(XForwardedProto, "http")
}
}
if IsWebsocketRequest(req) {
if req.Header.Get(XForwardedProto) == "https" {
req.Header.Set(XForwardedProto, "wss")
} else {
req.Header.Set(XForwardedProto, "ws")
}
}
if xfPort := req.Header.Get(XForwardedPort); xfPort == "" {
req.Header.Set(XForwardedPort, forwardedPort(req))
}
if xfHost := req.Header.Get(XForwardedHost); xfHost == "" && req.Host != "" {
req.Header.Set(XForwardedHost, req.Host)
}
if rw.Hostname != "" {
req.Header.Set(XForwardedServer, rw.Hostname)
}
} | [
"func",
"(",
"rw",
"*",
"HeaderRewriter",
")",
"Rewrite",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"!",
"rw",
".",
"TrustForwardHeader",
"{",
"utils",
".",
"RemoveHeaders",
"(",
"req",
".",
"Header",
",",
"XHeaders",
"...",
")",
"\n",
"}",
"\n\n",
"if",
"clientIP",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"req",
".",
"RemoteAddr",
")",
";",
"err",
"==",
"nil",
"{",
"clientIP",
"=",
"ipv6fix",
"(",
"clientIP",
")",
"\n",
"// If not websocket, done in http.ReverseProxy",
"if",
"IsWebsocketRequest",
"(",
"req",
")",
"{",
"if",
"prior",
",",
"ok",
":=",
"req",
".",
"Header",
"[",
"XForwardedFor",
"]",
";",
"ok",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedFor",
",",
"strings",
".",
"Join",
"(",
"prior",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
"+",
"clientIP",
")",
"\n",
"}",
"else",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedFor",
",",
"clientIP",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"req",
".",
"Header",
".",
"Get",
"(",
"XRealIp",
")",
"==",
"\"",
"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XRealIp",
",",
"clientIP",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"xfProto",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"XForwardedProto",
")",
"\n",
"if",
"xfProto",
"==",
"\"",
"\"",
"{",
"if",
"req",
".",
"TLS",
"!=",
"nil",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedProto",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedProto",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"IsWebsocketRequest",
"(",
"req",
")",
"{",
"if",
"req",
".",
"Header",
".",
"Get",
"(",
"XForwardedProto",
")",
"==",
"\"",
"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedProto",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedProto",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"xfPort",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"XForwardedPort",
")",
";",
"xfPort",
"==",
"\"",
"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedPort",
",",
"forwardedPort",
"(",
"req",
")",
")",
"\n",
"}",
"\n\n",
"if",
"xfHost",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"XForwardedHost",
")",
";",
"xfHost",
"==",
"\"",
"\"",
"&&",
"req",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedHost",
",",
"req",
".",
"Host",
")",
"\n",
"}",
"\n\n",
"if",
"rw",
".",
"Hostname",
"!=",
"\"",
"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"XForwardedServer",
",",
"rw",
".",
"Hostname",
")",
"\n",
"}",
"\n",
"}"
] | // Rewrite rewrite request headers | [
"Rewrite",
"rewrite",
"request",
"headers"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/forward/rewrite.go#L23-L72 |
149,274 | vulcand/oxy | ratelimit/bucketset.go | NewTokenBucketSet | func NewTokenBucketSet(rates *RateSet, clock timetools.TimeProvider) *TokenBucketSet {
tbs := new(TokenBucketSet)
tbs.clock = clock
// In the majority of cases we will have only one bucket.
tbs.buckets = make(map[time.Duration]*tokenBucket, len(rates.m))
for _, rate := range rates.m {
newBucket := newTokenBucket(rate, clock)
tbs.buckets[rate.period] = newBucket
tbs.maxPeriod = maxDuration(tbs.maxPeriod, rate.period)
}
return tbs
} | go | func NewTokenBucketSet(rates *RateSet, clock timetools.TimeProvider) *TokenBucketSet {
tbs := new(TokenBucketSet)
tbs.clock = clock
// In the majority of cases we will have only one bucket.
tbs.buckets = make(map[time.Duration]*tokenBucket, len(rates.m))
for _, rate := range rates.m {
newBucket := newTokenBucket(rate, clock)
tbs.buckets[rate.period] = newBucket
tbs.maxPeriod = maxDuration(tbs.maxPeriod, rate.period)
}
return tbs
} | [
"func",
"NewTokenBucketSet",
"(",
"rates",
"*",
"RateSet",
",",
"clock",
"timetools",
".",
"TimeProvider",
")",
"*",
"TokenBucketSet",
"{",
"tbs",
":=",
"new",
"(",
"TokenBucketSet",
")",
"\n",
"tbs",
".",
"clock",
"=",
"clock",
"\n",
"// In the majority of cases we will have only one bucket.",
"tbs",
".",
"buckets",
"=",
"make",
"(",
"map",
"[",
"time",
".",
"Duration",
"]",
"*",
"tokenBucket",
",",
"len",
"(",
"rates",
".",
"m",
")",
")",
"\n",
"for",
"_",
",",
"rate",
":=",
"range",
"rates",
".",
"m",
"{",
"newBucket",
":=",
"newTokenBucket",
"(",
"rate",
",",
"clock",
")",
"\n",
"tbs",
".",
"buckets",
"[",
"rate",
".",
"period",
"]",
"=",
"newBucket",
"\n",
"tbs",
".",
"maxPeriod",
"=",
"maxDuration",
"(",
"tbs",
".",
"maxPeriod",
",",
"rate",
".",
"period",
")",
"\n",
"}",
"\n",
"return",
"tbs",
"\n",
"}"
] | // NewTokenBucketSet creates a `TokenBucketSet` from the specified `rates`. | [
"NewTokenBucketSet",
"creates",
"a",
"TokenBucketSet",
"from",
"the",
"specified",
"rates",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/bucketset.go#L20-L31 |
149,275 | vulcand/oxy | ratelimit/bucketset.go | Update | func (tbs *TokenBucketSet) Update(rates *RateSet) {
// Update existing buckets and delete those that have no corresponding spec.
for _, bucket := range tbs.buckets {
if rate, ok := rates.m[bucket.period]; ok {
bucket.update(rate)
} else {
delete(tbs.buckets, bucket.period)
}
}
// Add missing buckets.
for _, rate := range rates.m {
if _, ok := tbs.buckets[rate.period]; !ok {
newBucket := newTokenBucket(rate, tbs.clock)
tbs.buckets[rate.period] = newBucket
}
}
// Identify the maximum period in the set
tbs.maxPeriod = 0
for _, bucket := range tbs.buckets {
tbs.maxPeriod = maxDuration(tbs.maxPeriod, bucket.period)
}
} | go | func (tbs *TokenBucketSet) Update(rates *RateSet) {
// Update existing buckets and delete those that have no corresponding spec.
for _, bucket := range tbs.buckets {
if rate, ok := rates.m[bucket.period]; ok {
bucket.update(rate)
} else {
delete(tbs.buckets, bucket.period)
}
}
// Add missing buckets.
for _, rate := range rates.m {
if _, ok := tbs.buckets[rate.period]; !ok {
newBucket := newTokenBucket(rate, tbs.clock)
tbs.buckets[rate.period] = newBucket
}
}
// Identify the maximum period in the set
tbs.maxPeriod = 0
for _, bucket := range tbs.buckets {
tbs.maxPeriod = maxDuration(tbs.maxPeriod, bucket.period)
}
} | [
"func",
"(",
"tbs",
"*",
"TokenBucketSet",
")",
"Update",
"(",
"rates",
"*",
"RateSet",
")",
"{",
"// Update existing buckets and delete those that have no corresponding spec.",
"for",
"_",
",",
"bucket",
":=",
"range",
"tbs",
".",
"buckets",
"{",
"if",
"rate",
",",
"ok",
":=",
"rates",
".",
"m",
"[",
"bucket",
".",
"period",
"]",
";",
"ok",
"{",
"bucket",
".",
"update",
"(",
"rate",
")",
"\n",
"}",
"else",
"{",
"delete",
"(",
"tbs",
".",
"buckets",
",",
"bucket",
".",
"period",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Add missing buckets.",
"for",
"_",
",",
"rate",
":=",
"range",
"rates",
".",
"m",
"{",
"if",
"_",
",",
"ok",
":=",
"tbs",
".",
"buckets",
"[",
"rate",
".",
"period",
"]",
";",
"!",
"ok",
"{",
"newBucket",
":=",
"newTokenBucket",
"(",
"rate",
",",
"tbs",
".",
"clock",
")",
"\n",
"tbs",
".",
"buckets",
"[",
"rate",
".",
"period",
"]",
"=",
"newBucket",
"\n",
"}",
"\n",
"}",
"\n",
"// Identify the maximum period in the set",
"tbs",
".",
"maxPeriod",
"=",
"0",
"\n",
"for",
"_",
",",
"bucket",
":=",
"range",
"tbs",
".",
"buckets",
"{",
"tbs",
".",
"maxPeriod",
"=",
"maxDuration",
"(",
"tbs",
".",
"maxPeriod",
",",
"bucket",
".",
"period",
")",
"\n",
"}",
"\n",
"}"
] | // Update brings the buckets in the set in accordance with the provided `rates`. | [
"Update",
"brings",
"the",
"buckets",
"in",
"the",
"set",
"in",
"accordance",
"with",
"the",
"provided",
"rates",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/bucketset.go#L34-L55 |
149,276 | vulcand/oxy | ratelimit/bucketset.go | Consume | func (tbs *TokenBucketSet) Consume(tokens int64) (time.Duration, error) {
var maxDelay time.Duration = UndefinedDelay
var firstErr error
for _, tokenBucket := range tbs.buckets {
// We keep calling `Consume` even after a error is returned for one of
// buckets because that allows us to simplify the rollback procedure,
// that is to just call `Rollback` for all buckets.
delay, err := tokenBucket.consume(tokens)
if firstErr == nil {
if err != nil {
firstErr = err
} else {
maxDelay = maxDuration(maxDelay, delay)
}
}
}
// If we could not make ALL buckets consume tokens for whatever reason,
// then rollback consumption for all of them.
if firstErr != nil || maxDelay > 0 {
for _, tokenBucket := range tbs.buckets {
tokenBucket.rollback()
}
}
return maxDelay, firstErr
} | go | func (tbs *TokenBucketSet) Consume(tokens int64) (time.Duration, error) {
var maxDelay time.Duration = UndefinedDelay
var firstErr error
for _, tokenBucket := range tbs.buckets {
// We keep calling `Consume` even after a error is returned for one of
// buckets because that allows us to simplify the rollback procedure,
// that is to just call `Rollback` for all buckets.
delay, err := tokenBucket.consume(tokens)
if firstErr == nil {
if err != nil {
firstErr = err
} else {
maxDelay = maxDuration(maxDelay, delay)
}
}
}
// If we could not make ALL buckets consume tokens for whatever reason,
// then rollback consumption for all of them.
if firstErr != nil || maxDelay > 0 {
for _, tokenBucket := range tbs.buckets {
tokenBucket.rollback()
}
}
return maxDelay, firstErr
} | [
"func",
"(",
"tbs",
"*",
"TokenBucketSet",
")",
"Consume",
"(",
"tokens",
"int64",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"var",
"maxDelay",
"time",
".",
"Duration",
"=",
"UndefinedDelay",
"\n",
"var",
"firstErr",
"error",
"\n",
"for",
"_",
",",
"tokenBucket",
":=",
"range",
"tbs",
".",
"buckets",
"{",
"// We keep calling `Consume` even after a error is returned for one of",
"// buckets because that allows us to simplify the rollback procedure,",
"// that is to just call `Rollback` for all buckets.",
"delay",
",",
"err",
":=",
"tokenBucket",
".",
"consume",
"(",
"tokens",
")",
"\n",
"if",
"firstErr",
"==",
"nil",
"{",
"if",
"err",
"!=",
"nil",
"{",
"firstErr",
"=",
"err",
"\n",
"}",
"else",
"{",
"maxDelay",
"=",
"maxDuration",
"(",
"maxDelay",
",",
"delay",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// If we could not make ALL buckets consume tokens for whatever reason,",
"// then rollback consumption for all of them.",
"if",
"firstErr",
"!=",
"nil",
"||",
"maxDelay",
">",
"0",
"{",
"for",
"_",
",",
"tokenBucket",
":=",
"range",
"tbs",
".",
"buckets",
"{",
"tokenBucket",
".",
"rollback",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"maxDelay",
",",
"firstErr",
"\n",
"}"
] | // Consume consume tokens | [
"Consume",
"consume",
"tokens"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/bucketset.go#L58-L82 |
149,277 | vulcand/oxy | ratelimit/bucketset.go | debugState | func (tbs *TokenBucketSet) debugState() string {
periods := sort.IntSlice(make([]int, 0, len(tbs.buckets)))
for period := range tbs.buckets {
periods = append(periods, int(period))
}
sort.Sort(periods)
bucketRepr := make([]string, 0, len(tbs.buckets))
for _, period := range periods {
bucket := tbs.buckets[time.Duration(period)]
bucketRepr = append(bucketRepr, fmt.Sprintf("{%v: %v}", bucket.period, bucket.availableTokens))
}
return strings.Join(bucketRepr, ", ")
} | go | func (tbs *TokenBucketSet) debugState() string {
periods := sort.IntSlice(make([]int, 0, len(tbs.buckets)))
for period := range tbs.buckets {
periods = append(periods, int(period))
}
sort.Sort(periods)
bucketRepr := make([]string, 0, len(tbs.buckets))
for _, period := range periods {
bucket := tbs.buckets[time.Duration(period)]
bucketRepr = append(bucketRepr, fmt.Sprintf("{%v: %v}", bucket.period, bucket.availableTokens))
}
return strings.Join(bucketRepr, ", ")
} | [
"func",
"(",
"tbs",
"*",
"TokenBucketSet",
")",
"debugState",
"(",
")",
"string",
"{",
"periods",
":=",
"sort",
".",
"IntSlice",
"(",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"len",
"(",
"tbs",
".",
"buckets",
")",
")",
")",
"\n",
"for",
"period",
":=",
"range",
"tbs",
".",
"buckets",
"{",
"periods",
"=",
"append",
"(",
"periods",
",",
"int",
"(",
"period",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"periods",
")",
"\n",
"bucketRepr",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"tbs",
".",
"buckets",
")",
")",
"\n",
"for",
"_",
",",
"period",
":=",
"range",
"periods",
"{",
"bucket",
":=",
"tbs",
".",
"buckets",
"[",
"time",
".",
"Duration",
"(",
"period",
")",
"]",
"\n",
"bucketRepr",
"=",
"append",
"(",
"bucketRepr",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bucket",
".",
"period",
",",
"bucket",
".",
"availableTokens",
")",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"bucketRepr",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // debugState returns string that reflects the current state of all buckets in
// this set. It is intended to be used for debugging and testing only. | [
"debugState",
"returns",
"string",
"that",
"reflects",
"the",
"current",
"state",
"of",
"all",
"buckets",
"in",
"this",
"set",
".",
"It",
"is",
"intended",
"to",
"be",
"used",
"for",
"debugging",
"and",
"testing",
"only",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/ratelimit/bucketset.go#L91-L103 |
149,278 | vulcand/oxy | cbreaker/predicates.go | parseExpression | func parseExpression(in string) (hpredicate, error) {
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: and,
OR: or,
EQ: eq,
NEQ: neq,
LT: lt,
LE: le,
GT: gt,
GE: ge,
},
Functions: map[string]interface{}{
"LatencyAtQuantileMS": latencyAtQuantile,
"NetworkErrorRatio": networkErrorRatio,
"ResponseCodeRatio": responseCodeRatio,
},
})
if err != nil {
return nil, err
}
out, err := p.Parse(in)
if err != nil {
return nil, err
}
pr, ok := out.(hpredicate)
if !ok {
return nil, fmt.Errorf("expected predicate, got %T", out)
}
return pr, nil
} | go | func parseExpression(in string) (hpredicate, error) {
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: and,
OR: or,
EQ: eq,
NEQ: neq,
LT: lt,
LE: le,
GT: gt,
GE: ge,
},
Functions: map[string]interface{}{
"LatencyAtQuantileMS": latencyAtQuantile,
"NetworkErrorRatio": networkErrorRatio,
"ResponseCodeRatio": responseCodeRatio,
},
})
if err != nil {
return nil, err
}
out, err := p.Parse(in)
if err != nil {
return nil, err
}
pr, ok := out.(hpredicate)
if !ok {
return nil, fmt.Errorf("expected predicate, got %T", out)
}
return pr, nil
} | [
"func",
"parseExpression",
"(",
"in",
"string",
")",
"(",
"hpredicate",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"predicate",
".",
"NewParser",
"(",
"predicate",
".",
"Def",
"{",
"Operators",
":",
"predicate",
".",
"Operators",
"{",
"AND",
":",
"and",
",",
"OR",
":",
"or",
",",
"EQ",
":",
"eq",
",",
"NEQ",
":",
"neq",
",",
"LT",
":",
"lt",
",",
"LE",
":",
"le",
",",
"GT",
":",
"gt",
",",
"GE",
":",
"ge",
",",
"}",
",",
"Functions",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"latencyAtQuantile",
",",
"\"",
"\"",
":",
"networkErrorRatio",
",",
"\"",
"\"",
":",
"responseCodeRatio",
",",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"out",
",",
"err",
":=",
"p",
".",
"Parse",
"(",
"in",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"pr",
",",
"ok",
":=",
"out",
".",
"(",
"hpredicate",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"out",
")",
"\n",
"}",
"\n",
"return",
"pr",
",",
"nil",
"\n",
"}"
] | // parseExpression parses expression in the go language into predicates. | [
"parseExpression",
"parses",
"expression",
"in",
"the",
"go",
"language",
"into",
"predicates",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/predicates.go#L13-L43 |
149,279 | vulcand/oxy | cbreaker/predicates.go | or | func or(fns ...hpredicate) hpredicate {
return func(c *CircuitBreaker) bool {
for _, fn := range fns {
if fn(c) {
return true
}
}
return false
}
} | go | func or(fns ...hpredicate) hpredicate {
return func(c *CircuitBreaker) bool {
for _, fn := range fns {
if fn(c) {
return true
}
}
return false
}
} | [
"func",
"or",
"(",
"fns",
"...",
"hpredicate",
")",
"hpredicate",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"bool",
"{",
"for",
"_",
",",
"fn",
":=",
"range",
"fns",
"{",
"if",
"fn",
"(",
"c",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // or returns predicate by joining the passed predicates with logical 'or' | [
"or",
"returns",
"predicate",
"by",
"joining",
"the",
"passed",
"predicates",
"with",
"logical",
"or"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/predicates.go#L72-L81 |
149,280 | vulcand/oxy | cbreaker/predicates.go | neq | func neq(m interface{}, value interface{}) (hpredicate, error) {
p, err := eq(m, value)
if err != nil {
return nil, err
}
return not(p), nil
} | go | func neq(m interface{}, value interface{}) (hpredicate, error) {
p, err := eq(m, value)
if err != nil {
return nil, err
}
return not(p), nil
} | [
"func",
"neq",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"hpredicate",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"eq",
"(",
"m",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"not",
"(",
"p",
")",
",",
"nil",
"\n",
"}"
] | // neq returns predicate that tests for inequality of the value of the mapper and the constant | [
"neq",
"returns",
"predicate",
"that",
"tests",
"for",
"inequality",
"of",
"the",
"value",
"of",
"the",
"mapper",
"and",
"the",
"constant"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/predicates.go#L114-L120 |
149,281 | vulcand/oxy | cbreaker/predicates.go | le | func le(m interface{}, value interface{}) (hpredicate, error) {
l, err := lt(m, value)
if err != nil {
return nil, err
}
e, err := eq(m, value)
if err != nil {
return nil, err
}
return func(c *CircuitBreaker) bool {
return l(c) || e(c)
}, nil
} | go | func le(m interface{}, value interface{}) (hpredicate, error) {
l, err := lt(m, value)
if err != nil {
return nil, err
}
e, err := eq(m, value)
if err != nil {
return nil, err
}
return func(c *CircuitBreaker) bool {
return l(c) || e(c)
}, nil
} | [
"func",
"le",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"hpredicate",
",",
"error",
")",
"{",
"l",
",",
"err",
":=",
"lt",
"(",
"m",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"e",
",",
"err",
":=",
"eq",
"(",
"m",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"bool",
"{",
"return",
"l",
"(",
"c",
")",
"||",
"e",
"(",
"c",
")",
"\n",
"}",
",",
"nil",
"\n",
"}"
] | // le returns predicate that tests that value of the mapper function is less or equal than the constant | [
"le",
"returns",
"predicate",
"that",
"tests",
"that",
"value",
"of",
"the",
"mapper",
"function",
"is",
"less",
"or",
"equal",
"than",
"the",
"constant"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/predicates.go#L134-L146 |
149,282 | vulcand/oxy | cbreaker/predicates.go | gt | func gt(m interface{}, value interface{}) (hpredicate, error) {
switch mapper := m.(type) {
case toInt:
return intGT(mapper, value)
case toFloat64:
return float64GT(mapper, value)
}
return nil, fmt.Errorf("gt: unsupported argument: %T", m)
} | go | func gt(m interface{}, value interface{}) (hpredicate, error) {
switch mapper := m.(type) {
case toInt:
return intGT(mapper, value)
case toFloat64:
return float64GT(mapper, value)
}
return nil, fmt.Errorf("gt: unsupported argument: %T", m)
} | [
"func",
"gt",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"hpredicate",
",",
"error",
")",
"{",
"switch",
"mapper",
":=",
"m",
".",
"(",
"type",
")",
"{",
"case",
"toInt",
":",
"return",
"intGT",
"(",
"mapper",
",",
"value",
")",
"\n",
"case",
"toFloat64",
":",
"return",
"float64GT",
"(",
"mapper",
",",
"value",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"m",
")",
"\n",
"}"
] | // gt returns predicate that tests that value of the mapper function is greater than the constant | [
"gt",
"returns",
"predicate",
"that",
"tests",
"that",
"value",
"of",
"the",
"mapper",
"function",
"is",
"greater",
"than",
"the",
"constant"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/predicates.go#L149-L157 |
149,283 | vulcand/oxy | cbreaker/predicates.go | ge | func ge(m interface{}, value interface{}) (hpredicate, error) {
g, err := gt(m, value)
if err != nil {
return nil, err
}
e, err := eq(m, value)
if err != nil {
return nil, err
}
return func(c *CircuitBreaker) bool {
return g(c) || e(c)
}, nil
} | go | func ge(m interface{}, value interface{}) (hpredicate, error) {
g, err := gt(m, value)
if err != nil {
return nil, err
}
e, err := eq(m, value)
if err != nil {
return nil, err
}
return func(c *CircuitBreaker) bool {
return g(c) || e(c)
}, nil
} | [
"func",
"ge",
"(",
"m",
"interface",
"{",
"}",
",",
"value",
"interface",
"{",
"}",
")",
"(",
"hpredicate",
",",
"error",
")",
"{",
"g",
",",
"err",
":=",
"gt",
"(",
"m",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"e",
",",
"err",
":=",
"eq",
"(",
"m",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"bool",
"{",
"return",
"g",
"(",
"c",
")",
"||",
"e",
"(",
"c",
")",
"\n",
"}",
",",
"nil",
"\n",
"}"
] | // ge returns predicate that tests that value of the mapper function is less or equal than the constant | [
"ge",
"returns",
"predicate",
"that",
"tests",
"that",
"value",
"of",
"the",
"mapper",
"function",
"is",
"less",
"or",
"equal",
"than",
"the",
"constant"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/predicates.go#L160-L172 |
149,284 | vulcand/oxy | cbreaker/cbreaker.go | activateFallback | func (c *CircuitBreaker) activateFallback(w http.ResponseWriter, req *http.Request) bool {
// Quick check with read locks optimized for normal operation use-case
if c.isStandby() {
return false
}
// Circuit breaker is in tripped or recovering state
c.m.Lock()
defer c.m.Unlock()
c.log.Warnf("%v is in error state", c)
switch c.state {
case stateStandby:
// someone else has set it to standby just now
return false
case stateTripped:
if c.clock.UtcNow().Before(c.until) {
return true
}
// We have been in active state enough, enter recovering state
c.setRecovering()
fallthrough
case stateRecovering:
// We have been in recovering state enough, enter standby and allow request
if c.clock.UtcNow().After(c.until) {
c.setState(stateStandby, c.clock.UtcNow())
return false
}
// ratio controller allows this request
if c.rc.allowRequest() {
return false
}
return true
}
return false
} | go | func (c *CircuitBreaker) activateFallback(w http.ResponseWriter, req *http.Request) bool {
// Quick check with read locks optimized for normal operation use-case
if c.isStandby() {
return false
}
// Circuit breaker is in tripped or recovering state
c.m.Lock()
defer c.m.Unlock()
c.log.Warnf("%v is in error state", c)
switch c.state {
case stateStandby:
// someone else has set it to standby just now
return false
case stateTripped:
if c.clock.UtcNow().Before(c.until) {
return true
}
// We have been in active state enough, enter recovering state
c.setRecovering()
fallthrough
case stateRecovering:
// We have been in recovering state enough, enter standby and allow request
if c.clock.UtcNow().After(c.until) {
c.setState(stateStandby, c.clock.UtcNow())
return false
}
// ratio controller allows this request
if c.rc.allowRequest() {
return false
}
return true
}
return false
} | [
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"activateFallback",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"// Quick check with read locks optimized for normal operation use-case",
"if",
"c",
".",
"isStandby",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// Circuit breaker is in tripped or recovering state",
"c",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"m",
".",
"Unlock",
"(",
")",
"\n\n",
"c",
".",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n\n",
"switch",
"c",
".",
"state",
"{",
"case",
"stateStandby",
":",
"// someone else has set it to standby just now",
"return",
"false",
"\n",
"case",
"stateTripped",
":",
"if",
"c",
".",
"clock",
".",
"UtcNow",
"(",
")",
".",
"Before",
"(",
"c",
".",
"until",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// We have been in active state enough, enter recovering state",
"c",
".",
"setRecovering",
"(",
")",
"\n",
"fallthrough",
"\n",
"case",
"stateRecovering",
":",
"// We have been in recovering state enough, enter standby and allow request",
"if",
"c",
".",
"clock",
".",
"UtcNow",
"(",
")",
".",
"After",
"(",
"c",
".",
"until",
")",
"{",
"c",
".",
"setState",
"(",
"stateStandby",
",",
"c",
".",
"clock",
".",
"UtcNow",
"(",
")",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"// ratio controller allows this request",
"if",
"c",
".",
"rc",
".",
"allowRequest",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // updateState updates internal state and returns true if fallback should be used and false otherwise | [
"updateState",
"updates",
"internal",
"state",
"and",
"returns",
"true",
"if",
"fallback",
"should",
"be",
"used",
"and",
"false",
"otherwise"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L133-L168 |
149,285 | vulcand/oxy | cbreaker/cbreaker.go | String | func (c *CircuitBreaker) String() string {
switch c.state {
case stateTripped, stateRecovering:
return fmt.Sprintf("CircuitBreaker(state=%v, until=%v)", c.state, c.until)
default:
return fmt.Sprintf("CircuitBreaker(state=%v)", c.state)
}
} | go | func (c *CircuitBreaker) String() string {
switch c.state {
case stateTripped, stateRecovering:
return fmt.Sprintf("CircuitBreaker(state=%v, until=%v)", c.state, c.until)
default:
return fmt.Sprintf("CircuitBreaker(state=%v)", c.state)
}
} | [
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"c",
".",
"state",
"{",
"case",
"stateTripped",
",",
"stateRecovering",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"state",
",",
"c",
".",
"until",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"state",
")",
"\n",
"}",
"\n",
"}"
] | // String returns log-friendly representation of the circuit breaker state | [
"String",
"returns",
"log",
"-",
"friendly",
"representation",
"of",
"the",
"circuit",
"breaker",
"state"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L191-L198 |
149,286 | vulcand/oxy | cbreaker/cbreaker.go | exec | func (c *CircuitBreaker) exec(s SideEffect) {
if s == nil {
return
}
go func() {
if err := s.Exec(); err != nil {
c.log.Errorf("%v side effect failure: %v", c, err)
}
}()
} | go | func (c *CircuitBreaker) exec(s SideEffect) {
if s == nil {
return
}
go func() {
if err := s.Exec(); err != nil {
c.log.Errorf("%v side effect failure: %v", c, err)
}
}()
} | [
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"exec",
"(",
"s",
"SideEffect",
")",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"s",
".",
"Exec",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"c",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // exec executes side effect | [
"exec",
"executes",
"side",
"effect"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L201-L210 |
149,287 | vulcand/oxy | cbreaker/cbreaker.go | checkAndSet | func (c *CircuitBreaker) checkAndSet() {
if !c.timeToCheck() {
return
}
c.m.Lock()
defer c.m.Unlock()
// Other goroutine could have updated the lastCheck variable before we grabbed mutex
if !c.clock.UtcNow().After(c.lastCheck) {
return
}
c.lastCheck = c.clock.UtcNow().Add(c.checkPeriod)
if c.state == stateTripped {
c.log.Debugf("%v skip set tripped", c)
return
}
if !c.condition(c) {
return
}
c.setState(stateTripped, c.clock.UtcNow().Add(c.fallbackDuration))
c.metrics.Reset()
} | go | func (c *CircuitBreaker) checkAndSet() {
if !c.timeToCheck() {
return
}
c.m.Lock()
defer c.m.Unlock()
// Other goroutine could have updated the lastCheck variable before we grabbed mutex
if !c.clock.UtcNow().After(c.lastCheck) {
return
}
c.lastCheck = c.clock.UtcNow().Add(c.checkPeriod)
if c.state == stateTripped {
c.log.Debugf("%v skip set tripped", c)
return
}
if !c.condition(c) {
return
}
c.setState(stateTripped, c.clock.UtcNow().Add(c.fallbackDuration))
c.metrics.Reset()
} | [
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"checkAndSet",
"(",
")",
"{",
"if",
"!",
"c",
".",
"timeToCheck",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"c",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"m",
".",
"Unlock",
"(",
")",
"\n\n",
"// Other goroutine could have updated the lastCheck variable before we grabbed mutex",
"if",
"!",
"c",
".",
"clock",
".",
"UtcNow",
"(",
")",
".",
"After",
"(",
"c",
".",
"lastCheck",
")",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"lastCheck",
"=",
"c",
".",
"clock",
".",
"UtcNow",
"(",
")",
".",
"Add",
"(",
"c",
".",
"checkPeriod",
")",
"\n\n",
"if",
"c",
".",
"state",
"==",
"stateTripped",
"{",
"c",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"c",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"!",
"c",
".",
"condition",
"(",
"c",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"c",
".",
"setState",
"(",
"stateTripped",
",",
"c",
".",
"clock",
".",
"UtcNow",
"(",
")",
".",
"Add",
"(",
"c",
".",
"fallbackDuration",
")",
")",
"\n",
"c",
".",
"metrics",
".",
"Reset",
"(",
")",
"\n",
"}"
] | // Checks if tripping condition matches and sets circuit breaker to the tripped state | [
"Checks",
"if",
"tripping",
"condition",
"matches",
"and",
"sets",
"circuit",
"breaker",
"to",
"the",
"tripped",
"state"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L231-L256 |
149,288 | vulcand/oxy | cbreaker/cbreaker.go | Clock | func Clock(clock timetools.TimeProvider) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.clock = clock
return nil
}
} | go | func Clock(clock timetools.TimeProvider) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.clock = clock
return nil
}
} | [
"func",
"Clock",
"(",
"clock",
"timetools",
".",
"TimeProvider",
")",
"CircuitBreakerOption",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"error",
"{",
"c",
".",
"clock",
"=",
"clock",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Clock allows you to fake che CircuitBreaker's view of the current time.
// Intended for unit tests. | [
"Clock",
"allows",
"you",
"to",
"fake",
"che",
"CircuitBreaker",
"s",
"view",
"of",
"the",
"current",
"time",
".",
"Intended",
"for",
"unit",
"tests",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L269-L274 |
149,289 | vulcand/oxy | cbreaker/cbreaker.go | FallbackDuration | func FallbackDuration(d time.Duration) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.fallbackDuration = d
return nil
}
} | go | func FallbackDuration(d time.Duration) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.fallbackDuration = d
return nil
}
} | [
"func",
"FallbackDuration",
"(",
"d",
"time",
".",
"Duration",
")",
"CircuitBreakerOption",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"error",
"{",
"c",
".",
"fallbackDuration",
"=",
"d",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // FallbackDuration is how long the CircuitBreaker will remain in the Tripped
// state before trying to recover. | [
"FallbackDuration",
"is",
"how",
"long",
"the",
"CircuitBreaker",
"will",
"remain",
"in",
"the",
"Tripped",
"state",
"before",
"trying",
"to",
"recover",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L278-L283 |
149,290 | vulcand/oxy | cbreaker/cbreaker.go | RecoveryDuration | func RecoveryDuration(d time.Duration) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.recoveryDuration = d
return nil
}
} | go | func RecoveryDuration(d time.Duration) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.recoveryDuration = d
return nil
}
} | [
"func",
"RecoveryDuration",
"(",
"d",
"time",
".",
"Duration",
")",
"CircuitBreakerOption",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"error",
"{",
"c",
".",
"recoveryDuration",
"=",
"d",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // RecoveryDuration is how long the CircuitBreaker will take to ramp up
// requests during the Recovering state. | [
"RecoveryDuration",
"is",
"how",
"long",
"the",
"CircuitBreaker",
"will",
"take",
"to",
"ramp",
"up",
"requests",
"during",
"the",
"Recovering",
"state",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L287-L292 |
149,291 | vulcand/oxy | cbreaker/cbreaker.go | CheckPeriod | func CheckPeriod(d time.Duration) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.checkPeriod = d
return nil
}
} | go | func CheckPeriod(d time.Duration) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.checkPeriod = d
return nil
}
} | [
"func",
"CheckPeriod",
"(",
"d",
"time",
".",
"Duration",
")",
"CircuitBreakerOption",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"error",
"{",
"c",
".",
"checkPeriod",
"=",
"d",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // CheckPeriod is how long the CircuitBreaker will wait between successive
// checks of the breaker condition. | [
"CheckPeriod",
"is",
"how",
"long",
"the",
"CircuitBreaker",
"will",
"wait",
"between",
"successive",
"checks",
"of",
"the",
"breaker",
"condition",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L296-L301 |
149,292 | vulcand/oxy | cbreaker/cbreaker.go | OnTripped | func OnTripped(s SideEffect) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.onTripped = s
return nil
}
} | go | func OnTripped(s SideEffect) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.onTripped = s
return nil
}
} | [
"func",
"OnTripped",
"(",
"s",
"SideEffect",
")",
"CircuitBreakerOption",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"error",
"{",
"c",
".",
"onTripped",
"=",
"s",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // OnTripped sets a SideEffect to run when entering the Tripped state.
// Only one SideEffect can be set for this hook. | [
"OnTripped",
"sets",
"a",
"SideEffect",
"to",
"run",
"when",
"entering",
"the",
"Tripped",
"state",
".",
"Only",
"one",
"SideEffect",
"can",
"be",
"set",
"for",
"this",
"hook",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L305-L310 |
149,293 | vulcand/oxy | cbreaker/cbreaker.go | OnStandby | func OnStandby(s SideEffect) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.onStandby = s
return nil
}
} | go | func OnStandby(s SideEffect) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.onStandby = s
return nil
}
} | [
"func",
"OnStandby",
"(",
"s",
"SideEffect",
")",
"CircuitBreakerOption",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"error",
"{",
"c",
".",
"onStandby",
"=",
"s",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // OnStandby sets a SideEffect to run when entering the Standby state.
// Only one SideEffect can be set for this hook. | [
"OnStandby",
"sets",
"a",
"SideEffect",
"to",
"run",
"when",
"entering",
"the",
"Standby",
"state",
".",
"Only",
"one",
"SideEffect",
"can",
"be",
"set",
"for",
"this",
"hook",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L314-L319 |
149,294 | vulcand/oxy | cbreaker/cbreaker.go | Fallback | func Fallback(h http.Handler) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.fallback = h
return nil
}
} | go | func Fallback(h http.Handler) CircuitBreakerOption {
return func(c *CircuitBreaker) error {
c.fallback = h
return nil
}
} | [
"func",
"Fallback",
"(",
"h",
"http",
".",
"Handler",
")",
"CircuitBreakerOption",
"{",
"return",
"func",
"(",
"c",
"*",
"CircuitBreaker",
")",
"error",
"{",
"c",
".",
"fallback",
"=",
"h",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Fallback defines the http.Handler that the CircuitBreaker should route
// requests to when it prevents a request from taking its normal path. | [
"Fallback",
"defines",
"the",
"http",
".",
"Handler",
"that",
"the",
"CircuitBreaker",
"should",
"route",
"requests",
"to",
"when",
"it",
"prevents",
"a",
"request",
"from",
"taking",
"its",
"normal",
"path",
"."
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/cbreaker/cbreaker.go#L323-L328 |
149,295 | vulcand/oxy | memmetrics/ratio.go | RatioClock | func RatioClock(clock timetools.TimeProvider) ratioOptSetter {
return func(r *RatioCounter) error {
r.clock = clock
return nil
}
} | go | func RatioClock(clock timetools.TimeProvider) ratioOptSetter {
return func(r *RatioCounter) error {
r.clock = clock
return nil
}
} | [
"func",
"RatioClock",
"(",
"clock",
"timetools",
".",
"TimeProvider",
")",
"ratioOptSetter",
"{",
"return",
"func",
"(",
"r",
"*",
"RatioCounter",
")",
"error",
"{",
"r",
".",
"clock",
"=",
"clock",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // RatioClock sets a clock | [
"RatioClock",
"sets",
"a",
"clock"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/ratio.go#L12-L17 |
149,296 | vulcand/oxy | memmetrics/ratio.go | NewRatioCounter | func NewRatioCounter(buckets int, resolution time.Duration, options ...ratioOptSetter) (*RatioCounter, error) {
rc := &RatioCounter{}
for _, o := range options {
if err := o(rc); err != nil {
return nil, err
}
}
if rc.clock == nil {
rc.clock = &timetools.RealTime{}
}
a, err := NewCounter(buckets, resolution, CounterClock(rc.clock))
if err != nil {
return nil, err
}
b, err := NewCounter(buckets, resolution, CounterClock(rc.clock))
if err != nil {
return nil, err
}
rc.a = a
rc.b = b
return rc, nil
} | go | func NewRatioCounter(buckets int, resolution time.Duration, options ...ratioOptSetter) (*RatioCounter, error) {
rc := &RatioCounter{}
for _, o := range options {
if err := o(rc); err != nil {
return nil, err
}
}
if rc.clock == nil {
rc.clock = &timetools.RealTime{}
}
a, err := NewCounter(buckets, resolution, CounterClock(rc.clock))
if err != nil {
return nil, err
}
b, err := NewCounter(buckets, resolution, CounterClock(rc.clock))
if err != nil {
return nil, err
}
rc.a = a
rc.b = b
return rc, nil
} | [
"func",
"NewRatioCounter",
"(",
"buckets",
"int",
",",
"resolution",
"time",
".",
"Duration",
",",
"options",
"...",
"ratioOptSetter",
")",
"(",
"*",
"RatioCounter",
",",
"error",
")",
"{",
"rc",
":=",
"&",
"RatioCounter",
"{",
"}",
"\n\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"if",
"err",
":=",
"o",
"(",
"rc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"rc",
".",
"clock",
"==",
"nil",
"{",
"rc",
".",
"clock",
"=",
"&",
"timetools",
".",
"RealTime",
"{",
"}",
"\n",
"}",
"\n\n",
"a",
",",
"err",
":=",
"NewCounter",
"(",
"buckets",
",",
"resolution",
",",
"CounterClock",
"(",
"rc",
".",
"clock",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"NewCounter",
"(",
"buckets",
",",
"resolution",
",",
"CounterClock",
"(",
"rc",
".",
"clock",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"rc",
".",
"a",
"=",
"a",
"\n",
"rc",
".",
"b",
"=",
"b",
"\n",
"return",
"rc",
",",
"nil",
"\n",
"}"
] | // NewRatioCounter creates a new RatioCounter | [
"NewRatioCounter",
"creates",
"a",
"new",
"RatioCounter"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/ratio.go#L27-L53 |
149,297 | vulcand/oxy | memmetrics/ratio.go | IsReady | func (r *RatioCounter) IsReady() bool {
return r.a.countedBuckets+r.b.countedBuckets >= len(r.a.values)
} | go | func (r *RatioCounter) IsReady() bool {
return r.a.countedBuckets+r.b.countedBuckets >= len(r.a.values)
} | [
"func",
"(",
"r",
"*",
"RatioCounter",
")",
"IsReady",
"(",
")",
"bool",
"{",
"return",
"r",
".",
"a",
".",
"countedBuckets",
"+",
"r",
".",
"b",
".",
"countedBuckets",
">=",
"len",
"(",
"r",
".",
"a",
".",
"values",
")",
"\n",
"}"
] | // IsReady returns true if the counter is ready | [
"IsReady",
"returns",
"true",
"if",
"the",
"counter",
"is",
"ready"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/ratio.go#L62-L64 |
149,298 | vulcand/oxy | memmetrics/ratio.go | Ratio | func (r *RatioCounter) Ratio() float64 {
a := r.a.Count()
b := r.b.Count()
// No data, return ok
if a+b == 0 {
return 0
}
return float64(a) / float64(a+b)
} | go | func (r *RatioCounter) Ratio() float64 {
a := r.a.Count()
b := r.b.Count()
// No data, return ok
if a+b == 0 {
return 0
}
return float64(a) / float64(a+b)
} | [
"func",
"(",
"r",
"*",
"RatioCounter",
")",
"Ratio",
"(",
")",
"float64",
"{",
"a",
":=",
"r",
".",
"a",
".",
"Count",
"(",
")",
"\n",
"b",
":=",
"r",
".",
"b",
".",
"Count",
"(",
")",
"\n",
"// No data, return ok",
"if",
"a",
"+",
"b",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"float64",
"(",
"a",
")",
"/",
"float64",
"(",
"a",
"+",
"b",
")",
"\n",
"}"
] | // Ratio gets ratio | [
"Ratio",
"gets",
"ratio"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/memmetrics/ratio.go#L97-L105 |
149,299 | vulcand/oxy | connlimit/connlimit.go | New | func New(next http.Handler, extract utils.SourceExtractor, maxConnections int64, options ...ConnLimitOption) (*ConnLimiter, error) {
if extract == nil {
return nil, fmt.Errorf("Extract function can not be nil")
}
cl := &ConnLimiter{
mutex: &sync.Mutex{},
extract: extract,
maxConnections: maxConnections,
connections: make(map[string]int64),
next: next,
log: log.StandardLogger(),
}
for _, o := range options {
if err := o(cl); err != nil {
return nil, err
}
}
if cl.errHandler == nil {
cl.errHandler = &ConnErrHandler{
log: cl.log,
}
}
return cl, nil
} | go | func New(next http.Handler, extract utils.SourceExtractor, maxConnections int64, options ...ConnLimitOption) (*ConnLimiter, error) {
if extract == nil {
return nil, fmt.Errorf("Extract function can not be nil")
}
cl := &ConnLimiter{
mutex: &sync.Mutex{},
extract: extract,
maxConnections: maxConnections,
connections: make(map[string]int64),
next: next,
log: log.StandardLogger(),
}
for _, o := range options {
if err := o(cl); err != nil {
return nil, err
}
}
if cl.errHandler == nil {
cl.errHandler = &ConnErrHandler{
log: cl.log,
}
}
return cl, nil
} | [
"func",
"New",
"(",
"next",
"http",
".",
"Handler",
",",
"extract",
"utils",
".",
"SourceExtractor",
",",
"maxConnections",
"int64",
",",
"options",
"...",
"ConnLimitOption",
")",
"(",
"*",
"ConnLimiter",
",",
"error",
")",
"{",
"if",
"extract",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"cl",
":=",
"&",
"ConnLimiter",
"{",
"mutex",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"extract",
":",
"extract",
",",
"maxConnections",
":",
"maxConnections",
",",
"connections",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"int64",
")",
",",
"next",
":",
"next",
",",
"log",
":",
"log",
".",
"StandardLogger",
"(",
")",
",",
"}",
"\n\n",
"for",
"_",
",",
"o",
":=",
"range",
"options",
"{",
"if",
"err",
":=",
"o",
"(",
"cl",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cl",
".",
"errHandler",
"==",
"nil",
"{",
"cl",
".",
"errHandler",
"=",
"&",
"ConnErrHandler",
"{",
"log",
":",
"cl",
".",
"log",
",",
"}",
"\n",
"}",
"\n",
"return",
"cl",
",",
"nil",
"\n",
"}"
] | // New creates a new ConnLimiter | [
"New",
"creates",
"a",
"new",
"ConnLimiter"
] | c34b0c501e43223bc816ac9b40b0ac29c44c8952 | https://github.com/vulcand/oxy/blob/c34b0c501e43223bc816ac9b40b0ac29c44c8952/connlimit/connlimit.go#L28-L52 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.