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
148,500
tjfoc/gmsm
sm2/cert_pool.go
AddCert
func (s *CertPool) AddCert(cert *Certificate) { if cert == nil { panic("adding nil Certificate to CertPool") } // Check that the certificate isn't being added twice. if s.contains(cert) { return } n := len(s.certs) s.certs = append(s.certs, cert) if len(cert.SubjectKeyId) > 0 { keyId := string(cert.SubjectKeyId) s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n) } name := string(cert.RawSubject) s.byName[name] = append(s.byName[name], n) }
go
func (s *CertPool) AddCert(cert *Certificate) { if cert == nil { panic("adding nil Certificate to CertPool") } // Check that the certificate isn't being added twice. if s.contains(cert) { return } n := len(s.certs) s.certs = append(s.certs, cert) if len(cert.SubjectKeyId) > 0 { keyId := string(cert.SubjectKeyId) s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n) } name := string(cert.RawSubject) s.byName[name] = append(s.byName[name], n) }
[ "func", "(", "s", "*", "CertPool", ")", "AddCert", "(", "cert", "*", "Certificate", ")", "{", "if", "cert", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check that the certificate isn't being added twice.", "if", "s", ".", "contains", "(", "cert", ")", "{", "return", "\n", "}", "\n\n", "n", ":=", "len", "(", "s", ".", "certs", ")", "\n", "s", ".", "certs", "=", "append", "(", "s", ".", "certs", ",", "cert", ")", "\n\n", "if", "len", "(", "cert", ".", "SubjectKeyId", ")", ">", "0", "{", "keyId", ":=", "string", "(", "cert", ".", "SubjectKeyId", ")", "\n", "s", ".", "bySubjectKeyId", "[", "keyId", "]", "=", "append", "(", "s", ".", "bySubjectKeyId", "[", "keyId", "]", ",", "n", ")", "\n", "}", "\n", "name", ":=", "string", "(", "cert", ".", "RawSubject", ")", "\n", "s", ".", "byName", "[", "name", "]", "=", "append", "(", "s", ".", "byName", "[", "name", "]", ",", "n", ")", "\n", "}" ]
// AddCert adds a certificate to a pool.
[ "AddCert", "adds", "a", "certificate", "to", "a", "pool", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/cert_pool.go#L171-L190
148,501
tjfoc/gmsm
sm2/cert_pool.go
Subjects
func (s *CertPool) Subjects() [][]byte { res := make([][]byte, len(s.certs)) for i, c := range s.certs { res[i] = c.RawSubject } return res }
go
func (s *CertPool) Subjects() [][]byte { res := make([][]byte, len(s.certs)) for i, c := range s.certs { res[i] = c.RawSubject } return res }
[ "func", "(", "s", "*", "CertPool", ")", "Subjects", "(", ")", "[", "]", "[", "]", "byte", "{", "res", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "s", ".", "certs", ")", ")", "\n", "for", "i", ",", "c", ":=", "range", "s", ".", "certs", "{", "res", "[", "i", "]", "=", "c", ".", "RawSubject", "\n", "}", "\n", "return", "res", "\n", "}" ]
// Subjects returns a list of the DER-encoded subjects of // all of the certificates in the pool.
[ "Subjects", "returns", "a", "list", "of", "the", "DER", "-", "encoded", "subjects", "of", "all", "of", "the", "certificates", "in", "the", "pool", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/cert_pool.go#L223-L229
148,502
tjfoc/gmsm
sm2/verify.go
isValid
func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error { if len(currentChain) > 0 { child := currentChain[len(currentChain)-1] if !bytes.Equal(child.RawIssuer, c.RawSubject) { return CertificateInvalidError{c, NameMismatch} } } now := opts.CurrentTime if now.IsZero() { now = time.Now() } if now.Before(c.NotBefore) || now.After(c.NotAfter) { return CertificateInvalidError{c, Expired} } if len(c.PermittedDNSDomains) > 0 { ok := false for _, constraint := range c.PermittedDNSDomains { ok = matchNameConstraint(opts.DNSName, constraint) if ok { break } } if !ok { return CertificateInvalidError{c, CANotAuthorizedForThisName} } } // KeyUsage status flags are ignored. From Engineering Security, Peter // Gutmann: A European government CA marked its signing certificates as // being valid for encryption only, but no-one noticed. Another // European CA marked its signature keys as not being valid for // signatures. A different CA marked its own trusted root certificate // as being invalid for certificate signing. Another national CA // distributed a certificate to be used to encrypt data for the // country’s tax authority that was marked as only being usable for // digital signatures but not for encryption. Yet another CA reversed // the order of the bit flags in the keyUsage due to confusion over // encoding endianness, essentially setting a random keyUsage in // certificates that it issued. Another CA created a self-invalidating // certificate by adding a certificate policy statement stipulating // that the certificate had to be used strictly as specified in the // keyUsage, and a keyUsage containing a flag indicating that the RSA // encryption key could only be used for Diffie-Hellman key agreement. if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) { return CertificateInvalidError{c, NotAuthorizedToSign} } if c.BasicConstraintsValid && c.MaxPathLen >= 0 { numIntermediates := len(currentChain) - 1 if numIntermediates > c.MaxPathLen { return CertificateInvalidError{c, TooManyIntermediates} } } return nil }
go
func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error { if len(currentChain) > 0 { child := currentChain[len(currentChain)-1] if !bytes.Equal(child.RawIssuer, c.RawSubject) { return CertificateInvalidError{c, NameMismatch} } } now := opts.CurrentTime if now.IsZero() { now = time.Now() } if now.Before(c.NotBefore) || now.After(c.NotAfter) { return CertificateInvalidError{c, Expired} } if len(c.PermittedDNSDomains) > 0 { ok := false for _, constraint := range c.PermittedDNSDomains { ok = matchNameConstraint(opts.DNSName, constraint) if ok { break } } if !ok { return CertificateInvalidError{c, CANotAuthorizedForThisName} } } // KeyUsage status flags are ignored. From Engineering Security, Peter // Gutmann: A European government CA marked its signing certificates as // being valid for encryption only, but no-one noticed. Another // European CA marked its signature keys as not being valid for // signatures. A different CA marked its own trusted root certificate // as being invalid for certificate signing. Another national CA // distributed a certificate to be used to encrypt data for the // country’s tax authority that was marked as only being usable for // digital signatures but not for encryption. Yet another CA reversed // the order of the bit flags in the keyUsage due to confusion over // encoding endianness, essentially setting a random keyUsage in // certificates that it issued. Another CA created a self-invalidating // certificate by adding a certificate policy statement stipulating // that the certificate had to be used strictly as specified in the // keyUsage, and a keyUsage containing a flag indicating that the RSA // encryption key could only be used for Diffie-Hellman key agreement. if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) { return CertificateInvalidError{c, NotAuthorizedToSign} } if c.BasicConstraintsValid && c.MaxPathLen >= 0 { numIntermediates := len(currentChain) - 1 if numIntermediates > c.MaxPathLen { return CertificateInvalidError{c, TooManyIntermediates} } } return nil }
[ "func", "(", "c", "*", "Certificate", ")", "isValid", "(", "certType", "int", ",", "currentChain", "[", "]", "*", "Certificate", ",", "opts", "*", "VerifyOptions", ")", "error", "{", "if", "len", "(", "currentChain", ")", ">", "0", "{", "child", ":=", "currentChain", "[", "len", "(", "currentChain", ")", "-", "1", "]", "\n", "if", "!", "bytes", ".", "Equal", "(", "child", ".", "RawIssuer", ",", "c", ".", "RawSubject", ")", "{", "return", "CertificateInvalidError", "{", "c", ",", "NameMismatch", "}", "\n", "}", "\n", "}", "\n", "now", ":=", "opts", ".", "CurrentTime", "\n", "if", "now", ".", "IsZero", "(", ")", "{", "now", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n", "if", "now", ".", "Before", "(", "c", ".", "NotBefore", ")", "||", "now", ".", "After", "(", "c", ".", "NotAfter", ")", "{", "return", "CertificateInvalidError", "{", "c", ",", "Expired", "}", "\n", "}", "\n", "if", "len", "(", "c", ".", "PermittedDNSDomains", ")", ">", "0", "{", "ok", ":=", "false", "\n", "for", "_", ",", "constraint", ":=", "range", "c", ".", "PermittedDNSDomains", "{", "ok", "=", "matchNameConstraint", "(", "opts", ".", "DNSName", ",", "constraint", ")", "\n", "if", "ok", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "ok", "{", "return", "CertificateInvalidError", "{", "c", ",", "CANotAuthorizedForThisName", "}", "\n", "}", "\n", "}", "\n\n", "// KeyUsage status flags are ignored. From Engineering Security, Peter", "// Gutmann: A European government CA marked its signing certificates as", "// being valid for encryption only, but no-one noticed. Another", "// European CA marked its signature keys as not being valid for", "// signatures. A different CA marked its own trusted root certificate", "// as being invalid for certificate signing. Another national CA", "// distributed a certificate to be used to encrypt data for the", "// country’s tax authority that was marked as only being usable for", "// digital signatures but not for encryption. Yet another CA reversed", "// the order of the bit flags in the keyUsage due to confusion over", "// encoding endianness, essentially setting a random keyUsage in", "// certificates that it issued. Another CA created a self-invalidating", "// certificate by adding a certificate policy statement stipulating", "// that the certificate had to be used strictly as specified in the", "// keyUsage, and a keyUsage containing a flag indicating that the RSA", "// encryption key could only be used for Diffie-Hellman key agreement.", "if", "certType", "==", "intermediateCertificate", "&&", "(", "!", "c", ".", "BasicConstraintsValid", "||", "!", "c", ".", "IsCA", ")", "{", "return", "CertificateInvalidError", "{", "c", ",", "NotAuthorizedToSign", "}", "\n", "}", "\n\n", "if", "c", ".", "BasicConstraintsValid", "&&", "c", ".", "MaxPathLen", ">=", "0", "{", "numIntermediates", ":=", "len", "(", "currentChain", ")", "-", "1", "\n", "if", "numIntermediates", ">", "c", ".", "MaxPathLen", "{", "return", "CertificateInvalidError", "{", "c", ",", "TooManyIntermediates", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// isValid performs validity checks on the c.
[ "isValid", "performs", "validity", "checks", "on", "the", "c", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/verify.go#L204-L261
148,503
tjfoc/gmsm
sm2/verify.go
toLowerCaseASCII
func toLowerCaseASCII(in string) string { // If the string is already lower-case then there's nothing to do. isAlreadyLowerCase := true for _, c := range in { if c == utf8.RuneError { // If we get a UTF-8 error then there might be // upper-case ASCII bytes in the invalid sequence. isAlreadyLowerCase = false break } if 'A' <= c && c <= 'Z' { isAlreadyLowerCase = false break } } if isAlreadyLowerCase { return in } out := []byte(in) for i, c := range out { if 'A' <= c && c <= 'Z' { out[i] += 'a' - 'A' } } return string(out) }
go
func toLowerCaseASCII(in string) string { // If the string is already lower-case then there's nothing to do. isAlreadyLowerCase := true for _, c := range in { if c == utf8.RuneError { // If we get a UTF-8 error then there might be // upper-case ASCII bytes in the invalid sequence. isAlreadyLowerCase = false break } if 'A' <= c && c <= 'Z' { isAlreadyLowerCase = false break } } if isAlreadyLowerCase { return in } out := []byte(in) for i, c := range out { if 'A' <= c && c <= 'Z' { out[i] += 'a' - 'A' } } return string(out) }
[ "func", "toLowerCaseASCII", "(", "in", "string", ")", "string", "{", "// If the string is already lower-case then there's nothing to do.", "isAlreadyLowerCase", ":=", "true", "\n", "for", "_", ",", "c", ":=", "range", "in", "{", "if", "c", "==", "utf8", ".", "RuneError", "{", "// If we get a UTF-8 error then there might be", "// upper-case ASCII bytes in the invalid sequence.", "isAlreadyLowerCase", "=", "false", "\n", "break", "\n", "}", "\n", "if", "'A'", "<=", "c", "&&", "c", "<=", "'Z'", "{", "isAlreadyLowerCase", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "isAlreadyLowerCase", "{", "return", "in", "\n", "}", "\n\n", "out", ":=", "[", "]", "byte", "(", "in", ")", "\n", "for", "i", ",", "c", ":=", "range", "out", "{", "if", "'A'", "<=", "c", "&&", "c", "<=", "'Z'", "{", "out", "[", "i", "]", "+=", "'a'", "-", "'A'", "\n", "}", "\n", "}", "\n", "return", "string", "(", "out", ")", "\n", "}" ]
// toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use // an explicitly ASCII function to avoid any sharp corners resulting from // performing Unicode operations on DNS labels.
[ "toLowerCaseASCII", "returns", "a", "lower", "-", "case", "version", "of", "in", ".", "See", "RFC", "6125", "6", ".", "4", ".", "1", ".", "We", "use", "an", "explicitly", "ASCII", "function", "to", "avoid", "any", "sharp", "corners", "resulting", "from", "performing", "Unicode", "operations", "on", "DNS", "labels", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/verify.go#L444-L471
148,504
tjfoc/gmsm
sm2/verify.go
VerifyHostname
func (c *Certificate) VerifyHostname(h string) error { // IP addresses may be written in [ ]. candidateIP := h if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' { candidateIP = h[1 : len(h)-1] } if ip := net.ParseIP(candidateIP); ip != nil { // We only match IP addresses against IP SANs. // https://tools.ietf.org/html/rfc6125#appendix-B.2 for _, candidate := range c.IPAddresses { if ip.Equal(candidate) { return nil } } return HostnameError{c, candidateIP} } lowered := toLowerCaseASCII(h) if len(c.DNSNames) > 0 { for _, match := range c.DNSNames { if matchHostnames(toLowerCaseASCII(match), lowered) { return nil } } // If Subject Alt Name is given, we ignore the common name. } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) { return nil } return HostnameError{c, h} }
go
func (c *Certificate) VerifyHostname(h string) error { // IP addresses may be written in [ ]. candidateIP := h if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' { candidateIP = h[1 : len(h)-1] } if ip := net.ParseIP(candidateIP); ip != nil { // We only match IP addresses against IP SANs. // https://tools.ietf.org/html/rfc6125#appendix-B.2 for _, candidate := range c.IPAddresses { if ip.Equal(candidate) { return nil } } return HostnameError{c, candidateIP} } lowered := toLowerCaseASCII(h) if len(c.DNSNames) > 0 { for _, match := range c.DNSNames { if matchHostnames(toLowerCaseASCII(match), lowered) { return nil } } // If Subject Alt Name is given, we ignore the common name. } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) { return nil } return HostnameError{c, h} }
[ "func", "(", "c", "*", "Certificate", ")", "VerifyHostname", "(", "h", "string", ")", "error", "{", "// IP addresses may be written in [ ].", "candidateIP", ":=", "h", "\n", "if", "len", "(", "h", ")", ">=", "3", "&&", "h", "[", "0", "]", "==", "'['", "&&", "h", "[", "len", "(", "h", ")", "-", "1", "]", "==", "']'", "{", "candidateIP", "=", "h", "[", "1", ":", "len", "(", "h", ")", "-", "1", "]", "\n", "}", "\n", "if", "ip", ":=", "net", ".", "ParseIP", "(", "candidateIP", ")", ";", "ip", "!=", "nil", "{", "// We only match IP addresses against IP SANs.", "// https://tools.ietf.org/html/rfc6125#appendix-B.2", "for", "_", ",", "candidate", ":=", "range", "c", ".", "IPAddresses", "{", "if", "ip", ".", "Equal", "(", "candidate", ")", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "HostnameError", "{", "c", ",", "candidateIP", "}", "\n", "}", "\n\n", "lowered", ":=", "toLowerCaseASCII", "(", "h", ")", "\n\n", "if", "len", "(", "c", ".", "DNSNames", ")", ">", "0", "{", "for", "_", ",", "match", ":=", "range", "c", ".", "DNSNames", "{", "if", "matchHostnames", "(", "toLowerCaseASCII", "(", "match", ")", ",", "lowered", ")", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "// If Subject Alt Name is given, we ignore the common name.", "}", "else", "if", "matchHostnames", "(", "toLowerCaseASCII", "(", "c", ".", "Subject", ".", "CommonName", ")", ",", "lowered", ")", "{", "return", "nil", "\n", "}", "\n\n", "return", "HostnameError", "{", "c", ",", "h", "}", "\n", "}" ]
// VerifyHostname returns nil if c is a valid certificate for the named host. // Otherwise it returns an error describing the mismatch.
[ "VerifyHostname", "returns", "nil", "if", "c", "is", "a", "valid", "certificate", "for", "the", "named", "host", ".", "Otherwise", "it", "returns", "an", "error", "describing", "the", "mismatch", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/verify.go#L475-L506
148,505
tjfoc/gmsm
sm2/x509.go
MarshalPKIXPublicKey
func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { var publicKeyBytes []byte var publicKeyAlgorithm pkix.AlgorithmIdentifier var err error if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { return nil, err } pkix := pkixPublicKey{ Algo: publicKeyAlgorithm, BitString: asn1.BitString{ Bytes: publicKeyBytes, BitLength: 8 * len(publicKeyBytes), }, } ret, _ := asn1.Marshal(pkix) return ret, nil }
go
func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { var publicKeyBytes []byte var publicKeyAlgorithm pkix.AlgorithmIdentifier var err error if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { return nil, err } pkix := pkixPublicKey{ Algo: publicKeyAlgorithm, BitString: asn1.BitString{ Bytes: publicKeyBytes, BitLength: 8 * len(publicKeyBytes), }, } ret, _ := asn1.Marshal(pkix) return ret, nil }
[ "func", "MarshalPKIXPublicKey", "(", "pub", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "publicKeyBytes", "[", "]", "byte", "\n", "var", "publicKeyAlgorithm", "pkix", ".", "AlgorithmIdentifier", "\n", "var", "err", "error", "\n\n", "if", "publicKeyBytes", ",", "publicKeyAlgorithm", ",", "err", "=", "marshalPublicKey", "(", "pub", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pkix", ":=", "pkixPublicKey", "{", "Algo", ":", "publicKeyAlgorithm", ",", "BitString", ":", "asn1", ".", "BitString", "{", "Bytes", ":", "publicKeyBytes", ",", "BitLength", ":", "8", "*", "len", "(", "publicKeyBytes", ")", ",", "}", ",", "}", "\n\n", "ret", ",", "_", ":=", "asn1", ".", "Marshal", "(", "pkix", ")", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
[ "MarshalPKIXPublicKey", "serialises", "a", "public", "key", "to", "DER", "-", "encoded", "PKIX", "format", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L130-L149
148,506
tjfoc/gmsm
sm2/x509.go
rsaPSSParameters
func rsaPSSParameters(hashFunc Hash) asn1.RawValue { var hashOID asn1.ObjectIdentifier switch hashFunc { case SHA256: hashOID = oidSHA256 case SHA384: hashOID = oidSHA384 case SHA512: hashOID = oidSHA512 } params := pssParameters{ Hash: pkix.AlgorithmIdentifier{ Algorithm: hashOID, Parameters: asn1.RawValue{ Tag: 5, /* ASN.1 NULL */ }, }, MGF: pkix.AlgorithmIdentifier{ Algorithm: oidMGF1, }, SaltLength: hashFunc.Size(), TrailerField: 1, } mgf1Params := pkix.AlgorithmIdentifier{ Algorithm: hashOID, Parameters: asn1.RawValue{ Tag: 5, /* ASN.1 NULL */ }, } var err error params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params) if err != nil { panic(err) } serialized, err := asn1.Marshal(params) if err != nil { panic(err) } return asn1.RawValue{FullBytes: serialized} }
go
func rsaPSSParameters(hashFunc Hash) asn1.RawValue { var hashOID asn1.ObjectIdentifier switch hashFunc { case SHA256: hashOID = oidSHA256 case SHA384: hashOID = oidSHA384 case SHA512: hashOID = oidSHA512 } params := pssParameters{ Hash: pkix.AlgorithmIdentifier{ Algorithm: hashOID, Parameters: asn1.RawValue{ Tag: 5, /* ASN.1 NULL */ }, }, MGF: pkix.AlgorithmIdentifier{ Algorithm: oidMGF1, }, SaltLength: hashFunc.Size(), TrailerField: 1, } mgf1Params := pkix.AlgorithmIdentifier{ Algorithm: hashOID, Parameters: asn1.RawValue{ Tag: 5, /* ASN.1 NULL */ }, } var err error params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params) if err != nil { panic(err) } serialized, err := asn1.Marshal(params) if err != nil { panic(err) } return asn1.RawValue{FullBytes: serialized} }
[ "func", "rsaPSSParameters", "(", "hashFunc", "Hash", ")", "asn1", ".", "RawValue", "{", "var", "hashOID", "asn1", ".", "ObjectIdentifier", "\n\n", "switch", "hashFunc", "{", "case", "SHA256", ":", "hashOID", "=", "oidSHA256", "\n", "case", "SHA384", ":", "hashOID", "=", "oidSHA384", "\n", "case", "SHA512", ":", "hashOID", "=", "oidSHA512", "\n", "}", "\n\n", "params", ":=", "pssParameters", "{", "Hash", ":", "pkix", ".", "AlgorithmIdentifier", "{", "Algorithm", ":", "hashOID", ",", "Parameters", ":", "asn1", ".", "RawValue", "{", "Tag", ":", "5", ",", "/* ASN.1 NULL */", "}", ",", "}", ",", "MGF", ":", "pkix", ".", "AlgorithmIdentifier", "{", "Algorithm", ":", "oidMGF1", ",", "}", ",", "SaltLength", ":", "hashFunc", ".", "Size", "(", ")", ",", "TrailerField", ":", "1", ",", "}", "\n\n", "mgf1Params", ":=", "pkix", ".", "AlgorithmIdentifier", "{", "Algorithm", ":", "hashOID", ",", "Parameters", ":", "asn1", ".", "RawValue", "{", "Tag", ":", "5", ",", "/* ASN.1 NULL */", "}", ",", "}", "\n\n", "var", "err", "error", "\n", "params", ".", "MGF", ".", "Parameters", ".", "FullBytes", ",", "err", "=", "asn1", ".", "Marshal", "(", "mgf1Params", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "serialized", ",", "err", ":=", "asn1", ".", "Marshal", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "return", "asn1", ".", "RawValue", "{", "FullBytes", ":", "serialized", "}", "\n", "}" ]
// rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters // in an AlgorithmIdentifier that specifies RSA PSS.
[ "rsaPSSParameters", "returns", "an", "asn1", ".", "RawValue", "suitable", "for", "use", "as", "the", "Parameters", "in", "an", "AlgorithmIdentifier", "that", "specifies", "RSA", "PSS", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L500-L545
148,507
tjfoc/gmsm
sm2/x509.go
CheckSignatureFrom
func (c *Certificate) CheckSignatureFrom(parent *Certificate) error { // RFC 5280, 4.2.1.9: // "If the basic constraints extension is not present in a version 3 // certificate, or the extension is present but the cA boolean is not // asserted, then the certified public key MUST NOT be used to verify // certificate signatures." // (except for Entrust, see comment above entrustBrokenSPKI) if (parent.Version == 3 && !parent.BasicConstraintsValid || parent.BasicConstraintsValid && !parent.IsCA) && !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { return ConstraintViolationError{} } if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { return ConstraintViolationError{} } if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { return ErrUnsupportedAlgorithm } // TODO(agl): don't ignore the path length constraint. return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) }
go
func (c *Certificate) CheckSignatureFrom(parent *Certificate) error { // RFC 5280, 4.2.1.9: // "If the basic constraints extension is not present in a version 3 // certificate, or the extension is present but the cA boolean is not // asserted, then the certified public key MUST NOT be used to verify // certificate signatures." // (except for Entrust, see comment above entrustBrokenSPKI) if (parent.Version == 3 && !parent.BasicConstraintsValid || parent.BasicConstraintsValid && !parent.IsCA) && !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { return ConstraintViolationError{} } if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { return ConstraintViolationError{} } if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { return ErrUnsupportedAlgorithm } // TODO(agl): don't ignore the path length constraint. return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) }
[ "func", "(", "c", "*", "Certificate", ")", "CheckSignatureFrom", "(", "parent", "*", "Certificate", ")", "error", "{", "// RFC 5280, 4.2.1.9:", "// \"If the basic constraints extension is not present in a version 3", "// certificate, or the extension is present but the cA boolean is not", "// asserted, then the certified public key MUST NOT be used to verify", "// certificate signatures.\"", "// (except for Entrust, see comment above entrustBrokenSPKI)", "if", "(", "parent", ".", "Version", "==", "3", "&&", "!", "parent", ".", "BasicConstraintsValid", "||", "parent", ".", "BasicConstraintsValid", "&&", "!", "parent", ".", "IsCA", ")", "&&", "!", "bytes", ".", "Equal", "(", "c", ".", "RawSubjectPublicKeyInfo", ",", "entrustBrokenSPKI", ")", "{", "return", "ConstraintViolationError", "{", "}", "\n", "}", "\n\n", "if", "parent", ".", "KeyUsage", "!=", "0", "&&", "parent", ".", "KeyUsage", "&", "KeyUsageCertSign", "==", "0", "{", "return", "ConstraintViolationError", "{", "}", "\n", "}", "\n\n", "if", "parent", ".", "PublicKeyAlgorithm", "==", "UnknownPublicKeyAlgorithm", "{", "return", "ErrUnsupportedAlgorithm", "\n", "}", "\n\n", "// TODO(agl): don't ignore the path length constraint.", "return", "parent", ".", "CheckSignature", "(", "c", ".", "SignatureAlgorithm", ",", "c", ".", "RawTBSCertificate", ",", "c", ".", "Signature", ")", "\n", "}" ]
// CheckSignatureFrom verifies that the signature on c is a valid signature // from parent.
[ "CheckSignatureFrom", "verifies", "that", "the", "signature", "on", "c", "is", "a", "valid", "signature", "from", "parent", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L937-L961
148,508
tjfoc/gmsm
sm2/x509.go
CheckSignature
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error { return checkSignature(algo, signed, signature, c.PublicKey) }
go
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error { return checkSignature(algo, signed, signature, c.PublicKey) }
[ "func", "(", "c", "*", "Certificate", ")", "CheckSignature", "(", "algo", "SignatureAlgorithm", ",", "signed", ",", "signature", "[", "]", "byte", ")", "error", "{", "return", "checkSignature", "(", "algo", ",", "signed", ",", "signature", ",", "c", ".", "PublicKey", ")", "\n", "}" ]
// CheckSignature verifies that signature is a valid signature over signed from // c's public key.
[ "CheckSignature", "verifies", "that", "signature", "is", "a", "valid", "signature", "over", "signed", "from", "c", "s", "public", "key", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L965-L967
148,509
tjfoc/gmsm
sm2/x509.go
CheckCRLSignature
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error { algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm) return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) }
go
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error { algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm) return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) }
[ "func", "(", "c", "*", "Certificate", ")", "CheckCRLSignature", "(", "crl", "*", "pkix", ".", "CertificateList", ")", "error", "{", "algo", ":=", "getSignatureAlgorithmFromAI", "(", "crl", ".", "SignatureAlgorithm", ")", "\n", "return", "c", ".", "CheckSignature", "(", "algo", ",", "crl", ".", "TBSCertList", ".", "Raw", ",", "crl", ".", "SignatureValue", ".", "RightAlign", "(", ")", ")", "\n", "}" ]
// CheckCRLSignature checks that the signature in crl is from c.
[ "CheckCRLSignature", "checks", "that", "the", "signature", "in", "crl", "is", "from", "c", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1050-L1053
148,510
tjfoc/gmsm
sm2/x509.go
ParseCertificate
func ParseCertificate(asn1Data []byte) (*Certificate, error) { var cert certificate rest, err := asn1.Unmarshal(asn1Data, &cert) if err != nil { return nil, err } if len(rest) > 0 { return nil, asn1.SyntaxError{Msg: "trailing data"} } return parseCertificate(&cert) }
go
func ParseCertificate(asn1Data []byte) (*Certificate, error) { var cert certificate rest, err := asn1.Unmarshal(asn1Data, &cert) if err != nil { return nil, err } if len(rest) > 0 { return nil, asn1.SyntaxError{Msg: "trailing data"} } return parseCertificate(&cert) }
[ "func", "ParseCertificate", "(", "asn1Data", "[", "]", "byte", ")", "(", "*", "Certificate", ",", "error", ")", "{", "var", "cert", "certificate", "\n", "rest", ",", "err", ":=", "asn1", ".", "Unmarshal", "(", "asn1Data", ",", "&", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "rest", ")", ">", "0", "{", "return", "nil", ",", "asn1", ".", "SyntaxError", "{", "Msg", ":", "\"", "\"", "}", "\n", "}", "\n\n", "return", "parseCertificate", "(", "&", "cert", ")", "\n", "}" ]
// ParseCertificate parses a single certificate from the given ASN.1 DER data.
[ "ParseCertificate", "parses", "a", "single", "certificate", "from", "the", "given", "ASN", ".", "1", "DER", "data", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1510-L1521
148,511
tjfoc/gmsm
sm2/x509.go
ParseCertificates
func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { var v []*certificate for len(asn1Data) > 0 { cert := new(certificate) var err error asn1Data, err = asn1.Unmarshal(asn1Data, cert) if err != nil { return nil, err } v = append(v, cert) } ret := make([]*Certificate, len(v)) for i, ci := range v { cert, err := parseCertificate(ci) if err != nil { return nil, err } ret[i] = cert } return ret, nil }
go
func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { var v []*certificate for len(asn1Data) > 0 { cert := new(certificate) var err error asn1Data, err = asn1.Unmarshal(asn1Data, cert) if err != nil { return nil, err } v = append(v, cert) } ret := make([]*Certificate, len(v)) for i, ci := range v { cert, err := parseCertificate(ci) if err != nil { return nil, err } ret[i] = cert } return ret, nil }
[ "func", "ParseCertificates", "(", "asn1Data", "[", "]", "byte", ")", "(", "[", "]", "*", "Certificate", ",", "error", ")", "{", "var", "v", "[", "]", "*", "certificate", "\n\n", "for", "len", "(", "asn1Data", ")", ">", "0", "{", "cert", ":=", "new", "(", "certificate", ")", "\n", "var", "err", "error", "\n", "asn1Data", ",", "err", "=", "asn1", ".", "Unmarshal", "(", "asn1Data", ",", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "v", "=", "append", "(", "v", ",", "cert", ")", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "*", "Certificate", ",", "len", "(", "v", ")", ")", "\n", "for", "i", ",", "ci", ":=", "range", "v", "{", "cert", ",", "err", ":=", "parseCertificate", "(", "ci", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ret", "[", "i", "]", "=", "cert", "\n", "}", "\n\n", "return", "ret", ",", "nil", "\n", "}" ]
// ParseCertificates parses one or more certificates from the given ASN.1 DER // data. The certificates must be concatenated with no intermediate padding.
[ "ParseCertificates", "parses", "one", "or", "more", "certificates", "from", "the", "given", "ASN", ".", "1", "DER", "data", ".", "The", "certificates", "must", "be", "concatenated", "with", "no", "intermediate", "padding", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1525-L1548
148,512
tjfoc/gmsm
sm2/x509.go
asn1BitLength
func asn1BitLength(bitString []byte) int { bitLen := len(bitString) * 8 for i := range bitString { b := bitString[len(bitString)-i-1] for bit := uint(0); bit < 8; bit++ { if (b>>bit)&1 == 1 { return bitLen } bitLen-- } } return 0 }
go
func asn1BitLength(bitString []byte) int { bitLen := len(bitString) * 8 for i := range bitString { b := bitString[len(bitString)-i-1] for bit := uint(0); bit < 8; bit++ { if (b>>bit)&1 == 1 { return bitLen } bitLen-- } } return 0 }
[ "func", "asn1BitLength", "(", "bitString", "[", "]", "byte", ")", "int", "{", "bitLen", ":=", "len", "(", "bitString", ")", "*", "8", "\n\n", "for", "i", ":=", "range", "bitString", "{", "b", ":=", "bitString", "[", "len", "(", "bitString", ")", "-", "i", "-", "1", "]", "\n\n", "for", "bit", ":=", "uint", "(", "0", ")", ";", "bit", "<", "8", ";", "bit", "++", "{", "if", "(", "b", ">>", "bit", ")", "&", "1", "==", "1", "{", "return", "bitLen", "\n", "}", "\n", "bitLen", "--", "\n", "}", "\n", "}", "\n\n", "return", "0", "\n", "}" ]
// asn1BitLength returns the bit-length of bitString by considering the // most-significant bit in a byte to be the "first" bit. This convention // matches ASN.1, but differs from almost everything else.
[ "asn1BitLength", "returns", "the", "bit", "-", "length", "of", "bitString", "by", "considering", "the", "most", "-", "significant", "bit", "in", "a", "byte", "to", "be", "the", "first", "bit", ".", "This", "convention", "matches", "ASN", ".", "1", "but", "differs", "from", "almost", "everything", "else", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1560-L1575
148,513
tjfoc/gmsm
sm2/x509.go
marshalSANs
func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) { var rawValues []asn1.RawValue for _, name := range dnsNames { rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) } for _, email := range emailAddresses { rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) } for _, rawIP := range ipAddresses { // If possible, we always want to encode IPv4 addresses in 4 bytes. ip := rawIP.To4() if ip == nil { ip = rawIP } rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) } return asn1.Marshal(rawValues) }
go
func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) { var rawValues []asn1.RawValue for _, name := range dnsNames { rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) } for _, email := range emailAddresses { rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) } for _, rawIP := range ipAddresses { // If possible, we always want to encode IPv4 addresses in 4 bytes. ip := rawIP.To4() if ip == nil { ip = rawIP } rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) } return asn1.Marshal(rawValues) }
[ "func", "marshalSANs", "(", "dnsNames", ",", "emailAddresses", "[", "]", "string", ",", "ipAddresses", "[", "]", "net", ".", "IP", ")", "(", "derBytes", "[", "]", "byte", ",", "err", "error", ")", "{", "var", "rawValues", "[", "]", "asn1", ".", "RawValue", "\n", "for", "_", ",", "name", ":=", "range", "dnsNames", "{", "rawValues", "=", "append", "(", "rawValues", ",", "asn1", ".", "RawValue", "{", "Tag", ":", "2", ",", "Class", ":", "2", ",", "Bytes", ":", "[", "]", "byte", "(", "name", ")", "}", ")", "\n", "}", "\n", "for", "_", ",", "email", ":=", "range", "emailAddresses", "{", "rawValues", "=", "append", "(", "rawValues", ",", "asn1", ".", "RawValue", "{", "Tag", ":", "1", ",", "Class", ":", "2", ",", "Bytes", ":", "[", "]", "byte", "(", "email", ")", "}", ")", "\n", "}", "\n", "for", "_", ",", "rawIP", ":=", "range", "ipAddresses", "{", "// If possible, we always want to encode IPv4 addresses in 4 bytes.", "ip", ":=", "rawIP", ".", "To4", "(", ")", "\n", "if", "ip", "==", "nil", "{", "ip", "=", "rawIP", "\n", "}", "\n", "rawValues", "=", "append", "(", "rawValues", ",", "asn1", ".", "RawValue", "{", "Tag", ":", "7", ",", "Class", ":", "2", ",", "Bytes", ":", "ip", "}", ")", "\n", "}", "\n", "return", "asn1", ".", "Marshal", "(", "rawValues", ")", "\n", "}" ]
// marshalSANs marshals a list of addresses into a the contents of an X.509 // SubjectAlternativeName extension.
[ "marshalSANs", "marshals", "a", "list", "of", "addresses", "into", "a", "the", "contents", "of", "an", "X", ".", "509", "SubjectAlternativeName", "extension", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1608-L1625
148,514
tjfoc/gmsm
sm2/x509.go
signingParamsForPublicKey
func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { var pubType PublicKeyAlgorithm switch pub := pub.(type) { case *rsa.PublicKey: pubType = RSA hashFunc = SHA256 sigAlgo.Algorithm = oidSignatureSHA256WithRSA sigAlgo.Parameters = asn1.RawValue{ Tag: 5, } case *ecdsa.PublicKey: pubType = ECDSA switch pub.Curve { case elliptic.P224(), elliptic.P256(): hashFunc = SHA256 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 case elliptic.P384(): hashFunc = SHA384 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 case elliptic.P521(): hashFunc = SHA512 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 default: err = errors.New("x509: unknown elliptic curve") } case *PublicKey: pubType = ECDSA switch pub.Curve { case P256Sm2(): hashFunc = SM3 sigAlgo.Algorithm = oidSignatureSM2WithSM3 default: err = errors.New("x509: unknown SM2 curve") } default: err = errors.New("x509: only RSA and ECDSA keys supported") } if err != nil { return } if requestedSigAlgo == 0 { return } found := false for _, details := range signatureAlgorithmDetails { if details.algo == requestedSigAlgo { if details.pubKeyAlgo != pubType { err = errors.New("x509: requested SignatureAlgorithm does not match private key type") return } sigAlgo.Algorithm, hashFunc = details.oid, details.hash if hashFunc == 0 { err = errors.New("x509: cannot sign with hash function requested") return } if requestedSigAlgo.isRSAPSS() { sigAlgo.Parameters = rsaPSSParameters(hashFunc) } found = true break } } if !found { err = errors.New("x509: unknown SignatureAlgorithm") } return }
go
func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { var pubType PublicKeyAlgorithm switch pub := pub.(type) { case *rsa.PublicKey: pubType = RSA hashFunc = SHA256 sigAlgo.Algorithm = oidSignatureSHA256WithRSA sigAlgo.Parameters = asn1.RawValue{ Tag: 5, } case *ecdsa.PublicKey: pubType = ECDSA switch pub.Curve { case elliptic.P224(), elliptic.P256(): hashFunc = SHA256 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 case elliptic.P384(): hashFunc = SHA384 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 case elliptic.P521(): hashFunc = SHA512 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 default: err = errors.New("x509: unknown elliptic curve") } case *PublicKey: pubType = ECDSA switch pub.Curve { case P256Sm2(): hashFunc = SM3 sigAlgo.Algorithm = oidSignatureSM2WithSM3 default: err = errors.New("x509: unknown SM2 curve") } default: err = errors.New("x509: only RSA and ECDSA keys supported") } if err != nil { return } if requestedSigAlgo == 0 { return } found := false for _, details := range signatureAlgorithmDetails { if details.algo == requestedSigAlgo { if details.pubKeyAlgo != pubType { err = errors.New("x509: requested SignatureAlgorithm does not match private key type") return } sigAlgo.Algorithm, hashFunc = details.oid, details.hash if hashFunc == 0 { err = errors.New("x509: cannot sign with hash function requested") return } if requestedSigAlgo.isRSAPSS() { sigAlgo.Parameters = rsaPSSParameters(hashFunc) } found = true break } } if !found { err = errors.New("x509: unknown SignatureAlgorithm") } return }
[ "func", "signingParamsForPublicKey", "(", "pub", "interface", "{", "}", ",", "requestedSigAlgo", "SignatureAlgorithm", ")", "(", "hashFunc", "Hash", ",", "sigAlgo", "pkix", ".", "AlgorithmIdentifier", ",", "err", "error", ")", "{", "var", "pubType", "PublicKeyAlgorithm", "\n\n", "switch", "pub", ":=", "pub", ".", "(", "type", ")", "{", "case", "*", "rsa", ".", "PublicKey", ":", "pubType", "=", "RSA", "\n", "hashFunc", "=", "SHA256", "\n", "sigAlgo", ".", "Algorithm", "=", "oidSignatureSHA256WithRSA", "\n", "sigAlgo", ".", "Parameters", "=", "asn1", ".", "RawValue", "{", "Tag", ":", "5", ",", "}", "\n\n", "case", "*", "ecdsa", ".", "PublicKey", ":", "pubType", "=", "ECDSA", "\n", "switch", "pub", ".", "Curve", "{", "case", "elliptic", ".", "P224", "(", ")", ",", "elliptic", ".", "P256", "(", ")", ":", "hashFunc", "=", "SHA256", "\n", "sigAlgo", ".", "Algorithm", "=", "oidSignatureECDSAWithSHA256", "\n", "case", "elliptic", ".", "P384", "(", ")", ":", "hashFunc", "=", "SHA384", "\n", "sigAlgo", ".", "Algorithm", "=", "oidSignatureECDSAWithSHA384", "\n", "case", "elliptic", ".", "P521", "(", ")", ":", "hashFunc", "=", "SHA512", "\n", "sigAlgo", ".", "Algorithm", "=", "oidSignatureECDSAWithSHA512", "\n", "default", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "*", "PublicKey", ":", "pubType", "=", "ECDSA", "\n", "switch", "pub", ".", "Curve", "{", "case", "P256Sm2", "(", ")", ":", "hashFunc", "=", "SM3", "\n", "sigAlgo", ".", "Algorithm", "=", "oidSignatureSM2WithSM3", "\n", "default", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "requestedSigAlgo", "==", "0", "{", "return", "\n", "}", "\n\n", "found", ":=", "false", "\n", "for", "_", ",", "details", ":=", "range", "signatureAlgorithmDetails", "{", "if", "details", ".", "algo", "==", "requestedSigAlgo", "{", "if", "details", ".", "pubKeyAlgo", "!=", "pubType", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "sigAlgo", ".", "Algorithm", ",", "hashFunc", "=", "details", ".", "oid", ",", "details", ".", "hash", "\n", "if", "hashFunc", "==", "0", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "requestedSigAlgo", ".", "isRSAPSS", "(", ")", "{", "sigAlgo", ".", "Parameters", "=", "rsaPSSParameters", "(", "hashFunc", ")", "\n", "}", "\n", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "found", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// signingParamsForPublicKey returns the parameters to use for signing with // priv. If requestedSigAlgo is not zero then it overrides the default // signature algorithm.
[ "signingParamsForPublicKey", "returns", "the", "parameters", "to", "use", "for", "signing", "with", "priv", ".", "If", "requestedSigAlgo", "is", "not", "zero", "then", "it", "overrides", "the", "default", "signature", "algorithm", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L1814-L1887
148,515
tjfoc/gmsm
sm2/x509.go
ParseCRL
func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) { if bytes.HasPrefix(crlBytes, pemCRLPrefix) { block, _ := pem.Decode(crlBytes) if block != nil && block.Type == pemType { crlBytes = block.Bytes } } return ParseDERCRL(crlBytes) }
go
func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) { if bytes.HasPrefix(crlBytes, pemCRLPrefix) { block, _ := pem.Decode(crlBytes) if block != nil && block.Type == pemType { crlBytes = block.Bytes } } return ParseDERCRL(crlBytes) }
[ "func", "ParseCRL", "(", "crlBytes", "[", "]", "byte", ")", "(", "*", "pkix", ".", "CertificateList", ",", "error", ")", "{", "if", "bytes", ".", "HasPrefix", "(", "crlBytes", ",", "pemCRLPrefix", ")", "{", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "crlBytes", ")", "\n", "if", "block", "!=", "nil", "&&", "block", ".", "Type", "==", "pemType", "{", "crlBytes", "=", "block", ".", "Bytes", "\n", "}", "\n", "}", "\n", "return", "ParseDERCRL", "(", "crlBytes", ")", "\n", "}" ]
// ParseCRL parses a CRL from the given bytes. It's often the case that PEM // encoded CRLs will appear where they should be DER encoded, so this function // will transparently handle PEM encoding as long as there isn't any leading // garbage.
[ "ParseCRL", "parses", "a", "CRL", "from", "the", "given", "bytes", ".", "It", "s", "often", "the", "case", "that", "PEM", "encoded", "CRLs", "will", "appear", "where", "they", "should", "be", "DER", "encoded", "so", "this", "function", "will", "transparently", "handle", "PEM", "encoding", "as", "long", "as", "there", "isn", "t", "any", "leading", "garbage", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2003-L2011
148,516
tjfoc/gmsm
sm2/x509.go
ParseDERCRL
func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) { certList := new(pkix.CertificateList) if rest, err := asn1.Unmarshal(derBytes, certList); err != nil { return nil, err } else if len(rest) != 0 { return nil, errors.New("x509: trailing data after CRL") } return certList, nil }
go
func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) { certList := new(pkix.CertificateList) if rest, err := asn1.Unmarshal(derBytes, certList); err != nil { return nil, err } else if len(rest) != 0 { return nil, errors.New("x509: trailing data after CRL") } return certList, nil }
[ "func", "ParseDERCRL", "(", "derBytes", "[", "]", "byte", ")", "(", "*", "pkix", ".", "CertificateList", ",", "error", ")", "{", "certList", ":=", "new", "(", "pkix", ".", "CertificateList", ")", "\n", "if", "rest", ",", "err", ":=", "asn1", ".", "Unmarshal", "(", "derBytes", ",", "certList", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "len", "(", "rest", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "certList", ",", "nil", "\n", "}" ]
// ParseDERCRL parses a DER encoded CRL from the given bytes.
[ "ParseDERCRL", "parses", "a", "DER", "encoded", "CRL", "from", "the", "given", "bytes", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2014-L2022
148,517
tjfoc/gmsm
sm2/x509.go
CreateCRL
func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { key, ok := priv.(crypto.Signer) if !ok { return nil, errors.New("x509: certificate private key does not implement crypto.Signer") } hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0) if err != nil { return nil, err } // Force revocation times to UTC per RFC 5280. revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts)) for i, rc := range revokedCerts { rc.RevocationTime = rc.RevocationTime.UTC() revokedCertsUTC[i] = rc } tbsCertList := pkix.TBSCertificateList{ Version: 1, Signature: signatureAlgorithm, Issuer: c.Subject.ToRDNSequence(), ThisUpdate: now.UTC(), NextUpdate: expiry.UTC(), RevokedCertificates: revokedCertsUTC, } // Authority Key Id if len(c.SubjectKeyId) > 0 { var aki pkix.Extension aki.Id = oidExtensionAuthorityKeyId aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId}) if err != nil { return } tbsCertList.Extensions = append(tbsCertList.Extensions, aki) } tbsCertListContents, err := asn1.Marshal(tbsCertList) if err != nil { return } digest := tbsCertListContents switch hashFunc { case SM3: break default: h := hashFunc.New() h.Write(tbsCertListContents) digest = h.Sum(nil) } var signature []byte signature, err = key.Sign(rand, digest, hashFunc) if err != nil { return } return asn1.Marshal(pkix.CertificateList{ TBSCertList: tbsCertList, SignatureAlgorithm: signatureAlgorithm, SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, }) }
go
func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { key, ok := priv.(crypto.Signer) if !ok { return nil, errors.New("x509: certificate private key does not implement crypto.Signer") } hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0) if err != nil { return nil, err } // Force revocation times to UTC per RFC 5280. revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts)) for i, rc := range revokedCerts { rc.RevocationTime = rc.RevocationTime.UTC() revokedCertsUTC[i] = rc } tbsCertList := pkix.TBSCertificateList{ Version: 1, Signature: signatureAlgorithm, Issuer: c.Subject.ToRDNSequence(), ThisUpdate: now.UTC(), NextUpdate: expiry.UTC(), RevokedCertificates: revokedCertsUTC, } // Authority Key Id if len(c.SubjectKeyId) > 0 { var aki pkix.Extension aki.Id = oidExtensionAuthorityKeyId aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId}) if err != nil { return } tbsCertList.Extensions = append(tbsCertList.Extensions, aki) } tbsCertListContents, err := asn1.Marshal(tbsCertList) if err != nil { return } digest := tbsCertListContents switch hashFunc { case SM3: break default: h := hashFunc.New() h.Write(tbsCertListContents) digest = h.Sum(nil) } var signature []byte signature, err = key.Sign(rand, digest, hashFunc) if err != nil { return } return asn1.Marshal(pkix.CertificateList{ TBSCertList: tbsCertList, SignatureAlgorithm: signatureAlgorithm, SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, }) }
[ "func", "(", "c", "*", "Certificate", ")", "CreateCRL", "(", "rand", "io", ".", "Reader", ",", "priv", "interface", "{", "}", ",", "revokedCerts", "[", "]", "pkix", ".", "RevokedCertificate", ",", "now", ",", "expiry", "time", ".", "Time", ")", "(", "crlBytes", "[", "]", "byte", ",", "err", "error", ")", "{", "key", ",", "ok", ":=", "priv", ".", "(", "crypto", ".", "Signer", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "hashFunc", ",", "signatureAlgorithm", ",", "err", ":=", "signingParamsForPublicKey", "(", "key", ".", "Public", "(", ")", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Force revocation times to UTC per RFC 5280.", "revokedCertsUTC", ":=", "make", "(", "[", "]", "pkix", ".", "RevokedCertificate", ",", "len", "(", "revokedCerts", ")", ")", "\n", "for", "i", ",", "rc", ":=", "range", "revokedCerts", "{", "rc", ".", "RevocationTime", "=", "rc", ".", "RevocationTime", ".", "UTC", "(", ")", "\n", "revokedCertsUTC", "[", "i", "]", "=", "rc", "\n", "}", "\n\n", "tbsCertList", ":=", "pkix", ".", "TBSCertificateList", "{", "Version", ":", "1", ",", "Signature", ":", "signatureAlgorithm", ",", "Issuer", ":", "c", ".", "Subject", ".", "ToRDNSequence", "(", ")", ",", "ThisUpdate", ":", "now", ".", "UTC", "(", ")", ",", "NextUpdate", ":", "expiry", ".", "UTC", "(", ")", ",", "RevokedCertificates", ":", "revokedCertsUTC", ",", "}", "\n\n", "// Authority Key Id", "if", "len", "(", "c", ".", "SubjectKeyId", ")", ">", "0", "{", "var", "aki", "pkix", ".", "Extension", "\n", "aki", ".", "Id", "=", "oidExtensionAuthorityKeyId", "\n", "aki", ".", "Value", ",", "err", "=", "asn1", ".", "Marshal", "(", "authKeyId", "{", "Id", ":", "c", ".", "SubjectKeyId", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "tbsCertList", ".", "Extensions", "=", "append", "(", "tbsCertList", ".", "Extensions", ",", "aki", ")", "\n", "}", "\n\n", "tbsCertListContents", ",", "err", ":=", "asn1", ".", "Marshal", "(", "tbsCertList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "digest", ":=", "tbsCertListContents", "\n", "switch", "hashFunc", "{", "case", "SM3", ":", "break", "\n", "default", ":", "h", ":=", "hashFunc", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "tbsCertListContents", ")", "\n", "digest", "=", "h", ".", "Sum", "(", "nil", ")", "\n", "}", "\n\n", "var", "signature", "[", "]", "byte", "\n", "signature", ",", "err", "=", "key", ".", "Sign", "(", "rand", ",", "digest", ",", "hashFunc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "return", "asn1", ".", "Marshal", "(", "pkix", ".", "CertificateList", "{", "TBSCertList", ":", "tbsCertList", ",", "SignatureAlgorithm", ":", "signatureAlgorithm", ",", "SignatureValue", ":", "asn1", ".", "BitString", "{", "Bytes", ":", "signature", ",", "BitLength", ":", "len", "(", "signature", ")", "*", "8", "}", ",", "}", ")", "\n", "}" ]
// CreateCRL returns a DER encoded CRL, signed by this Certificate, that // contains the given list of revoked certificates.
[ "CreateCRL", "returns", "a", "DER", "encoded", "CRL", "signed", "by", "this", "Certificate", "that", "contains", "the", "given", "list", "of", "revoked", "certificates", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2026-L2090
148,518
tjfoc/gmsm
sm2/x509.go
newRawAttributes
func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) { var rawAttributes []asn1.RawValue b, err := asn1.Marshal(attributes) if err != nil { return nil, err } rest, err := asn1.Unmarshal(b, &rawAttributes) if err != nil { return nil, err } if len(rest) != 0 { return nil, errors.New("x509: failed to unmarshal raw CSR Attributes") } return rawAttributes, nil }
go
func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) { var rawAttributes []asn1.RawValue b, err := asn1.Marshal(attributes) if err != nil { return nil, err } rest, err := asn1.Unmarshal(b, &rawAttributes) if err != nil { return nil, err } if len(rest) != 0 { return nil, errors.New("x509: failed to unmarshal raw CSR Attributes") } return rawAttributes, nil }
[ "func", "newRawAttributes", "(", "attributes", "[", "]", "pkix", ".", "AttributeTypeAndValueSET", ")", "(", "[", "]", "asn1", ".", "RawValue", ",", "error", ")", "{", "var", "rawAttributes", "[", "]", "asn1", ".", "RawValue", "\n", "b", ",", "err", ":=", "asn1", ".", "Marshal", "(", "attributes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rest", ",", "err", ":=", "asn1", ".", "Unmarshal", "(", "b", ",", "&", "rawAttributes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "rest", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "rawAttributes", ",", "nil", "\n", "}" ]
// newRawAttributes converts AttributeTypeAndValueSETs from a template // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
[ "newRawAttributes", "converts", "AttributeTypeAndValueSETs", "from", "a", "template", "CertificateRequest", "s", "Attributes", "into", "tbsCertificateRequest", "RawAttributes", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2155-L2169
148,519
tjfoc/gmsm
sm2/x509.go
parseRawAttributes
func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET { var attributes []pkix.AttributeTypeAndValueSET for _, rawAttr := range rawAttributes { var attr pkix.AttributeTypeAndValueSET rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr) // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET // (i.e.: challengePassword or unstructuredName). if err == nil && len(rest) == 0 { attributes = append(attributes, attr) } } return attributes }
go
func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET { var attributes []pkix.AttributeTypeAndValueSET for _, rawAttr := range rawAttributes { var attr pkix.AttributeTypeAndValueSET rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr) // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET // (i.e.: challengePassword or unstructuredName). if err == nil && len(rest) == 0 { attributes = append(attributes, attr) } } return attributes }
[ "func", "parseRawAttributes", "(", "rawAttributes", "[", "]", "asn1", ".", "RawValue", ")", "[", "]", "pkix", ".", "AttributeTypeAndValueSET", "{", "var", "attributes", "[", "]", "pkix", ".", "AttributeTypeAndValueSET", "\n", "for", "_", ",", "rawAttr", ":=", "range", "rawAttributes", "{", "var", "attr", "pkix", ".", "AttributeTypeAndValueSET", "\n", "rest", ",", "err", ":=", "asn1", ".", "Unmarshal", "(", "rawAttr", ".", "FullBytes", ",", "&", "attr", ")", "\n", "// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET", "// (i.e.: challengePassword or unstructuredName).", "if", "err", "==", "nil", "&&", "len", "(", "rest", ")", "==", "0", "{", "attributes", "=", "append", "(", "attributes", ",", "attr", ")", "\n", "}", "\n", "}", "\n", "return", "attributes", "\n", "}" ]
// parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs.
[ "parseRawAttributes", "Unmarshals", "RawAttributes", "intos", "AttributeTypeAndValueSETs", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2172-L2184
148,520
tjfoc/gmsm
sm2/x509.go
parseCSRExtensions
func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) { // pkcs10Attribute reflects the Attribute structure from section 4.1 of // https://tools.ietf.org/html/rfc2986. type pkcs10Attribute struct { Id asn1.ObjectIdentifier Values []asn1.RawValue `asn1:"set"` } var ret []pkix.Extension for _, rawAttr := range rawAttributes { var attr pkcs10Attribute if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 { // Ignore attributes that don't parse. continue } if !attr.Id.Equal(oidExtensionRequest) { continue } var extensions []pkix.Extension if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil { return nil, err } ret = append(ret, extensions...) } return ret, nil }
go
func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) { // pkcs10Attribute reflects the Attribute structure from section 4.1 of // https://tools.ietf.org/html/rfc2986. type pkcs10Attribute struct { Id asn1.ObjectIdentifier Values []asn1.RawValue `asn1:"set"` } var ret []pkix.Extension for _, rawAttr := range rawAttributes { var attr pkcs10Attribute if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 { // Ignore attributes that don't parse. continue } if !attr.Id.Equal(oidExtensionRequest) { continue } var extensions []pkix.Extension if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil { return nil, err } ret = append(ret, extensions...) } return ret, nil }
[ "func", "parseCSRExtensions", "(", "rawAttributes", "[", "]", "asn1", ".", "RawValue", ")", "(", "[", "]", "pkix", ".", "Extension", ",", "error", ")", "{", "// pkcs10Attribute reflects the Attribute structure from section 4.1 of", "// https://tools.ietf.org/html/rfc2986.", "type", "pkcs10Attribute", "struct", "{", "Id", "asn1", ".", "ObjectIdentifier", "\n", "Values", "[", "]", "asn1", ".", "RawValue", "`asn1:\"set\"`", "\n", "}", "\n\n", "var", "ret", "[", "]", "pkix", ".", "Extension", "\n", "for", "_", ",", "rawAttr", ":=", "range", "rawAttributes", "{", "var", "attr", "pkcs10Attribute", "\n", "if", "rest", ",", "err", ":=", "asn1", ".", "Unmarshal", "(", "rawAttr", ".", "FullBytes", ",", "&", "attr", ")", ";", "err", "!=", "nil", "||", "len", "(", "rest", ")", "!=", "0", "||", "len", "(", "attr", ".", "Values", ")", "==", "0", "{", "// Ignore attributes that don't parse.", "continue", "\n", "}", "\n\n", "if", "!", "attr", ".", "Id", ".", "Equal", "(", "oidExtensionRequest", ")", "{", "continue", "\n", "}", "\n\n", "var", "extensions", "[", "]", "pkix", ".", "Extension", "\n", "if", "_", ",", "err", ":=", "asn1", ".", "Unmarshal", "(", "attr", ".", "Values", "[", "0", "]", ".", "FullBytes", ",", "&", "extensions", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "extensions", "...", ")", "\n", "}", "\n\n", "return", "ret", ",", "nil", "\n", "}" ]
// parseCSRExtensions parses the attributes from a CSR and extracts any // requested extensions.
[ "parseCSRExtensions", "parses", "the", "attributes", "from", "a", "CSR", "and", "extracts", "any", "requested", "extensions", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2188-L2216
148,521
tjfoc/gmsm
sm2/x509.go
ParseCertificateRequest
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { var csr certificateRequest rest, err := asn1.Unmarshal(asn1Data, &csr) if err != nil { return nil, err } else if len(rest) != 0 { return nil, asn1.SyntaxError{Msg: "trailing data"} } return parseCertificateRequest(&csr) }
go
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { var csr certificateRequest rest, err := asn1.Unmarshal(asn1Data, &csr) if err != nil { return nil, err } else if len(rest) != 0 { return nil, asn1.SyntaxError{Msg: "trailing data"} } return parseCertificateRequest(&csr) }
[ "func", "ParseCertificateRequest", "(", "asn1Data", "[", "]", "byte", ")", "(", "*", "CertificateRequest", ",", "error", ")", "{", "var", "csr", "certificateRequest", "\n\n", "rest", ",", "err", ":=", "asn1", ".", "Unmarshal", "(", "asn1Data", ",", "&", "csr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "len", "(", "rest", ")", "!=", "0", "{", "return", "nil", ",", "asn1", ".", "SyntaxError", "{", "Msg", ":", "\"", "\"", "}", "\n", "}", "\n\n", "return", "parseCertificateRequest", "(", "&", "csr", ")", "\n", "}" ]
// ParseCertificateRequest parses a single certificate request from the // given ASN.1 DER data.
[ "ParseCertificateRequest", "parses", "a", "single", "certificate", "request", "from", "the", "given", "ASN", ".", "1", "DER", "data", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2382-L2393
148,522
tjfoc/gmsm
sm2/x509.go
CheckSignature
func (c *CertificateRequest) CheckSignature() error { return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey) }
go
func (c *CertificateRequest) CheckSignature() error { return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey) }
[ "func", "(", "c", "*", "CertificateRequest", ")", "CheckSignature", "(", ")", "error", "{", "return", "checkSignature", "(", "c", ".", "SignatureAlgorithm", ",", "c", ".", "RawTBSCertificateRequest", ",", "c", ".", "Signature", ",", "c", ".", "PublicKey", ")", "\n", "}" ]
// CheckSignature reports whether the signature on c is valid.
[ "CheckSignature", "reports", "whether", "the", "signature", "on", "c", "is", "valid", "." ]
18fd8096dc8a3dcd43e9eccbdb4ef598900ae252
https://github.com/tjfoc/gmsm/blob/18fd8096dc8a3dcd43e9eccbdb4ef598900ae252/sm2/x509.go#L2443-L2445
148,523
vmihailenco/msgpack
decode.go
NewDecoder
func NewDecoder(r io.Reader) *Decoder { d := &Decoder{ buf: makeBuffer(), } d.resetReader(r) return d }
go
func NewDecoder(r io.Reader) *Decoder { d := &Decoder{ buf: makeBuffer(), } d.resetReader(r) return d }
[ "func", "NewDecoder", "(", "r", "io", ".", "Reader", ")", "*", "Decoder", "{", "d", ":=", "&", "Decoder", "{", "buf", ":", "makeBuffer", "(", ")", ",", "}", "\n", "d", ".", "resetReader", "(", "r", ")", "\n", "return", "d", "\n", "}" ]
// NewDecoder returns a new decoder that reads from r. // // The decoder introduces its own buffering and may read data from r // beyond the MessagePack values requested. Buffering can be disabled // by passing a reader that implements io.ByteScanner interface.
[ "NewDecoder", "returns", "a", "new", "decoder", "that", "reads", "from", "r", ".", "The", "decoder", "introduces", "its", "own", "buffering", "and", "may", "read", "data", "from", "r", "beyond", "the", "MessagePack", "values", "requested", ".", "Buffering", "can", "be", "disabled", "by", "passing", "a", "reader", "that", "implements", "io", ".", "ByteScanner", "interface", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode.go#L58-L64
148,524
vmihailenco/msgpack
decode.go
UseJSONTag
func (d *Decoder) UseJSONTag(v bool) *Decoder { d.useJSONTag = v return d }
go
func (d *Decoder) UseJSONTag(v bool) *Decoder { d.useJSONTag = v return d }
[ "func", "(", "d", "*", "Decoder", ")", "UseJSONTag", "(", "v", "bool", ")", "*", "Decoder", "{", "d", ".", "useJSONTag", "=", "v", "\n", "return", "d", "\n", "}" ]
// UseJSONTag causes the Decoder to use json struct tag as fallback option // if there is no msgpack tag.
[ "UseJSONTag", "causes", "the", "Decoder", "to", "use", "json", "struct", "tag", "as", "fallback", "option", "if", "there", "is", "no", "msgpack", "tag", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode.go#L79-L82
148,525
vmihailenco/msgpack
decode.go
Skip
func (d *Decoder) Skip() error { c, err := d.readCode() if err != nil { return err } if codes.IsFixedNum(c) { return nil } else if codes.IsFixedMap(c) { return d.skipMap(c) } else if codes.IsFixedArray(c) { return d.skipSlice(c) } else if codes.IsFixedString(c) { return d.skipBytes(c) } switch c { case codes.Nil, codes.False, codes.True: return nil case codes.Uint8, codes.Int8: return d.skipN(1) case codes.Uint16, codes.Int16: return d.skipN(2) case codes.Uint32, codes.Int32, codes.Float: return d.skipN(4) case codes.Uint64, codes.Int64, codes.Double: return d.skipN(8) case codes.Bin8, codes.Bin16, codes.Bin32: return d.skipBytes(c) case codes.Str8, codes.Str16, codes.Str32: return d.skipBytes(c) case codes.Array16, codes.Array32: return d.skipSlice(c) case codes.Map16, codes.Map32: return d.skipMap(c) case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, codes.Ext8, codes.Ext16, codes.Ext32: return d.skipExt(c) } return fmt.Errorf("msgpack: unknown code %x", c) }
go
func (d *Decoder) Skip() error { c, err := d.readCode() if err != nil { return err } if codes.IsFixedNum(c) { return nil } else if codes.IsFixedMap(c) { return d.skipMap(c) } else if codes.IsFixedArray(c) { return d.skipSlice(c) } else if codes.IsFixedString(c) { return d.skipBytes(c) } switch c { case codes.Nil, codes.False, codes.True: return nil case codes.Uint8, codes.Int8: return d.skipN(1) case codes.Uint16, codes.Int16: return d.skipN(2) case codes.Uint32, codes.Int32, codes.Float: return d.skipN(4) case codes.Uint64, codes.Int64, codes.Double: return d.skipN(8) case codes.Bin8, codes.Bin16, codes.Bin32: return d.skipBytes(c) case codes.Str8, codes.Str16, codes.Str32: return d.skipBytes(c) case codes.Array16, codes.Array32: return d.skipSlice(c) case codes.Map16, codes.Map32: return d.skipMap(c) case codes.FixExt1, codes.FixExt2, codes.FixExt4, codes.FixExt8, codes.FixExt16, codes.Ext8, codes.Ext16, codes.Ext32: return d.skipExt(c) } return fmt.Errorf("msgpack: unknown code %x", c) }
[ "func", "(", "d", "*", "Decoder", ")", "Skip", "(", ")", "error", "{", "c", ",", "err", ":=", "d", ".", "readCode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "codes", ".", "IsFixedNum", "(", "c", ")", "{", "return", "nil", "\n", "}", "else", "if", "codes", ".", "IsFixedMap", "(", "c", ")", "{", "return", "d", ".", "skipMap", "(", "c", ")", "\n", "}", "else", "if", "codes", ".", "IsFixedArray", "(", "c", ")", "{", "return", "d", ".", "skipSlice", "(", "c", ")", "\n", "}", "else", "if", "codes", ".", "IsFixedString", "(", "c", ")", "{", "return", "d", ".", "skipBytes", "(", "c", ")", "\n", "}", "\n\n", "switch", "c", "{", "case", "codes", ".", "Nil", ",", "codes", ".", "False", ",", "codes", ".", "True", ":", "return", "nil", "\n", "case", "codes", ".", "Uint8", ",", "codes", ".", "Int8", ":", "return", "d", ".", "skipN", "(", "1", ")", "\n", "case", "codes", ".", "Uint16", ",", "codes", ".", "Int16", ":", "return", "d", ".", "skipN", "(", "2", ")", "\n", "case", "codes", ".", "Uint32", ",", "codes", ".", "Int32", ",", "codes", ".", "Float", ":", "return", "d", ".", "skipN", "(", "4", ")", "\n", "case", "codes", ".", "Uint64", ",", "codes", ".", "Int64", ",", "codes", ".", "Double", ":", "return", "d", ".", "skipN", "(", "8", ")", "\n", "case", "codes", ".", "Bin8", ",", "codes", ".", "Bin16", ",", "codes", ".", "Bin32", ":", "return", "d", ".", "skipBytes", "(", "c", ")", "\n", "case", "codes", ".", "Str8", ",", "codes", ".", "Str16", ",", "codes", ".", "Str32", ":", "return", "d", ".", "skipBytes", "(", "c", ")", "\n", "case", "codes", ".", "Array16", ",", "codes", ".", "Array32", ":", "return", "d", ".", "skipSlice", "(", "c", ")", "\n", "case", "codes", ".", "Map16", ",", "codes", ".", "Map32", ":", "return", "d", ".", "skipMap", "(", "c", ")", "\n", "case", "codes", ".", "FixExt1", ",", "codes", ".", "FixExt2", ",", "codes", ".", "FixExt4", ",", "codes", ".", "FixExt8", ",", "codes", ".", "FixExt16", ",", "codes", ".", "Ext8", ",", "codes", ".", "Ext16", ",", "codes", ".", "Ext32", ":", "return", "d", ".", "skipExt", "(", "c", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ")", "\n", "}" ]
// Skip skips next value.
[ "Skip", "skips", "next", "value", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode.go#L408-L449
148,526
vmihailenco/msgpack
decode_map.go
DecodeMapLen
func (d *Decoder) DecodeMapLen() (int, error) { c, err := d.readCode() if err != nil { return 0, err } if codes.IsExt(c) { if err = d.skipExtHeader(c); err != nil { return 0, err } c, err = d.readCode() if err != nil { return 0, err } } return d.mapLen(c) }
go
func (d *Decoder) DecodeMapLen() (int, error) { c, err := d.readCode() if err != nil { return 0, err } if codes.IsExt(c) { if err = d.skipExtHeader(c); err != nil { return 0, err } c, err = d.readCode() if err != nil { return 0, err } } return d.mapLen(c) }
[ "func", "(", "d", "*", "Decoder", ")", "DecodeMapLen", "(", ")", "(", "int", ",", "error", ")", "{", "c", ",", "err", ":=", "d", ".", "readCode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "if", "codes", ".", "IsExt", "(", "c", ")", "{", "if", "err", "=", "d", ".", "skipExtHeader", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "c", ",", "err", "=", "d", ".", "readCode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n", "return", "d", ".", "mapLen", "(", "c", ")", "\n", "}" ]
// DecodeMapLen decodes map length. Length is -1 when map is nil.
[ "DecodeMapLen", "decodes", "map", "length", ".", "Length", "is", "-", "1", "when", "map", "is", "nil", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode_map.go#L66-L83
148,527
vmihailenco/msgpack
encode.go
StructAsArray
func (e *Encoder) StructAsArray(flag bool) *Encoder { e.structAsArray = flag return e }
go
func (e *Encoder) StructAsArray(flag bool) *Encoder { e.structAsArray = flag return e }
[ "func", "(", "e", "*", "Encoder", ")", "StructAsArray", "(", "flag", "bool", ")", "*", "Encoder", "{", "e", ".", "structAsArray", "=", "flag", "\n", "return", "e", "\n", "}" ]
// StructAsArray causes the Encoder to encode Go structs as MessagePack arrays.
[ "StructAsArray", "causes", "the", "Encoder", "to", "encode", "Go", "structs", "as", "MessagePack", "arrays", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode.go#L91-L94
148,528
vmihailenco/msgpack
encode.go
UseJSONTag
func (e *Encoder) UseJSONTag(flag bool) *Encoder { e.useJSONTag = flag return e }
go
func (e *Encoder) UseJSONTag(flag bool) *Encoder { e.useJSONTag = flag return e }
[ "func", "(", "e", "*", "Encoder", ")", "UseJSONTag", "(", "flag", "bool", ")", "*", "Encoder", "{", "e", ".", "useJSONTag", "=", "flag", "\n", "return", "e", "\n", "}" ]
// UseJSONTag causes the Encoder to use json struct tag as fallback option // if there is no msgpack tag.
[ "UseJSONTag", "causes", "the", "Encoder", "to", "use", "json", "struct", "tag", "as", "fallback", "option", "if", "there", "is", "no", "msgpack", "tag", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode.go#L98-L101
148,529
vmihailenco/msgpack
encode.go
UseCompactEncoding
func (e *Encoder) UseCompactEncoding(flag bool) *Encoder { e.useCompact = flag return e }
go
func (e *Encoder) UseCompactEncoding(flag bool) *Encoder { e.useCompact = flag return e }
[ "func", "(", "e", "*", "Encoder", ")", "UseCompactEncoding", "(", "flag", "bool", ")", "*", "Encoder", "{", "e", ".", "useCompact", "=", "flag", "\n", "return", "e", "\n", "}" ]
// UseCompactEncoding causes the Encoder to chose the most compact encoding. // For example, it allows to encode Go int64 as msgpack int8 saving 7 bytes.
[ "UseCompactEncoding", "causes", "the", "Encoder", "to", "chose", "the", "most", "compact", "encoding", ".", "For", "example", "it", "allows", "to", "encode", "Go", "int64", "as", "msgpack", "int8", "saving", "7", "bytes", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode.go#L105-L108
148,530
vmihailenco/msgpack
decode_slice.go
DecodeArrayLen
func (d *Decoder) DecodeArrayLen() (int, error) { c, err := d.readCode() if err != nil { return 0, err } return d.arrayLen(c) }
go
func (d *Decoder) DecodeArrayLen() (int, error) { c, err := d.readCode() if err != nil { return 0, err } return d.arrayLen(c) }
[ "func", "(", "d", "*", "Decoder", ")", "DecodeArrayLen", "(", ")", "(", "int", ",", "error", ")", "{", "c", ",", "err", ":=", "d", ".", "readCode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "d", ".", "arrayLen", "(", "c", ")", "\n", "}" ]
// DecodeArrayLen decodes array length. Length is -1 when array is nil.
[ "DecodeArrayLen", "decodes", "array", "length", ".", "Length", "is", "-", "1", "when", "array", "is", "nil", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/decode_slice.go#L15-L21
148,531
vmihailenco/msgpack
encode_number.go
EncodeUint8
func (e *Encoder) EncodeUint8(n uint8) error { return e.write1(codes.Uint8, n) }
go
func (e *Encoder) EncodeUint8(n uint8) error { return e.write1(codes.Uint8, n) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeUint8", "(", "n", "uint8", ")", "error", "{", "return", "e", ".", "write1", "(", "codes", ".", "Uint8", ",", "n", ")", "\n", "}" ]
// EncodeUint8 encodes an uint8 in 2 bytes preserving type of the number.
[ "EncodeUint8", "encodes", "an", "uint8", "in", "2", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L11-L13
148,532
vmihailenco/msgpack
encode_number.go
EncodeUint16
func (e *Encoder) EncodeUint16(n uint16) error { return e.write2(codes.Uint16, n) }
go
func (e *Encoder) EncodeUint16(n uint16) error { return e.write2(codes.Uint16, n) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeUint16", "(", "n", "uint16", ")", "error", "{", "return", "e", ".", "write2", "(", "codes", ".", "Uint16", ",", "n", ")", "\n", "}" ]
// EncodeUint16 encodes an uint16 in 3 bytes preserving type of the number.
[ "EncodeUint16", "encodes", "an", "uint16", "in", "3", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L23-L25
148,533
vmihailenco/msgpack
encode_number.go
EncodeUint32
func (e *Encoder) EncodeUint32(n uint32) error { return e.write4(codes.Uint32, n) }
go
func (e *Encoder) EncodeUint32(n uint32) error { return e.write4(codes.Uint32, n) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeUint32", "(", "n", "uint32", ")", "error", "{", "return", "e", ".", "write4", "(", "codes", ".", "Uint32", ",", "n", ")", "\n", "}" ]
// EncodeUint32 encodes an uint16 in 5 bytes preserving type of the number.
[ "EncodeUint32", "encodes", "an", "uint16", "in", "5", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L35-L37
148,534
vmihailenco/msgpack
encode_number.go
EncodeUint64
func (e *Encoder) EncodeUint64(n uint64) error { return e.write8(codes.Uint64, n) }
go
func (e *Encoder) EncodeUint64(n uint64) error { return e.write8(codes.Uint64, n) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeUint64", "(", "n", "uint64", ")", "error", "{", "return", "e", ".", "write8", "(", "codes", ".", "Uint64", ",", "n", ")", "\n", "}" ]
// EncodeUint64 encodes an uint16 in 9 bytes preserving type of the number.
[ "EncodeUint64", "encodes", "an", "uint16", "in", "9", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L47-L49
148,535
vmihailenco/msgpack
encode_number.go
EncodeInt8
func (e *Encoder) EncodeInt8(n int8) error { return e.write1(codes.Int8, uint8(n)) }
go
func (e *Encoder) EncodeInt8(n int8) error { return e.write1(codes.Int8, uint8(n)) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeInt8", "(", "n", "int8", ")", "error", "{", "return", "e", ".", "write1", "(", "codes", ".", "Int8", ",", "uint8", "(", "n", ")", ")", "\n", "}" ]
// EncodeInt8 encodes an int8 in 2 bytes preserving type of the number.
[ "EncodeInt8", "encodes", "an", "int8", "in", "2", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L59-L61
148,536
vmihailenco/msgpack
encode_number.go
EncodeInt16
func (e *Encoder) EncodeInt16(n int16) error { return e.write2(codes.Int16, uint16(n)) }
go
func (e *Encoder) EncodeInt16(n int16) error { return e.write2(codes.Int16, uint16(n)) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeInt16", "(", "n", "int16", ")", "error", "{", "return", "e", ".", "write2", "(", "codes", ".", "Int16", ",", "uint16", "(", "n", ")", ")", "\n", "}" ]
// EncodeInt16 encodes an int16 in 3 bytes preserving type of the number.
[ "EncodeInt16", "encodes", "an", "int16", "in", "3", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L71-L73
148,537
vmihailenco/msgpack
encode_number.go
EncodeInt32
func (e *Encoder) EncodeInt32(n int32) error { return e.write4(codes.Int32, uint32(n)) }
go
func (e *Encoder) EncodeInt32(n int32) error { return e.write4(codes.Int32, uint32(n)) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeInt32", "(", "n", "int32", ")", "error", "{", "return", "e", ".", "write4", "(", "codes", ".", "Int32", ",", "uint32", "(", "n", ")", ")", "\n", "}" ]
// EncodeInt32 encodes an int32 in 5 bytes preserving type of the number.
[ "EncodeInt32", "encodes", "an", "int32", "in", "5", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L83-L85
148,538
vmihailenco/msgpack
encode_number.go
EncodeInt64
func (e *Encoder) EncodeInt64(n int64) error { return e.write8(codes.Int64, uint64(n)) }
go
func (e *Encoder) EncodeInt64(n int64) error { return e.write8(codes.Int64, uint64(n)) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeInt64", "(", "n", "int64", ")", "error", "{", "return", "e", ".", "write8", "(", "codes", ".", "Int64", ",", "uint64", "(", "n", ")", ")", "\n", "}" ]
// EncodeInt64 encodes an int64 in 9 bytes preserving type of the number.
[ "EncodeInt64", "encodes", "an", "int64", "in", "9", "bytes", "preserving", "type", "of", "the", "number", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L95-L97
148,539
vmihailenco/msgpack
encode_number.go
EncodeUint
func (e *Encoder) EncodeUint(n uint64) error { if n <= math.MaxInt8 { return e.w.WriteByte(byte(n)) } if n <= math.MaxUint8 { return e.EncodeUint8(uint8(n)) } if n <= math.MaxUint16 { return e.EncodeUint16(uint16(n)) } if n <= math.MaxUint32 { return e.EncodeUint32(uint32(n)) } return e.EncodeUint64(uint64(n)) }
go
func (e *Encoder) EncodeUint(n uint64) error { if n <= math.MaxInt8 { return e.w.WriteByte(byte(n)) } if n <= math.MaxUint8 { return e.EncodeUint8(uint8(n)) } if n <= math.MaxUint16 { return e.EncodeUint16(uint16(n)) } if n <= math.MaxUint32 { return e.EncodeUint32(uint32(n)) } return e.EncodeUint64(uint64(n)) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeUint", "(", "n", "uint64", ")", "error", "{", "if", "n", "<=", "math", ".", "MaxInt8", "{", "return", "e", ".", "w", ".", "WriteByte", "(", "byte", "(", "n", ")", ")", "\n", "}", "\n", "if", "n", "<=", "math", ".", "MaxUint8", "{", "return", "e", ".", "EncodeUint8", "(", "uint8", "(", "n", ")", ")", "\n", "}", "\n", "if", "n", "<=", "math", ".", "MaxUint16", "{", "return", "e", ".", "EncodeUint16", "(", "uint16", "(", "n", ")", ")", "\n", "}", "\n", "if", "n", "<=", "math", ".", "MaxUint32", "{", "return", "e", ".", "EncodeUint32", "(", "uint32", "(", "n", ")", ")", "\n", "}", "\n", "return", "e", ".", "EncodeUint64", "(", "uint64", "(", "n", ")", ")", "\n", "}" ]
// EncodeUnsignedNumber encodes an uint64 in 1, 2, 3, 5, or 9 bytes. // Type of the number is lost during encoding.
[ "EncodeUnsignedNumber", "encodes", "an", "uint64", "in", "1", "2", "3", "5", "or", "9", "bytes", ".", "Type", "of", "the", "number", "is", "lost", "during", "encoding", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L108-L122
148,540
vmihailenco/msgpack
encode_number.go
EncodeInt
func (e *Encoder) EncodeInt(n int64) error { if n >= 0 { return e.EncodeUint(uint64(n)) } if n >= int64(int8(codes.NegFixedNumLow)) { return e.w.WriteByte(byte(n)) } if n >= math.MinInt8 { return e.EncodeInt8(int8(n)) } if n >= math.MinInt16 { return e.EncodeInt16(int16(n)) } if n >= math.MinInt32 { return e.EncodeInt32(int32(n)) } return e.EncodeInt64(int64(n)) }
go
func (e *Encoder) EncodeInt(n int64) error { if n >= 0 { return e.EncodeUint(uint64(n)) } if n >= int64(int8(codes.NegFixedNumLow)) { return e.w.WriteByte(byte(n)) } if n >= math.MinInt8 { return e.EncodeInt8(int8(n)) } if n >= math.MinInt16 { return e.EncodeInt16(int16(n)) } if n >= math.MinInt32 { return e.EncodeInt32(int32(n)) } return e.EncodeInt64(int64(n)) }
[ "func", "(", "e", "*", "Encoder", ")", "EncodeInt", "(", "n", "int64", ")", "error", "{", "if", "n", ">=", "0", "{", "return", "e", ".", "EncodeUint", "(", "uint64", "(", "n", ")", ")", "\n", "}", "\n", "if", "n", ">=", "int64", "(", "int8", "(", "codes", ".", "NegFixedNumLow", ")", ")", "{", "return", "e", ".", "w", ".", "WriteByte", "(", "byte", "(", "n", ")", ")", "\n", "}", "\n", "if", "n", ">=", "math", ".", "MinInt8", "{", "return", "e", ".", "EncodeInt8", "(", "int8", "(", "n", ")", ")", "\n", "}", "\n", "if", "n", ">=", "math", ".", "MinInt16", "{", "return", "e", ".", "EncodeInt16", "(", "int16", "(", "n", ")", ")", "\n", "}", "\n", "if", "n", ">=", "math", ".", "MinInt32", "{", "return", "e", ".", "EncodeInt32", "(", "int32", "(", "n", ")", ")", "\n", "}", "\n", "return", "e", ".", "EncodeInt64", "(", "int64", "(", "n", ")", ")", "\n", "}" ]
// EncodeNumber encodes an int64 in 1, 2, 3, 5, or 9 bytes. // Type of number is lost during encoding.
[ "EncodeNumber", "encodes", "an", "int64", "in", "1", "2", "3", "5", "or", "9", "bytes", ".", "Type", "of", "number", "is", "lost", "during", "encoding", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/encode_number.go#L126-L143
148,541
vmihailenco/msgpack
ext.go
RegisterExt
func RegisterExt(id int8, value interface{}) { typ := reflect.TypeOf(value) if typ.Kind() == reflect.Ptr { typ = typ.Elem() } ptr := reflect.PtrTo(typ) if _, ok := extTypes[id]; ok { panic(fmt.Errorf("msgpack: ext with id=%d is already registered", id)) } registerExt(id, ptr, getEncoder(ptr), getDecoder(ptr)) registerExt(id, typ, getEncoder(typ), getDecoder(typ)) }
go
func RegisterExt(id int8, value interface{}) { typ := reflect.TypeOf(value) if typ.Kind() == reflect.Ptr { typ = typ.Elem() } ptr := reflect.PtrTo(typ) if _, ok := extTypes[id]; ok { panic(fmt.Errorf("msgpack: ext with id=%d is already registered", id)) } registerExt(id, ptr, getEncoder(ptr), getDecoder(ptr)) registerExt(id, typ, getEncoder(typ), getDecoder(typ)) }
[ "func", "RegisterExt", "(", "id", "int8", ",", "value", "interface", "{", "}", ")", "{", "typ", ":=", "reflect", ".", "TypeOf", "(", "value", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "typ", "=", "typ", ".", "Elem", "(", ")", "\n", "}", "\n", "ptr", ":=", "reflect", ".", "PtrTo", "(", "typ", ")", "\n\n", "if", "_", ",", "ok", ":=", "extTypes", "[", "id", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n\n", "registerExt", "(", "id", ",", "ptr", ",", "getEncoder", "(", "ptr", ")", ",", "getDecoder", "(", "ptr", ")", ")", "\n", "registerExt", "(", "id", ",", "typ", ",", "getEncoder", "(", "typ", ")", ",", "getDecoder", "(", "typ", ")", ")", "\n", "}" ]
// RegisterExt records a type, identified by a value for that type, // under the provided id. That id will identify the concrete type of a value // sent or received as an interface variable. Only types that will be // transferred as implementations of interface values need to be registered. // Expecting to be used only during initialization, it panics if the mapping // between types and ids is not a bijection.
[ "RegisterExt", "records", "a", "type", "identified", "by", "a", "value", "for", "that", "type", "under", "the", "provided", "id", ".", "That", "id", "will", "identify", "the", "concrete", "type", "of", "a", "value", "sent", "or", "received", "as", "an", "interface", "variable", ".", "Only", "types", "that", "will", "be", "transferred", "as", "implementations", "of", "interface", "values", "need", "to", "be", "registered", ".", "Expecting", "to", "be", "used", "only", "during", "initialization", "it", "panics", "if", "the", "mapping", "between", "types", "and", "ids", "is", "not", "a", "bijection", "." ]
5467b4fb032b68b160f4acce954153280cf5e05b
https://github.com/vmihailenco/msgpack/blob/5467b4fb032b68b160f4acce954153280cf5e05b/ext.go#L31-L44
148,542
minio/minio-go
bucket-notification.go
NewArn
func NewArn(partition, service, region, accountID, resource string) Arn { return Arn{Partition: partition, Service: service, Region: region, AccountID: accountID, Resource: resource} }
go
func NewArn(partition, service, region, accountID, resource string) Arn { return Arn{Partition: partition, Service: service, Region: region, AccountID: accountID, Resource: resource} }
[ "func", "NewArn", "(", "partition", ",", "service", ",", "region", ",", "accountID", ",", "resource", "string", ")", "Arn", "{", "return", "Arn", "{", "Partition", ":", "partition", ",", "Service", ":", "service", ",", "Region", ":", "region", ",", "AccountID", ":", "accountID", ",", "Resource", ":", "resource", "}", "\n", "}" ]
// NewArn creates new ARN based on the given partition, service, region, account id and resource
[ "NewArn", "creates", "new", "ARN", "based", "on", "the", "given", "partition", "service", "region", "account", "id", "and", "resource" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L76-L82
148,543
minio/minio-go
bucket-notification.go
String
func (arn Arn) String() string { return "arn:" + arn.Partition + ":" + arn.Service + ":" + arn.Region + ":" + arn.AccountID + ":" + arn.Resource }
go
func (arn Arn) String() string { return "arn:" + arn.Partition + ":" + arn.Service + ":" + arn.Region + ":" + arn.AccountID + ":" + arn.Resource }
[ "func", "(", "arn", "Arn", ")", "String", "(", ")", "string", "{", "return", "\"", "\"", "+", "arn", ".", "Partition", "+", "\"", "\"", "+", "arn", ".", "Service", "+", "\"", "\"", "+", "arn", ".", "Region", "+", "\"", "\"", "+", "arn", ".", "AccountID", "+", "\"", "\"", "+", "arn", ".", "Resource", "\n", "}" ]
// Return the string format of the ARN
[ "Return", "the", "string", "format", "of", "the", "ARN" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L85-L87
148,544
minio/minio-go
bucket-notification.go
AddEvents
func (t *NotificationConfig) AddEvents(events ...NotificationEventType) { t.Events = append(t.Events, events...) }
go
func (t *NotificationConfig) AddEvents(events ...NotificationEventType) { t.Events = append(t.Events, events...) }
[ "func", "(", "t", "*", "NotificationConfig", ")", "AddEvents", "(", "events", "...", "NotificationEventType", ")", "{", "t", ".", "Events", "=", "append", "(", "t", ".", "Events", ",", "events", "...", ")", "\n", "}" ]
// AddEvents adds one event to the current notification config
[ "AddEvents", "adds", "one", "event", "to", "the", "current", "notification", "config" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L104-L106
148,545
minio/minio-go
bucket-notification.go
AddFilterSuffix
func (t *NotificationConfig) AddFilterSuffix(suffix string) { if t.Filter == nil { t.Filter = &Filter{} } newFilterRule := FilterRule{Name: "suffix", Value: suffix} // Replace any suffix rule if existing and add to the list otherwise for index := range t.Filter.S3Key.FilterRules { if t.Filter.S3Key.FilterRules[index].Name == "suffix" { t.Filter.S3Key.FilterRules[index] = newFilterRule return } } t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule) }
go
func (t *NotificationConfig) AddFilterSuffix(suffix string) { if t.Filter == nil { t.Filter = &Filter{} } newFilterRule := FilterRule{Name: "suffix", Value: suffix} // Replace any suffix rule if existing and add to the list otherwise for index := range t.Filter.S3Key.FilterRules { if t.Filter.S3Key.FilterRules[index].Name == "suffix" { t.Filter.S3Key.FilterRules[index] = newFilterRule return } } t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule) }
[ "func", "(", "t", "*", "NotificationConfig", ")", "AddFilterSuffix", "(", "suffix", "string", ")", "{", "if", "t", ".", "Filter", "==", "nil", "{", "t", ".", "Filter", "=", "&", "Filter", "{", "}", "\n", "}", "\n", "newFilterRule", ":=", "FilterRule", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "suffix", "}", "\n", "// Replace any suffix rule if existing and add to the list otherwise", "for", "index", ":=", "range", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "{", "if", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "[", "index", "]", ".", "Name", "==", "\"", "\"", "{", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "[", "index", "]", "=", "newFilterRule", "\n", "return", "\n", "}", "\n", "}", "\n", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "=", "append", "(", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", ",", "newFilterRule", ")", "\n", "}" ]
// AddFilterSuffix sets the suffix configuration to the current notification config
[ "AddFilterSuffix", "sets", "the", "suffix", "configuration", "to", "the", "current", "notification", "config" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L109-L122
148,546
minio/minio-go
bucket-notification.go
AddFilterPrefix
func (t *NotificationConfig) AddFilterPrefix(prefix string) { if t.Filter == nil { t.Filter = &Filter{} } newFilterRule := FilterRule{Name: "prefix", Value: prefix} // Replace any prefix rule if existing and add to the list otherwise for index := range t.Filter.S3Key.FilterRules { if t.Filter.S3Key.FilterRules[index].Name == "prefix" { t.Filter.S3Key.FilterRules[index] = newFilterRule return } } t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule) }
go
func (t *NotificationConfig) AddFilterPrefix(prefix string) { if t.Filter == nil { t.Filter = &Filter{} } newFilterRule := FilterRule{Name: "prefix", Value: prefix} // Replace any prefix rule if existing and add to the list otherwise for index := range t.Filter.S3Key.FilterRules { if t.Filter.S3Key.FilterRules[index].Name == "prefix" { t.Filter.S3Key.FilterRules[index] = newFilterRule return } } t.Filter.S3Key.FilterRules = append(t.Filter.S3Key.FilterRules, newFilterRule) }
[ "func", "(", "t", "*", "NotificationConfig", ")", "AddFilterPrefix", "(", "prefix", "string", ")", "{", "if", "t", ".", "Filter", "==", "nil", "{", "t", ".", "Filter", "=", "&", "Filter", "{", "}", "\n", "}", "\n", "newFilterRule", ":=", "FilterRule", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "prefix", "}", "\n", "// Replace any prefix rule if existing and add to the list otherwise", "for", "index", ":=", "range", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "{", "if", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "[", "index", "]", ".", "Name", "==", "\"", "\"", "{", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "[", "index", "]", "=", "newFilterRule", "\n", "return", "\n", "}", "\n", "}", "\n", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", "=", "append", "(", "t", ".", "Filter", ".", "S3Key", ".", "FilterRules", ",", "newFilterRule", ")", "\n", "}" ]
// AddFilterPrefix sets the prefix configuration to the current notification config
[ "AddFilterPrefix", "sets", "the", "prefix", "configuration", "to", "the", "current", "notification", "config" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L125-L138
148,547
minio/minio-go
bucket-notification.go
AddTopic
func (b *BucketNotification) AddTopic(topicConfig NotificationConfig) bool { newTopicConfig := TopicConfig{NotificationConfig: topicConfig, Topic: topicConfig.Arn.String()} for _, n := range b.TopicConfigs { // If new config matches existing one if n.Topic == newTopicConfig.Arn.String() && newTopicConfig.Filter == n.Filter { existingConfig := set.NewStringSet() for _, v := range n.Events { existingConfig.Add(string(v)) } newConfig := set.NewStringSet() for _, v := range topicConfig.Events { newConfig.Add(string(v)) } if !newConfig.Intersection(existingConfig).IsEmpty() { return false } } } b.TopicConfigs = append(b.TopicConfigs, newTopicConfig) return true }
go
func (b *BucketNotification) AddTopic(topicConfig NotificationConfig) bool { newTopicConfig := TopicConfig{NotificationConfig: topicConfig, Topic: topicConfig.Arn.String()} for _, n := range b.TopicConfigs { // If new config matches existing one if n.Topic == newTopicConfig.Arn.String() && newTopicConfig.Filter == n.Filter { existingConfig := set.NewStringSet() for _, v := range n.Events { existingConfig.Add(string(v)) } newConfig := set.NewStringSet() for _, v := range topicConfig.Events { newConfig.Add(string(v)) } if !newConfig.Intersection(existingConfig).IsEmpty() { return false } } } b.TopicConfigs = append(b.TopicConfigs, newTopicConfig) return true }
[ "func", "(", "b", "*", "BucketNotification", ")", "AddTopic", "(", "topicConfig", "NotificationConfig", ")", "bool", "{", "newTopicConfig", ":=", "TopicConfig", "{", "NotificationConfig", ":", "topicConfig", ",", "Topic", ":", "topicConfig", ".", "Arn", ".", "String", "(", ")", "}", "\n", "for", "_", ",", "n", ":=", "range", "b", ".", "TopicConfigs", "{", "// If new config matches existing one", "if", "n", ".", "Topic", "==", "newTopicConfig", ".", "Arn", ".", "String", "(", ")", "&&", "newTopicConfig", ".", "Filter", "==", "n", ".", "Filter", "{", "existingConfig", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "n", ".", "Events", "{", "existingConfig", ".", "Add", "(", "string", "(", "v", ")", ")", "\n", "}", "\n\n", "newConfig", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "topicConfig", ".", "Events", "{", "newConfig", ".", "Add", "(", "string", "(", "v", ")", ")", "\n", "}", "\n\n", "if", "!", "newConfig", ".", "Intersection", "(", "existingConfig", ")", ".", "IsEmpty", "(", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "b", ".", "TopicConfigs", "=", "append", "(", "b", ".", "TopicConfigs", ",", "newTopicConfig", ")", "\n", "return", "true", "\n", "}" ]
// AddTopic adds a given topic config to the general bucket notification config
[ "AddTopic", "adds", "a", "given", "topic", "config", "to", "the", "general", "bucket", "notification", "config" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L167-L190
148,548
minio/minio-go
bucket-notification.go
AddQueue
func (b *BucketNotification) AddQueue(queueConfig NotificationConfig) bool { newQueueConfig := QueueConfig{NotificationConfig: queueConfig, Queue: queueConfig.Arn.String()} for _, n := range b.QueueConfigs { if n.Queue == newQueueConfig.Arn.String() && newQueueConfig.Filter == n.Filter { existingConfig := set.NewStringSet() for _, v := range n.Events { existingConfig.Add(string(v)) } newConfig := set.NewStringSet() for _, v := range queueConfig.Events { newConfig.Add(string(v)) } if !newConfig.Intersection(existingConfig).IsEmpty() { return false } } } b.QueueConfigs = append(b.QueueConfigs, newQueueConfig) return true }
go
func (b *BucketNotification) AddQueue(queueConfig NotificationConfig) bool { newQueueConfig := QueueConfig{NotificationConfig: queueConfig, Queue: queueConfig.Arn.String()} for _, n := range b.QueueConfigs { if n.Queue == newQueueConfig.Arn.String() && newQueueConfig.Filter == n.Filter { existingConfig := set.NewStringSet() for _, v := range n.Events { existingConfig.Add(string(v)) } newConfig := set.NewStringSet() for _, v := range queueConfig.Events { newConfig.Add(string(v)) } if !newConfig.Intersection(existingConfig).IsEmpty() { return false } } } b.QueueConfigs = append(b.QueueConfigs, newQueueConfig) return true }
[ "func", "(", "b", "*", "BucketNotification", ")", "AddQueue", "(", "queueConfig", "NotificationConfig", ")", "bool", "{", "newQueueConfig", ":=", "QueueConfig", "{", "NotificationConfig", ":", "queueConfig", ",", "Queue", ":", "queueConfig", ".", "Arn", ".", "String", "(", ")", "}", "\n", "for", "_", ",", "n", ":=", "range", "b", ".", "QueueConfigs", "{", "if", "n", ".", "Queue", "==", "newQueueConfig", ".", "Arn", ".", "String", "(", ")", "&&", "newQueueConfig", ".", "Filter", "==", "n", ".", "Filter", "{", "existingConfig", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "n", ".", "Events", "{", "existingConfig", ".", "Add", "(", "string", "(", "v", ")", ")", "\n", "}", "\n\n", "newConfig", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "queueConfig", ".", "Events", "{", "newConfig", ".", "Add", "(", "string", "(", "v", ")", ")", "\n", "}", "\n\n", "if", "!", "newConfig", ".", "Intersection", "(", "existingConfig", ")", ".", "IsEmpty", "(", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "b", ".", "QueueConfigs", "=", "append", "(", "b", ".", "QueueConfigs", ",", "newQueueConfig", ")", "\n", "return", "true", "\n", "}" ]
// AddQueue adds a given queue config to the general bucket notification config
[ "AddQueue", "adds", "a", "given", "queue", "config", "to", "the", "general", "bucket", "notification", "config" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L193-L215
148,549
minio/minio-go
bucket-notification.go
AddLambda
func (b *BucketNotification) AddLambda(lambdaConfig NotificationConfig) bool { newLambdaConfig := LambdaConfig{NotificationConfig: lambdaConfig, Lambda: lambdaConfig.Arn.String()} for _, n := range b.LambdaConfigs { if n.Lambda == newLambdaConfig.Arn.String() && newLambdaConfig.Filter == n.Filter { existingConfig := set.NewStringSet() for _, v := range n.Events { existingConfig.Add(string(v)) } newConfig := set.NewStringSet() for _, v := range lambdaConfig.Events { newConfig.Add(string(v)) } if !newConfig.Intersection(existingConfig).IsEmpty() { return false } } } b.LambdaConfigs = append(b.LambdaConfigs, newLambdaConfig) return true }
go
func (b *BucketNotification) AddLambda(lambdaConfig NotificationConfig) bool { newLambdaConfig := LambdaConfig{NotificationConfig: lambdaConfig, Lambda: lambdaConfig.Arn.String()} for _, n := range b.LambdaConfigs { if n.Lambda == newLambdaConfig.Arn.String() && newLambdaConfig.Filter == n.Filter { existingConfig := set.NewStringSet() for _, v := range n.Events { existingConfig.Add(string(v)) } newConfig := set.NewStringSet() for _, v := range lambdaConfig.Events { newConfig.Add(string(v)) } if !newConfig.Intersection(existingConfig).IsEmpty() { return false } } } b.LambdaConfigs = append(b.LambdaConfigs, newLambdaConfig) return true }
[ "func", "(", "b", "*", "BucketNotification", ")", "AddLambda", "(", "lambdaConfig", "NotificationConfig", ")", "bool", "{", "newLambdaConfig", ":=", "LambdaConfig", "{", "NotificationConfig", ":", "lambdaConfig", ",", "Lambda", ":", "lambdaConfig", ".", "Arn", ".", "String", "(", ")", "}", "\n", "for", "_", ",", "n", ":=", "range", "b", ".", "LambdaConfigs", "{", "if", "n", ".", "Lambda", "==", "newLambdaConfig", ".", "Arn", ".", "String", "(", ")", "&&", "newLambdaConfig", ".", "Filter", "==", "n", ".", "Filter", "{", "existingConfig", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "n", ".", "Events", "{", "existingConfig", ".", "Add", "(", "string", "(", "v", ")", ")", "\n", "}", "\n\n", "newConfig", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "lambdaConfig", ".", "Events", "{", "newConfig", ".", "Add", "(", "string", "(", "v", ")", ")", "\n", "}", "\n\n", "if", "!", "newConfig", ".", "Intersection", "(", "existingConfig", ")", ".", "IsEmpty", "(", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "b", ".", "LambdaConfigs", "=", "append", "(", "b", ".", "LambdaConfigs", ",", "newLambdaConfig", ")", "\n", "return", "true", "\n", "}" ]
// AddLambda adds a given lambda config to the general bucket notification config
[ "AddLambda", "adds", "a", "given", "lambda", "config", "to", "the", "general", "bucket", "notification", "config" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L218-L240
148,550
minio/minio-go
bucket-notification.go
RemoveTopicByArn
func (b *BucketNotification) RemoveTopicByArn(arn Arn) { var topics []TopicConfig for _, topic := range b.TopicConfigs { if topic.Topic != arn.String() { topics = append(topics, topic) } } b.TopicConfigs = topics }
go
func (b *BucketNotification) RemoveTopicByArn(arn Arn) { var topics []TopicConfig for _, topic := range b.TopicConfigs { if topic.Topic != arn.String() { topics = append(topics, topic) } } b.TopicConfigs = topics }
[ "func", "(", "b", "*", "BucketNotification", ")", "RemoveTopicByArn", "(", "arn", "Arn", ")", "{", "var", "topics", "[", "]", "TopicConfig", "\n", "for", "_", ",", "topic", ":=", "range", "b", ".", "TopicConfigs", "{", "if", "topic", ".", "Topic", "!=", "arn", ".", "String", "(", ")", "{", "topics", "=", "append", "(", "topics", ",", "topic", ")", "\n", "}", "\n", "}", "\n", "b", ".", "TopicConfigs", "=", "topics", "\n", "}" ]
// RemoveTopicByArn removes all topic configurations that match the exact specified ARN
[ "RemoveTopicByArn", "removes", "all", "topic", "configurations", "that", "match", "the", "exact", "specified", "ARN" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L243-L251
148,551
minio/minio-go
bucket-notification.go
RemoveQueueByArn
func (b *BucketNotification) RemoveQueueByArn(arn Arn) { var queues []QueueConfig for _, queue := range b.QueueConfigs { if queue.Queue != arn.String() { queues = append(queues, queue) } } b.QueueConfigs = queues }
go
func (b *BucketNotification) RemoveQueueByArn(arn Arn) { var queues []QueueConfig for _, queue := range b.QueueConfigs { if queue.Queue != arn.String() { queues = append(queues, queue) } } b.QueueConfigs = queues }
[ "func", "(", "b", "*", "BucketNotification", ")", "RemoveQueueByArn", "(", "arn", "Arn", ")", "{", "var", "queues", "[", "]", "QueueConfig", "\n", "for", "_", ",", "queue", ":=", "range", "b", ".", "QueueConfigs", "{", "if", "queue", ".", "Queue", "!=", "arn", ".", "String", "(", ")", "{", "queues", "=", "append", "(", "queues", ",", "queue", ")", "\n", "}", "\n", "}", "\n", "b", ".", "QueueConfigs", "=", "queues", "\n", "}" ]
// RemoveQueueByArn removes all queue configurations that match the exact specified ARN
[ "RemoveQueueByArn", "removes", "all", "queue", "configurations", "that", "match", "the", "exact", "specified", "ARN" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L254-L262
148,552
minio/minio-go
bucket-notification.go
RemoveLambdaByArn
func (b *BucketNotification) RemoveLambdaByArn(arn Arn) { var lambdas []LambdaConfig for _, lambda := range b.LambdaConfigs { if lambda.Lambda != arn.String() { lambdas = append(lambdas, lambda) } } b.LambdaConfigs = lambdas }
go
func (b *BucketNotification) RemoveLambdaByArn(arn Arn) { var lambdas []LambdaConfig for _, lambda := range b.LambdaConfigs { if lambda.Lambda != arn.String() { lambdas = append(lambdas, lambda) } } b.LambdaConfigs = lambdas }
[ "func", "(", "b", "*", "BucketNotification", ")", "RemoveLambdaByArn", "(", "arn", "Arn", ")", "{", "var", "lambdas", "[", "]", "LambdaConfig", "\n", "for", "_", ",", "lambda", ":=", "range", "b", ".", "LambdaConfigs", "{", "if", "lambda", ".", "Lambda", "!=", "arn", ".", "String", "(", ")", "{", "lambdas", "=", "append", "(", "lambdas", ",", "lambda", ")", "\n", "}", "\n", "}", "\n", "b", ".", "LambdaConfigs", "=", "lambdas", "\n", "}" ]
// RemoveLambdaByArn removes all lambda configurations that match the exact specified ARN
[ "RemoveLambdaByArn", "removes", "all", "lambda", "configurations", "that", "match", "the", "exact", "specified", "ARN" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-notification.go#L265-L273
148,553
minio/minio-go
retry.go
newRetryTimer
func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int { attemptCh := make(chan int) // computes the exponential backoff duration according to // https://www.awsarchitectureblog.com/2015/03/backoff.html exponentialBackoffWait := func(attempt int) time.Duration { // normalize jitter to the range [0, 1.0] if jitter < NoJitter { jitter = NoJitter } if jitter > MaxJitter { jitter = MaxJitter } //sleep = random_between(0, min(cap, base * 2 ** attempt)) sleep := unit * time.Duration(1<<uint(attempt)) if sleep > cap { sleep = cap } if jitter != NoJitter { sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter) } return sleep } go func() { defer close(attemptCh) for i := 0; i < maxRetry; i++ { select { // Attempts start from 1. case attemptCh <- i + 1: case <-doneCh: // Stop the routine. return } time.Sleep(exponentialBackoffWait(i)) } }() return attemptCh }
go
func (c Client) newRetryTimer(maxRetry int, unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int { attemptCh := make(chan int) // computes the exponential backoff duration according to // https://www.awsarchitectureblog.com/2015/03/backoff.html exponentialBackoffWait := func(attempt int) time.Duration { // normalize jitter to the range [0, 1.0] if jitter < NoJitter { jitter = NoJitter } if jitter > MaxJitter { jitter = MaxJitter } //sleep = random_between(0, min(cap, base * 2 ** attempt)) sleep := unit * time.Duration(1<<uint(attempt)) if sleep > cap { sleep = cap } if jitter != NoJitter { sleep -= time.Duration(c.random.Float64() * float64(sleep) * jitter) } return sleep } go func() { defer close(attemptCh) for i := 0; i < maxRetry; i++ { select { // Attempts start from 1. case attemptCh <- i + 1: case <-doneCh: // Stop the routine. return } time.Sleep(exponentialBackoffWait(i)) } }() return attemptCh }
[ "func", "(", "c", "Client", ")", "newRetryTimer", "(", "maxRetry", "int", ",", "unit", "time", ".", "Duration", ",", "cap", "time", ".", "Duration", ",", "jitter", "float64", ",", "doneCh", "chan", "struct", "{", "}", ")", "<-", "chan", "int", "{", "attemptCh", ":=", "make", "(", "chan", "int", ")", "\n\n", "// computes the exponential backoff duration according to", "// https://www.awsarchitectureblog.com/2015/03/backoff.html", "exponentialBackoffWait", ":=", "func", "(", "attempt", "int", ")", "time", ".", "Duration", "{", "// normalize jitter to the range [0, 1.0]", "if", "jitter", "<", "NoJitter", "{", "jitter", "=", "NoJitter", "\n", "}", "\n", "if", "jitter", ">", "MaxJitter", "{", "jitter", "=", "MaxJitter", "\n", "}", "\n\n", "//sleep = random_between(0, min(cap, base * 2 ** attempt))", "sleep", ":=", "unit", "*", "time", ".", "Duration", "(", "1", "<<", "uint", "(", "attempt", ")", ")", "\n", "if", "sleep", ">", "cap", "{", "sleep", "=", "cap", "\n", "}", "\n", "if", "jitter", "!=", "NoJitter", "{", "sleep", "-=", "time", ".", "Duration", "(", "c", ".", "random", ".", "Float64", "(", ")", "*", "float64", "(", "sleep", ")", "*", "jitter", ")", "\n", "}", "\n", "return", "sleep", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "attemptCh", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "maxRetry", ";", "i", "++", "{", "select", "{", "// Attempts start from 1.", "case", "attemptCh", "<-", "i", "+", "1", ":", "case", "<-", "doneCh", ":", "// Stop the routine.", "return", "\n", "}", "\n", "time", ".", "Sleep", "(", "exponentialBackoffWait", "(", "i", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "attemptCh", "\n", "}" ]
// newRetryTimer creates a timer with exponentially increasing // delays until the maximum retry attempts are reached.
[ "newRetryTimer", "creates", "a", "timer", "with", "exponentially", "increasing", "delays", "until", "the", "maximum", "retry", "attempts", "are", "reached", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/retry.go#L47-L86
148,554
minio/minio-go
retry.go
isS3CodeRetryable
func isS3CodeRetryable(s3Code string) (ok bool) { _, ok = retryableS3Codes[s3Code] return ok }
go
func isS3CodeRetryable(s3Code string) (ok bool) { _, ok = retryableS3Codes[s3Code] return ok }
[ "func", "isS3CodeRetryable", "(", "s3Code", "string", ")", "(", "ok", "bool", ")", "{", "_", ",", "ok", "=", "retryableS3Codes", "[", "s3Code", "]", "\n", "return", "ok", "\n", "}" ]
// isS3CodeRetryable - is s3 error code retryable.
[ "isS3CodeRetryable", "-", "is", "s3", "error", "code", "retryable", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/retry.go#L135-L138
148,555
minio/minio-go
retry.go
isHTTPStatusRetryable
func isHTTPStatusRetryable(httpStatusCode int) (ok bool) { _, ok = retryableHTTPStatusCodes[httpStatusCode] return ok }
go
func isHTTPStatusRetryable(httpStatusCode int) (ok bool) { _, ok = retryableHTTPStatusCodes[httpStatusCode] return ok }
[ "func", "isHTTPStatusRetryable", "(", "httpStatusCode", "int", ")", "(", "ok", "bool", ")", "{", "_", ",", "ok", "=", "retryableHTTPStatusCodes", "[", "httpStatusCode", "]", "\n", "return", "ok", "\n", "}" ]
// isHTTPStatusRetryable - is HTTP error code retryable.
[ "isHTTPStatusRetryable", "-", "is", "HTTP", "error", "code", "retryable", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/retry.go#L150-L153
148,556
minio/minio-go
api-put-object-multipart.go
initiateMultipartUpload
func (c Client) initiateMultipartUpload(ctx context.Context, bucketName, objectName string, opts PutObjectOptions) (initiateMultipartUploadResult, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return initiateMultipartUploadResult{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return initiateMultipartUploadResult{}, err } // Initialize url queries. urlValues := make(url.Values) urlValues.Set("uploads", "") // Set ContentType header. customHeader := opts.Header() reqMetadata := requestMetadata{ bucketName: bucketName, objectName: objectName, queryValues: urlValues, customHeader: customHeader, } // Execute POST on an objectName to initiate multipart upload. resp, err := c.executeMethod(ctx, "POST", reqMetadata) defer closeResponse(resp) if err != nil { return initiateMultipartUploadResult{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { return initiateMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Decode xml for new multipart upload. initiateMultipartUploadResult := initiateMultipartUploadResult{} err = xmlDecoder(resp.Body, &initiateMultipartUploadResult) if err != nil { return initiateMultipartUploadResult, err } return initiateMultipartUploadResult, nil }
go
func (c Client) initiateMultipartUpload(ctx context.Context, bucketName, objectName string, opts PutObjectOptions) (initiateMultipartUploadResult, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return initiateMultipartUploadResult{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return initiateMultipartUploadResult{}, err } // Initialize url queries. urlValues := make(url.Values) urlValues.Set("uploads", "") // Set ContentType header. customHeader := opts.Header() reqMetadata := requestMetadata{ bucketName: bucketName, objectName: objectName, queryValues: urlValues, customHeader: customHeader, } // Execute POST on an objectName to initiate multipart upload. resp, err := c.executeMethod(ctx, "POST", reqMetadata) defer closeResponse(resp) if err != nil { return initiateMultipartUploadResult{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { return initiateMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Decode xml for new multipart upload. initiateMultipartUploadResult := initiateMultipartUploadResult{} err = xmlDecoder(resp.Body, &initiateMultipartUploadResult) if err != nil { return initiateMultipartUploadResult, err } return initiateMultipartUploadResult, nil }
[ "func", "(", "c", "Client", ")", "initiateMultipartUpload", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", "string", ",", "opts", "PutObjectOptions", ")", "(", "initiateMultipartUploadResult", ",", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "initiateMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "initiateMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n\n", "// Initialize url queries.", "urlValues", ":=", "make", "(", "url", ".", "Values", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Set ContentType header.", "customHeader", ":=", "opts", ".", "Header", "(", ")", "\n\n", "reqMetadata", ":=", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "objectName", ":", "objectName", ",", "queryValues", ":", "urlValues", ",", "customHeader", ":", "customHeader", ",", "}", "\n\n", "// Execute POST on an objectName to initiate multipart upload.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "ctx", ",", "\"", "\"", ",", "reqMetadata", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "initiateMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "initiateMultipartUploadResult", "{", "}", ",", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "}", "\n", "// Decode xml for new multipart upload.", "initiateMultipartUploadResult", ":=", "initiateMultipartUploadResult", "{", "}", "\n", "err", "=", "xmlDecoder", "(", "resp", ".", "Body", ",", "&", "initiateMultipartUploadResult", ")", "\n", "if", "err", "!=", "nil", "{", "return", "initiateMultipartUploadResult", ",", "err", "\n", "}", "\n", "return", "initiateMultipartUploadResult", ",", "nil", "\n", "}" ]
// initiateMultipartUpload - Initiates a multipart upload and returns an upload ID.
[ "initiateMultipartUpload", "-", "Initiates", "a", "multipart", "upload", "and", "returns", "an", "upload", "ID", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-multipart.go#L187-L228
148,557
minio/minio-go
api-put-object-multipart.go
uploadPart
func (c Client) uploadPart(ctx context.Context, bucketName, objectName, uploadID string, reader io.Reader, partNumber int, md5Base64, sha256Hex string, size int64, sse encrypt.ServerSide) (ObjectPart, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return ObjectPart{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return ObjectPart{}, err } if size > maxPartSize { return ObjectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName) } if size <= -1 { return ObjectPart{}, ErrEntityTooSmall(size, bucketName, objectName) } if partNumber <= 0 { return ObjectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.") } if uploadID == "" { return ObjectPart{}, ErrInvalidArgument("UploadID cannot be empty.") } // Get resources properly escaped and lined up before using them in http request. urlValues := make(url.Values) // Set part number. urlValues.Set("partNumber", strconv.Itoa(partNumber)) // Set upload id. urlValues.Set("uploadId", uploadID) // Set encryption headers, if any. customHeader := make(http.Header) // https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html // Server-side encryption is supported by the S3 Multipart Upload actions. // Unless you are using a customer-provided encryption key, you don't need // to specify the encryption parameters in each UploadPart request. if sse != nil && sse.Type() == encrypt.SSEC { sse.Marshal(customHeader) } reqMetadata := requestMetadata{ bucketName: bucketName, objectName: objectName, queryValues: urlValues, customHeader: customHeader, contentBody: reader, contentLength: size, contentMD5Base64: md5Base64, contentSHA256Hex: sha256Hex, } // Execute PUT on each part. resp, err := c.executeMethod(ctx, "PUT", reqMetadata) defer closeResponse(resp) if err != nil { return ObjectPart{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { return ObjectPart{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Once successfully uploaded, return completed part. objPart := ObjectPart{} objPart.Size = size objPart.PartNumber = partNumber // Trim off the odd double quotes from ETag in the beginning and end. objPart.ETag = strings.TrimPrefix(resp.Header.Get("ETag"), "\"") objPart.ETag = strings.TrimSuffix(objPart.ETag, "\"") return objPart, nil }
go
func (c Client) uploadPart(ctx context.Context, bucketName, objectName, uploadID string, reader io.Reader, partNumber int, md5Base64, sha256Hex string, size int64, sse encrypt.ServerSide) (ObjectPart, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return ObjectPart{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return ObjectPart{}, err } if size > maxPartSize { return ObjectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName) } if size <= -1 { return ObjectPart{}, ErrEntityTooSmall(size, bucketName, objectName) } if partNumber <= 0 { return ObjectPart{}, ErrInvalidArgument("Part number cannot be negative or equal to zero.") } if uploadID == "" { return ObjectPart{}, ErrInvalidArgument("UploadID cannot be empty.") } // Get resources properly escaped and lined up before using them in http request. urlValues := make(url.Values) // Set part number. urlValues.Set("partNumber", strconv.Itoa(partNumber)) // Set upload id. urlValues.Set("uploadId", uploadID) // Set encryption headers, if any. customHeader := make(http.Header) // https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html // Server-side encryption is supported by the S3 Multipart Upload actions. // Unless you are using a customer-provided encryption key, you don't need // to specify the encryption parameters in each UploadPart request. if sse != nil && sse.Type() == encrypt.SSEC { sse.Marshal(customHeader) } reqMetadata := requestMetadata{ bucketName: bucketName, objectName: objectName, queryValues: urlValues, customHeader: customHeader, contentBody: reader, contentLength: size, contentMD5Base64: md5Base64, contentSHA256Hex: sha256Hex, } // Execute PUT on each part. resp, err := c.executeMethod(ctx, "PUT", reqMetadata) defer closeResponse(resp) if err != nil { return ObjectPart{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { return ObjectPart{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Once successfully uploaded, return completed part. objPart := ObjectPart{} objPart.Size = size objPart.PartNumber = partNumber // Trim off the odd double quotes from ETag in the beginning and end. objPart.ETag = strings.TrimPrefix(resp.Header.Get("ETag"), "\"") objPart.ETag = strings.TrimSuffix(objPart.ETag, "\"") return objPart, nil }
[ "func", "(", "c", "Client", ")", "uploadPart", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", ",", "uploadID", "string", ",", "reader", "io", ".", "Reader", ",", "partNumber", "int", ",", "md5Base64", ",", "sha256Hex", "string", ",", "size", "int64", ",", "sse", "encrypt", ".", "ServerSide", ")", "(", "ObjectPart", ",", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "ObjectPart", "{", "}", ",", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "ObjectPart", "{", "}", ",", "err", "\n", "}", "\n", "if", "size", ">", "maxPartSize", "{", "return", "ObjectPart", "{", "}", ",", "ErrEntityTooLarge", "(", "size", ",", "maxPartSize", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "if", "size", "<=", "-", "1", "{", "return", "ObjectPart", "{", "}", ",", "ErrEntityTooSmall", "(", "size", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "if", "partNumber", "<=", "0", "{", "return", "ObjectPart", "{", "}", ",", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "uploadID", "==", "\"", "\"", "{", "return", "ObjectPart", "{", "}", ",", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Get resources properly escaped and lined up before using them in http request.", "urlValues", ":=", "make", "(", "url", ".", "Values", ")", "\n", "// Set part number.", "urlValues", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "partNumber", ")", ")", "\n", "// Set upload id.", "urlValues", ".", "Set", "(", "\"", "\"", ",", "uploadID", ")", "\n\n", "// Set encryption headers, if any.", "customHeader", ":=", "make", "(", "http", ".", "Header", ")", "\n", "// https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html", "// Server-side encryption is supported by the S3 Multipart Upload actions.", "// Unless you are using a customer-provided encryption key, you don't need", "// to specify the encryption parameters in each UploadPart request.", "if", "sse", "!=", "nil", "&&", "sse", ".", "Type", "(", ")", "==", "encrypt", ".", "SSEC", "{", "sse", ".", "Marshal", "(", "customHeader", ")", "\n", "}", "\n\n", "reqMetadata", ":=", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "objectName", ":", "objectName", ",", "queryValues", ":", "urlValues", ",", "customHeader", ":", "customHeader", ",", "contentBody", ":", "reader", ",", "contentLength", ":", "size", ",", "contentMD5Base64", ":", "md5Base64", ",", "contentSHA256Hex", ":", "sha256Hex", ",", "}", "\n\n", "// Execute PUT on each part.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "ctx", ",", "\"", "\"", ",", "reqMetadata", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ObjectPart", "{", "}", ",", "err", "\n", "}", "\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "ObjectPart", "{", "}", ",", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "}", "\n", "// Once successfully uploaded, return completed part.", "objPart", ":=", "ObjectPart", "{", "}", "\n", "objPart", ".", "Size", "=", "size", "\n", "objPart", ".", "PartNumber", "=", "partNumber", "\n", "// Trim off the odd double quotes from ETag in the beginning and end.", "objPart", ".", "ETag", "=", "strings", ".", "TrimPrefix", "(", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "\"", "\\\"", "\"", ")", "\n", "objPart", ".", "ETag", "=", "strings", ".", "TrimSuffix", "(", "objPart", ".", "ETag", ",", "\"", "\\\"", "\"", ")", "\n", "return", "objPart", ",", "nil", "\n", "}" ]
// uploadPart - Uploads a part in a multipart upload.
[ "uploadPart", "-", "Uploads", "a", "part", "in", "a", "multipart", "upload", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-multipart.go#L231-L300
148,558
minio/minio-go
api-put-object-multipart.go
completeMultipartUpload
func (c Client) completeMultipartUpload(ctx context.Context, bucketName, objectName, uploadID string, complete completeMultipartUpload) (completeMultipartUploadResult, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return completeMultipartUploadResult{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return completeMultipartUploadResult{}, err } // Initialize url queries. urlValues := make(url.Values) urlValues.Set("uploadId", uploadID) // Marshal complete multipart body. completeMultipartUploadBytes, err := xml.Marshal(complete) if err != nil { return completeMultipartUploadResult{}, err } // Instantiate all the complete multipart buffer. completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes) reqMetadata := requestMetadata{ bucketName: bucketName, objectName: objectName, queryValues: urlValues, contentBody: completeMultipartUploadBuffer, contentLength: int64(len(completeMultipartUploadBytes)), contentSHA256Hex: sum256Hex(completeMultipartUploadBytes), } // Execute POST to complete multipart upload for an objectName. resp, err := c.executeMethod(ctx, "POST", reqMetadata) defer closeResponse(resp) if err != nil { return completeMultipartUploadResult{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { return completeMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Read resp.Body into a []bytes to parse for Error response inside the body var b []byte b, err = ioutil.ReadAll(resp.Body) if err != nil { return completeMultipartUploadResult{}, err } // Decode completed multipart upload response on success. completeMultipartUploadResult := completeMultipartUploadResult{} err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadResult) if err != nil { // xml parsing failure due to presence an ill-formed xml fragment return completeMultipartUploadResult, err } else if completeMultipartUploadResult.Bucket == "" { // xml's Decode method ignores well-formed xml that don't apply to the type of value supplied. // In this case, it would leave completeMultipartUploadResult with the corresponding zero-values // of the members. // Decode completed multipart upload response on failure completeMultipartUploadErr := ErrorResponse{} err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadErr) if err != nil { // xml parsing failure due to presence an ill-formed xml fragment return completeMultipartUploadResult, err } return completeMultipartUploadResult, completeMultipartUploadErr } return completeMultipartUploadResult, nil }
go
func (c Client) completeMultipartUpload(ctx context.Context, bucketName, objectName, uploadID string, complete completeMultipartUpload) (completeMultipartUploadResult, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return completeMultipartUploadResult{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return completeMultipartUploadResult{}, err } // Initialize url queries. urlValues := make(url.Values) urlValues.Set("uploadId", uploadID) // Marshal complete multipart body. completeMultipartUploadBytes, err := xml.Marshal(complete) if err != nil { return completeMultipartUploadResult{}, err } // Instantiate all the complete multipart buffer. completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes) reqMetadata := requestMetadata{ bucketName: bucketName, objectName: objectName, queryValues: urlValues, contentBody: completeMultipartUploadBuffer, contentLength: int64(len(completeMultipartUploadBytes)), contentSHA256Hex: sum256Hex(completeMultipartUploadBytes), } // Execute POST to complete multipart upload for an objectName. resp, err := c.executeMethod(ctx, "POST", reqMetadata) defer closeResponse(resp) if err != nil { return completeMultipartUploadResult{}, err } if resp != nil { if resp.StatusCode != http.StatusOK { return completeMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Read resp.Body into a []bytes to parse for Error response inside the body var b []byte b, err = ioutil.ReadAll(resp.Body) if err != nil { return completeMultipartUploadResult{}, err } // Decode completed multipart upload response on success. completeMultipartUploadResult := completeMultipartUploadResult{} err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadResult) if err != nil { // xml parsing failure due to presence an ill-formed xml fragment return completeMultipartUploadResult, err } else if completeMultipartUploadResult.Bucket == "" { // xml's Decode method ignores well-formed xml that don't apply to the type of value supplied. // In this case, it would leave completeMultipartUploadResult with the corresponding zero-values // of the members. // Decode completed multipart upload response on failure completeMultipartUploadErr := ErrorResponse{} err = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadErr) if err != nil { // xml parsing failure due to presence an ill-formed xml fragment return completeMultipartUploadResult, err } return completeMultipartUploadResult, completeMultipartUploadErr } return completeMultipartUploadResult, nil }
[ "func", "(", "c", "Client", ")", "completeMultipartUpload", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", ",", "uploadID", "string", ",", "complete", "completeMultipartUpload", ")", "(", "completeMultipartUploadResult", ",", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "completeMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "completeMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n\n", "// Initialize url queries.", "urlValues", ":=", "make", "(", "url", ".", "Values", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "uploadID", ")", "\n", "// Marshal complete multipart body.", "completeMultipartUploadBytes", ",", "err", ":=", "xml", ".", "Marshal", "(", "complete", ")", "\n", "if", "err", "!=", "nil", "{", "return", "completeMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n\n", "// Instantiate all the complete multipart buffer.", "completeMultipartUploadBuffer", ":=", "bytes", ".", "NewReader", "(", "completeMultipartUploadBytes", ")", "\n", "reqMetadata", ":=", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "objectName", ":", "objectName", ",", "queryValues", ":", "urlValues", ",", "contentBody", ":", "completeMultipartUploadBuffer", ",", "contentLength", ":", "int64", "(", "len", "(", "completeMultipartUploadBytes", ")", ")", ",", "contentSHA256Hex", ":", "sum256Hex", "(", "completeMultipartUploadBytes", ")", ",", "}", "\n\n", "// Execute POST to complete multipart upload for an objectName.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "ctx", ",", "\"", "\"", ",", "reqMetadata", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "completeMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "completeMultipartUploadResult", "{", "}", ",", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "}", "\n\n", "// Read resp.Body into a []bytes to parse for Error response inside the body", "var", "b", "[", "]", "byte", "\n", "b", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "completeMultipartUploadResult", "{", "}", ",", "err", "\n", "}", "\n", "// Decode completed multipart upload response on success.", "completeMultipartUploadResult", ":=", "completeMultipartUploadResult", "{", "}", "\n", "err", "=", "xmlDecoder", "(", "bytes", ".", "NewReader", "(", "b", ")", ",", "&", "completeMultipartUploadResult", ")", "\n", "if", "err", "!=", "nil", "{", "// xml parsing failure due to presence an ill-formed xml fragment", "return", "completeMultipartUploadResult", ",", "err", "\n", "}", "else", "if", "completeMultipartUploadResult", ".", "Bucket", "==", "\"", "\"", "{", "// xml's Decode method ignores well-formed xml that don't apply to the type of value supplied.", "// In this case, it would leave completeMultipartUploadResult with the corresponding zero-values", "// of the members.", "// Decode completed multipart upload response on failure", "completeMultipartUploadErr", ":=", "ErrorResponse", "{", "}", "\n", "err", "=", "xmlDecoder", "(", "bytes", ".", "NewReader", "(", "b", ")", ",", "&", "completeMultipartUploadErr", ")", "\n", "if", "err", "!=", "nil", "{", "// xml parsing failure due to presence an ill-formed xml fragment", "return", "completeMultipartUploadResult", ",", "err", "\n", "}", "\n", "return", "completeMultipartUploadResult", ",", "completeMultipartUploadErr", "\n", "}", "\n", "return", "completeMultipartUploadResult", ",", "nil", "\n", "}" ]
// completeMultipartUpload - Completes a multipart upload by assembling previously uploaded parts.
[ "completeMultipartUpload", "-", "Completes", "a", "multipart", "upload", "by", "assembling", "previously", "uploaded", "parts", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-multipart.go#L303-L372
148,559
minio/minio-go
api-select.go
Header
func (o SelectObjectOptions) Header() http.Header { headers := make(http.Header) if o.ServerSideEncryption != nil && o.ServerSideEncryption.Type() == encrypt.SSEC { o.ServerSideEncryption.Marshal(headers) } return headers }
go
func (o SelectObjectOptions) Header() http.Header { headers := make(http.Header) if o.ServerSideEncryption != nil && o.ServerSideEncryption.Type() == encrypt.SSEC { o.ServerSideEncryption.Marshal(headers) } return headers }
[ "func", "(", "o", "SelectObjectOptions", ")", "Header", "(", ")", "http", ".", "Header", "{", "headers", ":=", "make", "(", "http", ".", "Header", ")", "\n", "if", "o", ".", "ServerSideEncryption", "!=", "nil", "&&", "o", ".", "ServerSideEncryption", ".", "Type", "(", ")", "==", "encrypt", ".", "SSEC", "{", "o", ".", "ServerSideEncryption", ".", "Marshal", "(", "headers", ")", "\n", "}", "\n", "return", "headers", "\n", "}" ]
// Header returns the http.Header representation of the SelectObject options.
[ "Header", "returns", "the", "http", ".", "Header", "representation", "of", "the", "SelectObject", "options", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L146-L152
148,560
minio/minio-go
api-select.go
Close
func (s *SelectResults) Close() error { defer closeResponse(s.resp) return s.pipeReader.Close() }
go
func (s *SelectResults) Close() error { defer closeResponse(s.resp) return s.pipeReader.Close() }
[ "func", "(", "s", "*", "SelectResults", ")", "Close", "(", ")", "error", "{", "defer", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "s", ".", "pipeReader", ".", "Close", "(", ")", "\n", "}" ]
// Close - closes the underlying response body and the stream reader.
[ "Close", "-", "closes", "the", "underlying", "response", "body", "and", "the", "stream", "reader", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L270-L273
148,561
minio/minio-go
api-select.go
Read
func (s *SelectResults) Read(b []byte) (n int, err error) { return s.pipeReader.Read(b) }
go
func (s *SelectResults) Read(b []byte) (n int, err error) { return s.pipeReader.Read(b) }
[ "func", "(", "s", "*", "SelectResults", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "s", ".", "pipeReader", ".", "Read", "(", "b", ")", "\n", "}" ]
// Read - is a reader compatible implementation for SelectObjectContent records.
[ "Read", "-", "is", "a", "reader", "compatible", "implementation", "for", "SelectObjectContent", "records", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L276-L278
148,562
minio/minio-go
api-select.go
start
func (s *SelectResults) start(pipeWriter *io.PipeWriter) { go func() { for { var prelude preludeInfo var headers = make(http.Header) var err error // Create CRC code crc := crc32.New(crc32.IEEETable) crcReader := io.TeeReader(s.resp.Body, crc) // Extract the prelude(12 bytes) into a struct to extract relevant information. prelude, err = processPrelude(crcReader, crc) if err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } // Extract the headers(variable bytes) into a struct to extract relevant information if prelude.headerLen > 0 { if err = extractHeader(io.LimitReader(crcReader, int64(prelude.headerLen)), headers); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } } // Get the actual payload length so that the appropriate amount of // bytes can be read or parsed. payloadLen := prelude.PayloadLen() m := messageType(headers.Get("message-type")) switch m { case errorMsg: pipeWriter.CloseWithError(errors.New(headers.Get("error-code") + ":\"" + headers.Get("error-message") + "\"")) closeResponse(s.resp) return case commonMsg: // Get content-type of the payload. c := contentType(headers.Get("content-type")) // Get event type of the payload. e := eventType(headers.Get("event-type")) // Handle all supported events. switch e { case endEvent: pipeWriter.Close() closeResponse(s.resp) return case recordsEvent: if _, err = io.Copy(pipeWriter, io.LimitReader(crcReader, payloadLen)); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } case progressEvent: switch c { case xmlContent: if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.progress); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } default: pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, progressEvent)) closeResponse(s.resp) return } case statsEvent: switch c { case xmlContent: if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.stats); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } default: pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, statsEvent)) closeResponse(s.resp) return } } } // Ensures that the full message's CRC is correct and // that the message is not corrupted if err := checkCRC(s.resp.Body, crc.Sum32()); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } } }() }
go
func (s *SelectResults) start(pipeWriter *io.PipeWriter) { go func() { for { var prelude preludeInfo var headers = make(http.Header) var err error // Create CRC code crc := crc32.New(crc32.IEEETable) crcReader := io.TeeReader(s.resp.Body, crc) // Extract the prelude(12 bytes) into a struct to extract relevant information. prelude, err = processPrelude(crcReader, crc) if err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } // Extract the headers(variable bytes) into a struct to extract relevant information if prelude.headerLen > 0 { if err = extractHeader(io.LimitReader(crcReader, int64(prelude.headerLen)), headers); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } } // Get the actual payload length so that the appropriate amount of // bytes can be read or parsed. payloadLen := prelude.PayloadLen() m := messageType(headers.Get("message-type")) switch m { case errorMsg: pipeWriter.CloseWithError(errors.New(headers.Get("error-code") + ":\"" + headers.Get("error-message") + "\"")) closeResponse(s.resp) return case commonMsg: // Get content-type of the payload. c := contentType(headers.Get("content-type")) // Get event type of the payload. e := eventType(headers.Get("event-type")) // Handle all supported events. switch e { case endEvent: pipeWriter.Close() closeResponse(s.resp) return case recordsEvent: if _, err = io.Copy(pipeWriter, io.LimitReader(crcReader, payloadLen)); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } case progressEvent: switch c { case xmlContent: if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.progress); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } default: pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, progressEvent)) closeResponse(s.resp) return } case statsEvent: switch c { case xmlContent: if err = xmlDecoder(io.LimitReader(crcReader, payloadLen), s.stats); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } default: pipeWriter.CloseWithError(fmt.Errorf("Unexpected content-type %s sent for event-type %s", c, statsEvent)) closeResponse(s.resp) return } } } // Ensures that the full message's CRC is correct and // that the message is not corrupted if err := checkCRC(s.resp.Body, crc.Sum32()); err != nil { pipeWriter.CloseWithError(err) closeResponse(s.resp) return } } }() }
[ "func", "(", "s", "*", "SelectResults", ")", "start", "(", "pipeWriter", "*", "io", ".", "PipeWriter", ")", "{", "go", "func", "(", ")", "{", "for", "{", "var", "prelude", "preludeInfo", "\n", "var", "headers", "=", "make", "(", "http", ".", "Header", ")", "\n", "var", "err", "error", "\n\n", "// Create CRC code", "crc", ":=", "crc32", ".", "New", "(", "crc32", ".", "IEEETable", ")", "\n", "crcReader", ":=", "io", ".", "TeeReader", "(", "s", ".", "resp", ".", "Body", ",", "crc", ")", "\n\n", "// Extract the prelude(12 bytes) into a struct to extract relevant information.", "prelude", ",", "err", "=", "processPrelude", "(", "crcReader", ",", "crc", ")", "\n", "if", "err", "!=", "nil", "{", "pipeWriter", ".", "CloseWithError", "(", "err", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n\n", "// Extract the headers(variable bytes) into a struct to extract relevant information", "if", "prelude", ".", "headerLen", ">", "0", "{", "if", "err", "=", "extractHeader", "(", "io", ".", "LimitReader", "(", "crcReader", ",", "int64", "(", "prelude", ".", "headerLen", ")", ")", ",", "headers", ")", ";", "err", "!=", "nil", "{", "pipeWriter", ".", "CloseWithError", "(", "err", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// Get the actual payload length so that the appropriate amount of", "// bytes can be read or parsed.", "payloadLen", ":=", "prelude", ".", "PayloadLen", "(", ")", "\n\n", "m", ":=", "messageType", "(", "headers", ".", "Get", "(", "\"", "\"", ")", ")", "\n\n", "switch", "m", "{", "case", "errorMsg", ":", "pipeWriter", ".", "CloseWithError", "(", "errors", ".", "New", "(", "headers", ".", "Get", "(", "\"", "\"", ")", "+", "\"", "\\\"", "\"", "+", "headers", ".", "Get", "(", "\"", "\"", ")", "+", "\"", "\\\"", "\"", ")", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "case", "commonMsg", ":", "// Get content-type of the payload.", "c", ":=", "contentType", "(", "headers", ".", "Get", "(", "\"", "\"", ")", ")", "\n\n", "// Get event type of the payload.", "e", ":=", "eventType", "(", "headers", ".", "Get", "(", "\"", "\"", ")", ")", "\n\n", "// Handle all supported events.", "switch", "e", "{", "case", "endEvent", ":", "pipeWriter", ".", "Close", "(", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "case", "recordsEvent", ":", "if", "_", ",", "err", "=", "io", ".", "Copy", "(", "pipeWriter", ",", "io", ".", "LimitReader", "(", "crcReader", ",", "payloadLen", ")", ")", ";", "err", "!=", "nil", "{", "pipeWriter", ".", "CloseWithError", "(", "err", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n", "case", "progressEvent", ":", "switch", "c", "{", "case", "xmlContent", ":", "if", "err", "=", "xmlDecoder", "(", "io", ".", "LimitReader", "(", "crcReader", ",", "payloadLen", ")", ",", "s", ".", "progress", ")", ";", "err", "!=", "nil", "{", "pipeWriter", ".", "CloseWithError", "(", "err", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n", "default", ":", "pipeWriter", ".", "CloseWithError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ",", "progressEvent", ")", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n", "case", "statsEvent", ":", "switch", "c", "{", "case", "xmlContent", ":", "if", "err", "=", "xmlDecoder", "(", "io", ".", "LimitReader", "(", "crcReader", ",", "payloadLen", ")", ",", "s", ".", "stats", ")", ";", "err", "!=", "nil", "{", "pipeWriter", ".", "CloseWithError", "(", "err", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n", "default", ":", "pipeWriter", ".", "CloseWithError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ",", "statsEvent", ")", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Ensures that the full message's CRC is correct and", "// that the message is not corrupted", "if", "err", ":=", "checkCRC", "(", "s", ".", "resp", ".", "Body", ",", "crc", ".", "Sum32", "(", ")", ")", ";", "err", "!=", "nil", "{", "pipeWriter", ".", "CloseWithError", "(", "err", ")", "\n", "closeResponse", "(", "s", ".", "resp", ")", "\n", "return", "\n", "}", "\n\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// start is the main function that decodes the large byte array into // several events that are sent through the eventstream.
[ "start", "is", "the", "main", "function", "that", "decodes", "the", "large", "byte", "array", "into", "several", "events", "that", "are", "sent", "through", "the", "eventstream", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L292-L389
148,563
minio/minio-go
api-select.go
processPrelude
func processPrelude(prelude io.Reader, crc hash.Hash32) (preludeInfo, error) { var err error var pInfo = preludeInfo{} // reads total length of the message (first 4 bytes) pInfo.totalLen, err = extractUint32(prelude) if err != nil { return pInfo, err } // reads total header length of the message (2nd 4 bytes) pInfo.headerLen, err = extractUint32(prelude) if err != nil { return pInfo, err } // checks that the CRC is correct (3rd 4 bytes) preCRC := crc.Sum32() if err := checkCRC(prelude, preCRC); err != nil { return pInfo, err } return pInfo, nil }
go
func processPrelude(prelude io.Reader, crc hash.Hash32) (preludeInfo, error) { var err error var pInfo = preludeInfo{} // reads total length of the message (first 4 bytes) pInfo.totalLen, err = extractUint32(prelude) if err != nil { return pInfo, err } // reads total header length of the message (2nd 4 bytes) pInfo.headerLen, err = extractUint32(prelude) if err != nil { return pInfo, err } // checks that the CRC is correct (3rd 4 bytes) preCRC := crc.Sum32() if err := checkCRC(prelude, preCRC); err != nil { return pInfo, err } return pInfo, nil }
[ "func", "processPrelude", "(", "prelude", "io", ".", "Reader", ",", "crc", "hash", ".", "Hash32", ")", "(", "preludeInfo", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "pInfo", "=", "preludeInfo", "{", "}", "\n\n", "// reads total length of the message (first 4 bytes)", "pInfo", ".", "totalLen", ",", "err", "=", "extractUint32", "(", "prelude", ")", "\n", "if", "err", "!=", "nil", "{", "return", "pInfo", ",", "err", "\n", "}", "\n\n", "// reads total header length of the message (2nd 4 bytes)", "pInfo", ".", "headerLen", ",", "err", "=", "extractUint32", "(", "prelude", ")", "\n", "if", "err", "!=", "nil", "{", "return", "pInfo", ",", "err", "\n", "}", "\n\n", "// checks that the CRC is correct (3rd 4 bytes)", "preCRC", ":=", "crc", ".", "Sum32", "(", ")", "\n", "if", "err", ":=", "checkCRC", "(", "prelude", ",", "preCRC", ")", ";", "err", "!=", "nil", "{", "return", "pInfo", ",", "err", "\n", "}", "\n\n", "return", "pInfo", ",", "nil", "\n", "}" ]
// processPrelude is the function that reads the 12 bytes of the prelude and // ensures the CRC is correct while also extracting relevant information into // the struct,
[ "processPrelude", "is", "the", "function", "that", "reads", "the", "12", "bytes", "of", "the", "prelude", "and", "ensures", "the", "CRC", "is", "correct", "while", "also", "extracting", "relevant", "information", "into", "the", "struct" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L399-L422
148,564
minio/minio-go
api-select.go
extractHeader
func extractHeader(body io.Reader, myHeaders http.Header) error { for { // extracts the first part of the header, headerTypeName, err := extractHeaderType(body) if err != nil { // Since end of file, we have read all of our headers if err == io.EOF { break } return err } // reads the 7 present in the header and ignores it. extractUint8(body) headerValueName, err := extractHeaderValue(body) if err != nil { return err } myHeaders.Set(headerTypeName, headerValueName) } return nil }
go
func extractHeader(body io.Reader, myHeaders http.Header) error { for { // extracts the first part of the header, headerTypeName, err := extractHeaderType(body) if err != nil { // Since end of file, we have read all of our headers if err == io.EOF { break } return err } // reads the 7 present in the header and ignores it. extractUint8(body) headerValueName, err := extractHeaderValue(body) if err != nil { return err } myHeaders.Set(headerTypeName, headerValueName) } return nil }
[ "func", "extractHeader", "(", "body", "io", ".", "Reader", ",", "myHeaders", "http", ".", "Header", ")", "error", "{", "for", "{", "// extracts the first part of the header,", "headerTypeName", ",", "err", ":=", "extractHeaderType", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "// Since end of file, we have read all of our headers", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "// reads the 7 present in the header and ignores it.", "extractUint8", "(", "body", ")", "\n\n", "headerValueName", ",", "err", ":=", "extractHeaderValue", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "myHeaders", ".", "Set", "(", "headerTypeName", ",", "headerValueName", ")", "\n\n", "}", "\n", "return", "nil", "\n", "}" ]
// extracts the relevant information from the Headers.
[ "extracts", "the", "relevant", "information", "from", "the", "Headers", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L425-L449
148,565
minio/minio-go
api-select.go
extractHeaderType
func extractHeaderType(body io.Reader) (string, error) { // extracts 2 bit integer headerNameLen, err := extractUint8(body) if err != nil { return "", err } // extracts the string with the appropriate number of bytes headerName, err := extractString(body, int(headerNameLen)) if err != nil { return "", err } return strings.TrimPrefix(headerName, ":"), nil }
go
func extractHeaderType(body io.Reader) (string, error) { // extracts 2 bit integer headerNameLen, err := extractUint8(body) if err != nil { return "", err } // extracts the string with the appropriate number of bytes headerName, err := extractString(body, int(headerNameLen)) if err != nil { return "", err } return strings.TrimPrefix(headerName, ":"), nil }
[ "func", "extractHeaderType", "(", "body", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "// extracts 2 bit integer", "headerNameLen", ",", "err", ":=", "extractUint8", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "// extracts the string with the appropriate number of bytes", "headerName", ",", "err", ":=", "extractString", "(", "body", ",", "int", "(", "headerNameLen", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "strings", ".", "TrimPrefix", "(", "headerName", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// extractHeaderType extracts the first half of the header message, the header type.
[ "extractHeaderType", "extracts", "the", "first", "half", "of", "the", "header", "message", "the", "header", "type", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L452-L464
148,566
minio/minio-go
api-select.go
extractHeaderValue
func extractHeaderValue(body io.Reader) (string, error) { bodyLen, err := extractUint16(body) if err != nil { return "", err } bodyName, err := extractString(body, int(bodyLen)) if err != nil { return "", err } return bodyName, nil }
go
func extractHeaderValue(body io.Reader) (string, error) { bodyLen, err := extractUint16(body) if err != nil { return "", err } bodyName, err := extractString(body, int(bodyLen)) if err != nil { return "", err } return bodyName, nil }
[ "func", "extractHeaderValue", "(", "body", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "bodyLen", ",", "err", ":=", "extractUint16", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "bodyName", ",", "err", ":=", "extractString", "(", "body", ",", "int", "(", "bodyLen", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "bodyName", ",", "nil", "\n", "}" ]
// extractsHeaderValue extracts the second half of the header message, the // header value
[ "extractsHeaderValue", "extracts", "the", "second", "half", "of", "the", "header", "message", "the", "header", "value" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L468-L478
148,567
minio/minio-go
api-select.go
extractString
func extractString(source io.Reader, lenBytes int) (string, error) { myVal := make([]byte, lenBytes) _, err := source.Read(myVal) if err != nil { return "", err } return string(myVal), nil }
go
func extractString(source io.Reader, lenBytes int) (string, error) { myVal := make([]byte, lenBytes) _, err := source.Read(myVal) if err != nil { return "", err } return string(myVal), nil }
[ "func", "extractString", "(", "source", "io", ".", "Reader", ",", "lenBytes", "int", ")", "(", "string", ",", "error", ")", "{", "myVal", ":=", "make", "(", "[", "]", "byte", ",", "lenBytes", ")", "\n", "_", ",", "err", ":=", "source", ".", "Read", "(", "myVal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "myVal", ")", ",", "nil", "\n", "}" ]
// extracts a string from byte array of a particular number of bytes.
[ "extracts", "a", "string", "from", "byte", "array", "of", "a", "particular", "number", "of", "bytes", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L481-L488
148,568
minio/minio-go
api-select.go
extractUint32
func extractUint32(r io.Reader) (uint32, error) { buf := make([]byte, 4) _, err := io.ReadFull(r, buf) if err != nil { return 0, err } return binary.BigEndian.Uint32(buf), nil }
go
func extractUint32(r io.Reader) (uint32, error) { buf := make([]byte, 4) _, err := io.ReadFull(r, buf) if err != nil { return 0, err } return binary.BigEndian.Uint32(buf), nil }
[ "func", "extractUint32", "(", "r", "io", ".", "Reader", ")", "(", "uint32", ",", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "binary", ".", "BigEndian", ".", "Uint32", "(", "buf", ")", ",", "nil", "\n", "}" ]
// extractUint32 extracts a 4 byte integer from the byte array.
[ "extractUint32", "extracts", "a", "4", "byte", "integer", "from", "the", "byte", "array", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L491-L498
148,569
minio/minio-go
api-select.go
extractUint16
func extractUint16(r io.Reader) (uint16, error) { buf := make([]byte, 2) _, err := io.ReadFull(r, buf) if err != nil { return 0, err } return binary.BigEndian.Uint16(buf), nil }
go
func extractUint16(r io.Reader) (uint16, error) { buf := make([]byte, 2) _, err := io.ReadFull(r, buf) if err != nil { return 0, err } return binary.BigEndian.Uint16(buf), nil }
[ "func", "extractUint16", "(", "r", "io", ".", "Reader", ")", "(", "uint16", ",", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "2", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "binary", ".", "BigEndian", ".", "Uint16", "(", "buf", ")", ",", "nil", "\n", "}" ]
// extractUint16 extracts a 2 byte integer from the byte array.
[ "extractUint16", "extracts", "a", "2", "byte", "integer", "from", "the", "byte", "array", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L501-L508
148,570
minio/minio-go
api-select.go
extractUint8
func extractUint8(r io.Reader) (uint8, error) { buf := make([]byte, 1) _, err := io.ReadFull(r, buf) if err != nil { return 0, err } return buf[0], nil }
go
func extractUint8(r io.Reader) (uint8, error) { buf := make([]byte, 1) _, err := io.ReadFull(r, buf) if err != nil { return 0, err } return buf[0], nil }
[ "func", "extractUint8", "(", "r", "io", ".", "Reader", ")", "(", "uint8", ",", "error", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "buf", "[", "0", "]", ",", "nil", "\n", "}" ]
// extractUint8 extracts a 1 byte integer from the byte array.
[ "extractUint8", "extracts", "a", "1", "byte", "integer", "from", "the", "byte", "array", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L511-L518
148,571
minio/minio-go
api-select.go
checkCRC
func checkCRC(r io.Reader, expect uint32) error { msgCRC, err := extractUint32(r) if err != nil { return err } if msgCRC != expect { return fmt.Errorf("Checksum Mismatch, MessageCRC of 0x%X does not equal expected CRC of 0x%X", msgCRC, expect) } return nil }
go
func checkCRC(r io.Reader, expect uint32) error { msgCRC, err := extractUint32(r) if err != nil { return err } if msgCRC != expect { return fmt.Errorf("Checksum Mismatch, MessageCRC of 0x%X does not equal expected CRC of 0x%X", msgCRC, expect) } return nil }
[ "func", "checkCRC", "(", "r", "io", ".", "Reader", ",", "expect", "uint32", ")", "error", "{", "msgCRC", ",", "err", ":=", "extractUint32", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "msgCRC", "!=", "expect", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "msgCRC", ",", "expect", ")", "\n\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkCRC ensures that the CRC matches with the one from the reader.
[ "checkCRC", "ensures", "that", "the", "CRC", "matches", "with", "the", "one", "from", "the", "reader", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-select.go#L521-L532
148,572
minio/minio-go
api-stat.go
BucketExists
func (c Client) BucketExists(bucketName string) (bool, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return false, err } // Execute HEAD on bucketName. resp, err := c.executeMethod(context.Background(), "HEAD", requestMetadata{ bucketName: bucketName, contentSHA256Hex: emptySHA256Hex, }) defer closeResponse(resp) if err != nil { if ToErrorResponse(err).Code == "NoSuchBucket" { return false, nil } return false, err } if resp != nil { resperr := httpRespToErrorResponse(resp, bucketName, "") if ToErrorResponse(resperr).Code == "NoSuchBucket" { return false, nil } if resp.StatusCode != http.StatusOK { return false, httpRespToErrorResponse(resp, bucketName, "") } } return true, nil }
go
func (c Client) BucketExists(bucketName string) (bool, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return false, err } // Execute HEAD on bucketName. resp, err := c.executeMethod(context.Background(), "HEAD", requestMetadata{ bucketName: bucketName, contentSHA256Hex: emptySHA256Hex, }) defer closeResponse(resp) if err != nil { if ToErrorResponse(err).Code == "NoSuchBucket" { return false, nil } return false, err } if resp != nil { resperr := httpRespToErrorResponse(resp, bucketName, "") if ToErrorResponse(resperr).Code == "NoSuchBucket" { return false, nil } if resp.StatusCode != http.StatusOK { return false, httpRespToErrorResponse(resp, bucketName, "") } } return true, nil }
[ "func", "(", "c", "Client", ")", "BucketExists", "(", "bucketName", "string", ")", "(", "bool", ",", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "// Execute HEAD on bucketName.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "contentSHA256Hex", ":", "emptySHA256Hex", ",", "}", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "if", "ToErrorResponse", "(", "err", ")", ".", "Code", "==", "\"", "\"", "{", "return", "false", ",", "nil", "\n", "}", "\n", "return", "false", ",", "err", "\n", "}", "\n", "if", "resp", "!=", "nil", "{", "resperr", ":=", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "if", "ToErrorResponse", "(", "resperr", ")", ".", "Code", "==", "\"", "\"", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "false", ",", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// BucketExists verify if bucket exists and you have permission to access it.
[ "BucketExists", "verify", "if", "bucket", "exists", "and", "you", "have", "permission", "to", "access", "it", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-stat.go#L31-L59
148,573
minio/minio-go
api-stat.go
StatObject
func (c Client) StatObject(bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return ObjectInfo{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return ObjectInfo{}, err } return c.statObject(context.Background(), bucketName, objectName, opts) }
go
func (c Client) StatObject(bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return ObjectInfo{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return ObjectInfo{}, err } return c.statObject(context.Background(), bucketName, objectName, opts) }
[ "func", "(", "c", "Client", ")", "StatObject", "(", "bucketName", ",", "objectName", "string", ",", "opts", "StatObjectOptions", ")", "(", "ObjectInfo", ",", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "ObjectInfo", "{", "}", ",", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "ObjectInfo", "{", "}", ",", "err", "\n", "}", "\n", "return", "c", ".", "statObject", "(", "context", ".", "Background", "(", ")", ",", "bucketName", ",", "objectName", ",", "opts", ")", "\n", "}" ]
// StatObject verifies if object exists and you have permission to access.
[ "StatObject", "verifies", "if", "object", "exists", "and", "you", "have", "permission", "to", "access", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-stat.go#L93-L102
148,574
minio/minio-go
api-stat.go
statObject
func (c Client) statObject(ctx context.Context, bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return ObjectInfo{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return ObjectInfo{}, err } // Execute HEAD on objectName. resp, err := c.executeMethod(ctx, "HEAD", requestMetadata{ bucketName: bucketName, objectName: objectName, contentSHA256Hex: emptySHA256Hex, customHeader: opts.Header(), }) defer closeResponse(resp) if err != nil { return ObjectInfo{}, err } if resp != nil { if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { return ObjectInfo{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Trim off the odd double quotes from ETag in the beginning and end. md5sum := strings.TrimPrefix(resp.Header.Get("ETag"), "\"") md5sum = strings.TrimSuffix(md5sum, "\"") // Parse content length is exists var size int64 = -1 contentLengthStr := resp.Header.Get("Content-Length") if contentLengthStr != "" { size, err = strconv.ParseInt(contentLengthStr, 10, 64) if err != nil { // Content-Length is not valid return ObjectInfo{}, ErrorResponse{ Code: "InternalError", Message: "Content-Length is invalid. " + reportIssue, BucketName: bucketName, Key: objectName, RequestID: resp.Header.Get("x-amz-request-id"), HostID: resp.Header.Get("x-amz-id-2"), Region: resp.Header.Get("x-amz-bucket-region"), } } } // Parse Last-Modified has http time format. date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified")) if err != nil { return ObjectInfo{}, ErrorResponse{ Code: "InternalError", Message: "Last-Modified time format is invalid. " + reportIssue, BucketName: bucketName, Key: objectName, RequestID: resp.Header.Get("x-amz-request-id"), HostID: resp.Header.Get("x-amz-id-2"), Region: resp.Header.Get("x-amz-bucket-region"), } } // Fetch content type if any present. contentType := strings.TrimSpace(resp.Header.Get("Content-Type")) if contentType == "" { contentType = "application/octet-stream" } expiryStr := resp.Header.Get("Expires") var expTime time.Time if t, err := time.Parse(http.TimeFormat, expiryStr); err == nil { expTime = t.UTC() } // Save object metadata info. return ObjectInfo{ ETag: md5sum, Key: objectName, Size: size, LastModified: date, ContentType: contentType, Expires: expTime, // Extract only the relevant header keys describing the object. // following function filters out a list of standard set of keys // which are not part of object metadata. Metadata: extractObjMetadata(resp.Header), }, nil }
go
func (c Client) statObject(ctx context.Context, bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return ObjectInfo{}, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return ObjectInfo{}, err } // Execute HEAD on objectName. resp, err := c.executeMethod(ctx, "HEAD", requestMetadata{ bucketName: bucketName, objectName: objectName, contentSHA256Hex: emptySHA256Hex, customHeader: opts.Header(), }) defer closeResponse(resp) if err != nil { return ObjectInfo{}, err } if resp != nil { if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent { return ObjectInfo{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Trim off the odd double quotes from ETag in the beginning and end. md5sum := strings.TrimPrefix(resp.Header.Get("ETag"), "\"") md5sum = strings.TrimSuffix(md5sum, "\"") // Parse content length is exists var size int64 = -1 contentLengthStr := resp.Header.Get("Content-Length") if contentLengthStr != "" { size, err = strconv.ParseInt(contentLengthStr, 10, 64) if err != nil { // Content-Length is not valid return ObjectInfo{}, ErrorResponse{ Code: "InternalError", Message: "Content-Length is invalid. " + reportIssue, BucketName: bucketName, Key: objectName, RequestID: resp.Header.Get("x-amz-request-id"), HostID: resp.Header.Get("x-amz-id-2"), Region: resp.Header.Get("x-amz-bucket-region"), } } } // Parse Last-Modified has http time format. date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified")) if err != nil { return ObjectInfo{}, ErrorResponse{ Code: "InternalError", Message: "Last-Modified time format is invalid. " + reportIssue, BucketName: bucketName, Key: objectName, RequestID: resp.Header.Get("x-amz-request-id"), HostID: resp.Header.Get("x-amz-id-2"), Region: resp.Header.Get("x-amz-bucket-region"), } } // Fetch content type if any present. contentType := strings.TrimSpace(resp.Header.Get("Content-Type")) if contentType == "" { contentType = "application/octet-stream" } expiryStr := resp.Header.Get("Expires") var expTime time.Time if t, err := time.Parse(http.TimeFormat, expiryStr); err == nil { expTime = t.UTC() } // Save object metadata info. return ObjectInfo{ ETag: md5sum, Key: objectName, Size: size, LastModified: date, ContentType: contentType, Expires: expTime, // Extract only the relevant header keys describing the object. // following function filters out a list of standard set of keys // which are not part of object metadata. Metadata: extractObjMetadata(resp.Header), }, nil }
[ "func", "(", "c", "Client", ")", "statObject", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", "string", ",", "opts", "StatObjectOptions", ")", "(", "ObjectInfo", ",", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "ObjectInfo", "{", "}", ",", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "ObjectInfo", "{", "}", ",", "err", "\n", "}", "\n\n", "// Execute HEAD on objectName.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "ctx", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "objectName", ":", "objectName", ",", "contentSHA256Hex", ":", "emptySHA256Hex", ",", "customHeader", ":", "opts", ".", "Header", "(", ")", ",", "}", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ObjectInfo", "{", "}", ",", "err", "\n", "}", "\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "&&", "resp", ".", "StatusCode", "!=", "http", ".", "StatusPartialContent", "{", "return", "ObjectInfo", "{", "}", ",", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "}", "\n\n", "// Trim off the odd double quotes from ETag in the beginning and end.", "md5sum", ":=", "strings", ".", "TrimPrefix", "(", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "\"", "\\\"", "\"", ")", "\n", "md5sum", "=", "strings", ".", "TrimSuffix", "(", "md5sum", ",", "\"", "\\\"", "\"", ")", "\n\n", "// Parse content length is exists", "var", "size", "int64", "=", "-", "1", "\n", "contentLengthStr", ":=", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "contentLengthStr", "!=", "\"", "\"", "{", "size", ",", "err", "=", "strconv", ".", "ParseInt", "(", "contentLengthStr", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "// Content-Length is not valid", "return", "ObjectInfo", "{", "}", ",", "ErrorResponse", "{", "Code", ":", "\"", "\"", ",", "Message", ":", "\"", "\"", "+", "reportIssue", ",", "BucketName", ":", "bucketName", ",", "Key", ":", "objectName", ",", "RequestID", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "HostID", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "Region", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "}", "\n", "}", "\n", "}", "\n\n", "// Parse Last-Modified has http time format.", "date", ",", "err", ":=", "time", ".", "Parse", "(", "http", ".", "TimeFormat", ",", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ObjectInfo", "{", "}", ",", "ErrorResponse", "{", "Code", ":", "\"", "\"", ",", "Message", ":", "\"", "\"", "+", "reportIssue", ",", "BucketName", ":", "bucketName", ",", "Key", ":", "objectName", ",", "RequestID", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "HostID", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "Region", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "}", "\n", "}", "\n\n", "// Fetch content type if any present.", "contentType", ":=", "strings", ".", "TrimSpace", "(", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "contentType", "==", "\"", "\"", "{", "contentType", "=", "\"", "\"", "\n", "}", "\n\n", "expiryStr", ":=", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "var", "expTime", "time", ".", "Time", "\n", "if", "t", ",", "err", ":=", "time", ".", "Parse", "(", "http", ".", "TimeFormat", ",", "expiryStr", ")", ";", "err", "==", "nil", "{", "expTime", "=", "t", ".", "UTC", "(", ")", "\n", "}", "\n", "// Save object metadata info.", "return", "ObjectInfo", "{", "ETag", ":", "md5sum", ",", "Key", ":", "objectName", ",", "Size", ":", "size", ",", "LastModified", ":", "date", ",", "ContentType", ":", "contentType", ",", "Expires", ":", "expTime", ",", "// Extract only the relevant header keys describing the object.", "// following function filters out a list of standard set of keys", "// which are not part of object metadata.", "Metadata", ":", "extractObjMetadata", "(", "resp", ".", "Header", ")", ",", "}", ",", "nil", "\n", "}" ]
// Lower level API for statObject supporting pre-conditions and range headers.
[ "Lower", "level", "API", "for", "statObject", "supporting", "pre", "-", "conditions", "and", "range", "headers", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-stat.go#L105-L192
148,575
minio/minio-go
api-get-options.go
Header
func (o GetObjectOptions) Header() http.Header { headers := make(http.Header, len(o.headers)) for k, v := range o.headers { headers.Set(k, v) } if o.ServerSideEncryption != nil && o.ServerSideEncryption.Type() == encrypt.SSEC { o.ServerSideEncryption.Marshal(headers) } return headers }
go
func (o GetObjectOptions) Header() http.Header { headers := make(http.Header, len(o.headers)) for k, v := range o.headers { headers.Set(k, v) } if o.ServerSideEncryption != nil && o.ServerSideEncryption.Type() == encrypt.SSEC { o.ServerSideEncryption.Marshal(headers) } return headers }
[ "func", "(", "o", "GetObjectOptions", ")", "Header", "(", ")", "http", ".", "Header", "{", "headers", ":=", "make", "(", "http", ".", "Header", ",", "len", "(", "o", ".", "headers", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "o", ".", "headers", "{", "headers", ".", "Set", "(", "k", ",", "v", ")", "\n", "}", "\n", "if", "o", ".", "ServerSideEncryption", "!=", "nil", "&&", "o", ".", "ServerSideEncryption", ".", "Type", "(", ")", "==", "encrypt", ".", "SSEC", "{", "o", ".", "ServerSideEncryption", ".", "Marshal", "(", "headers", ")", "\n", "}", "\n", "return", "headers", "\n", "}" ]
// Header returns the http.Header representation of the GET options.
[ "Header", "returns", "the", "http", ".", "Header", "representation", "of", "the", "GET", "options", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-options.go#L42-L51
148,576
minio/minio-go
api-get-options.go
Set
func (o *GetObjectOptions) Set(key, value string) { if o.headers == nil { o.headers = make(map[string]string) } o.headers[http.CanonicalHeaderKey(key)] = value }
go
func (o *GetObjectOptions) Set(key, value string) { if o.headers == nil { o.headers = make(map[string]string) } o.headers[http.CanonicalHeaderKey(key)] = value }
[ "func", "(", "o", "*", "GetObjectOptions", ")", "Set", "(", "key", ",", "value", "string", ")", "{", "if", "o", ".", "headers", "==", "nil", "{", "o", ".", "headers", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "o", ".", "headers", "[", "http", ".", "CanonicalHeaderKey", "(", "key", ")", "]", "=", "value", "\n", "}" ]
// Set adds a key value pair to the options. The // key-value pair will be part of the HTTP GET request // headers.
[ "Set", "adds", "a", "key", "value", "pair", "to", "the", "options", ".", "The", "key", "-", "value", "pair", "will", "be", "part", "of", "the", "HTTP", "GET", "request", "headers", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-options.go#L56-L61
148,577
minio/minio-go
api-get-options.go
SetMatchETag
func (o *GetObjectOptions) SetMatchETag(etag string) error { if etag == "" { return ErrInvalidArgument("ETag cannot be empty.") } o.Set("If-Match", "\""+etag+"\"") return nil }
go
func (o *GetObjectOptions) SetMatchETag(etag string) error { if etag == "" { return ErrInvalidArgument("ETag cannot be empty.") } o.Set("If-Match", "\""+etag+"\"") return nil }
[ "func", "(", "o", "*", "GetObjectOptions", ")", "SetMatchETag", "(", "etag", "string", ")", "error", "{", "if", "etag", "==", "\"", "\"", "{", "return", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "o", ".", "Set", "(", "\"", "\"", ",", "\"", "\\\"", "\"", "+", "etag", "+", "\"", "\\\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// SetMatchETag - set match etag.
[ "SetMatchETag", "-", "set", "match", "etag", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-options.go#L64-L70
148,578
minio/minio-go
api-get-options.go
SetUnmodified
func (o *GetObjectOptions) SetUnmodified(modTime time.Time) error { if modTime.IsZero() { return ErrInvalidArgument("Modified since cannot be empty.") } o.Set("If-Unmodified-Since", modTime.Format(http.TimeFormat)) return nil }
go
func (o *GetObjectOptions) SetUnmodified(modTime time.Time) error { if modTime.IsZero() { return ErrInvalidArgument("Modified since cannot be empty.") } o.Set("If-Unmodified-Since", modTime.Format(http.TimeFormat)) return nil }
[ "func", "(", "o", "*", "GetObjectOptions", ")", "SetUnmodified", "(", "modTime", "time", ".", "Time", ")", "error", "{", "if", "modTime", ".", "IsZero", "(", ")", "{", "return", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "o", ".", "Set", "(", "\"", "\"", ",", "modTime", ".", "Format", "(", "http", ".", "TimeFormat", ")", ")", "\n", "return", "nil", "\n", "}" ]
// SetUnmodified - set unmodified time since.
[ "SetUnmodified", "-", "set", "unmodified", "time", "since", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-options.go#L82-L88
148,579
minio/minio-go
api-put-object-streaming.go
putObjectNoChecksum
func (c Client) putObjectNoChecksum(ctx context.Context, bucketName, objectName string, reader io.Reader, size int64, opts PutObjectOptions) (n int64, err error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return 0, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return 0, err } // Size -1 is only supported on Google Cloud Storage, we error // out in all other situations. if size < 0 && !s3utils.IsGoogleEndpoint(*c.endpointURL) { return 0, ErrEntityTooSmall(size, bucketName, objectName) } if size > 0 { if isReadAt(reader) && !isObject(reader) { seeker, _ := reader.(io.Seeker) offset, err := seeker.Seek(0, io.SeekCurrent) if err != nil { return 0, ErrInvalidArgument(err.Error()) } reader = io.NewSectionReader(reader.(io.ReaderAt), offset, size) } } // Update progress reader appropriately to the latest offset as we // read from the source. readSeeker := newHook(reader, opts.Progress) // This function does not calculate sha256 and md5sum for payload. // Execute put object. st, err := c.putObjectDo(ctx, bucketName, objectName, readSeeker, "", "", size, opts) if err != nil { return 0, err } if st.Size != size { return 0, ErrUnexpectedEOF(st.Size, size, bucketName, objectName) } return size, nil }
go
func (c Client) putObjectNoChecksum(ctx context.Context, bucketName, objectName string, reader io.Reader, size int64, opts PutObjectOptions) (n int64, err error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return 0, err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return 0, err } // Size -1 is only supported on Google Cloud Storage, we error // out in all other situations. if size < 0 && !s3utils.IsGoogleEndpoint(*c.endpointURL) { return 0, ErrEntityTooSmall(size, bucketName, objectName) } if size > 0 { if isReadAt(reader) && !isObject(reader) { seeker, _ := reader.(io.Seeker) offset, err := seeker.Seek(0, io.SeekCurrent) if err != nil { return 0, ErrInvalidArgument(err.Error()) } reader = io.NewSectionReader(reader.(io.ReaderAt), offset, size) } } // Update progress reader appropriately to the latest offset as we // read from the source. readSeeker := newHook(reader, opts.Progress) // This function does not calculate sha256 and md5sum for payload. // Execute put object. st, err := c.putObjectDo(ctx, bucketName, objectName, readSeeker, "", "", size, opts) if err != nil { return 0, err } if st.Size != size { return 0, ErrUnexpectedEOF(st.Size, size, bucketName, objectName) } return size, nil }
[ "func", "(", "c", "Client", ")", "putObjectNoChecksum", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", "string", ",", "reader", "io", ".", "Reader", ",", "size", "int64", ",", "opts", "PutObjectOptions", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// Size -1 is only supported on Google Cloud Storage, we error", "// out in all other situations.", "if", "size", "<", "0", "&&", "!", "s3utils", ".", "IsGoogleEndpoint", "(", "*", "c", ".", "endpointURL", ")", "{", "return", "0", ",", "ErrEntityTooSmall", "(", "size", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "if", "size", ">", "0", "{", "if", "isReadAt", "(", "reader", ")", "&&", "!", "isObject", "(", "reader", ")", "{", "seeker", ",", "_", ":=", "reader", ".", "(", "io", ".", "Seeker", ")", "\n", "offset", ",", "err", ":=", "seeker", ".", "Seek", "(", "0", ",", "io", ".", "SeekCurrent", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "ErrInvalidArgument", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "reader", "=", "io", ".", "NewSectionReader", "(", "reader", ".", "(", "io", ".", "ReaderAt", ")", ",", "offset", ",", "size", ")", "\n", "}", "\n", "}", "\n\n", "// Update progress reader appropriately to the latest offset as we", "// read from the source.", "readSeeker", ":=", "newHook", "(", "reader", ",", "opts", ".", "Progress", ")", "\n\n", "// This function does not calculate sha256 and md5sum for payload.", "// Execute put object.", "st", ",", "err", ":=", "c", ".", "putObjectDo", "(", "ctx", ",", "bucketName", ",", "objectName", ",", "readSeeker", ",", "\"", "\"", ",", "\"", "\"", ",", "size", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "st", ".", "Size", "!=", "size", "{", "return", "0", ",", "ErrUnexpectedEOF", "(", "st", ".", "Size", ",", "size", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "return", "size", ",", "nil", "\n", "}" ]
// putObjectNoChecksum special function used Google Cloud Storage. This special function // is used for Google Cloud Storage since Google's multipart API is not S3 compatible.
[ "putObjectNoChecksum", "special", "function", "used", "Google", "Cloud", "Storage", ".", "This", "special", "function", "is", "used", "for", "Google", "Cloud", "Storage", "since", "Google", "s", "multipart", "API", "is", "not", "S3", "compatible", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-streaming.go#L331-L370
148,580
minio/minio-go
api-put-object-common.go
isReadAt
func isReadAt(reader io.Reader) (ok bool) { var v *os.File v, ok = reader.(*os.File) if ok { // Stdin, Stdout and Stderr all have *os.File type // which happen to also be io.ReaderAt compatible // we need to add special conditions for them to // be ignored by this function. for _, f := range []string{ "/dev/stdin", "/dev/stdout", "/dev/stderr", } { if f == v.Name() { ok = false break } } } else { _, ok = reader.(io.ReaderAt) } return }
go
func isReadAt(reader io.Reader) (ok bool) { var v *os.File v, ok = reader.(*os.File) if ok { // Stdin, Stdout and Stderr all have *os.File type // which happen to also be io.ReaderAt compatible // we need to add special conditions for them to // be ignored by this function. for _, f := range []string{ "/dev/stdin", "/dev/stdout", "/dev/stderr", } { if f == v.Name() { ok = false break } } } else { _, ok = reader.(io.ReaderAt) } return }
[ "func", "isReadAt", "(", "reader", "io", ".", "Reader", ")", "(", "ok", "bool", ")", "{", "var", "v", "*", "os", ".", "File", "\n", "v", ",", "ok", "=", "reader", ".", "(", "*", "os", ".", "File", ")", "\n", "if", "ok", "{", "// Stdin, Stdout and Stderr all have *os.File type", "// which happen to also be io.ReaderAt compatible", "// we need to add special conditions for them to", "// be ignored by this function.", "for", "_", ",", "f", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "{", "if", "f", "==", "v", ".", "Name", "(", ")", "{", "ok", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "else", "{", "_", ",", "ok", "=", "reader", ".", "(", "io", ".", "ReaderAt", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Verify if reader is a generic ReaderAt
[ "Verify", "if", "reader", "is", "a", "generic", "ReaderAt" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-common.go#L36-L58
148,581
minio/minio-go
api-put-object-common.go
newUploadID
func (c Client) newUploadID(ctx context.Context, bucketName, objectName string, opts PutObjectOptions) (uploadID string, err error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return "", err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return "", err } // Initiate multipart upload for an object. initMultipartUploadResult, err := c.initiateMultipartUpload(ctx, bucketName, objectName, opts) if err != nil { return "", err } return initMultipartUploadResult.UploadID, nil }
go
func (c Client) newUploadID(ctx context.Context, bucketName, objectName string, opts PutObjectOptions) (uploadID string, err error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return "", err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return "", err } // Initiate multipart upload for an object. initMultipartUploadResult, err := c.initiateMultipartUpload(ctx, bucketName, objectName, opts) if err != nil { return "", err } return initMultipartUploadResult.UploadID, nil }
[ "func", "(", "c", "Client", ")", "newUploadID", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", "string", ",", "opts", "PutObjectOptions", ")", "(", "uploadID", "string", ",", "err", "error", ")", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Initiate multipart upload for an object.", "initMultipartUploadResult", ",", "err", ":=", "c", ".", "initiateMultipartUpload", "(", "ctx", ",", "bucketName", ",", "objectName", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "initMultipartUploadResult", ".", "UploadID", ",", "nil", "\n", "}" ]
// getUploadID - fetch upload id if already present for an object name // or initiate a new request to fetch a new upload id.
[ "getUploadID", "-", "fetch", "upload", "id", "if", "already", "present", "for", "an", "object", "name", "or", "initiate", "a", "new", "request", "to", "fetch", "a", "new", "upload", "id", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-common.go#L123-L138
148,582
minio/minio-go
api-put-object.go
getNumThreads
func (opts PutObjectOptions) getNumThreads() (numThreads int) { if opts.NumThreads > 0 { numThreads = int(opts.NumThreads) } else { numThreads = totalWorkers } return }
go
func (opts PutObjectOptions) getNumThreads() (numThreads int) { if opts.NumThreads > 0 { numThreads = int(opts.NumThreads) } else { numThreads = totalWorkers } return }
[ "func", "(", "opts", "PutObjectOptions", ")", "getNumThreads", "(", ")", "(", "numThreads", "int", ")", "{", "if", "opts", ".", "NumThreads", ">", "0", "{", "numThreads", "=", "int", "(", "opts", ".", "NumThreads", ")", "\n", "}", "else", "{", "numThreads", "=", "totalWorkers", "\n", "}", "\n", "return", "\n", "}" ]
// getNumThreads - gets the number of threads to be used in the multipart // put object operation
[ "getNumThreads", "-", "gets", "the", "number", "of", "threads", "to", "be", "used", "in", "the", "multipart", "put", "object", "operation" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object.go#L52-L59
148,583
minio/minio-go
api-put-object.go
Header
func (opts PutObjectOptions) Header() (header http.Header) { header = make(http.Header) if opts.ContentType != "" { header["Content-Type"] = []string{opts.ContentType} } else { header["Content-Type"] = []string{"application/octet-stream"} } if opts.ContentEncoding != "" { header["Content-Encoding"] = []string{opts.ContentEncoding} } if opts.ContentDisposition != "" { header["Content-Disposition"] = []string{opts.ContentDisposition} } if opts.ContentLanguage != "" { header["Content-Language"] = []string{opts.ContentLanguage} } if opts.CacheControl != "" { header["Cache-Control"] = []string{opts.CacheControl} } if opts.ServerSideEncryption != nil { opts.ServerSideEncryption.Marshal(header) } if opts.StorageClass != "" { header[amzStorageClass] = []string{opts.StorageClass} } if opts.WebsiteRedirectLocation != "" { header[amzWebsiteRedirectLocation] = []string{opts.WebsiteRedirectLocation} } for k, v := range opts.UserMetadata { if !isAmzHeader(k) && !isStandardHeader(k) && !isStorageClassHeader(k) { header["X-Amz-Meta-"+k] = []string{v} } else { header[k] = []string{v} } } return }
go
func (opts PutObjectOptions) Header() (header http.Header) { header = make(http.Header) if opts.ContentType != "" { header["Content-Type"] = []string{opts.ContentType} } else { header["Content-Type"] = []string{"application/octet-stream"} } if opts.ContentEncoding != "" { header["Content-Encoding"] = []string{opts.ContentEncoding} } if opts.ContentDisposition != "" { header["Content-Disposition"] = []string{opts.ContentDisposition} } if opts.ContentLanguage != "" { header["Content-Language"] = []string{opts.ContentLanguage} } if opts.CacheControl != "" { header["Cache-Control"] = []string{opts.CacheControl} } if opts.ServerSideEncryption != nil { opts.ServerSideEncryption.Marshal(header) } if opts.StorageClass != "" { header[amzStorageClass] = []string{opts.StorageClass} } if opts.WebsiteRedirectLocation != "" { header[amzWebsiteRedirectLocation] = []string{opts.WebsiteRedirectLocation} } for k, v := range opts.UserMetadata { if !isAmzHeader(k) && !isStandardHeader(k) && !isStorageClassHeader(k) { header["X-Amz-Meta-"+k] = []string{v} } else { header[k] = []string{v} } } return }
[ "func", "(", "opts", "PutObjectOptions", ")", "Header", "(", ")", "(", "header", "http", ".", "Header", ")", "{", "header", "=", "make", "(", "http", ".", "Header", ")", "\n\n", "if", "opts", ".", "ContentType", "!=", "\"", "\"", "{", "header", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "opts", ".", "ContentType", "}", "\n", "}", "else", "{", "header", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n", "if", "opts", ".", "ContentEncoding", "!=", "\"", "\"", "{", "header", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "opts", ".", "ContentEncoding", "}", "\n", "}", "\n", "if", "opts", ".", "ContentDisposition", "!=", "\"", "\"", "{", "header", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "opts", ".", "ContentDisposition", "}", "\n", "}", "\n", "if", "opts", ".", "ContentLanguage", "!=", "\"", "\"", "{", "header", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "opts", ".", "ContentLanguage", "}", "\n", "}", "\n", "if", "opts", ".", "CacheControl", "!=", "\"", "\"", "{", "header", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "opts", ".", "CacheControl", "}", "\n", "}", "\n", "if", "opts", ".", "ServerSideEncryption", "!=", "nil", "{", "opts", ".", "ServerSideEncryption", ".", "Marshal", "(", "header", ")", "\n", "}", "\n", "if", "opts", ".", "StorageClass", "!=", "\"", "\"", "{", "header", "[", "amzStorageClass", "]", "=", "[", "]", "string", "{", "opts", ".", "StorageClass", "}", "\n", "}", "\n", "if", "opts", ".", "WebsiteRedirectLocation", "!=", "\"", "\"", "{", "header", "[", "amzWebsiteRedirectLocation", "]", "=", "[", "]", "string", "{", "opts", ".", "WebsiteRedirectLocation", "}", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "opts", ".", "UserMetadata", "{", "if", "!", "isAmzHeader", "(", "k", ")", "&&", "!", "isStandardHeader", "(", "k", ")", "&&", "!", "isStorageClassHeader", "(", "k", ")", "{", "header", "[", "\"", "\"", "+", "k", "]", "=", "[", "]", "string", "{", "v", "}", "\n", "}", "else", "{", "header", "[", "k", "]", "=", "[", "]", "string", "{", "v", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Header - constructs the headers from metadata entered by user in // PutObjectOptions struct
[ "Header", "-", "constructs", "the", "headers", "from", "metadata", "entered", "by", "user", "in", "PutObjectOptions", "struct" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object.go#L63-L100
148,584
minio/minio-go
api-put-object.go
PutObject
func (c Client) PutObject(bucketName, objectName string, reader io.Reader, objectSize int64, opts PutObjectOptions) (n int64, err error) { return c.PutObjectWithContext(context.Background(), bucketName, objectName, reader, objectSize, opts) }
go
func (c Client) PutObject(bucketName, objectName string, reader io.Reader, objectSize int64, opts PutObjectOptions) (n int64, err error) { return c.PutObjectWithContext(context.Background(), bucketName, objectName, reader, objectSize, opts) }
[ "func", "(", "c", "Client", ")", "PutObject", "(", "bucketName", ",", "objectName", "string", ",", "reader", "io", ".", "Reader", ",", "objectSize", "int64", ",", "opts", "PutObjectOptions", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "return", "c", ".", "PutObjectWithContext", "(", "context", ".", "Background", "(", ")", ",", "bucketName", ",", "objectName", ",", "reader", ",", "objectSize", ",", "opts", ")", "\n", "}" ]
// PutObject creates an object in a bucket. // // You must have WRITE permissions on a bucket to create an object. // // - For size smaller than 64MiB PutObject automatically does a // single atomic Put operation. // - For size larger than 64MiB PutObject automatically does a // multipart Put operation. // - For size input as -1 PutObject does a multipart Put operation // until input stream reaches EOF. Maximum object size that can // be uploaded through this operation will be 5TiB.
[ "PutObject", "creates", "an", "object", "in", "a", "bucket", ".", "You", "must", "have", "WRITE", "permissions", "on", "a", "bucket", "to", "create", "an", "object", ".", "-", "For", "size", "smaller", "than", "64MiB", "PutObject", "automatically", "does", "a", "single", "atomic", "Put", "operation", ".", "-", "For", "size", "larger", "than", "64MiB", "PutObject", "automatically", "does", "a", "multipart", "Put", "operation", ".", "-", "For", "size", "input", "as", "-", "1", "PutObject", "does", "a", "multipart", "Put", "operation", "until", "input", "stream", "reaches", "EOF", ".", "Maximum", "object", "size", "that", "can", "be", "uploaded", "through", "this", "operation", "will", "be", "5TiB", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object.go#L134-L137
148,585
minio/minio-go
api-get-object-file.go
FGetObjectWithContext
func (c Client) FGetObjectWithContext(ctx context.Context, bucketName, objectName, filePath string, opts GetObjectOptions) error { return c.fGetObjectWithContext(ctx, bucketName, objectName, filePath, opts) }
go
func (c Client) FGetObjectWithContext(ctx context.Context, bucketName, objectName, filePath string, opts GetObjectOptions) error { return c.fGetObjectWithContext(ctx, bucketName, objectName, filePath, opts) }
[ "func", "(", "c", "Client", ")", "FGetObjectWithContext", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", ",", "filePath", "string", ",", "opts", "GetObjectOptions", ")", "error", "{", "return", "c", ".", "fGetObjectWithContext", "(", "ctx", ",", "bucketName", ",", "objectName", ",", "filePath", ",", "opts", ")", "\n", "}" ]
// FGetObjectWithContext - download contents of an object to a local file. // The options can be used to specify the GET request further.
[ "FGetObjectWithContext", "-", "download", "contents", "of", "an", "object", "to", "a", "local", "file", ".", "The", "options", "can", "be", "used", "to", "specify", "the", "GET", "request", "further", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-object-file.go#L31-L33
148,586
minio/minio-go
api-get-object-file.go
FGetObject
func (c Client) FGetObject(bucketName, objectName, filePath string, opts GetObjectOptions) error { return c.fGetObjectWithContext(context.Background(), bucketName, objectName, filePath, opts) }
go
func (c Client) FGetObject(bucketName, objectName, filePath string, opts GetObjectOptions) error { return c.fGetObjectWithContext(context.Background(), bucketName, objectName, filePath, opts) }
[ "func", "(", "c", "Client", ")", "FGetObject", "(", "bucketName", ",", "objectName", ",", "filePath", "string", ",", "opts", "GetObjectOptions", ")", "error", "{", "return", "c", ".", "fGetObjectWithContext", "(", "context", ".", "Background", "(", ")", ",", "bucketName", ",", "objectName", ",", "filePath", ",", "opts", ")", "\n", "}" ]
// FGetObject - download contents of an object to a local file.
[ "FGetObject", "-", "download", "contents", "of", "an", "object", "to", "a", "local", "file", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-object-file.go#L36-L38
148,587
minio/minio-go
api-get-object-file.go
fGetObjectWithContext
func (c Client) fGetObjectWithContext(ctx context.Context, bucketName, objectName, filePath string, opts GetObjectOptions) error { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return err } // Verify if destination already exists. st, err := os.Stat(filePath) if err == nil { // If the destination exists and is a directory. if st.IsDir() { return ErrInvalidArgument("fileName is a directory.") } } // Proceed if file does not exist. return for all other errors. if err != nil { if !os.IsNotExist(err) { return err } } // Extract top level directory. objectDir, _ := filepath.Split(filePath) if objectDir != "" { // Create any missing top level directories. if err := os.MkdirAll(objectDir, 0700); err != nil { return err } } // Gather md5sum. objectStat, err := c.StatObject(bucketName, objectName, StatObjectOptions{opts}) if err != nil { return err } // Write to a temporary file "fileName.part.minio" before saving. filePartPath := filePath + objectStat.ETag + ".part.minio" // If exists, open in append mode. If not create it as a part file. filePart, err := os.OpenFile(filePartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { return err } // Issue Stat to get the current offset. st, err = filePart.Stat() if err != nil { return err } // Initialize get object request headers to set the // appropriate range offsets to read from. if st.Size() > 0 { opts.SetRange(st.Size(), 0) } // Seek to current position for incoming reader. objectReader, objectStat, err := c.getObject(ctx, bucketName, objectName, opts) if err != nil { return err } // Write to the part file. if _, err = io.CopyN(filePart, objectReader, objectStat.Size); err != nil { return err } // Close the file before rename, this is specifically needed for Windows users. if err = filePart.Close(); err != nil { return err } // Safely completed. Now commit by renaming to actual filename. if err = os.Rename(filePartPath, filePath); err != nil { return err } // Return. return nil }
go
func (c Client) fGetObjectWithContext(ctx context.Context, bucketName, objectName, filePath string, opts GetObjectOptions) error { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return err } if err := s3utils.CheckValidObjectName(objectName); err != nil { return err } // Verify if destination already exists. st, err := os.Stat(filePath) if err == nil { // If the destination exists and is a directory. if st.IsDir() { return ErrInvalidArgument("fileName is a directory.") } } // Proceed if file does not exist. return for all other errors. if err != nil { if !os.IsNotExist(err) { return err } } // Extract top level directory. objectDir, _ := filepath.Split(filePath) if objectDir != "" { // Create any missing top level directories. if err := os.MkdirAll(objectDir, 0700); err != nil { return err } } // Gather md5sum. objectStat, err := c.StatObject(bucketName, objectName, StatObjectOptions{opts}) if err != nil { return err } // Write to a temporary file "fileName.part.minio" before saving. filePartPath := filePath + objectStat.ETag + ".part.minio" // If exists, open in append mode. If not create it as a part file. filePart, err := os.OpenFile(filePartPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { return err } // Issue Stat to get the current offset. st, err = filePart.Stat() if err != nil { return err } // Initialize get object request headers to set the // appropriate range offsets to read from. if st.Size() > 0 { opts.SetRange(st.Size(), 0) } // Seek to current position for incoming reader. objectReader, objectStat, err := c.getObject(ctx, bucketName, objectName, opts) if err != nil { return err } // Write to the part file. if _, err = io.CopyN(filePart, objectReader, objectStat.Size); err != nil { return err } // Close the file before rename, this is specifically needed for Windows users. if err = filePart.Close(); err != nil { return err } // Safely completed. Now commit by renaming to actual filename. if err = os.Rename(filePartPath, filePath); err != nil { return err } // Return. return nil }
[ "func", "(", "c", "Client", ")", "fGetObjectWithContext", "(", "ctx", "context", ".", "Context", ",", "bucketName", ",", "objectName", ",", "filePath", "string", ",", "opts", "GetObjectOptions", ")", "error", "{", "// Input validation.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Verify if destination already exists.", "st", ",", "err", ":=", "os", ".", "Stat", "(", "filePath", ")", "\n", "if", "err", "==", "nil", "{", "// If the destination exists and is a directory.", "if", "st", ".", "IsDir", "(", ")", "{", "return", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// Proceed if file does not exist. return for all other errors.", "if", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Extract top level directory.", "objectDir", ",", "_", ":=", "filepath", ".", "Split", "(", "filePath", ")", "\n", "if", "objectDir", "!=", "\"", "\"", "{", "// Create any missing top level directories.", "if", "err", ":=", "os", ".", "MkdirAll", "(", "objectDir", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Gather md5sum.", "objectStat", ",", "err", ":=", "c", ".", "StatObject", "(", "bucketName", ",", "objectName", ",", "StatObjectOptions", "{", "opts", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Write to a temporary file \"fileName.part.minio\" before saving.", "filePartPath", ":=", "filePath", "+", "objectStat", ".", "ETag", "+", "\"", "\"", "\n\n", "// If exists, open in append mode. If not create it as a part file.", "filePart", ",", "err", ":=", "os", ".", "OpenFile", "(", "filePartPath", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_APPEND", "|", "os", ".", "O_WRONLY", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Issue Stat to get the current offset.", "st", ",", "err", "=", "filePart", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Initialize get object request headers to set the", "// appropriate range offsets to read from.", "if", "st", ".", "Size", "(", ")", ">", "0", "{", "opts", ".", "SetRange", "(", "st", ".", "Size", "(", ")", ",", "0", ")", "\n", "}", "\n\n", "// Seek to current position for incoming reader.", "objectReader", ",", "objectStat", ",", "err", ":=", "c", ".", "getObject", "(", "ctx", ",", "bucketName", ",", "objectName", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Write to the part file.", "if", "_", ",", "err", "=", "io", ".", "CopyN", "(", "filePart", ",", "objectReader", ",", "objectStat", ".", "Size", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Close the file before rename, this is specifically needed for Windows users.", "if", "err", "=", "filePart", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Safely completed. Now commit by renaming to actual filename.", "if", "err", "=", "os", ".", "Rename", "(", "filePartPath", ",", "filePath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Return.", "return", "nil", "\n", "}" ]
// fGetObjectWithContext - fgetObject wrapper function with context
[ "fGetObjectWithContext", "-", "fgetObject", "wrapper", "function", "with", "context" ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-object-file.go#L41-L125
148,588
minio/minio-go
bucket-cache.go
Get
func (r *bucketLocationCache) Get(bucketName string) (location string, ok bool) { r.RLock() defer r.RUnlock() location, ok = r.items[bucketName] return }
go
func (r *bucketLocationCache) Get(bucketName string) (location string, ok bool) { r.RLock() defer r.RUnlock() location, ok = r.items[bucketName] return }
[ "func", "(", "r", "*", "bucketLocationCache", ")", "Get", "(", "bucketName", "string", ")", "(", "location", "string", ",", "ok", "bool", ")", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "location", ",", "ok", "=", "r", ".", "items", "[", "bucketName", "]", "\n", "return", "\n", "}" ]
// Get - Returns a value of a given key if it exists.
[ "Get", "-", "Returns", "a", "value", "of", "a", "given", "key", "if", "it", "exists", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-cache.go#L52-L57
148,589
minio/minio-go
bucket-cache.go
Set
func (r *bucketLocationCache) Set(bucketName string, location string) { r.Lock() defer r.Unlock() r.items[bucketName] = location }
go
func (r *bucketLocationCache) Set(bucketName string, location string) { r.Lock() defer r.Unlock() r.items[bucketName] = location }
[ "func", "(", "r", "*", "bucketLocationCache", ")", "Set", "(", "bucketName", "string", ",", "location", "string", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "r", ".", "items", "[", "bucketName", "]", "=", "location", "\n", "}" ]
// Set - Will persist a value into cache.
[ "Set", "-", "Will", "persist", "a", "value", "into", "cache", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-cache.go#L60-L64
148,590
minio/minio-go
bucket-cache.go
Delete
func (r *bucketLocationCache) Delete(bucketName string) { r.Lock() defer r.Unlock() delete(r.items, bucketName) }
go
func (r *bucketLocationCache) Delete(bucketName string) { r.Lock() defer r.Unlock() delete(r.items, bucketName) }
[ "func", "(", "r", "*", "bucketLocationCache", ")", "Delete", "(", "bucketName", "string", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "delete", "(", "r", ".", "items", ",", "bucketName", ")", "\n", "}" ]
// Delete - Deletes a bucket name from cache.
[ "Delete", "-", "Deletes", "a", "bucket", "name", "from", "cache", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-cache.go#L67-L71
148,591
minio/minio-go
bucket-cache.go
GetBucketLocation
func (c Client) GetBucketLocation(bucketName string) (string, error) { if err := s3utils.CheckValidBucketName(bucketName); err != nil { return "", err } return c.getBucketLocation(bucketName) }
go
func (c Client) GetBucketLocation(bucketName string) (string, error) { if err := s3utils.CheckValidBucketName(bucketName); err != nil { return "", err } return c.getBucketLocation(bucketName) }
[ "func", "(", "c", "Client", ")", "GetBucketLocation", "(", "bucketName", "string", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "c", ".", "getBucketLocation", "(", "bucketName", ")", "\n", "}" ]
// GetBucketLocation - get location for the bucket name from location cache, if not // fetch freshly by making a new request.
[ "GetBucketLocation", "-", "get", "location", "for", "the", "bucket", "name", "from", "location", "cache", "if", "not", "fetch", "freshly", "by", "making", "a", "new", "request", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-cache.go#L75-L80
148,592
minio/minio-go
bucket-cache.go
getBucketLocation
func (c Client) getBucketLocation(bucketName string) (string, error) { if err := s3utils.CheckValidBucketName(bucketName); err != nil { return "", err } // Region set then no need to fetch bucket location. if c.region != "" { return c.region, nil } if location, ok := c.bucketLocCache.Get(bucketName); ok { return location, nil } // Initialize a new request. req, err := c.getBucketLocationRequest(bucketName) if err != nil { return "", err } // Initiate the request. resp, err := c.do(req) defer closeResponse(resp) if err != nil { return "", err } location, err := processBucketLocationResponse(resp, bucketName) if err != nil { return "", err } c.bucketLocCache.Set(bucketName, location) return location, nil }
go
func (c Client) getBucketLocation(bucketName string) (string, error) { if err := s3utils.CheckValidBucketName(bucketName); err != nil { return "", err } // Region set then no need to fetch bucket location. if c.region != "" { return c.region, nil } if location, ok := c.bucketLocCache.Get(bucketName); ok { return location, nil } // Initialize a new request. req, err := c.getBucketLocationRequest(bucketName) if err != nil { return "", err } // Initiate the request. resp, err := c.do(req) defer closeResponse(resp) if err != nil { return "", err } location, err := processBucketLocationResponse(resp, bucketName) if err != nil { return "", err } c.bucketLocCache.Set(bucketName, location) return location, nil }
[ "func", "(", "c", "Client", ")", "getBucketLocation", "(", "bucketName", "string", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Region set then no need to fetch bucket location.", "if", "c", ".", "region", "!=", "\"", "\"", "{", "return", "c", ".", "region", ",", "nil", "\n", "}", "\n\n", "if", "location", ",", "ok", ":=", "c", ".", "bucketLocCache", ".", "Get", "(", "bucketName", ")", ";", "ok", "{", "return", "location", ",", "nil", "\n", "}", "\n\n", "// Initialize a new request.", "req", ",", "err", ":=", "c", ".", "getBucketLocationRequest", "(", "bucketName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Initiate the request.", "resp", ",", "err", ":=", "c", ".", "do", "(", "req", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "location", ",", "err", ":=", "processBucketLocationResponse", "(", "resp", ",", "bucketName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "c", ".", "bucketLocCache", ".", "Set", "(", "bucketName", ",", "location", ")", "\n", "return", "location", ",", "nil", "\n", "}" ]
// getBucketLocation - Get location for the bucketName from location map cache, if not // fetch freshly by making a new request.
[ "getBucketLocation", "-", "Get", "location", "for", "the", "bucketName", "from", "location", "map", "cache", "if", "not", "fetch", "freshly", "by", "making", "a", "new", "request", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-cache.go#L84-L116
148,593
minio/minio-go
bucket-cache.go
processBucketLocationResponse
func processBucketLocationResponse(resp *http.Response, bucketName string) (bucketLocation string, err error) { if resp != nil { if resp.StatusCode != http.StatusOK { err = httpRespToErrorResponse(resp, bucketName, "") errResp := ToErrorResponse(err) // For access denied error, it could be an anonymous // request. Move forward and let the top level callers // succeed if possible based on their policy. if errResp.Code == "AccessDenied" { return "us-east-1", nil } return "", err } } // Extract location. var locationConstraint string err = xmlDecoder(resp.Body, &locationConstraint) if err != nil { return "", err } location := locationConstraint // Location is empty will be 'us-east-1'. if location == "" { location = "us-east-1" } // Location can be 'EU' convert it to meaningful 'eu-west-1'. if location == "EU" { location = "eu-west-1" } // Save the location into cache. // Return. return location, nil }
go
func processBucketLocationResponse(resp *http.Response, bucketName string) (bucketLocation string, err error) { if resp != nil { if resp.StatusCode != http.StatusOK { err = httpRespToErrorResponse(resp, bucketName, "") errResp := ToErrorResponse(err) // For access denied error, it could be an anonymous // request. Move forward and let the top level callers // succeed if possible based on their policy. if errResp.Code == "AccessDenied" { return "us-east-1", nil } return "", err } } // Extract location. var locationConstraint string err = xmlDecoder(resp.Body, &locationConstraint) if err != nil { return "", err } location := locationConstraint // Location is empty will be 'us-east-1'. if location == "" { location = "us-east-1" } // Location can be 'EU' convert it to meaningful 'eu-west-1'. if location == "EU" { location = "eu-west-1" } // Save the location into cache. // Return. return location, nil }
[ "func", "processBucketLocationResponse", "(", "resp", "*", "http", ".", "Response", ",", "bucketName", "string", ")", "(", "bucketLocation", "string", ",", "err", "error", ")", "{", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "err", "=", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "errResp", ":=", "ToErrorResponse", "(", "err", ")", "\n", "// For access denied error, it could be an anonymous", "// request. Move forward and let the top level callers", "// succeed if possible based on their policy.", "if", "errResp", ".", "Code", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Extract location.", "var", "locationConstraint", "string", "\n", "err", "=", "xmlDecoder", "(", "resp", ".", "Body", ",", "&", "locationConstraint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "location", ":=", "locationConstraint", "\n", "// Location is empty will be 'us-east-1'.", "if", "location", "==", "\"", "\"", "{", "location", "=", "\"", "\"", "\n", "}", "\n\n", "// Location can be 'EU' convert it to meaningful 'eu-west-1'.", "if", "location", "==", "\"", "\"", "{", "location", "=", "\"", "\"", "\n", "}", "\n\n", "// Save the location into cache.", "// Return.", "return", "location", ",", "nil", "\n", "}" ]
// processes the getBucketLocation http response from the server.
[ "processes", "the", "getBucketLocation", "http", "response", "from", "the", "server", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-cache.go#L119-L156
148,594
minio/minio-go
bucket-cache.go
getBucketLocationRequest
func (c Client) getBucketLocationRequest(bucketName string) (*http.Request, error) { // Set location query. urlValues := make(url.Values) urlValues.Set("location", "") // Set get bucket location always as path style. targetURL := c.endpointURL // as it works in makeTargetURL method from api.go file if h, p, err := net.SplitHostPort(targetURL.Host); err == nil { if targetURL.Scheme == "http" && p == "80" || targetURL.Scheme == "https" && p == "443" { targetURL.Host = h } } targetURL.Path = path.Join(bucketName, "") + "/" targetURL.RawQuery = urlValues.Encode() // Get a new HTTP request for the method. req, err := http.NewRequest("GET", targetURL.String(), nil) if err != nil { return nil, err } // Set UserAgent for the request. c.setUserAgent(req) // Get credentials from the configured credentials provider. value, err := c.credsProvider.Get() if err != nil { return nil, err } var ( signerType = value.SignerType accessKeyID = value.AccessKeyID secretAccessKey = value.SecretAccessKey sessionToken = value.SessionToken ) // Custom signer set then override the behavior. if c.overrideSignerType != credentials.SignatureDefault { signerType = c.overrideSignerType } // If signerType returned by credentials helper is anonymous, // then do not sign regardless of signerType override. if value.SignerType == credentials.SignatureAnonymous { signerType = credentials.SignatureAnonymous } if signerType.IsAnonymous() { return req, nil } if signerType.IsV2() { // Get Bucket Location calls should be always path style isVirtualHost := false req = s3signer.SignV2(*req, accessKeyID, secretAccessKey, isVirtualHost) return req, nil } // Set sha256 sum for signature calculation only with signature version '4'. contentSha256 := emptySHA256Hex if c.secure { contentSha256 = unsignedPayload } req.Header.Set("X-Amz-Content-Sha256", contentSha256) req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1") return req, nil }
go
func (c Client) getBucketLocationRequest(bucketName string) (*http.Request, error) { // Set location query. urlValues := make(url.Values) urlValues.Set("location", "") // Set get bucket location always as path style. targetURL := c.endpointURL // as it works in makeTargetURL method from api.go file if h, p, err := net.SplitHostPort(targetURL.Host); err == nil { if targetURL.Scheme == "http" && p == "80" || targetURL.Scheme == "https" && p == "443" { targetURL.Host = h } } targetURL.Path = path.Join(bucketName, "") + "/" targetURL.RawQuery = urlValues.Encode() // Get a new HTTP request for the method. req, err := http.NewRequest("GET", targetURL.String(), nil) if err != nil { return nil, err } // Set UserAgent for the request. c.setUserAgent(req) // Get credentials from the configured credentials provider. value, err := c.credsProvider.Get() if err != nil { return nil, err } var ( signerType = value.SignerType accessKeyID = value.AccessKeyID secretAccessKey = value.SecretAccessKey sessionToken = value.SessionToken ) // Custom signer set then override the behavior. if c.overrideSignerType != credentials.SignatureDefault { signerType = c.overrideSignerType } // If signerType returned by credentials helper is anonymous, // then do not sign regardless of signerType override. if value.SignerType == credentials.SignatureAnonymous { signerType = credentials.SignatureAnonymous } if signerType.IsAnonymous() { return req, nil } if signerType.IsV2() { // Get Bucket Location calls should be always path style isVirtualHost := false req = s3signer.SignV2(*req, accessKeyID, secretAccessKey, isVirtualHost) return req, nil } // Set sha256 sum for signature calculation only with signature version '4'. contentSha256 := emptySHA256Hex if c.secure { contentSha256 = unsignedPayload } req.Header.Set("X-Amz-Content-Sha256", contentSha256) req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1") return req, nil }
[ "func", "(", "c", "Client", ")", "getBucketLocationRequest", "(", "bucketName", "string", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "// Set location query.", "urlValues", ":=", "make", "(", "url", ".", "Values", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Set get bucket location always as path style.", "targetURL", ":=", "c", ".", "endpointURL", "\n\n", "// as it works in makeTargetURL method from api.go file", "if", "h", ",", "p", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "targetURL", ".", "Host", ")", ";", "err", "==", "nil", "{", "if", "targetURL", ".", "Scheme", "==", "\"", "\"", "&&", "p", "==", "\"", "\"", "||", "targetURL", ".", "Scheme", "==", "\"", "\"", "&&", "p", "==", "\"", "\"", "{", "targetURL", ".", "Host", "=", "h", "\n", "}", "\n", "}", "\n\n", "targetURL", ".", "Path", "=", "path", ".", "Join", "(", "bucketName", ",", "\"", "\"", ")", "+", "\"", "\"", "\n", "targetURL", ".", "RawQuery", "=", "urlValues", ".", "Encode", "(", ")", "\n\n", "// Get a new HTTP request for the method.", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "targetURL", ".", "String", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Set UserAgent for the request.", "c", ".", "setUserAgent", "(", "req", ")", "\n\n", "// Get credentials from the configured credentials provider.", "value", ",", "err", ":=", "c", ".", "credsProvider", ".", "Get", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "(", "signerType", "=", "value", ".", "SignerType", "\n", "accessKeyID", "=", "value", ".", "AccessKeyID", "\n", "secretAccessKey", "=", "value", ".", "SecretAccessKey", "\n", "sessionToken", "=", "value", ".", "SessionToken", "\n", ")", "\n\n", "// Custom signer set then override the behavior.", "if", "c", ".", "overrideSignerType", "!=", "credentials", ".", "SignatureDefault", "{", "signerType", "=", "c", ".", "overrideSignerType", "\n", "}", "\n\n", "// If signerType returned by credentials helper is anonymous,", "// then do not sign regardless of signerType override.", "if", "value", ".", "SignerType", "==", "credentials", ".", "SignatureAnonymous", "{", "signerType", "=", "credentials", ".", "SignatureAnonymous", "\n", "}", "\n\n", "if", "signerType", ".", "IsAnonymous", "(", ")", "{", "return", "req", ",", "nil", "\n", "}", "\n\n", "if", "signerType", ".", "IsV2", "(", ")", "{", "// Get Bucket Location calls should be always path style", "isVirtualHost", ":=", "false", "\n", "req", "=", "s3signer", ".", "SignV2", "(", "*", "req", ",", "accessKeyID", ",", "secretAccessKey", ",", "isVirtualHost", ")", "\n", "return", "req", ",", "nil", "\n", "}", "\n\n", "// Set sha256 sum for signature calculation only with signature version '4'.", "contentSha256", ":=", "emptySHA256Hex", "\n", "if", "c", ".", "secure", "{", "contentSha256", "=", "unsignedPayload", "\n", "}", "\n\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "contentSha256", ")", "\n", "req", "=", "s3signer", ".", "SignV4", "(", "*", "req", ",", "accessKeyID", ",", "secretAccessKey", ",", "sessionToken", ",", "\"", "\"", ")", "\n", "return", "req", ",", "nil", "\n", "}" ]
// getBucketLocationRequest - Wrapper creates a new getBucketLocation request.
[ "getBucketLocationRequest", "-", "Wrapper", "creates", "a", "new", "getBucketLocation", "request", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/bucket-cache.go#L159-L230
148,595
minio/minio-go
pkg/credentials/sts_web_identity.go
NewSTSWebIdentity
func NewSTSWebIdentity(stsEndpoint string, getWebIDTokenExpiry func() (*WebIdentityToken, error)) (*Credentials, error) { if stsEndpoint == "" { return nil, errors.New("STS endpoint cannot be empty") } if getWebIDTokenExpiry == nil { return nil, errors.New("Web ID token and expiry retrieval function should be defined") } return New(&STSWebIdentity{ Client: &http.Client{ Transport: http.DefaultTransport, }, stsEndpoint: stsEndpoint, getWebIDTokenExpiry: getWebIDTokenExpiry, }), nil }
go
func NewSTSWebIdentity(stsEndpoint string, getWebIDTokenExpiry func() (*WebIdentityToken, error)) (*Credentials, error) { if stsEndpoint == "" { return nil, errors.New("STS endpoint cannot be empty") } if getWebIDTokenExpiry == nil { return nil, errors.New("Web ID token and expiry retrieval function should be defined") } return New(&STSWebIdentity{ Client: &http.Client{ Transport: http.DefaultTransport, }, stsEndpoint: stsEndpoint, getWebIDTokenExpiry: getWebIDTokenExpiry, }), nil }
[ "func", "NewSTSWebIdentity", "(", "stsEndpoint", "string", ",", "getWebIDTokenExpiry", "func", "(", ")", "(", "*", "WebIdentityToken", ",", "error", ")", ")", "(", "*", "Credentials", ",", "error", ")", "{", "if", "stsEndpoint", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "getWebIDTokenExpiry", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "New", "(", "&", "STSWebIdentity", "{", "Client", ":", "&", "http", ".", "Client", "{", "Transport", ":", "http", ".", "DefaultTransport", ",", "}", ",", "stsEndpoint", ":", "stsEndpoint", ",", "getWebIDTokenExpiry", ":", "getWebIDTokenExpiry", ",", "}", ")", ",", "nil", "\n", "}" ]
// NewSTSWebIdentity returns a pointer to a new // Credentials object wrapping the STSWebIdentity.
[ "NewSTSWebIdentity", "returns", "a", "pointer", "to", "a", "new", "Credentials", "object", "wrapping", "the", "STSWebIdentity", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/sts_web_identity.go#L82-L96
148,596
minio/minio-go
api-get-object.go
GetObject
func (c Client) GetObject(bucketName, objectName string, opts GetObjectOptions) (*Object, error) { return c.getObjectWithContext(context.Background(), bucketName, objectName, opts) }
go
func (c Client) GetObject(bucketName, objectName string, opts GetObjectOptions) (*Object, error) { return c.getObjectWithContext(context.Background(), bucketName, objectName, opts) }
[ "func", "(", "c", "Client", ")", "GetObject", "(", "bucketName", ",", "objectName", "string", ",", "opts", "GetObjectOptions", ")", "(", "*", "Object", ",", "error", ")", "{", "return", "c", ".", "getObjectWithContext", "(", "context", ".", "Background", "(", ")", ",", "bucketName", ",", "objectName", ",", "opts", ")", "\n", "}" ]
// GetObject - returns an seekable, readable object.
[ "GetObject", "-", "returns", "an", "seekable", "readable", "object", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-object.go#L34-L36
148,597
minio/minio-go
api-get-object.go
doGetRequest
func (o *Object) doGetRequest(request getRequest) (getResponse, error) { o.reqCh <- request response := <-o.resCh // Return any error to the top level. if response.Error != nil { return response, response.Error } // This was the first request. if !o.isStarted { // The object has been operated on. o.isStarted = true } // Set the objectInfo if the request was not readAt // and it hasn't been set before. if !o.objectInfoSet && !request.isReadAt { o.objectInfo = response.objectInfo o.objectInfoSet = true } // Set beenRead only if it has not been set before. if !o.beenRead { o.beenRead = response.didRead } // Data are ready on the wire, no need to reinitiate connection in lower level o.seekData = false return response, nil }
go
func (o *Object) doGetRequest(request getRequest) (getResponse, error) { o.reqCh <- request response := <-o.resCh // Return any error to the top level. if response.Error != nil { return response, response.Error } // This was the first request. if !o.isStarted { // The object has been operated on. o.isStarted = true } // Set the objectInfo if the request was not readAt // and it hasn't been set before. if !o.objectInfoSet && !request.isReadAt { o.objectInfo = response.objectInfo o.objectInfoSet = true } // Set beenRead only if it has not been set before. if !o.beenRead { o.beenRead = response.didRead } // Data are ready on the wire, no need to reinitiate connection in lower level o.seekData = false return response, nil }
[ "func", "(", "o", "*", "Object", ")", "doGetRequest", "(", "request", "getRequest", ")", "(", "getResponse", ",", "error", ")", "{", "o", ".", "reqCh", "<-", "request", "\n", "response", ":=", "<-", "o", ".", "resCh", "\n\n", "// Return any error to the top level.", "if", "response", ".", "Error", "!=", "nil", "{", "return", "response", ",", "response", ".", "Error", "\n", "}", "\n\n", "// This was the first request.", "if", "!", "o", ".", "isStarted", "{", "// The object has been operated on.", "o", ".", "isStarted", "=", "true", "\n", "}", "\n", "// Set the objectInfo if the request was not readAt", "// and it hasn't been set before.", "if", "!", "o", ".", "objectInfoSet", "&&", "!", "request", ".", "isReadAt", "{", "o", ".", "objectInfo", "=", "response", ".", "objectInfo", "\n", "o", ".", "objectInfoSet", "=", "true", "\n", "}", "\n", "// Set beenRead only if it has not been set before.", "if", "!", "o", ".", "beenRead", "{", "o", ".", "beenRead", "=", "response", ".", "didRead", "\n", "}", "\n", "// Data are ready on the wire, no need to reinitiate connection in lower level", "o", ".", "seekData", "=", "false", "\n\n", "return", "response", ",", "nil", "\n", "}" ]
// doGetRequest - sends and blocks on the firstReqCh and reqCh of an object. // Returns back the size of the buffer read, if anything was read, as well // as any error encountered. For all first requests sent on the object // it is also responsible for sending back the objectInfo.
[ "doGetRequest", "-", "sends", "and", "blocks", "on", "the", "firstReqCh", "and", "reqCh", "of", "an", "object", ".", "Returns", "back", "the", "size", "of", "the", "buffer", "read", "if", "anything", "was", "read", "as", "well", "as", "any", "error", "encountered", ".", "For", "all", "first", "requests", "sent", "on", "the", "object", "it", "is", "also", "responsible", "for", "sending", "back", "the", "objectInfo", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-object.go#L266-L294
148,598
minio/minio-go
api-get-object.go
Stat
func (o *Object) Stat() (ObjectInfo, error) { if o == nil { return ObjectInfo{}, ErrInvalidArgument("Object is nil") } // Locking. o.mutex.Lock() defer o.mutex.Unlock() if o.prevErr != nil && o.prevErr != io.EOF || o.isClosed { return ObjectInfo{}, o.prevErr } // This is the first request. if !o.isStarted || !o.objectInfoSet { // Send the request and get the response. _, err := o.doGetRequest(getRequest{ isFirstReq: !o.isStarted, settingObjectInfo: !o.objectInfoSet, }) if err != nil { o.prevErr = err return ObjectInfo{}, err } } return o.objectInfo, nil }
go
func (o *Object) Stat() (ObjectInfo, error) { if o == nil { return ObjectInfo{}, ErrInvalidArgument("Object is nil") } // Locking. o.mutex.Lock() defer o.mutex.Unlock() if o.prevErr != nil && o.prevErr != io.EOF || o.isClosed { return ObjectInfo{}, o.prevErr } // This is the first request. if !o.isStarted || !o.objectInfoSet { // Send the request and get the response. _, err := o.doGetRequest(getRequest{ isFirstReq: !o.isStarted, settingObjectInfo: !o.objectInfoSet, }) if err != nil { o.prevErr = err return ObjectInfo{}, err } } return o.objectInfo, nil }
[ "func", "(", "o", "*", "Object", ")", "Stat", "(", ")", "(", "ObjectInfo", ",", "error", ")", "{", "if", "o", "==", "nil", "{", "return", "ObjectInfo", "{", "}", ",", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "// Locking.", "o", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "o", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "o", ".", "prevErr", "!=", "nil", "&&", "o", ".", "prevErr", "!=", "io", ".", "EOF", "||", "o", ".", "isClosed", "{", "return", "ObjectInfo", "{", "}", ",", "o", ".", "prevErr", "\n", "}", "\n\n", "// This is the first request.", "if", "!", "o", ".", "isStarted", "||", "!", "o", ".", "objectInfoSet", "{", "// Send the request and get the response.", "_", ",", "err", ":=", "o", ".", "doGetRequest", "(", "getRequest", "{", "isFirstReq", ":", "!", "o", ".", "isStarted", ",", "settingObjectInfo", ":", "!", "o", ".", "objectInfoSet", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "o", ".", "prevErr", "=", "err", "\n", "return", "ObjectInfo", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "o", ".", "objectInfo", ",", "nil", "\n", "}" ]
// Stat returns the ObjectInfo structure describing Object.
[ "Stat", "returns", "the", "ObjectInfo", "structure", "describing", "Object", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-object.go#L364-L390
148,599
minio/minio-go
api-presigned.go
presignURL
func (c Client) presignURL(method string, bucketName string, objectName string, expires time.Duration, reqParams url.Values) (u *url.URL, err error) { // Input validation. if method == "" { return nil, ErrInvalidArgument("method cannot be empty.") } if err = s3utils.CheckValidBucketName(bucketName); err != nil { return nil, err } if err = isValidExpiry(expires); err != nil { return nil, err } // Convert expires into seconds. expireSeconds := int64(expires / time.Second) reqMetadata := requestMetadata{ presignURL: true, bucketName: bucketName, objectName: objectName, expires: expireSeconds, queryValues: reqParams, } // Instantiate a new request. // Since expires is set newRequest will presign the request. var req *http.Request if req, err = c.newRequest(method, reqMetadata); err != nil { return nil, err } return req.URL, nil }
go
func (c Client) presignURL(method string, bucketName string, objectName string, expires time.Duration, reqParams url.Values) (u *url.URL, err error) { // Input validation. if method == "" { return nil, ErrInvalidArgument("method cannot be empty.") } if err = s3utils.CheckValidBucketName(bucketName); err != nil { return nil, err } if err = isValidExpiry(expires); err != nil { return nil, err } // Convert expires into seconds. expireSeconds := int64(expires / time.Second) reqMetadata := requestMetadata{ presignURL: true, bucketName: bucketName, objectName: objectName, expires: expireSeconds, queryValues: reqParams, } // Instantiate a new request. // Since expires is set newRequest will presign the request. var req *http.Request if req, err = c.newRequest(method, reqMetadata); err != nil { return nil, err } return req.URL, nil }
[ "func", "(", "c", "Client", ")", "presignURL", "(", "method", "string", ",", "bucketName", "string", ",", "objectName", "string", ",", "expires", "time", ".", "Duration", ",", "reqParams", "url", ".", "Values", ")", "(", "u", "*", "url", ".", "URL", ",", "err", "error", ")", "{", "// Input validation.", "if", "method", "==", "\"", "\"", "{", "return", "nil", ",", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", "=", "isValidExpiry", "(", "expires", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Convert expires into seconds.", "expireSeconds", ":=", "int64", "(", "expires", "/", "time", ".", "Second", ")", "\n", "reqMetadata", ":=", "requestMetadata", "{", "presignURL", ":", "true", ",", "bucketName", ":", "bucketName", ",", "objectName", ":", "objectName", ",", "expires", ":", "expireSeconds", ",", "queryValues", ":", "reqParams", ",", "}", "\n\n", "// Instantiate a new request.", "// Since expires is set newRequest will presign the request.", "var", "req", "*", "http", ".", "Request", "\n", "if", "req", ",", "err", "=", "c", ".", "newRequest", "(", "method", ",", "reqMetadata", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "req", ".", "URL", ",", "nil", "\n", "}" ]
// presignURL - Returns a presigned URL for an input 'method'. // Expires maximum is 7days - ie. 604800 and minimum is 1.
[ "presignURL", "-", "Returns", "a", "presigned", "URL", "for", "an", "input", "method", ".", "Expires", "maximum", "is", "7days", "-", "ie", ".", "604800", "and", "minimum", "is", "1", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-presigned.go#L32-L61