repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
minio/minio-go | api-put-bucket.go | RemoveAllBucketNotification | func (c Client) RemoveAllBucketNotification(bucketName string) error {
return c.SetBucketNotification(bucketName, BucketNotification{})
} | go | func (c Client) RemoveAllBucketNotification(bucketName string) error {
return c.SetBucketNotification(bucketName, BucketNotification{})
} | [
"func",
"(",
"c",
"Client",
")",
"RemoveAllBucketNotification",
"(",
"bucketName",
"string",
")",
"error",
"{",
"return",
"c",
".",
"SetBucketNotification",
"(",
"bucketName",
",",
"BucketNotification",
"{",
"}",
")",
"\n",
"}"
] | // RemoveAllBucketNotification - Remove bucket notification clears all previously specified config | [
"RemoveAllBucketNotification",
"-",
"Remove",
"bucket",
"notification",
"clears",
"all",
"previously",
"specified",
"config"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-bucket.go#L304-L306 | train |
minio/minio-go | pkg/credentials/static.go | NewStaticV2 | func NewStaticV2(id, secret, token string) *Credentials {
return NewStatic(id, secret, token, SignatureV2)
} | go | func NewStaticV2(id, secret, token string) *Credentials {
return NewStatic(id, secret, token, SignatureV2)
} | [
"func",
"NewStaticV2",
"(",
"id",
",",
"secret",
",",
"token",
"string",
")",
"*",
"Credentials",
"{",
"return",
"NewStatic",
"(",
"id",
",",
"secret",
",",
"token",
",",
"SignatureV2",
")",
"\n",
"}"
] | // NewStaticV2 returns a pointer to a new Credentials object
// wrapping a static credentials value provider, signature is
// set to v2. If access and secret are not specified then
// regardless of signature type set it Value will return
// as anonymous. | [
"NewStaticV2",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"Credentials",
"object",
"wrapping",
"a",
"static",
"credentials",
"value",
"provider",
"signature",
"is",
"set",
"to",
"v2",
".",
"If",
"access",
"and",
"secret",
"are",
"not",
"specified",
"then",
... | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/static.go#L31-L33 | train |
minio/minio-go | pkg/credentials/static.go | NewStaticV4 | func NewStaticV4(id, secret, token string) *Credentials {
return NewStatic(id, secret, token, SignatureV4)
} | go | func NewStaticV4(id, secret, token string) *Credentials {
return NewStatic(id, secret, token, SignatureV4)
} | [
"func",
"NewStaticV4",
"(",
"id",
",",
"secret",
",",
"token",
"string",
")",
"*",
"Credentials",
"{",
"return",
"NewStatic",
"(",
"id",
",",
"secret",
",",
"token",
",",
"SignatureV4",
")",
"\n",
"}"
] | // NewStaticV4 is similar to NewStaticV2 with similar considerations. | [
"NewStaticV4",
"is",
"similar",
"to",
"NewStaticV2",
"with",
"similar",
"considerations",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/static.go#L36-L38 | train |
minio/minio-go | pkg/credentials/static.go | NewStatic | func NewStatic(id, secret, token string, signerType SignatureType) *Credentials {
return New(&Static{
Value: Value{
AccessKeyID: id,
SecretAccessKey: secret,
SessionToken: token,
SignerType: signerType,
},
})
} | go | func NewStatic(id, secret, token string, signerType SignatureType) *Credentials {
return New(&Static{
Value: Value{
AccessKeyID: id,
SecretAccessKey: secret,
SessionToken: token,
SignerType: signerType,
},
})
} | [
"func",
"NewStatic",
"(",
"id",
",",
"secret",
",",
"token",
"string",
",",
"signerType",
"SignatureType",
")",
"*",
"Credentials",
"{",
"return",
"New",
"(",
"&",
"Static",
"{",
"Value",
":",
"Value",
"{",
"AccessKeyID",
":",
"id",
",",
"SecretAccessKey",... | // NewStatic returns a pointer to a new Credentials object
// wrapping a static credentials value provider. | [
"NewStatic",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"Credentials",
"object",
"wrapping",
"a",
"static",
"credentials",
"value",
"provider",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/static.go#L42-L51 | train |
minio/minio-go | pkg/credentials/static.go | Retrieve | func (s *Static) Retrieve() (Value, error) {
if s.AccessKeyID == "" || s.SecretAccessKey == "" {
// Anonymous is not an error
return Value{SignerType: SignatureAnonymous}, nil
}
return s.Value, nil
} | go | func (s *Static) Retrieve() (Value, error) {
if s.AccessKeyID == "" || s.SecretAccessKey == "" {
// Anonymous is not an error
return Value{SignerType: SignatureAnonymous}, nil
}
return s.Value, nil
} | [
"func",
"(",
"s",
"*",
"Static",
")",
"Retrieve",
"(",
")",
"(",
"Value",
",",
"error",
")",
"{",
"if",
"s",
".",
"AccessKeyID",
"==",
"\"",
"\"",
"||",
"s",
".",
"SecretAccessKey",
"==",
"\"",
"\"",
"{",
"// Anonymous is not an error",
"return",
"Valu... | // Retrieve returns the static credentials. | [
"Retrieve",
"returns",
"the",
"static",
"credentials",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/static.go#L54-L60 | train |
minio/minio-go | api-put-object-file-context.go | FPutObjectWithContext | func (c Client) FPutObjectWithContext(ctx context.Context, bucketName, objectName, filePath string, 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
}
// Open the referenced file.
fileReader, err := os.Open(filePath)
// If any error fail quickly here.
if err != nil {
return 0, err
}
defer fileReader.Close()
// Save the file stat.
fileStat, err := fileReader.Stat()
if err != nil {
return 0, err
}
// Save the file size.
fileSize := fileStat.Size()
// Set contentType based on filepath extension if not given or default
// value of "application/octet-stream" if the extension has no associated type.
if opts.ContentType == "" {
if opts.ContentType = mime.TypeByExtension(filepath.Ext(filePath)); opts.ContentType == "" {
opts.ContentType = "application/octet-stream"
}
}
return c.PutObjectWithContext(ctx, bucketName, objectName, fileReader, fileSize, opts)
} | go | func (c Client) FPutObjectWithContext(ctx context.Context, bucketName, objectName, filePath string, 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
}
// Open the referenced file.
fileReader, err := os.Open(filePath)
// If any error fail quickly here.
if err != nil {
return 0, err
}
defer fileReader.Close()
// Save the file stat.
fileStat, err := fileReader.Stat()
if err != nil {
return 0, err
}
// Save the file size.
fileSize := fileStat.Size()
// Set contentType based on filepath extension if not given or default
// value of "application/octet-stream" if the extension has no associated type.
if opts.ContentType == "" {
if opts.ContentType = mime.TypeByExtension(filepath.Ext(filePath)); opts.ContentType == "" {
opts.ContentType = "application/octet-stream"
}
}
return c.PutObjectWithContext(ctx, bucketName, objectName, fileReader, fileSize, opts)
} | [
"func",
"(",
"c",
"Client",
")",
"FPutObjectWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
",",
"objectName",
",",
"filePath",
"string",
",",
"opts",
"PutObjectOptions",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"// In... | // FPutObjectWithContext - Create an object in a bucket, with contents from file at filePath. Allows request cancellation. | [
"FPutObjectWithContext",
"-",
"Create",
"an",
"object",
"in",
"a",
"bucket",
"with",
"contents",
"from",
"file",
"at",
"filePath",
".",
"Allows",
"request",
"cancellation",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-file-context.go#L30-L64 | train |
minio/minio-go | api.go | NewV2 | func NewV2(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV2(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
clnt.overrideSignerType = credentials.SignatureV2
return clnt, nil
} | go | func NewV2(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV2(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
clnt.overrideSignerType = credentials.SignatureV2
return clnt, nil
} | [
"func",
"NewV2",
"(",
"endpoint",
"string",
",",
"accessKeyID",
",",
"secretAccessKey",
"string",
",",
"secure",
"bool",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"creds",
":=",
"credentials",
".",
"NewStaticV2",
"(",
"accessKeyID",
",",
"secretAccess... | // NewV2 - instantiate minio client with Amazon S3 signature version
// '2' compatibility. | [
"NewV2",
"-",
"instantiate",
"minio",
"client",
"with",
"Amazon",
"S3",
"signature",
"version",
"2",
"compatibility",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L129-L137 | train |
minio/minio-go | api.go | NewV4 | func NewV4(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
clnt.overrideSignerType = credentials.SignatureV4
return clnt, nil
} | go | func NewV4(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
clnt.overrideSignerType = credentials.SignatureV4
return clnt, nil
} | [
"func",
"NewV4",
"(",
"endpoint",
"string",
",",
"accessKeyID",
",",
"secretAccessKey",
"string",
",",
"secure",
"bool",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"creds",
":=",
"credentials",
".",
"NewStaticV4",
"(",
"accessKeyID",
",",
"secretAccess... | // NewV4 - instantiate minio client with Amazon S3 signature version
// '4' compatibility. | [
"NewV4",
"-",
"instantiate",
"minio",
"client",
"with",
"Amazon",
"S3",
"signature",
"version",
"4",
"compatibility",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L141-L149 | train |
minio/minio-go | api.go | New | func New(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
// Google cloud storage should be set to signature V2, force it if not.
if s3utils.IsGoogleEndpoint(*clnt.endpointURL) {
clnt.overrideSignerType = credentials.SignatureV2
}
// If Amazon S3 set to signature v4.
if s3utils.IsAmazonEndpoint(*clnt.endpointURL) {
clnt.overrideSignerType = credentials.SignatureV4
}
return clnt, nil
} | go | func New(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
if err != nil {
return nil, err
}
// Google cloud storage should be set to signature V2, force it if not.
if s3utils.IsGoogleEndpoint(*clnt.endpointURL) {
clnt.overrideSignerType = credentials.SignatureV2
}
// If Amazon S3 set to signature v4.
if s3utils.IsAmazonEndpoint(*clnt.endpointURL) {
clnt.overrideSignerType = credentials.SignatureV4
}
return clnt, nil
} | [
"func",
"New",
"(",
"endpoint",
",",
"accessKeyID",
",",
"secretAccessKey",
"string",
",",
"secure",
"bool",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"creds",
":=",
"credentials",
".",
"NewStaticV4",
"(",
"accessKeyID",
",",
"secretAccessKey",
",",
... | // New - instantiate minio client, adds automatic verification of signature. | [
"New",
"-",
"instantiate",
"minio",
"client",
"adds",
"automatic",
"verification",
"of",
"signature",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L152-L167 | train |
minio/minio-go | api.go | NewWithCredentials | func NewWithCredentials(endpoint string, creds *credentials.Credentials, secure bool, region string) (*Client, error) {
return privateNew(endpoint, creds, secure, region, BucketLookupAuto)
} | go | func NewWithCredentials(endpoint string, creds *credentials.Credentials, secure bool, region string) (*Client, error) {
return privateNew(endpoint, creds, secure, region, BucketLookupAuto)
} | [
"func",
"NewWithCredentials",
"(",
"endpoint",
"string",
",",
"creds",
"*",
"credentials",
".",
"Credentials",
",",
"secure",
"bool",
",",
"region",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"return",
"privateNew",
"(",
"endpoint",
",",
"c... | // NewWithCredentials - instantiate minio client with credentials provider
// for retrieving credentials from various credentials provider such as
// IAM, File, Env etc. | [
"NewWithCredentials",
"-",
"instantiate",
"minio",
"client",
"with",
"credentials",
"provider",
"for",
"retrieving",
"credentials",
"from",
"various",
"credentials",
"provider",
"such",
"as",
"IAM",
"File",
"Env",
"etc",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L172-L174 | train |
minio/minio-go | api.go | NewWithOptions | func NewWithOptions(endpoint string, opts *Options) (*Client, error) {
return privateNew(endpoint, opts.Creds, opts.Secure, opts.Region, opts.BucketLookup)
} | go | func NewWithOptions(endpoint string, opts *Options) (*Client, error) {
return privateNew(endpoint, opts.Creds, opts.Secure, opts.Region, opts.BucketLookup)
} | [
"func",
"NewWithOptions",
"(",
"endpoint",
"string",
",",
"opts",
"*",
"Options",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"return",
"privateNew",
"(",
"endpoint",
",",
"opts",
".",
"Creds",
",",
"opts",
".",
"Secure",
",",
"opts",
".",
"Region... | // NewWithOptions - instantiate minio client with options | [
"NewWithOptions",
"-",
"instantiate",
"minio",
"client",
"with",
"options"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L185-L187 | train |
minio/minio-go | api.go | redirectHeaders | func (c *Client) redirectHeaders(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return errors.New("stopped after 5 redirects")
}
if len(via) == 0 {
return nil
}
lastRequest := via[len(via)-1]
var reAuth bool
for attr, val := range lastRequest.Header {
// if hosts do not match do not copy Authorization header
if attr == "Authorization" && req.Host != lastRequest.Host {
reAuth = true
continue
}
if _, ok := req.Header[attr]; !ok {
req.Header[attr] = val
}
}
*c.endpointURL = *req.URL
value, err := c.credsProvider.Get()
if err != nil {
return err
}
var (
signerType = value.SignerType
accessKeyID = value.AccessKeyID
secretAccessKey = value.SecretAccessKey
sessionToken = value.SessionToken
region = c.region
)
// 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 reAuth {
// Check if there is no region override, if not get it from the URL if possible.
if region == "" {
region = s3utils.GetRegionFromURL(*c.endpointURL)
}
switch {
case signerType.IsV2():
return errors.New("signature V2 cannot support redirection")
case signerType.IsV4():
req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, getDefaultLocation(*c.endpointURL, region))
}
}
return nil
} | go | func (c *Client) redirectHeaders(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return errors.New("stopped after 5 redirects")
}
if len(via) == 0 {
return nil
}
lastRequest := via[len(via)-1]
var reAuth bool
for attr, val := range lastRequest.Header {
// if hosts do not match do not copy Authorization header
if attr == "Authorization" && req.Host != lastRequest.Host {
reAuth = true
continue
}
if _, ok := req.Header[attr]; !ok {
req.Header[attr] = val
}
}
*c.endpointURL = *req.URL
value, err := c.credsProvider.Get()
if err != nil {
return err
}
var (
signerType = value.SignerType
accessKeyID = value.AccessKeyID
secretAccessKey = value.SecretAccessKey
sessionToken = value.SessionToken
region = c.region
)
// 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 reAuth {
// Check if there is no region override, if not get it from the URL if possible.
if region == "" {
region = s3utils.GetRegionFromURL(*c.endpointURL)
}
switch {
case signerType.IsV2():
return errors.New("signature V2 cannot support redirection")
case signerType.IsV4():
req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, getDefaultLocation(*c.endpointURL, region))
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"redirectHeaders",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"via",
"[",
"]",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"if",
"len",
"(",
"via",
")",
">=",
"5",
"{",
"return",
"errors",
".",
"New",
... | // Redirect requests by re signing the request. | [
"Redirect",
"requests",
"by",
"re",
"signing",
"the",
"request",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L212-L270 | train |
minio/minio-go | api.go | hashMaterials | func (c *Client) hashMaterials() (hashAlgos map[string]hash.Hash, hashSums map[string][]byte) {
hashSums = make(map[string][]byte)
hashAlgos = make(map[string]hash.Hash)
if c.overrideSignerType.IsV4() {
if c.secure {
hashAlgos["md5"] = md5.New()
} else {
hashAlgos["sha256"] = sha256.New()
}
} else {
if c.overrideSignerType.IsAnonymous() {
hashAlgos["md5"] = md5.New()
}
}
return hashAlgos, hashSums
} | go | func (c *Client) hashMaterials() (hashAlgos map[string]hash.Hash, hashSums map[string][]byte) {
hashSums = make(map[string][]byte)
hashAlgos = make(map[string]hash.Hash)
if c.overrideSignerType.IsV4() {
if c.secure {
hashAlgos["md5"] = md5.New()
} else {
hashAlgos["sha256"] = sha256.New()
}
} else {
if c.overrideSignerType.IsAnonymous() {
hashAlgos["md5"] = md5.New()
}
}
return hashAlgos, hashSums
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"hashMaterials",
"(",
")",
"(",
"hashAlgos",
"map",
"[",
"string",
"]",
"hash",
".",
"Hash",
",",
"hashSums",
"map",
"[",
"string",
"]",
"[",
"]",
"byte",
")",
"{",
"hashSums",
"=",
"make",
"(",
"map",
"[",
"... | // Hash materials provides relevant initialized hash algo writers
// based on the expected signature type.
//
// - For signature v4 request if the connection is insecure compute only sha256.
// - For signature v4 request if the connection is secure compute only md5.
// - For anonymous request compute md5. | [
"Hash",
"materials",
"provides",
"relevant",
"initialized",
"hash",
"algo",
"writers",
"based",
"on",
"the",
"expected",
"signature",
"type",
".",
"-",
"For",
"signature",
"v4",
"request",
"if",
"the",
"connection",
"is",
"insecure",
"compute",
"only",
"sha256",... | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L399-L414 | train |
minio/minio-go | api.go | isVirtualHostStyleRequest | func (c *Client) isVirtualHostStyleRequest(url url.URL, bucketName string) bool {
if bucketName == "" {
return false
}
if c.lookup == BucketLookupDNS {
return true
}
if c.lookup == BucketLookupPath {
return false
}
// default to virtual only for Amazon/Google storage. In all other cases use
// path style requests
return s3utils.IsVirtualHostSupported(url, bucketName)
} | go | func (c *Client) isVirtualHostStyleRequest(url url.URL, bucketName string) bool {
if bucketName == "" {
return false
}
if c.lookup == BucketLookupDNS {
return true
}
if c.lookup == BucketLookupPath {
return false
}
// default to virtual only for Amazon/Google storage. In all other cases use
// path style requests
return s3utils.IsVirtualHostSupported(url, bucketName)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"isVirtualHostStyleRequest",
"(",
"url",
"url",
".",
"URL",
",",
"bucketName",
"string",
")",
"bool",
"{",
"if",
"bucketName",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"lookup",
... | // returns true if virtual hosted style requests are to be used. | [
"returns",
"true",
"if",
"virtual",
"hosted",
"style",
"requests",
"are",
"to",
"be",
"used",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api.go#L888-L903 | train |
minio/minio-go | api-list.go | listIncompleteUploads | func (c Client) listIncompleteUploads(bucketName, objectPrefix string, recursive, aggregateSize bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo {
// Allocate channel for multipart uploads.
objectMultipartStatCh := make(chan ObjectMultipartInfo, 1)
// Delimiter is set to "/" by default.
delimiter := "/"
if recursive {
// If recursive do not delimit.
delimiter = ""
}
// Validate bucket name.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
defer close(objectMultipartStatCh)
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
return objectMultipartStatCh
}
// Validate incoming object prefix.
if err := s3utils.CheckValidObjectNamePrefix(objectPrefix); err != nil {
defer close(objectMultipartStatCh)
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
return objectMultipartStatCh
}
go func(objectMultipartStatCh chan<- ObjectMultipartInfo) {
defer close(objectMultipartStatCh)
// object and upload ID marker for future requests.
var objectMarker string
var uploadIDMarker string
for {
// list all multipart uploads.
result, err := c.listMultipartUploadsQuery(bucketName, objectMarker, uploadIDMarker, objectPrefix, delimiter, 1000)
if err != nil {
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
return
}
// Save objectMarker and uploadIDMarker for next request.
objectMarker = result.NextKeyMarker
uploadIDMarker = result.NextUploadIDMarker
// Send all multipart uploads.
for _, obj := range result.Uploads {
// Calculate total size of the uploaded parts if 'aggregateSize' is enabled.
if aggregateSize {
// Get total multipart size.
obj.Size, err = c.getTotalMultipartSize(bucketName, obj.Key, obj.UploadID)
if err != nil {
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
continue
}
}
select {
// Send individual uploads here.
case objectMultipartStatCh <- obj:
// If done channel return here.
case <-doneCh:
return
}
}
// Send all common prefixes if any.
// NOTE: prefixes are only present if the request is delimited.
for _, obj := range result.CommonPrefixes {
object := ObjectMultipartInfo{}
object.Key = obj.Prefix
object.Size = 0
select {
// Send delimited prefixes here.
case objectMultipartStatCh <- object:
// If done channel return here.
case <-doneCh:
return
}
}
// Listing ends if result not truncated, return right here.
if !result.IsTruncated {
return
}
}
}(objectMultipartStatCh)
// return.
return objectMultipartStatCh
} | go | func (c Client) listIncompleteUploads(bucketName, objectPrefix string, recursive, aggregateSize bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo {
// Allocate channel for multipart uploads.
objectMultipartStatCh := make(chan ObjectMultipartInfo, 1)
// Delimiter is set to "/" by default.
delimiter := "/"
if recursive {
// If recursive do not delimit.
delimiter = ""
}
// Validate bucket name.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
defer close(objectMultipartStatCh)
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
return objectMultipartStatCh
}
// Validate incoming object prefix.
if err := s3utils.CheckValidObjectNamePrefix(objectPrefix); err != nil {
defer close(objectMultipartStatCh)
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
return objectMultipartStatCh
}
go func(objectMultipartStatCh chan<- ObjectMultipartInfo) {
defer close(objectMultipartStatCh)
// object and upload ID marker for future requests.
var objectMarker string
var uploadIDMarker string
for {
// list all multipart uploads.
result, err := c.listMultipartUploadsQuery(bucketName, objectMarker, uploadIDMarker, objectPrefix, delimiter, 1000)
if err != nil {
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
return
}
// Save objectMarker and uploadIDMarker for next request.
objectMarker = result.NextKeyMarker
uploadIDMarker = result.NextUploadIDMarker
// Send all multipart uploads.
for _, obj := range result.Uploads {
// Calculate total size of the uploaded parts if 'aggregateSize' is enabled.
if aggregateSize {
// Get total multipart size.
obj.Size, err = c.getTotalMultipartSize(bucketName, obj.Key, obj.UploadID)
if err != nil {
objectMultipartStatCh <- ObjectMultipartInfo{
Err: err,
}
continue
}
}
select {
// Send individual uploads here.
case objectMultipartStatCh <- obj:
// If done channel return here.
case <-doneCh:
return
}
}
// Send all common prefixes if any.
// NOTE: prefixes are only present if the request is delimited.
for _, obj := range result.CommonPrefixes {
object := ObjectMultipartInfo{}
object.Key = obj.Prefix
object.Size = 0
select {
// Send delimited prefixes here.
case objectMultipartStatCh <- object:
// If done channel return here.
case <-doneCh:
return
}
}
// Listing ends if result not truncated, return right here.
if !result.IsTruncated {
return
}
}
}(objectMultipartStatCh)
// return.
return objectMultipartStatCh
} | [
"func",
"(",
"c",
"Client",
")",
"listIncompleteUploads",
"(",
"bucketName",
",",
"objectPrefix",
"string",
",",
"recursive",
",",
"aggregateSize",
"bool",
",",
"doneCh",
"<-",
"chan",
"struct",
"{",
"}",
")",
"<-",
"chan",
"ObjectMultipartInfo",
"{",
"// Allo... | // listIncompleteUploads lists all incomplete uploads. | [
"listIncompleteUploads",
"lists",
"all",
"incomplete",
"uploads",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-list.go#L452-L537 | train |
minio/minio-go | api-list.go | listObjectParts | func (c Client) listObjectParts(bucketName, objectName, uploadID string) (partsInfo map[int]ObjectPart, err error) {
// Part number marker for the next batch of request.
var nextPartNumberMarker int
partsInfo = make(map[int]ObjectPart)
for {
// Get list of uploaded parts a maximum of 1000 per request.
listObjPartsResult, err := c.listObjectPartsQuery(bucketName, objectName, uploadID, nextPartNumberMarker, 1000)
if err != nil {
return nil, err
}
// Append to parts info.
for _, part := range listObjPartsResult.ObjectParts {
// Trim off the odd double quotes from ETag in the beginning and end.
part.ETag = strings.TrimPrefix(part.ETag, "\"")
part.ETag = strings.TrimSuffix(part.ETag, "\"")
partsInfo[part.PartNumber] = part
}
// Keep part number marker, for the next iteration.
nextPartNumberMarker = listObjPartsResult.NextPartNumberMarker
// Listing ends result is not truncated, return right here.
if !listObjPartsResult.IsTruncated {
break
}
}
// Return all the parts.
return partsInfo, nil
} | go | func (c Client) listObjectParts(bucketName, objectName, uploadID string) (partsInfo map[int]ObjectPart, err error) {
// Part number marker for the next batch of request.
var nextPartNumberMarker int
partsInfo = make(map[int]ObjectPart)
for {
// Get list of uploaded parts a maximum of 1000 per request.
listObjPartsResult, err := c.listObjectPartsQuery(bucketName, objectName, uploadID, nextPartNumberMarker, 1000)
if err != nil {
return nil, err
}
// Append to parts info.
for _, part := range listObjPartsResult.ObjectParts {
// Trim off the odd double quotes from ETag in the beginning and end.
part.ETag = strings.TrimPrefix(part.ETag, "\"")
part.ETag = strings.TrimSuffix(part.ETag, "\"")
partsInfo[part.PartNumber] = part
}
// Keep part number marker, for the next iteration.
nextPartNumberMarker = listObjPartsResult.NextPartNumberMarker
// Listing ends result is not truncated, return right here.
if !listObjPartsResult.IsTruncated {
break
}
}
// Return all the parts.
return partsInfo, nil
} | [
"func",
"(",
"c",
"Client",
")",
"listObjectParts",
"(",
"bucketName",
",",
"objectName",
",",
"uploadID",
"string",
")",
"(",
"partsInfo",
"map",
"[",
"int",
"]",
"ObjectPart",
",",
"err",
"error",
")",
"{",
"// Part number marker for the next batch of request.",... | // listObjectParts list all object parts recursively. | [
"listObjectParts",
"list",
"all",
"object",
"parts",
"recursively",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-list.go#L602-L629 | train |
minio/minio-go | api-list.go | findUploadIDs | func (c Client) findUploadIDs(bucketName, objectName string) ([]string, error) {
var uploadIDs []string
// Make list incomplete uploads recursive.
isRecursive := true
// Turn off size aggregation of individual parts, in this request.
isAggregateSize := false
// Create done channel to cleanup the routine.
doneCh := make(chan struct{})
defer close(doneCh)
// List all incomplete uploads.
for mpUpload := range c.listIncompleteUploads(bucketName, objectName, isRecursive, isAggregateSize, doneCh) {
if mpUpload.Err != nil {
return nil, mpUpload.Err
}
if objectName == mpUpload.Key {
uploadIDs = append(uploadIDs, mpUpload.UploadID)
}
}
// Return the latest upload id.
return uploadIDs, nil
} | go | func (c Client) findUploadIDs(bucketName, objectName string) ([]string, error) {
var uploadIDs []string
// Make list incomplete uploads recursive.
isRecursive := true
// Turn off size aggregation of individual parts, in this request.
isAggregateSize := false
// Create done channel to cleanup the routine.
doneCh := make(chan struct{})
defer close(doneCh)
// List all incomplete uploads.
for mpUpload := range c.listIncompleteUploads(bucketName, objectName, isRecursive, isAggregateSize, doneCh) {
if mpUpload.Err != nil {
return nil, mpUpload.Err
}
if objectName == mpUpload.Key {
uploadIDs = append(uploadIDs, mpUpload.UploadID)
}
}
// Return the latest upload id.
return uploadIDs, nil
} | [
"func",
"(",
"c",
"Client",
")",
"findUploadIDs",
"(",
"bucketName",
",",
"objectName",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"uploadIDs",
"[",
"]",
"string",
"\n",
"// Make list incomplete uploads recursive.",
"isRecursive",
"... | // findUploadIDs lists all incomplete uploads and find the uploadIDs of the matching object name. | [
"findUploadIDs",
"lists",
"all",
"incomplete",
"uploads",
"and",
"find",
"the",
"uploadIDs",
"of",
"the",
"matching",
"object",
"name",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-list.go#L632-L652 | train |
minio/minio-go | api-list.go | getTotalMultipartSize | func (c Client) getTotalMultipartSize(bucketName, objectName, uploadID string) (size int64, err error) {
// Iterate over all parts and aggregate the size.
partsInfo, err := c.listObjectParts(bucketName, objectName, uploadID)
if err != nil {
return 0, err
}
for _, partInfo := range partsInfo {
size += partInfo.Size
}
return size, nil
} | go | func (c Client) getTotalMultipartSize(bucketName, objectName, uploadID string) (size int64, err error) {
// Iterate over all parts and aggregate the size.
partsInfo, err := c.listObjectParts(bucketName, objectName, uploadID)
if err != nil {
return 0, err
}
for _, partInfo := range partsInfo {
size += partInfo.Size
}
return size, nil
} | [
"func",
"(",
"c",
"Client",
")",
"getTotalMultipartSize",
"(",
"bucketName",
",",
"objectName",
",",
"uploadID",
"string",
")",
"(",
"size",
"int64",
",",
"err",
"error",
")",
"{",
"// Iterate over all parts and aggregate the size.",
"partsInfo",
",",
"err",
":=",... | // getTotalMultipartSize - calculate total uploaded size for the a given multipart object. | [
"getTotalMultipartSize",
"-",
"calculate",
"total",
"uploaded",
"size",
"for",
"the",
"a",
"given",
"multipart",
"object",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-list.go#L655-L665 | train |
minio/minio-go | retry-continous.go | newRetryTimerContinous | func (c Client) newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
attemptCh := make(chan int)
// normalize jitter to the range [0, 1.0]
if jitter < NoJitter {
jitter = NoJitter
}
if jitter > MaxJitter {
jitter = MaxJitter
}
// computes the exponential backoff duration according to
// https://www.awsarchitectureblog.com/2015/03/backoff.html
exponentialBackoffWait := func(attempt int) time.Duration {
// 1<<uint(attempt) below could overflow, so limit the value of attempt
maxAttempt := 30
if attempt > maxAttempt {
attempt = maxAttempt
}
//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)
var nextBackoff int
for {
select {
// Attempts starts.
case attemptCh <- nextBackoff:
nextBackoff++
case <-doneCh:
// Stop the routine.
return
}
time.Sleep(exponentialBackoffWait(nextBackoff))
}
}()
return attemptCh
} | go | func (c Client) newRetryTimerContinous(unit time.Duration, cap time.Duration, jitter float64, doneCh chan struct{}) <-chan int {
attemptCh := make(chan int)
// normalize jitter to the range [0, 1.0]
if jitter < NoJitter {
jitter = NoJitter
}
if jitter > MaxJitter {
jitter = MaxJitter
}
// computes the exponential backoff duration according to
// https://www.awsarchitectureblog.com/2015/03/backoff.html
exponentialBackoffWait := func(attempt int) time.Duration {
// 1<<uint(attempt) below could overflow, so limit the value of attempt
maxAttempt := 30
if attempt > maxAttempt {
attempt = maxAttempt
}
//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)
var nextBackoff int
for {
select {
// Attempts starts.
case attemptCh <- nextBackoff:
nextBackoff++
case <-doneCh:
// Stop the routine.
return
}
time.Sleep(exponentialBackoffWait(nextBackoff))
}
}()
return attemptCh
} | [
"func",
"(",
"c",
"Client",
")",
"newRetryTimerContinous",
"(",
"unit",
"time",
".",
"Duration",
",",
"cap",
"time",
".",
"Duration",
",",
"jitter",
"float64",
",",
"doneCh",
"chan",
"struct",
"{",
"}",
")",
"<-",
"chan",
"int",
"{",
"attemptCh",
":=",
... | // newRetryTimerContinous creates a timer with exponentially increasing delays forever. | [
"newRetryTimerContinous",
"creates",
"a",
"timer",
"with",
"exponentially",
"increasing",
"delays",
"forever",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/retry-continous.go#L23-L69 | train |
minio/minio-go | pkg/credentials/iam_aws.go | NewIAM | func NewIAM(endpoint string) *Credentials {
p := &IAM{
Client: &http.Client{
Transport: http.DefaultTransport,
},
endpoint: endpoint,
}
return New(p)
} | go | func NewIAM(endpoint string) *Credentials {
p := &IAM{
Client: &http.Client{
Transport: http.DefaultTransport,
},
endpoint: endpoint,
}
return New(p)
} | [
"func",
"NewIAM",
"(",
"endpoint",
"string",
")",
"*",
"Credentials",
"{",
"p",
":=",
"&",
"IAM",
"{",
"Client",
":",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"http",
".",
"DefaultTransport",
",",
"}",
",",
"endpoint",
":",
"endpoint",
",",
... | // NewIAM returns a pointer to a new Credentials object wrapping the IAM. | [
"NewIAM",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"Credentials",
"object",
"wrapping",
"the",
"IAM",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/iam_aws.go#L71-L79 | train |
minio/minio-go | pkg/credentials/iam_aws.go | Retrieve | func (m *IAM) Retrieve() (Value, error) {
endpoint, isEcsTask := getEndpoint(m.endpoint)
var roleCreds ec2RoleCredRespBody
var err error
if isEcsTask {
roleCreds, err = getEcsTaskCredentials(m.Client, endpoint)
} else {
roleCreds, err = getCredentials(m.Client, endpoint)
}
if err != nil {
return Value{}, err
}
// Expiry window is set to 10secs.
m.SetExpiration(roleCreds.Expiration, DefaultExpiryWindow)
return Value{
AccessKeyID: roleCreds.AccessKeyID,
SecretAccessKey: roleCreds.SecretAccessKey,
SessionToken: roleCreds.Token,
SignerType: SignatureV4,
}, nil
} | go | func (m *IAM) Retrieve() (Value, error) {
endpoint, isEcsTask := getEndpoint(m.endpoint)
var roleCreds ec2RoleCredRespBody
var err error
if isEcsTask {
roleCreds, err = getEcsTaskCredentials(m.Client, endpoint)
} else {
roleCreds, err = getCredentials(m.Client, endpoint)
}
if err != nil {
return Value{}, err
}
// Expiry window is set to 10secs.
m.SetExpiration(roleCreds.Expiration, DefaultExpiryWindow)
return Value{
AccessKeyID: roleCreds.AccessKeyID,
SecretAccessKey: roleCreds.SecretAccessKey,
SessionToken: roleCreds.Token,
SignerType: SignatureV4,
}, nil
} | [
"func",
"(",
"m",
"*",
"IAM",
")",
"Retrieve",
"(",
")",
"(",
"Value",
",",
"error",
")",
"{",
"endpoint",
",",
"isEcsTask",
":=",
"getEndpoint",
"(",
"m",
".",
"endpoint",
")",
"\n",
"var",
"roleCreds",
"ec2RoleCredRespBody",
"\n",
"var",
"err",
"erro... | // Retrieve retrieves credentials from the EC2 service.
// Error will be returned if the request fails, or unable to extract
// the desired | [
"Retrieve",
"retrieves",
"credentials",
"from",
"the",
"EC2",
"service",
".",
"Error",
"will",
"be",
"returned",
"if",
"the",
"request",
"fails",
"or",
"unable",
"to",
"extract",
"the",
"desired"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/iam_aws.go#L84-L105 | train |
minio/minio-go | pkg/credentials/iam_aws.go | getCredentials | func getCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody, error) {
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
u, err := getIAMRoleURL(endpoint)
if err != nil {
return ec2RoleCredRespBody{}, err
}
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
roleNames, err := listRoleNames(client, u)
if err != nil {
return ec2RoleCredRespBody{}, err
}
if len(roleNames) == 0 {
return ec2RoleCredRespBody{}, errors.New("No IAM roles attached to this EC2 service")
}
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
// - An instance profile can contain only one IAM role. This limit cannot be increased.
roleName := roleNames[0]
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
// The following command retrieves the security credentials for an
// IAM role named `s3access`.
//
// $ curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
//
u.Path = path.Join(u.Path, roleName)
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return ec2RoleCredRespBody{}, err
}
resp, err := client.Do(req)
if err != nil {
return ec2RoleCredRespBody{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ec2RoleCredRespBody{}, errors.New(resp.Status)
}
respCreds := ec2RoleCredRespBody{}
if err := json.NewDecoder(resp.Body).Decode(&respCreds); err != nil {
return ec2RoleCredRespBody{}, err
}
if respCreds.Code != "Success" {
// If an error code was returned something failed requesting the role.
return ec2RoleCredRespBody{}, errors.New(respCreds.Message)
}
return respCreds, nil
} | go | func getCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody, error) {
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
u, err := getIAMRoleURL(endpoint)
if err != nil {
return ec2RoleCredRespBody{}, err
}
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
roleNames, err := listRoleNames(client, u)
if err != nil {
return ec2RoleCredRespBody{}, err
}
if len(roleNames) == 0 {
return ec2RoleCredRespBody{}, errors.New("No IAM roles attached to this EC2 service")
}
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
// - An instance profile can contain only one IAM role. This limit cannot be increased.
roleName := roleNames[0]
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
// The following command retrieves the security credentials for an
// IAM role named `s3access`.
//
// $ curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
//
u.Path = path.Join(u.Path, roleName)
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return ec2RoleCredRespBody{}, err
}
resp, err := client.Do(req)
if err != nil {
return ec2RoleCredRespBody{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ec2RoleCredRespBody{}, errors.New(resp.Status)
}
respCreds := ec2RoleCredRespBody{}
if err := json.NewDecoder(resp.Body).Decode(&respCreds); err != nil {
return ec2RoleCredRespBody{}, err
}
if respCreds.Code != "Success" {
// If an error code was returned something failed requesting the role.
return ec2RoleCredRespBody{}, errors.New(respCreds.Message)
}
return respCreds, nil
} | [
"func",
"getCredentials",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"endpoint",
"string",
")",
"(",
"ec2RoleCredRespBody",
",",
"error",
")",
"{",
"// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html",
"u",
",",
"err",
":=",
"getIAM... | // getCredentials - obtains the credentials from the IAM role name associated with
// the current EC2 service.
//
// If the credentials cannot be found, or there is an error
// reading the response an error will be returned. | [
"getCredentials",
"-",
"obtains",
"the",
"credentials",
"from",
"the",
"IAM",
"role",
"name",
"associated",
"with",
"the",
"current",
"EC2",
"service",
".",
"If",
"the",
"credentials",
"cannot",
"be",
"found",
"or",
"there",
"is",
"an",
"error",
"reading",
"... | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/iam_aws.go#L196-L250 | train |
minio/minio-go | api-put-object-copy.go | CopyObject | func (c Client) CopyObject(dst DestinationInfo, src SourceInfo) error {
return c.CopyObjectWithProgress(dst, src, nil)
} | go | func (c Client) CopyObject(dst DestinationInfo, src SourceInfo) error {
return c.CopyObjectWithProgress(dst, src, nil)
} | [
"func",
"(",
"c",
"Client",
")",
"CopyObject",
"(",
"dst",
"DestinationInfo",
",",
"src",
"SourceInfo",
")",
"error",
"{",
"return",
"c",
".",
"CopyObjectWithProgress",
"(",
"dst",
",",
"src",
",",
"nil",
")",
"\n",
"}"
] | // CopyObject - copy a source object into a new object | [
"CopyObject",
"-",
"copy",
"a",
"source",
"object",
"into",
"a",
"new",
"object"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-copy.go#L30-L32 | train |
minio/minio-go | api-put-object-copy.go | CopyObjectWithProgress | func (c Client) CopyObjectWithProgress(dst DestinationInfo, src SourceInfo, progress io.Reader) error {
header := make(http.Header)
for k, v := range src.Headers {
header[k] = v
}
var err error
var size int64
// If progress bar is specified, size should be requested as well initiate a StatObject request.
if progress != nil {
size, _, _, err = src.getProps(c)
if err != nil {
return err
}
}
if src.encryption != nil {
encrypt.SSECopy(src.encryption).Marshal(header)
}
if dst.encryption != nil {
dst.encryption.Marshal(header)
}
for k, v := range dst.getUserMetaHeadersMap(true) {
header.Set(k, v)
}
resp, err := c.executeMethod(context.Background(), "PUT", requestMetadata{
bucketName: dst.bucket,
objectName: dst.object,
customHeader: header,
})
if err != nil {
return err
}
defer closeResponse(resp)
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp, dst.bucket, dst.object)
}
// Update the progress properly after successful copy.
if progress != nil {
io.CopyN(ioutil.Discard, progress, size)
}
return nil
} | go | func (c Client) CopyObjectWithProgress(dst DestinationInfo, src SourceInfo, progress io.Reader) error {
header := make(http.Header)
for k, v := range src.Headers {
header[k] = v
}
var err error
var size int64
// If progress bar is specified, size should be requested as well initiate a StatObject request.
if progress != nil {
size, _, _, err = src.getProps(c)
if err != nil {
return err
}
}
if src.encryption != nil {
encrypt.SSECopy(src.encryption).Marshal(header)
}
if dst.encryption != nil {
dst.encryption.Marshal(header)
}
for k, v := range dst.getUserMetaHeadersMap(true) {
header.Set(k, v)
}
resp, err := c.executeMethod(context.Background(), "PUT", requestMetadata{
bucketName: dst.bucket,
objectName: dst.object,
customHeader: header,
})
if err != nil {
return err
}
defer closeResponse(resp)
if resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp, dst.bucket, dst.object)
}
// Update the progress properly after successful copy.
if progress != nil {
io.CopyN(ioutil.Discard, progress, size)
}
return nil
} | [
"func",
"(",
"c",
"Client",
")",
"CopyObjectWithProgress",
"(",
"dst",
"DestinationInfo",
",",
"src",
"SourceInfo",
",",
"progress",
"io",
".",
"Reader",
")",
"error",
"{",
"header",
":=",
"make",
"(",
"http",
".",
"Header",
")",
"\n",
"for",
"k",
",",
... | // CopyObjectWithProgress - copy a source object into a new object, optionally takes
// progress bar input to notify current progress. | [
"CopyObjectWithProgress",
"-",
"copy",
"a",
"source",
"object",
"into",
"a",
"new",
"object",
"optionally",
"takes",
"progress",
"bar",
"input",
"to",
"notify",
"current",
"progress",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-copy.go#L36-L83 | train |
minio/minio-go | api-put-object-file.go | FPutObject | func (c Client) FPutObject(bucketName, objectName, filePath string, opts PutObjectOptions) (n int64, err error) {
return c.FPutObjectWithContext(context.Background(), bucketName, objectName, filePath, opts)
} | go | func (c Client) FPutObject(bucketName, objectName, filePath string, opts PutObjectOptions) (n int64, err error) {
return c.FPutObjectWithContext(context.Background(), bucketName, objectName, filePath, opts)
} | [
"func",
"(",
"c",
"Client",
")",
"FPutObject",
"(",
"bucketName",
",",
"objectName",
",",
"filePath",
"string",
",",
"opts",
"PutObjectOptions",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"return",
"c",
".",
"FPutObjectWithContext",
"(",
"conte... | // FPutObject - Create an object in a bucket, with contents from file at filePath | [
"FPutObject",
"-",
"Create",
"an",
"object",
"in",
"a",
"bucket",
"with",
"contents",
"from",
"file",
"at",
"filePath"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-file.go#L25-L27 | train |
minio/minio-go | s3-endpoints.go | getS3Endpoint | func getS3Endpoint(bucketLocation string) (s3Endpoint string) {
s3Endpoint, ok := awsS3EndpointMap[bucketLocation]
if !ok {
// Default to 's3.dualstack.us-east-1.amazonaws.com' endpoint.
s3Endpoint = "s3.dualstack.us-east-1.amazonaws.com"
}
return s3Endpoint
} | go | func getS3Endpoint(bucketLocation string) (s3Endpoint string) {
s3Endpoint, ok := awsS3EndpointMap[bucketLocation]
if !ok {
// Default to 's3.dualstack.us-east-1.amazonaws.com' endpoint.
s3Endpoint = "s3.dualstack.us-east-1.amazonaws.com"
}
return s3Endpoint
} | [
"func",
"getS3Endpoint",
"(",
"bucketLocation",
"string",
")",
"(",
"s3Endpoint",
"string",
")",
"{",
"s3Endpoint",
",",
"ok",
":=",
"awsS3EndpointMap",
"[",
"bucketLocation",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// Default to 's3.dualstack.us-east-1.amazonaws.com' endpo... | // getS3Endpoint get Amazon S3 endpoint based on the bucket location. | [
"getS3Endpoint",
"get",
"Amazon",
"S3",
"endpoint",
"based",
"on",
"the",
"bucket",
"location",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/s3-endpoints.go#L45-L52 | train |
minio/minio-go | api-get-policy.go | GetBucketPolicy | func (c Client) GetBucketPolicy(bucketName string) (string, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return "", err
}
bucketPolicy, err := c.getBucketPolicy(bucketName)
if err != nil {
errResponse := ToErrorResponse(err)
if errResponse.Code == "NoSuchBucketPolicy" {
return "", nil
}
return "", err
}
return bucketPolicy, nil
} | go | func (c Client) GetBucketPolicy(bucketName string) (string, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return "", err
}
bucketPolicy, err := c.getBucketPolicy(bucketName)
if err != nil {
errResponse := ToErrorResponse(err)
if errResponse.Code == "NoSuchBucketPolicy" {
return "", nil
}
return "", err
}
return bucketPolicy, nil
} | [
"func",
"(",
"c",
"Client",
")",
"GetBucketPolicy",
"(",
"bucketName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Input validation.",
"if",
"err",
":=",
"s3utils",
".",
"CheckValidBucketName",
"(",
"bucketName",
")",
";",
"err",
"!=",
"nil",
... | // GetBucketPolicy - get bucket policy at a given path. | [
"GetBucketPolicy",
"-",
"get",
"bucket",
"policy",
"at",
"a",
"given",
"path",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-policy.go#L30-L44 | train |
minio/minio-go | api-get-policy.go | getBucketPolicy | func (c Client) getBucketPolicy(bucketName string) (string, error) {
// Get resources properly escaped and lined up before
// using them in http request.
urlValues := make(url.Values)
urlValues.Set("policy", "")
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return "", err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return "", httpRespToErrorResponse(resp, bucketName, "")
}
}
bucketPolicyBuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
policy := string(bucketPolicyBuf)
return policy, err
} | go | func (c Client) getBucketPolicy(bucketName string) (string, error) {
// Get resources properly escaped and lined up before
// using them in http request.
urlValues := make(url.Values)
urlValues.Set("policy", "")
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return "", err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return "", httpRespToErrorResponse(resp, bucketName, "")
}
}
bucketPolicyBuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
policy := string(bucketPolicyBuf)
return policy, err
} | [
"func",
"(",
"c",
"Client",
")",
"getBucketPolicy",
"(",
"bucketName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Get resources properly escaped and lined up before",
"// using them in http request.",
"urlValues",
":=",
"make",
"(",
"url",
".",
"Values"... | // Request server for current bucket policy. | [
"Request",
"server",
"for",
"current",
"bucket",
"policy",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-policy.go#L47-L78 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | getSignedChunkLength | func getSignedChunkLength(chunkDataSize int64) int64 {
return int64(len(fmt.Sprintf("%x", chunkDataSize))) +
chunkSigConstLen +
signatureStrLen +
crlfLen +
chunkDataSize +
crlfLen
} | go | func getSignedChunkLength(chunkDataSize int64) int64 {
return int64(len(fmt.Sprintf("%x", chunkDataSize))) +
chunkSigConstLen +
signatureStrLen +
crlfLen +
chunkDataSize +
crlfLen
} | [
"func",
"getSignedChunkLength",
"(",
"chunkDataSize",
"int64",
")",
"int64",
"{",
"return",
"int64",
"(",
"len",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"chunkDataSize",
")",
")",
")",
"+",
"chunkSigConstLen",
"+",
"signatureStrLen",
"+",
"crlfLen"... | // getSignedChunkLength - calculates the length of chunk metadata | [
"getSignedChunkLength",
"-",
"calculates",
"the",
"length",
"of",
"chunk",
"metadata"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L53-L60 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | buildChunkStringToSign | func buildChunkStringToSign(t time.Time, region, previousSig string, chunkData []byte) string {
stringToSignParts := []string{
streamingPayloadHdr,
t.Format(iso8601DateFormat),
getScope(region, t),
previousSig,
emptySHA256,
hex.EncodeToString(sum256(chunkData)),
}
return strings.Join(stringToSignParts, "\n")
} | go | func buildChunkStringToSign(t time.Time, region, previousSig string, chunkData []byte) string {
stringToSignParts := []string{
streamingPayloadHdr,
t.Format(iso8601DateFormat),
getScope(region, t),
previousSig,
emptySHA256,
hex.EncodeToString(sum256(chunkData)),
}
return strings.Join(stringToSignParts, "\n")
} | [
"func",
"buildChunkStringToSign",
"(",
"t",
"time",
".",
"Time",
",",
"region",
",",
"previousSig",
"string",
",",
"chunkData",
"[",
"]",
"byte",
")",
"string",
"{",
"stringToSignParts",
":=",
"[",
"]",
"string",
"{",
"streamingPayloadHdr",
",",
"t",
".",
... | // buildChunkStringToSign - returns the string to sign given chunk data
// and previous signature. | [
"buildChunkStringToSign",
"-",
"returns",
"the",
"string",
"to",
"sign",
"given",
"chunk",
"data",
"and",
"previous",
"signature",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L81-L92 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | prepareStreamingRequest | func prepareStreamingRequest(req *http.Request, sessionToken string, dataLen int64, timestamp time.Time) {
// Set x-amz-content-sha256 header.
req.Header.Set("X-Amz-Content-Sha256", streamingSignAlgorithm)
if sessionToken != "" {
req.Header.Set("X-Amz-Security-Token", sessionToken)
}
req.Header.Set("X-Amz-Date", timestamp.Format(iso8601DateFormat))
// Set content length with streaming signature for each chunk included.
req.ContentLength = getStreamLength(dataLen, int64(payloadChunkSize))
req.Header.Set("x-amz-decoded-content-length", strconv.FormatInt(dataLen, 10))
} | go | func prepareStreamingRequest(req *http.Request, sessionToken string, dataLen int64, timestamp time.Time) {
// Set x-amz-content-sha256 header.
req.Header.Set("X-Amz-Content-Sha256", streamingSignAlgorithm)
if sessionToken != "" {
req.Header.Set("X-Amz-Security-Token", sessionToken)
}
req.Header.Set("X-Amz-Date", timestamp.Format(iso8601DateFormat))
// Set content length with streaming signature for each chunk included.
req.ContentLength = getStreamLength(dataLen, int64(payloadChunkSize))
req.Header.Set("x-amz-decoded-content-length", strconv.FormatInt(dataLen, 10))
} | [
"func",
"prepareStreamingRequest",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"sessionToken",
"string",
",",
"dataLen",
"int64",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"// Set x-amz-content-sha256 header.",
"req",
".",
"Header",
".",
"Set",
"(",
"... | // prepareStreamingRequest - prepares a request with appropriate
// headers before computing the seed signature. | [
"prepareStreamingRequest",
"-",
"prepares",
"a",
"request",
"with",
"appropriate",
"headers",
"before",
"computing",
"the",
"seed",
"signature",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L96-L107 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | buildChunkSignature | func buildChunkSignature(chunkData []byte, reqTime time.Time, region,
previousSignature, secretAccessKey string) string {
chunkStringToSign := buildChunkStringToSign(reqTime, region,
previousSignature, chunkData)
signingKey := getSigningKey(secretAccessKey, region, reqTime)
return getSignature(signingKey, chunkStringToSign)
} | go | func buildChunkSignature(chunkData []byte, reqTime time.Time, region,
previousSignature, secretAccessKey string) string {
chunkStringToSign := buildChunkStringToSign(reqTime, region,
previousSignature, chunkData)
signingKey := getSigningKey(secretAccessKey, region, reqTime)
return getSignature(signingKey, chunkStringToSign)
} | [
"func",
"buildChunkSignature",
"(",
"chunkData",
"[",
"]",
"byte",
",",
"reqTime",
"time",
".",
"Time",
",",
"region",
",",
"previousSignature",
",",
"secretAccessKey",
"string",
")",
"string",
"{",
"chunkStringToSign",
":=",
"buildChunkStringToSign",
"(",
"reqTim... | // buildChunkSignature - returns chunk signature for a given chunk and previous signature. | [
"buildChunkSignature",
"-",
"returns",
"chunk",
"signature",
"for",
"a",
"given",
"chunk",
"and",
"previous",
"signature",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L116-L123 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | setSeedSignature | func (s *StreamingReader) setSeedSignature(req *http.Request) {
// Get canonical request
canonicalRequest := getCanonicalRequest(*req, ignoredStreamingHeaders)
// Get string to sign from canonical request.
stringToSign := getStringToSignV4(s.reqTime, s.region, canonicalRequest)
signingKey := getSigningKey(s.secretAccessKey, s.region, s.reqTime)
// Calculate signature.
s.seedSignature = getSignature(signingKey, stringToSign)
} | go | func (s *StreamingReader) setSeedSignature(req *http.Request) {
// Get canonical request
canonicalRequest := getCanonicalRequest(*req, ignoredStreamingHeaders)
// Get string to sign from canonical request.
stringToSign := getStringToSignV4(s.reqTime, s.region, canonicalRequest)
signingKey := getSigningKey(s.secretAccessKey, s.region, s.reqTime)
// Calculate signature.
s.seedSignature = getSignature(signingKey, stringToSign)
} | [
"func",
"(",
"s",
"*",
"StreamingReader",
")",
"setSeedSignature",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"// Get canonical request",
"canonicalRequest",
":=",
"getCanonicalRequest",
"(",
"*",
"req",
",",
"ignoredStreamingHeaders",
")",
"\n\n",
"// Get... | // getSeedSignature - returns the seed signature for a given request. | [
"getSeedSignature",
"-",
"returns",
"the",
"seed",
"signature",
"for",
"a",
"given",
"request",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L126-L137 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | signChunk | func (s *StreamingReader) signChunk(chunkLen int) {
// Compute chunk signature for next header
signature := buildChunkSignature(s.chunkBuf[:chunkLen], s.reqTime,
s.region, s.prevSignature, s.secretAccessKey)
// For next chunk signature computation
s.prevSignature = signature
// Write chunk header into streaming buffer
chunkHdr := buildChunkHeader(int64(chunkLen), signature)
s.buf.Write(chunkHdr)
// Write chunk data into streaming buffer
s.buf.Write(s.chunkBuf[:chunkLen])
// Write the chunk trailer.
s.buf.Write([]byte("\r\n"))
// Reset chunkBufLen for next chunk read.
s.chunkBufLen = 0
s.chunkNum++
} | go | func (s *StreamingReader) signChunk(chunkLen int) {
// Compute chunk signature for next header
signature := buildChunkSignature(s.chunkBuf[:chunkLen], s.reqTime,
s.region, s.prevSignature, s.secretAccessKey)
// For next chunk signature computation
s.prevSignature = signature
// Write chunk header into streaming buffer
chunkHdr := buildChunkHeader(int64(chunkLen), signature)
s.buf.Write(chunkHdr)
// Write chunk data into streaming buffer
s.buf.Write(s.chunkBuf[:chunkLen])
// Write the chunk trailer.
s.buf.Write([]byte("\r\n"))
// Reset chunkBufLen for next chunk read.
s.chunkBufLen = 0
s.chunkNum++
} | [
"func",
"(",
"s",
"*",
"StreamingReader",
")",
"signChunk",
"(",
"chunkLen",
"int",
")",
"{",
"// Compute chunk signature for next header",
"signature",
":=",
"buildChunkSignature",
"(",
"s",
".",
"chunkBuf",
"[",
":",
"chunkLen",
"]",
",",
"s",
".",
"reqTime",
... | // signChunk - signs a chunk read from s.baseReader of chunkLen size. | [
"signChunk",
"-",
"signs",
"a",
"chunk",
"read",
"from",
"s",
".",
"baseReader",
"of",
"chunkLen",
"size",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L162-L183 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | setStreamingAuthHeader | func (s *StreamingReader) setStreamingAuthHeader(req *http.Request) {
credential := GetCredential(s.accessKeyID, s.region, s.reqTime)
authParts := []string{
signV4Algorithm + " Credential=" + credential,
"SignedHeaders=" + getSignedHeaders(*req, ignoredStreamingHeaders),
"Signature=" + s.seedSignature,
}
// Set authorization header.
auth := strings.Join(authParts, ",")
req.Header.Set("Authorization", auth)
} | go | func (s *StreamingReader) setStreamingAuthHeader(req *http.Request) {
credential := GetCredential(s.accessKeyID, s.region, s.reqTime)
authParts := []string{
signV4Algorithm + " Credential=" + credential,
"SignedHeaders=" + getSignedHeaders(*req, ignoredStreamingHeaders),
"Signature=" + s.seedSignature,
}
// Set authorization header.
auth := strings.Join(authParts, ",")
req.Header.Set("Authorization", auth)
} | [
"func",
"(",
"s",
"*",
"StreamingReader",
")",
"setStreamingAuthHeader",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"credential",
":=",
"GetCredential",
"(",
"s",
".",
"accessKeyID",
",",
"s",
".",
"region",
",",
"s",
".",
"reqTime",
")",
"\n",
... | // setStreamingAuthHeader - builds and sets authorization header value
// for streaming signature. | [
"setStreamingAuthHeader",
"-",
"builds",
"and",
"sets",
"authorization",
"header",
"value",
"for",
"streaming",
"signature",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L187-L198 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | StreamingSignV4 | func StreamingSignV4(req *http.Request, accessKeyID, secretAccessKey, sessionToken,
region string, dataLen int64, reqTime time.Time) *http.Request {
// Set headers needed for streaming signature.
prepareStreamingRequest(req, sessionToken, dataLen, reqTime)
if req.Body == nil {
req.Body = ioutil.NopCloser(bytes.NewReader([]byte("")))
}
stReader := &StreamingReader{
baseReadCloser: req.Body,
accessKeyID: accessKeyID,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
region: region,
reqTime: reqTime,
chunkBuf: make([]byte, payloadChunkSize),
contentLen: dataLen,
chunkNum: 1,
totalChunks: int((dataLen+payloadChunkSize-1)/payloadChunkSize) + 1,
lastChunkSize: int(dataLen % payloadChunkSize),
}
// Add the request headers required for chunk upload signing.
// Compute the seed signature.
stReader.setSeedSignature(req)
// Set the authorization header with the seed signature.
stReader.setStreamingAuthHeader(req)
// Set seed signature as prevSignature for subsequent
// streaming signing process.
stReader.prevSignature = stReader.seedSignature
req.Body = stReader
return req
} | go | func StreamingSignV4(req *http.Request, accessKeyID, secretAccessKey, sessionToken,
region string, dataLen int64, reqTime time.Time) *http.Request {
// Set headers needed for streaming signature.
prepareStreamingRequest(req, sessionToken, dataLen, reqTime)
if req.Body == nil {
req.Body = ioutil.NopCloser(bytes.NewReader([]byte("")))
}
stReader := &StreamingReader{
baseReadCloser: req.Body,
accessKeyID: accessKeyID,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
region: region,
reqTime: reqTime,
chunkBuf: make([]byte, payloadChunkSize),
contentLen: dataLen,
chunkNum: 1,
totalChunks: int((dataLen+payloadChunkSize-1)/payloadChunkSize) + 1,
lastChunkSize: int(dataLen % payloadChunkSize),
}
// Add the request headers required for chunk upload signing.
// Compute the seed signature.
stReader.setSeedSignature(req)
// Set the authorization header with the seed signature.
stReader.setStreamingAuthHeader(req)
// Set seed signature as prevSignature for subsequent
// streaming signing process.
stReader.prevSignature = stReader.seedSignature
req.Body = stReader
return req
} | [
"func",
"StreamingSignV4",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"accessKeyID",
",",
"secretAccessKey",
",",
"sessionToken",
",",
"region",
"string",
",",
"dataLen",
"int64",
",",
"reqTime",
"time",
".",
"Time",
")",
"*",
"http",
".",
"Request",
"{... | // StreamingSignV4 - provides chunked upload signatureV4 support by
// implementing io.Reader. | [
"StreamingSignV4",
"-",
"provides",
"chunked",
"upload",
"signatureV4",
"support",
"by",
"implementing",
"io",
".",
"Reader",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L202-L240 | train |
minio/minio-go | pkg/s3signer/request-signature-streaming.go | Read | func (s *StreamingReader) Read(buf []byte) (int, error) {
switch {
// After the last chunk is read from underlying reader, we
// never re-fill s.buf.
case s.done:
// s.buf will be (re-)filled with next chunk when has lesser
// bytes than asked for.
case s.buf.Len() < len(buf):
s.chunkBufLen = 0
for {
n1, err := s.baseReadCloser.Read(s.chunkBuf[s.chunkBufLen:])
// Usually we validate `err` first, but in this case
// we are validating n > 0 for the following reasons.
//
// 1. n > 0, err is one of io.EOF, nil (near end of stream)
// A Reader returning a non-zero number of bytes at the end
// of the input stream may return either err == EOF or err == nil
//
// 2. n == 0, err is io.EOF (actual end of stream)
//
// Callers should always process the n > 0 bytes returned
// before considering the error err.
if n1 > 0 {
s.chunkBufLen += n1
s.bytesRead += int64(n1)
if s.chunkBufLen == payloadChunkSize ||
(s.chunkNum == s.totalChunks-1 &&
s.chunkBufLen == s.lastChunkSize) {
// Sign the chunk and write it to s.buf.
s.signChunk(s.chunkBufLen)
break
}
}
if err != nil {
if err == io.EOF {
// No more data left in baseReader - last chunk.
// Done reading the last chunk from baseReader.
s.done = true
// bytes read from baseReader different than
// content length provided.
if s.bytesRead != s.contentLen {
return 0, io.ErrUnexpectedEOF
}
// Sign the chunk and write it to s.buf.
s.signChunk(0)
break
}
return 0, err
}
}
}
return s.buf.Read(buf)
} | go | func (s *StreamingReader) Read(buf []byte) (int, error) {
switch {
// After the last chunk is read from underlying reader, we
// never re-fill s.buf.
case s.done:
// s.buf will be (re-)filled with next chunk when has lesser
// bytes than asked for.
case s.buf.Len() < len(buf):
s.chunkBufLen = 0
for {
n1, err := s.baseReadCloser.Read(s.chunkBuf[s.chunkBufLen:])
// Usually we validate `err` first, but in this case
// we are validating n > 0 for the following reasons.
//
// 1. n > 0, err is one of io.EOF, nil (near end of stream)
// A Reader returning a non-zero number of bytes at the end
// of the input stream may return either err == EOF or err == nil
//
// 2. n == 0, err is io.EOF (actual end of stream)
//
// Callers should always process the n > 0 bytes returned
// before considering the error err.
if n1 > 0 {
s.chunkBufLen += n1
s.bytesRead += int64(n1)
if s.chunkBufLen == payloadChunkSize ||
(s.chunkNum == s.totalChunks-1 &&
s.chunkBufLen == s.lastChunkSize) {
// Sign the chunk and write it to s.buf.
s.signChunk(s.chunkBufLen)
break
}
}
if err != nil {
if err == io.EOF {
// No more data left in baseReader - last chunk.
// Done reading the last chunk from baseReader.
s.done = true
// bytes read from baseReader different than
// content length provided.
if s.bytesRead != s.contentLen {
return 0, io.ErrUnexpectedEOF
}
// Sign the chunk and write it to s.buf.
s.signChunk(0)
break
}
return 0, err
}
}
}
return s.buf.Read(buf)
} | [
"func",
"(",
"s",
"*",
"StreamingReader",
")",
"Read",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"switch",
"{",
"// After the last chunk is read from underlying reader, we",
"// never re-fill s.buf.",
"case",
"s",
".",
"done",
":",
... | // Read - this method performs chunk upload signature providing a
// io.Reader interface. | [
"Read",
"-",
"this",
"method",
"performs",
"chunk",
"upload",
"signature",
"providing",
"a",
"io",
".",
"Reader",
"interface",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-streaming.go#L244-L301 | train |
minio/minio-go | api-notification.go | GetBucketNotification | func (c Client) GetBucketNotification(bucketName string) (bucketNotification BucketNotification, err error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return BucketNotification{}, err
}
notification, err := c.getBucketNotification(bucketName)
if err != nil {
return BucketNotification{}, err
}
return notification, nil
} | go | func (c Client) GetBucketNotification(bucketName string) (bucketNotification BucketNotification, err error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return BucketNotification{}, err
}
notification, err := c.getBucketNotification(bucketName)
if err != nil {
return BucketNotification{}, err
}
return notification, nil
} | [
"func",
"(",
"c",
"Client",
")",
"GetBucketNotification",
"(",
"bucketName",
"string",
")",
"(",
"bucketNotification",
"BucketNotification",
",",
"err",
"error",
")",
"{",
"// Input validation.",
"if",
"err",
":=",
"s3utils",
".",
"CheckValidBucketName",
"(",
"buc... | // GetBucketNotification - get bucket notification at a given path. | [
"GetBucketNotification",
"-",
"get",
"bucket",
"notification",
"at",
"a",
"given",
"path",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-notification.go#L33-L43 | train |
minio/minio-go | api-notification.go | getBucketNotification | func (c Client) getBucketNotification(bucketName string) (BucketNotification, error) {
urlValues := make(url.Values)
urlValues.Set("notification", "")
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return BucketNotification{}, err
}
return processBucketNotificationResponse(bucketName, resp)
} | go | func (c Client) getBucketNotification(bucketName string) (BucketNotification, error) {
urlValues := make(url.Values)
urlValues.Set("notification", "")
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return BucketNotification{}, err
}
return processBucketNotificationResponse(bucketName, resp)
} | [
"func",
"(",
"c",
"Client",
")",
"getBucketNotification",
"(",
"bucketName",
"string",
")",
"(",
"BucketNotification",
",",
"error",
")",
"{",
"urlValues",
":=",
"make",
"(",
"url",
".",
"Values",
")",
"\n",
"urlValues",
".",
"Set",
"(",
"\"",
"\"",
",",... | // Request server for notification rules. | [
"Request",
"server",
"for",
"notification",
"rules",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-notification.go#L46-L63 | train |
minio/minio-go | api-notification.go | processBucketNotificationResponse | func processBucketNotificationResponse(bucketName string, resp *http.Response) (BucketNotification, error) {
if resp.StatusCode != http.StatusOK {
errResponse := httpRespToErrorResponse(resp, bucketName, "")
return BucketNotification{}, errResponse
}
var bucketNotification BucketNotification
err := xmlDecoder(resp.Body, &bucketNotification)
if err != nil {
return BucketNotification{}, err
}
return bucketNotification, nil
} | go | func processBucketNotificationResponse(bucketName string, resp *http.Response) (BucketNotification, error) {
if resp.StatusCode != http.StatusOK {
errResponse := httpRespToErrorResponse(resp, bucketName, "")
return BucketNotification{}, errResponse
}
var bucketNotification BucketNotification
err := xmlDecoder(resp.Body, &bucketNotification)
if err != nil {
return BucketNotification{}, err
}
return bucketNotification, nil
} | [
"func",
"processBucketNotificationResponse",
"(",
"bucketName",
"string",
",",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"BucketNotification",
",",
"error",
")",
"{",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"errResponse",
":=... | // processes the GetNotification http response from the server. | [
"processes",
"the",
"GetNotification",
"http",
"response",
"from",
"the",
"server",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-notification.go#L66-L77 | train |
minio/minio-go | api-notification.go | ListenBucketNotification | func (c Client) ListenBucketNotification(bucketName, prefix, suffix string, events []string, doneCh <-chan struct{}) <-chan NotificationInfo {
notificationInfoCh := make(chan NotificationInfo, 1)
// Only success, start a routine to start reading line by line.
go func(notificationInfoCh chan<- NotificationInfo) {
defer close(notificationInfoCh)
// Validate the bucket name.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
notificationInfoCh <- NotificationInfo{
Err: err,
}
return
}
// Check ARN partition to verify if listening bucket is supported
if s3utils.IsAmazonEndpoint(*c.endpointURL) || s3utils.IsGoogleEndpoint(*c.endpointURL) {
notificationInfoCh <- NotificationInfo{
Err: ErrAPINotSupported("Listening for bucket notification is specific only to `minio` server endpoints"),
}
return
}
// Continuously run and listen on bucket notification.
// Create a done channel to control 'ListObjects' go routine.
retryDoneCh := make(chan struct{}, 1)
// Indicate to our routine to exit cleanly upon return.
defer close(retryDoneCh)
// Wait on the jitter retry loop.
for range c.newRetryTimerContinous(time.Second, time.Second*30, MaxJitter, retryDoneCh) {
urlValues := make(url.Values)
urlValues.Set("prefix", prefix)
urlValues.Set("suffix", suffix)
urlValues["events"] = events
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
if err != nil {
notificationInfoCh <- NotificationInfo{
Err: err,
}
return
}
// Validate http response, upon error return quickly.
if resp.StatusCode != http.StatusOK {
errResponse := httpRespToErrorResponse(resp, bucketName, "")
notificationInfoCh <- NotificationInfo{
Err: errResponse,
}
return
}
// Initialize a new bufio scanner, to read line by line.
bio := bufio.NewScanner(resp.Body)
// Close the response body.
defer resp.Body.Close()
// Unmarshal each line, returns marshalled values.
for bio.Scan() {
var notificationInfo NotificationInfo
if err = json.Unmarshal(bio.Bytes(), ¬ificationInfo); err != nil {
continue
}
// Send notificationInfo
select {
case notificationInfoCh <- notificationInfo:
case <-doneCh:
return
}
}
// Look for any underlying errors.
if err = bio.Err(); err != nil {
// For an unexpected connection drop from server, we close the body
// and re-connect.
if err == io.ErrUnexpectedEOF {
resp.Body.Close()
}
}
}
}(notificationInfoCh)
// Returns the notification info channel, for caller to start reading from.
return notificationInfoCh
} | go | func (c Client) ListenBucketNotification(bucketName, prefix, suffix string, events []string, doneCh <-chan struct{}) <-chan NotificationInfo {
notificationInfoCh := make(chan NotificationInfo, 1)
// Only success, start a routine to start reading line by line.
go func(notificationInfoCh chan<- NotificationInfo) {
defer close(notificationInfoCh)
// Validate the bucket name.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
notificationInfoCh <- NotificationInfo{
Err: err,
}
return
}
// Check ARN partition to verify if listening bucket is supported
if s3utils.IsAmazonEndpoint(*c.endpointURL) || s3utils.IsGoogleEndpoint(*c.endpointURL) {
notificationInfoCh <- NotificationInfo{
Err: ErrAPINotSupported("Listening for bucket notification is specific only to `minio` server endpoints"),
}
return
}
// Continuously run and listen on bucket notification.
// Create a done channel to control 'ListObjects' go routine.
retryDoneCh := make(chan struct{}, 1)
// Indicate to our routine to exit cleanly upon return.
defer close(retryDoneCh)
// Wait on the jitter retry loop.
for range c.newRetryTimerContinous(time.Second, time.Second*30, MaxJitter, retryDoneCh) {
urlValues := make(url.Values)
urlValues.Set("prefix", prefix)
urlValues.Set("suffix", suffix)
urlValues["events"] = events
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
if err != nil {
notificationInfoCh <- NotificationInfo{
Err: err,
}
return
}
// Validate http response, upon error return quickly.
if resp.StatusCode != http.StatusOK {
errResponse := httpRespToErrorResponse(resp, bucketName, "")
notificationInfoCh <- NotificationInfo{
Err: errResponse,
}
return
}
// Initialize a new bufio scanner, to read line by line.
bio := bufio.NewScanner(resp.Body)
// Close the response body.
defer resp.Body.Close()
// Unmarshal each line, returns marshalled values.
for bio.Scan() {
var notificationInfo NotificationInfo
if err = json.Unmarshal(bio.Bytes(), ¬ificationInfo); err != nil {
continue
}
// Send notificationInfo
select {
case notificationInfoCh <- notificationInfo:
case <-doneCh:
return
}
}
// Look for any underlying errors.
if err = bio.Err(); err != nil {
// For an unexpected connection drop from server, we close the body
// and re-connect.
if err == io.ErrUnexpectedEOF {
resp.Body.Close()
}
}
}
}(notificationInfoCh)
// Returns the notification info channel, for caller to start reading from.
return notificationInfoCh
} | [
"func",
"(",
"c",
"Client",
")",
"ListenBucketNotification",
"(",
"bucketName",
",",
"prefix",
",",
"suffix",
"string",
",",
"events",
"[",
"]",
"string",
",",
"doneCh",
"<-",
"chan",
"struct",
"{",
"}",
")",
"<-",
"chan",
"NotificationInfo",
"{",
"notific... | // ListenBucketNotification - listen on bucket notifications. | [
"ListenBucketNotification",
"-",
"listen",
"on",
"bucket",
"notifications",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-notification.go#L138-L228 | train |
minio/minio-go | pkg/credentials/signature-type.go | String | func (s SignatureType) String() string {
if s.IsV2() {
return "S3v2"
} else if s.IsV4() {
return "S3v4"
} else if s.IsStreamingV4() {
return "S3v4Streaming"
}
return "Anonymous"
} | go | func (s SignatureType) String() string {
if s.IsV2() {
return "S3v2"
} else if s.IsV4() {
return "S3v4"
} else if s.IsStreamingV4() {
return "S3v4Streaming"
}
return "Anonymous"
} | [
"func",
"(",
"s",
"SignatureType",
")",
"String",
"(",
")",
"string",
"{",
"if",
"s",
".",
"IsV2",
"(",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"s",
".",
"IsV4",
"(",
")",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"... | // Stringer humanized version of signature type,
// strings returned here are case insensitive. | [
"Stringer",
"humanized",
"version",
"of",
"signature",
"type",
"strings",
"returned",
"here",
"are",
"case",
"insensitive",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/signature-type.go#L57-L66 | train |
minio/minio-go | pkg/s3signer/utils.go | getHostAddr | func getHostAddr(req *http.Request) string {
if req.Host != "" {
return req.Host
}
return req.URL.Host
} | go | func getHostAddr(req *http.Request) string {
if req.Host != "" {
return req.Host
}
return req.URL.Host
} | [
"func",
"getHostAddr",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"if",
"req",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"return",
"req",
".",
"Host",
"\n",
"}",
"\n",
"return",
"req",
".",
"URL",
".",
"Host",
"\n",
"}"
] | // getHostAddr returns host header if available, otherwise returns host from URL | [
"getHostAddr",
"returns",
"host",
"header",
"if",
"available",
"otherwise",
"returns",
"host",
"from",
"URL"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/utils.go#L45-L50 | train |
minio/minio-go | api-error-response.go | Error | func (e ErrorResponse) Error() string {
if e.Message == "" {
msg, ok := s3ErrorResponseMap[e.Code]
if !ok {
msg = fmt.Sprintf("Error response code %s.", e.Code)
}
return msg
}
return e.Message
} | go | func (e ErrorResponse) Error() string {
if e.Message == "" {
msg, ok := s3ErrorResponseMap[e.Code]
if !ok {
msg = fmt.Sprintf("Error response code %s.", e.Code)
}
return msg
}
return e.Message
} | [
"func",
"(",
"e",
"ErrorResponse",
")",
"Error",
"(",
")",
"string",
"{",
"if",
"e",
".",
"Message",
"==",
"\"",
"\"",
"{",
"msg",
",",
"ok",
":=",
"s3ErrorResponseMap",
"[",
"e",
".",
"Code",
"]",
"\n",
"if",
"!",
"ok",
"{",
"msg",
"=",
"fmt",
... | // Error - Returns S3 error string. | [
"Error",
"-",
"Returns",
"S3",
"error",
"string",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L81-L90 | train |
minio/minio-go | api-error-response.go | ErrTransferAccelerationBucket | func ErrTransferAccelerationBucket(bucketName string) error {
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "InvalidArgument",
Message: "The name of the bucket used for Transfer Acceleration must be DNS-compliant and must not contain periods ‘.’.",
BucketName: bucketName,
}
} | go | func ErrTransferAccelerationBucket(bucketName string) error {
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "InvalidArgument",
Message: "The name of the bucket used for Transfer Acceleration must be DNS-compliant and must not contain periods ‘.’.",
BucketName: bucketName,
}
} | [
"func",
"ErrTransferAccelerationBucket",
"(",
"bucketName",
"string",
")",
"error",
"{",
"return",
"ErrorResponse",
"{",
"StatusCode",
":",
"http",
".",
"StatusBadRequest",
",",
"Code",
":",
"\"",
"\"",
",",
"Message",
":",
"\"",
"",
"",
"BucketName",
":",
"... | // ErrTransferAccelerationBucket - bucket name is invalid to be used with transfer acceleration. | [
"ErrTransferAccelerationBucket",
"-",
"bucket",
"name",
"is",
"invalid",
"to",
"be",
"used",
"with",
"transfer",
"acceleration",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L183-L190 | train |
minio/minio-go | api-error-response.go | ErrEntityTooLarge | func ErrEntityTooLarge(totalSize, maxObjectSize int64, bucketName, objectName string) error {
msg := fmt.Sprintf("Your proposed upload size ‘%d’ exceeds the maximum allowed object size ‘%d’ for single PUT operation.", totalSize, maxObjectSize)
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "EntityTooLarge",
Message: msg,
BucketName: bucketName,
Key: objectName,
}
} | go | func ErrEntityTooLarge(totalSize, maxObjectSize int64, bucketName, objectName string) error {
msg := fmt.Sprintf("Your proposed upload size ‘%d’ exceeds the maximum allowed object size ‘%d’ for single PUT operation.", totalSize, maxObjectSize)
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "EntityTooLarge",
Message: msg,
BucketName: bucketName,
Key: objectName,
}
} | [
"func",
"ErrEntityTooLarge",
"(",
"totalSize",
",",
"maxObjectSize",
"int64",
",",
"bucketName",
",",
"objectName",
"string",
")",
"error",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"S",
"i",
"e, maxObj",
"e",
"tSize)",
"",
"\n",
"return",
"Error... | // ErrEntityTooLarge - Input size is larger than supported maximum. | [
"ErrEntityTooLarge",
"-",
"Input",
"size",
"is",
"larger",
"than",
"supported",
"maximum",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L193-L202 | train |
minio/minio-go | api-error-response.go | ErrEntityTooSmall | func ErrEntityTooSmall(totalSize int64, bucketName, objectName string) error {
msg := fmt.Sprintf("Your proposed upload size ‘%d’ is below the minimum allowed object size ‘0B’ for single PUT operation.", totalSize)
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "EntityTooSmall",
Message: msg,
BucketName: bucketName,
Key: objectName,
}
} | go | func ErrEntityTooSmall(totalSize int64, bucketName, objectName string) error {
msg := fmt.Sprintf("Your proposed upload size ‘%d’ is below the minimum allowed object size ‘0B’ for single PUT operation.", totalSize)
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "EntityTooSmall",
Message: msg,
BucketName: bucketName,
Key: objectName,
}
} | [
"func",
"ErrEntityTooSmall",
"(",
"totalSize",
"int64",
",",
"bucketName",
",",
"objectName",
"string",
")",
"error",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"S",
"i",
"e)",
"",
"\n",
"return",
"ErrorResponse",
"{",
"StatusCode",
":",
"http",
... | // ErrEntityTooSmall - Input size is smaller than supported minimum. | [
"ErrEntityTooSmall",
"-",
"Input",
"size",
"is",
"smaller",
"than",
"supported",
"minimum",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L205-L214 | train |
minio/minio-go | api-error-response.go | ErrUnexpectedEOF | func ErrUnexpectedEOF(totalRead, totalSize int64, bucketName, objectName string) error {
msg := fmt.Sprintf("Data read ‘%d’ is not equal to the size ‘%d’ of the input Reader.", totalRead, totalSize)
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "UnexpectedEOF",
Message: msg,
BucketName: bucketName,
Key: objectName,
}
} | go | func ErrUnexpectedEOF(totalRead, totalSize int64, bucketName, objectName string) error {
msg := fmt.Sprintf("Data read ‘%d’ is not equal to the size ‘%d’ of the input Reader.", totalRead, totalSize)
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "UnexpectedEOF",
Message: msg,
BucketName: bucketName,
Key: objectName,
}
} | [
"func",
"ErrUnexpectedEOF",
"(",
"totalRead",
",",
"totalSize",
"int64",
",",
"bucketName",
",",
"objectName",
"string",
")",
"error",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"R",
"e",
"d, totalS",
"i",
"e)",
"",
"\n",
"return",
"ErrorResponse"... | // ErrUnexpectedEOF - Unexpected end of file reached. | [
"ErrUnexpectedEOF",
"-",
"Unexpected",
"end",
"of",
"file",
"reached",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L217-L226 | train |
minio/minio-go | api-error-response.go | ErrInvalidBucketName | func ErrInvalidBucketName(message string) error {
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "InvalidBucketName",
Message: message,
RequestID: "minio",
}
} | go | func ErrInvalidBucketName(message string) error {
return ErrorResponse{
StatusCode: http.StatusBadRequest,
Code: "InvalidBucketName",
Message: message,
RequestID: "minio",
}
} | [
"func",
"ErrInvalidBucketName",
"(",
"message",
"string",
")",
"error",
"{",
"return",
"ErrorResponse",
"{",
"StatusCode",
":",
"http",
".",
"StatusBadRequest",
",",
"Code",
":",
"\"",
"\"",
",",
"Message",
":",
"message",
",",
"RequestID",
":",
"\"",
"\"",
... | // ErrInvalidBucketName - Invalid bucket name response. | [
"ErrInvalidBucketName",
"-",
"Invalid",
"bucket",
"name",
"response",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L229-L236 | train |
minio/minio-go | api-error-response.go | ErrInvalidObjectName | func ErrInvalidObjectName(message string) error {
return ErrorResponse{
StatusCode: http.StatusNotFound,
Code: "NoSuchKey",
Message: message,
RequestID: "minio",
}
} | go | func ErrInvalidObjectName(message string) error {
return ErrorResponse{
StatusCode: http.StatusNotFound,
Code: "NoSuchKey",
Message: message,
RequestID: "minio",
}
} | [
"func",
"ErrInvalidObjectName",
"(",
"message",
"string",
")",
"error",
"{",
"return",
"ErrorResponse",
"{",
"StatusCode",
":",
"http",
".",
"StatusNotFound",
",",
"Code",
":",
"\"",
"\"",
",",
"Message",
":",
"message",
",",
"RequestID",
":",
"\"",
"\"",
... | // ErrInvalidObjectName - Invalid object name response. | [
"ErrInvalidObjectName",
"-",
"Invalid",
"object",
"name",
"response",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L239-L246 | train |
minio/minio-go | api-error-response.go | ErrAPINotSupported | func ErrAPINotSupported(message string) error {
return ErrorResponse{
StatusCode: http.StatusNotImplemented,
Code: "APINotSupported",
Message: message,
RequestID: "minio",
}
} | go | func ErrAPINotSupported(message string) error {
return ErrorResponse{
StatusCode: http.StatusNotImplemented,
Code: "APINotSupported",
Message: message,
RequestID: "minio",
}
} | [
"func",
"ErrAPINotSupported",
"(",
"message",
"string",
")",
"error",
"{",
"return",
"ErrorResponse",
"{",
"StatusCode",
":",
"http",
".",
"StatusNotImplemented",
",",
"Code",
":",
"\"",
"\"",
",",
"Message",
":",
"message",
",",
"RequestID",
":",
"\"",
"\""... | // ErrAPINotSupported - API not supported response
// The specified API call is not supported | [
"ErrAPINotSupported",
"-",
"API",
"not",
"supported",
"response",
"The",
"specified",
"API",
"call",
"is",
"not",
"supported"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-error-response.go#L275-L282 | train |
minio/minio-go | pkg/s3signer/request-signature-v2.go | encodeURL2Path | func encodeURL2Path(req *http.Request, virtualHost bool) (path string) {
if virtualHost {
reqHost := getHostAddr(req)
dotPos := strings.Index(reqHost, ".")
if dotPos > -1 {
bucketName := reqHost[:dotPos]
path = "/" + bucketName
path += req.URL.Path
path = s3utils.EncodePath(path)
return
}
}
path = s3utils.EncodePath(req.URL.Path)
return
} | go | func encodeURL2Path(req *http.Request, virtualHost bool) (path string) {
if virtualHost {
reqHost := getHostAddr(req)
dotPos := strings.Index(reqHost, ".")
if dotPos > -1 {
bucketName := reqHost[:dotPos]
path = "/" + bucketName
path += req.URL.Path
path = s3utils.EncodePath(path)
return
}
}
path = s3utils.EncodePath(req.URL.Path)
return
} | [
"func",
"encodeURL2Path",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"virtualHost",
"bool",
")",
"(",
"path",
"string",
")",
"{",
"if",
"virtualHost",
"{",
"reqHost",
":=",
"getHostAddr",
"(",
"req",
")",
"\n",
"dotPos",
":=",
"strings",
".",
"Index",... | // Encode input URL path to URL encoded path. | [
"Encode",
"input",
"URL",
"path",
"to",
"URL",
"encoded",
"path",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-v2.go#L42-L56 | train |
minio/minio-go | pkg/s3signer/request-signature-v2.go | PostPresignSignatureV2 | func PostPresignSignatureV2(policyBase64, secretAccessKey string) string {
hm := hmac.New(sha1.New, []byte(secretAccessKey))
hm.Write([]byte(policyBase64))
signature := base64.StdEncoding.EncodeToString(hm.Sum(nil))
return signature
} | go | func PostPresignSignatureV2(policyBase64, secretAccessKey string) string {
hm := hmac.New(sha1.New, []byte(secretAccessKey))
hm.Write([]byte(policyBase64))
signature := base64.StdEncoding.EncodeToString(hm.Sum(nil))
return signature
} | [
"func",
"PostPresignSignatureV2",
"(",
"policyBase64",
",",
"secretAccessKey",
"string",
")",
"string",
"{",
"hm",
":=",
"hmac",
".",
"New",
"(",
"sha1",
".",
"New",
",",
"[",
"]",
"byte",
"(",
"secretAccessKey",
")",
")",
"\n",
"hm",
".",
"Write",
"(",
... | // PostPresignSignatureV2 - presigned signature for PostPolicy
// request. | [
"PostPresignSignatureV2",
"-",
"presigned",
"signature",
"for",
"PostPolicy",
"request",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-v2.go#L106-L111 | train |
minio/minio-go | pkg/s3signer/request-signature-v2.go | writeSignV2Headers | func writeSignV2Headers(buf *bytes.Buffer, req http.Request) {
buf.WriteString(req.Method + "\n")
buf.WriteString(req.Header.Get("Content-Md5") + "\n")
buf.WriteString(req.Header.Get("Content-Type") + "\n")
buf.WriteString(req.Header.Get("Date") + "\n")
} | go | func writeSignV2Headers(buf *bytes.Buffer, req http.Request) {
buf.WriteString(req.Method + "\n")
buf.WriteString(req.Header.Get("Content-Md5") + "\n")
buf.WriteString(req.Header.Get("Content-Type") + "\n")
buf.WriteString(req.Header.Get("Date") + "\n")
} | [
"func",
"writeSignV2Headers",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
",",
"req",
"http",
".",
"Request",
")",
"{",
"buf",
".",
"WriteString",
"(",
"req",
".",
"Method",
"+",
"\"",
"\\n",
"\"",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"req",
".",
... | // writeSignV2Headers - write signV2 required headers. | [
"writeSignV2Headers",
"-",
"write",
"signV2",
"required",
"headers",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-v2.go#L209-L214 | train |
minio/minio-go | pkg/s3signer/request-signature-v2.go | writeCanonicalizedHeaders | func writeCanonicalizedHeaders(buf *bytes.Buffer, req http.Request) {
var protoHeaders []string
vals := make(map[string][]string)
for k, vv := range req.Header {
// All the AMZ headers should be lowercase
lk := strings.ToLower(k)
if strings.HasPrefix(lk, "x-amz") {
protoHeaders = append(protoHeaders, lk)
vals[lk] = vv
}
}
sort.Strings(protoHeaders)
for _, k := range protoHeaders {
buf.WriteString(k)
buf.WriteByte(':')
for idx, v := range vals[k] {
if idx > 0 {
buf.WriteByte(',')
}
if strings.Contains(v, "\n") {
// TODO: "Unfold" long headers that
// span multiple lines (as allowed by
// RFC 2616, section 4.2) by replacing
// the folding white-space (including
// new-line) by a single space.
buf.WriteString(v)
} else {
buf.WriteString(v)
}
}
buf.WriteByte('\n')
}
} | go | func writeCanonicalizedHeaders(buf *bytes.Buffer, req http.Request) {
var protoHeaders []string
vals := make(map[string][]string)
for k, vv := range req.Header {
// All the AMZ headers should be lowercase
lk := strings.ToLower(k)
if strings.HasPrefix(lk, "x-amz") {
protoHeaders = append(protoHeaders, lk)
vals[lk] = vv
}
}
sort.Strings(protoHeaders)
for _, k := range protoHeaders {
buf.WriteString(k)
buf.WriteByte(':')
for idx, v := range vals[k] {
if idx > 0 {
buf.WriteByte(',')
}
if strings.Contains(v, "\n") {
// TODO: "Unfold" long headers that
// span multiple lines (as allowed by
// RFC 2616, section 4.2) by replacing
// the folding white-space (including
// new-line) by a single space.
buf.WriteString(v)
} else {
buf.WriteString(v)
}
}
buf.WriteByte('\n')
}
} | [
"func",
"writeCanonicalizedHeaders",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
",",
"req",
"http",
".",
"Request",
")",
"{",
"var",
"protoHeaders",
"[",
"]",
"string",
"\n",
"vals",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
... | // writeCanonicalizedHeaders - write canonicalized headers. | [
"writeCanonicalizedHeaders",
"-",
"write",
"canonicalized",
"headers",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/s3signer/request-signature-v2.go#L217-L249 | train |
minio/minio-go | pkg/credentials/sts_client_grants.go | NewSTSClientGrants | func NewSTSClientGrants(stsEndpoint string, getClientGrantsTokenExpiry func() (*ClientGrantsToken, error)) (*Credentials, error) {
if stsEndpoint == "" {
return nil, errors.New("STS endpoint cannot be empty")
}
if getClientGrantsTokenExpiry == nil {
return nil, errors.New("Client grants access token and expiry retrieval function should be defined")
}
return New(&STSClientGrants{
Client: &http.Client{
Transport: http.DefaultTransport,
},
stsEndpoint: stsEndpoint,
getClientGrantsTokenExpiry: getClientGrantsTokenExpiry,
}), nil
} | go | func NewSTSClientGrants(stsEndpoint string, getClientGrantsTokenExpiry func() (*ClientGrantsToken, error)) (*Credentials, error) {
if stsEndpoint == "" {
return nil, errors.New("STS endpoint cannot be empty")
}
if getClientGrantsTokenExpiry == nil {
return nil, errors.New("Client grants access token and expiry retrieval function should be defined")
}
return New(&STSClientGrants{
Client: &http.Client{
Transport: http.DefaultTransport,
},
stsEndpoint: stsEndpoint,
getClientGrantsTokenExpiry: getClientGrantsTokenExpiry,
}), nil
} | [
"func",
"NewSTSClientGrants",
"(",
"stsEndpoint",
"string",
",",
"getClientGrantsTokenExpiry",
"func",
"(",
")",
"(",
"*",
"ClientGrantsToken",
",",
"error",
")",
")",
"(",
"*",
"Credentials",
",",
"error",
")",
"{",
"if",
"stsEndpoint",
"==",
"\"",
"\"",
"{... | // NewSTSClientGrants returns a pointer to a new
// Credentials object wrapping the STSClientGrants. | [
"NewSTSClientGrants",
"returns",
"a",
"pointer",
"to",
"a",
"new",
"Credentials",
"object",
"wrapping",
"the",
"STSClientGrants",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/credentials/sts_client_grants.go#L89-L103 | train |
minio/minio-go | api-remove.go | RemoveObject | func (c Client) RemoveObject(bucketName, objectName string) error {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return err
}
// Execute DELETE on objectName.
resp, err := c.executeMethod(context.Background(), "DELETE", requestMetadata{
bucketName: bucketName,
objectName: objectName,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return err
}
if resp != nil {
// if some unexpected error happened and max retry is reached, we want to let client know
if resp.StatusCode != http.StatusNoContent {
return httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// DeleteObject always responds with http '204' even for
// objects which do not exist. So no need to handle them
// specifically.
return nil
} | go | func (c Client) RemoveObject(bucketName, objectName string) error {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return err
}
// Execute DELETE on objectName.
resp, err := c.executeMethod(context.Background(), "DELETE", requestMetadata{
bucketName: bucketName,
objectName: objectName,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return err
}
if resp != nil {
// if some unexpected error happened and max retry is reached, we want to let client know
if resp.StatusCode != http.StatusNoContent {
return httpRespToErrorResponse(resp, bucketName, objectName)
}
}
// DeleteObject always responds with http '204' even for
// objects which do not exist. So no need to handle them
// specifically.
return nil
} | [
"func",
"(",
"c",
"Client",
")",
"RemoveObject",
"(",
"bucketName",
",",
"objectName",
"string",
")",
"error",
"{",
"// Input validation.",
"if",
"err",
":=",
"s3utils",
".",
"CheckValidBucketName",
"(",
"bucketName",
")",
";",
"err",
"!=",
"nil",
"{",
"retu... | // RemoveObject remove an object from a bucket. | [
"RemoveObject",
"remove",
"an",
"object",
"from",
"a",
"bucket",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-remove.go#L62-L91 | train |
minio/minio-go | api-remove.go | generateRemoveMultiObjectsRequest | func generateRemoveMultiObjectsRequest(objects []string) []byte {
rmObjects := []deleteObject{}
for _, obj := range objects {
rmObjects = append(rmObjects, deleteObject{Key: obj})
}
xmlBytes, _ := xml.Marshal(deleteMultiObjects{Objects: rmObjects, Quiet: true})
return xmlBytes
} | go | func generateRemoveMultiObjectsRequest(objects []string) []byte {
rmObjects := []deleteObject{}
for _, obj := range objects {
rmObjects = append(rmObjects, deleteObject{Key: obj})
}
xmlBytes, _ := xml.Marshal(deleteMultiObjects{Objects: rmObjects, Quiet: true})
return xmlBytes
} | [
"func",
"generateRemoveMultiObjectsRequest",
"(",
"objects",
"[",
"]",
"string",
")",
"[",
"]",
"byte",
"{",
"rmObjects",
":=",
"[",
"]",
"deleteObject",
"{",
"}",
"\n",
"for",
"_",
",",
"obj",
":=",
"range",
"objects",
"{",
"rmObjects",
"=",
"append",
"... | // generateRemoveMultiObjects - generate the XML request for remove multi objects request | [
"generateRemoveMultiObjects",
"-",
"generate",
"the",
"XML",
"request",
"for",
"remove",
"multi",
"objects",
"request"
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-remove.go#L100-L107 | train |
minio/minio-go | api-remove.go | RemoveObjectsWithContext | func (c Client) RemoveObjectsWithContext(ctx context.Context, bucketName string, objectsCh <-chan string) <-chan RemoveObjectError {
errorCh := make(chan RemoveObjectError, 1)
// Validate if bucket name is valid.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
defer close(errorCh)
errorCh <- RemoveObjectError{
Err: err,
}
return errorCh
}
// Validate objects channel to be properly allocated.
if objectsCh == nil {
defer close(errorCh)
errorCh <- RemoveObjectError{
Err: ErrInvalidArgument("Objects channel cannot be nil"),
}
return errorCh
}
// Generate and call MultiDelete S3 requests based on entries received from objectsCh
go func(errorCh chan<- RemoveObjectError) {
maxEntries := 1000
finish := false
urlValues := make(url.Values)
urlValues.Set("delete", "")
// Close error channel when Multi delete finishes.
defer close(errorCh)
// Loop over entries by 1000 and call MultiDelete requests
for {
if finish {
break
}
count := 0
var batch []string
// Try to gather 1000 entries
for object := range objectsCh {
batch = append(batch, object)
if count++; count >= maxEntries {
break
}
}
if count == 0 {
// Multi Objects Delete API doesn't accept empty object list, quit immediately
break
}
if count < maxEntries {
// We didn't have 1000 entries, so this is the last batch
finish = true
}
// Generate remove multi objects XML request
removeBytes := generateRemoveMultiObjectsRequest(batch)
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(ctx, "POST", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentBody: bytes.NewReader(removeBytes),
contentLength: int64(len(removeBytes)),
contentMD5Base64: sumMD5Base64(removeBytes),
contentSHA256Hex: sum256Hex(removeBytes),
})
if resp != nil {
if resp.StatusCode != http.StatusOK {
e := httpRespToErrorResponse(resp, bucketName, "")
errorCh <- RemoveObjectError{ObjectName: "", Err: e}
}
}
if err != nil {
for _, b := range batch {
errorCh <- RemoveObjectError{ObjectName: b, Err: err}
}
continue
}
// Process multiobjects remove xml response
processRemoveMultiObjectsResponse(resp.Body, batch, errorCh)
closeResponse(resp)
}
}(errorCh)
return errorCh
} | go | func (c Client) RemoveObjectsWithContext(ctx context.Context, bucketName string, objectsCh <-chan string) <-chan RemoveObjectError {
errorCh := make(chan RemoveObjectError, 1)
// Validate if bucket name is valid.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
defer close(errorCh)
errorCh <- RemoveObjectError{
Err: err,
}
return errorCh
}
// Validate objects channel to be properly allocated.
if objectsCh == nil {
defer close(errorCh)
errorCh <- RemoveObjectError{
Err: ErrInvalidArgument("Objects channel cannot be nil"),
}
return errorCh
}
// Generate and call MultiDelete S3 requests based on entries received from objectsCh
go func(errorCh chan<- RemoveObjectError) {
maxEntries := 1000
finish := false
urlValues := make(url.Values)
urlValues.Set("delete", "")
// Close error channel when Multi delete finishes.
defer close(errorCh)
// Loop over entries by 1000 and call MultiDelete requests
for {
if finish {
break
}
count := 0
var batch []string
// Try to gather 1000 entries
for object := range objectsCh {
batch = append(batch, object)
if count++; count >= maxEntries {
break
}
}
if count == 0 {
// Multi Objects Delete API doesn't accept empty object list, quit immediately
break
}
if count < maxEntries {
// We didn't have 1000 entries, so this is the last batch
finish = true
}
// Generate remove multi objects XML request
removeBytes := generateRemoveMultiObjectsRequest(batch)
// Execute GET on bucket to list objects.
resp, err := c.executeMethod(ctx, "POST", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
contentBody: bytes.NewReader(removeBytes),
contentLength: int64(len(removeBytes)),
contentMD5Base64: sumMD5Base64(removeBytes),
contentSHA256Hex: sum256Hex(removeBytes),
})
if resp != nil {
if resp.StatusCode != http.StatusOK {
e := httpRespToErrorResponse(resp, bucketName, "")
errorCh <- RemoveObjectError{ObjectName: "", Err: e}
}
}
if err != nil {
for _, b := range batch {
errorCh <- RemoveObjectError{ObjectName: b, Err: err}
}
continue
}
// Process multiobjects remove xml response
processRemoveMultiObjectsResponse(resp.Body, batch, errorCh)
closeResponse(resp)
}
}(errorCh)
return errorCh
} | [
"func",
"(",
"c",
"Client",
")",
"RemoveObjectsWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
"string",
",",
"objectsCh",
"<-",
"chan",
"string",
")",
"<-",
"chan",
"RemoveObjectError",
"{",
"errorCh",
":=",
"make",
"(",
"chan",
"Rem... | // RemoveObjectsWithContext - Identical to RemoveObjects call, but accepts context to facilitate request cancellation. | [
"RemoveObjectsWithContext",
"-",
"Identical",
"to",
"RemoveObjects",
"call",
"but",
"accepts",
"context",
"to",
"facilitate",
"request",
"cancellation",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-remove.go#L133-L218 | train |
minio/minio-go | api-remove.go | RemoveObjects | func (c Client) RemoveObjects(bucketName string, objectsCh <-chan string) <-chan RemoveObjectError {
return c.RemoveObjectsWithContext(context.Background(), bucketName, objectsCh)
} | go | func (c Client) RemoveObjects(bucketName string, objectsCh <-chan string) <-chan RemoveObjectError {
return c.RemoveObjectsWithContext(context.Background(), bucketName, objectsCh)
} | [
"func",
"(",
"c",
"Client",
")",
"RemoveObjects",
"(",
"bucketName",
"string",
",",
"objectsCh",
"<-",
"chan",
"string",
")",
"<-",
"chan",
"RemoveObjectError",
"{",
"return",
"c",
".",
"RemoveObjectsWithContext",
"(",
"context",
".",
"Background",
"(",
")",
... | // RemoveObjects removes multiple objects from a bucket.
// The list of objects to remove are received from objectsCh.
// Remove failures are sent back via error channel. | [
"RemoveObjects",
"removes",
"multiple",
"objects",
"from",
"a",
"bucket",
".",
"The",
"list",
"of",
"objects",
"to",
"remove",
"are",
"received",
"from",
"objectsCh",
".",
"Remove",
"failures",
"are",
"sent",
"back",
"via",
"error",
"channel",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-remove.go#L223-L225 | train |
minio/minio-go | api-remove.go | RemoveIncompleteUpload | func (c Client) RemoveIncompleteUpload(bucketName, objectName string) error {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return err
}
// Find multipart upload ids of the object to be aborted.
uploadIDs, err := c.findUploadIDs(bucketName, objectName)
if err != nil {
return err
}
for _, uploadID := range uploadIDs {
// abort incomplete multipart upload, based on the upload id passed.
err := c.abortMultipartUpload(context.Background(), bucketName, objectName, uploadID)
if err != nil {
return err
}
}
return nil
} | go | func (c Client) RemoveIncompleteUpload(bucketName, objectName string) error {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return err
}
// Find multipart upload ids of the object to be aborted.
uploadIDs, err := c.findUploadIDs(bucketName, objectName)
if err != nil {
return err
}
for _, uploadID := range uploadIDs {
// abort incomplete multipart upload, based on the upload id passed.
err := c.abortMultipartUpload(context.Background(), bucketName, objectName, uploadID)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"Client",
")",
"RemoveIncompleteUpload",
"(",
"bucketName",
",",
"objectName",
"string",
")",
"error",
"{",
"// Input validation.",
"if",
"err",
":=",
"s3utils",
".",
"CheckValidBucketName",
"(",
"bucketName",
")",
";",
"err",
"!=",
"nil",
"{... | // RemoveIncompleteUpload aborts an partially uploaded object. | [
"RemoveIncompleteUpload",
"aborts",
"an",
"partially",
"uploaded",
"object",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-remove.go#L228-L251 | train |
minio/minio-go | api-remove.go | abortMultipartUpload | func (c Client) abortMultipartUpload(ctx context.Context, bucketName, objectName, uploadID string) error {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return err
}
// Initialize url queries.
urlValues := make(url.Values)
urlValues.Set("uploadId", uploadID)
// Execute DELETE on multipart upload.
resp, err := c.executeMethod(ctx, "DELETE", requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode != http.StatusNoContent {
// Abort has no response body, handle it for any errors.
var errorResponse ErrorResponse
switch resp.StatusCode {
case http.StatusNotFound:
// This is needed specifically for abort and it cannot
// be converged into default case.
errorResponse = ErrorResponse{
Code: "NoSuchUpload",
Message: "The specified multipart upload does not exist.",
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"),
}
default:
return httpRespToErrorResponse(resp, bucketName, objectName)
}
return errorResponse
}
}
return nil
} | go | func (c Client) abortMultipartUpload(ctx context.Context, bucketName, objectName, uploadID string) error {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return err
}
if err := s3utils.CheckValidObjectName(objectName); err != nil {
return err
}
// Initialize url queries.
urlValues := make(url.Values)
urlValues.Set("uploadId", uploadID)
// Execute DELETE on multipart upload.
resp, err := c.executeMethod(ctx, "DELETE", requestMetadata{
bucketName: bucketName,
objectName: objectName,
queryValues: urlValues,
contentSHA256Hex: emptySHA256Hex,
})
defer closeResponse(resp)
if err != nil {
return err
}
if resp != nil {
if resp.StatusCode != http.StatusNoContent {
// Abort has no response body, handle it for any errors.
var errorResponse ErrorResponse
switch resp.StatusCode {
case http.StatusNotFound:
// This is needed specifically for abort and it cannot
// be converged into default case.
errorResponse = ErrorResponse{
Code: "NoSuchUpload",
Message: "The specified multipart upload does not exist.",
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"),
}
default:
return httpRespToErrorResponse(resp, bucketName, objectName)
}
return errorResponse
}
}
return nil
} | [
"func",
"(",
"c",
"Client",
")",
"abortMultipartUpload",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
",",
"objectName",
",",
"uploadID",
"string",
")",
"error",
"{",
"// Input validation.",
"if",
"err",
":=",
"s3utils",
".",
"CheckValidBucketName",... | // abortMultipartUpload aborts a multipart upload for the given
// uploadID, all previously uploaded parts are deleted. | [
"abortMultipartUpload",
"aborts",
"a",
"multipart",
"upload",
"for",
"the",
"given",
"uploadID",
"all",
"previously",
"uploaded",
"parts",
"are",
"deleted",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-remove.go#L255-L303 | train |
minio/minio-go | hook-reader.go | newHook | func newHook(source, hook io.Reader) io.Reader {
if hook == nil {
return source
}
return &hookReader{source, hook}
} | go | func newHook(source, hook io.Reader) io.Reader {
if hook == nil {
return source
}
return &hookReader{source, hook}
} | [
"func",
"newHook",
"(",
"source",
",",
"hook",
"io",
".",
"Reader",
")",
"io",
".",
"Reader",
"{",
"if",
"hook",
"==",
"nil",
"{",
"return",
"source",
"\n",
"}",
"\n",
"return",
"&",
"hookReader",
"{",
"source",
",",
"hook",
"}",
"\n",
"}"
] | // newHook returns a io.ReadSeeker which implements hookReader that
// reports the data read from the source to the hook. | [
"newHook",
"returns",
"a",
"io",
".",
"ReadSeeker",
"which",
"implements",
"hookReader",
"that",
"reports",
"the",
"data",
"read",
"from",
"the",
"source",
"to",
"the",
"hook",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/hook-reader.go#L80-L85 | train |
minio/minio-go | post-policy.go | NewPostPolicy | func NewPostPolicy() *PostPolicy {
p := &PostPolicy{}
p.conditions = make([]policyCondition, 0)
p.formData = make(map[string]string)
return p
} | go | func NewPostPolicy() *PostPolicy {
p := &PostPolicy{}
p.conditions = make([]policyCondition, 0)
p.formData = make(map[string]string)
return p
} | [
"func",
"NewPostPolicy",
"(",
")",
"*",
"PostPolicy",
"{",
"p",
":=",
"&",
"PostPolicy",
"{",
"}",
"\n",
"p",
".",
"conditions",
"=",
"make",
"(",
"[",
"]",
"policyCondition",
",",
"0",
")",
"\n",
"p",
".",
"formData",
"=",
"make",
"(",
"map",
"[",... | // NewPostPolicy - Instantiate new post policy. | [
"NewPostPolicy",
"-",
"Instantiate",
"new",
"post",
"policy",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L66-L71 | train |
minio/minio-go | post-policy.go | SetExpires | func (p *PostPolicy) SetExpires(t time.Time) error {
if t.IsZero() {
return ErrInvalidArgument("No expiry time set.")
}
p.expiration = t
return nil
} | go | func (p *PostPolicy) SetExpires(t time.Time) error {
if t.IsZero() {
return ErrInvalidArgument("No expiry time set.")
}
p.expiration = t
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"SetExpires",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"if",
"t",
".",
"IsZero",
"(",
")",
"{",
"return",
"ErrInvalidArgument",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"p",
".",
"expiration",
"=",
... | // SetExpires - Sets expiration time for the new policy. | [
"SetExpires",
"-",
"Sets",
"expiration",
"time",
"for",
"the",
"new",
"policy",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L74-L80 | train |
minio/minio-go | post-policy.go | SetKey | func (p *PostPolicy) SetKey(key string) error {
if strings.TrimSpace(key) == "" || key == "" {
return ErrInvalidArgument("Object name is empty.")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$key",
value: key,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["key"] = key
return nil
} | go | func (p *PostPolicy) SetKey(key string) error {
if strings.TrimSpace(key) == "" || key == "" {
return ErrInvalidArgument("Object name is empty.")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$key",
value: key,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["key"] = key
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"SetKey",
"(",
"key",
"string",
")",
"error",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"key",
")",
"==",
"\"",
"\"",
"||",
"key",
"==",
"\"",
"\"",
"{",
"return",
"ErrInvalidArgument",
"(",
"\"",
"\"",
... | // SetKey - Sets an object name for the policy based upload. | [
"SetKey",
"-",
"Sets",
"an",
"object",
"name",
"for",
"the",
"policy",
"based",
"upload",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L83-L97 | train |
minio/minio-go | post-policy.go | SetKeyStartsWith | func (p *PostPolicy) SetKeyStartsWith(keyStartsWith string) error {
if strings.TrimSpace(keyStartsWith) == "" || keyStartsWith == "" {
return ErrInvalidArgument("Object prefix is empty.")
}
policyCond := policyCondition{
matchType: "starts-with",
condition: "$key",
value: keyStartsWith,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["key"] = keyStartsWith
return nil
} | go | func (p *PostPolicy) SetKeyStartsWith(keyStartsWith string) error {
if strings.TrimSpace(keyStartsWith) == "" || keyStartsWith == "" {
return ErrInvalidArgument("Object prefix is empty.")
}
policyCond := policyCondition{
matchType: "starts-with",
condition: "$key",
value: keyStartsWith,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["key"] = keyStartsWith
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"SetKeyStartsWith",
"(",
"keyStartsWith",
"string",
")",
"error",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"keyStartsWith",
")",
"==",
"\"",
"\"",
"||",
"keyStartsWith",
"==",
"\"",
"\"",
"{",
"return",
"ErrInv... | // SetKeyStartsWith - Sets an object name that an policy based upload
// can start with. | [
"SetKeyStartsWith",
"-",
"Sets",
"an",
"object",
"name",
"that",
"an",
"policy",
"based",
"upload",
"can",
"start",
"with",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L101-L115 | train |
minio/minio-go | post-policy.go | SetBucket | func (p *PostPolicy) SetBucket(bucketName string) error {
if strings.TrimSpace(bucketName) == "" || bucketName == "" {
return ErrInvalidArgument("Bucket name is empty.")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$bucket",
value: bucketName,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["bucket"] = bucketName
return nil
} | go | func (p *PostPolicy) SetBucket(bucketName string) error {
if strings.TrimSpace(bucketName) == "" || bucketName == "" {
return ErrInvalidArgument("Bucket name is empty.")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$bucket",
value: bucketName,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["bucket"] = bucketName
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"SetBucket",
"(",
"bucketName",
"string",
")",
"error",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"bucketName",
")",
"==",
"\"",
"\"",
"||",
"bucketName",
"==",
"\"",
"\"",
"{",
"return",
"ErrInvalidArgument",
... | // SetBucket - Sets bucket at which objects will be uploaded to. | [
"SetBucket",
"-",
"Sets",
"bucket",
"at",
"which",
"objects",
"will",
"be",
"uploaded",
"to",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L118-L132 | train |
minio/minio-go | post-policy.go | SetContentType | func (p *PostPolicy) SetContentType(contentType string) error {
if strings.TrimSpace(contentType) == "" || contentType == "" {
return ErrInvalidArgument("No content type specified.")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$Content-Type",
value: contentType,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["Content-Type"] = contentType
return nil
} | go | func (p *PostPolicy) SetContentType(contentType string) error {
if strings.TrimSpace(contentType) == "" || contentType == "" {
return ErrInvalidArgument("No content type specified.")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$Content-Type",
value: contentType,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["Content-Type"] = contentType
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"SetContentType",
"(",
"contentType",
"string",
")",
"error",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"contentType",
")",
"==",
"\"",
"\"",
"||",
"contentType",
"==",
"\"",
"\"",
"{",
"return",
"ErrInvalidArgu... | // SetContentType - Sets content-type of the object for this policy
// based upload. | [
"SetContentType",
"-",
"Sets",
"content",
"-",
"type",
"of",
"the",
"object",
"for",
"this",
"policy",
"based",
"upload",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L136-L150 | train |
minio/minio-go | post-policy.go | SetContentLengthRange | func (p *PostPolicy) SetContentLengthRange(min, max int64) error {
if min > max {
return ErrInvalidArgument("Minimum limit is larger than maximum limit.")
}
if min < 0 {
return ErrInvalidArgument("Minimum limit cannot be negative.")
}
if max < 0 {
return ErrInvalidArgument("Maximum limit cannot be negative.")
}
p.contentLengthRange.min = min
p.contentLengthRange.max = max
return nil
} | go | func (p *PostPolicy) SetContentLengthRange(min, max int64) error {
if min > max {
return ErrInvalidArgument("Minimum limit is larger than maximum limit.")
}
if min < 0 {
return ErrInvalidArgument("Minimum limit cannot be negative.")
}
if max < 0 {
return ErrInvalidArgument("Maximum limit cannot be negative.")
}
p.contentLengthRange.min = min
p.contentLengthRange.max = max
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"SetContentLengthRange",
"(",
"min",
",",
"max",
"int64",
")",
"error",
"{",
"if",
"min",
">",
"max",
"{",
"return",
"ErrInvalidArgument",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"min",
"<",
"0",
"{",
... | // SetContentLengthRange - Set new min and max content length
// condition for all incoming uploads. | [
"SetContentLengthRange",
"-",
"Set",
"new",
"min",
"and",
"max",
"content",
"length",
"condition",
"for",
"all",
"incoming",
"uploads",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L154-L167 | train |
minio/minio-go | post-policy.go | SetSuccessStatusAction | func (p *PostPolicy) SetSuccessStatusAction(status string) error {
if strings.TrimSpace(status) == "" || status == "" {
return ErrInvalidArgument("Status is empty")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$success_action_status",
value: status,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["success_action_status"] = status
return nil
} | go | func (p *PostPolicy) SetSuccessStatusAction(status string) error {
if strings.TrimSpace(status) == "" || status == "" {
return ErrInvalidArgument("Status is empty")
}
policyCond := policyCondition{
matchType: "eq",
condition: "$success_action_status",
value: status,
}
if err := p.addNewPolicy(policyCond); err != nil {
return err
}
p.formData["success_action_status"] = status
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"SetSuccessStatusAction",
"(",
"status",
"string",
")",
"error",
"{",
"if",
"strings",
".",
"TrimSpace",
"(",
"status",
")",
"==",
"\"",
"\"",
"||",
"status",
"==",
"\"",
"\"",
"{",
"return",
"ErrInvalidArgument",
... | // SetSuccessStatusAction - Sets the status success code of the object for this policy
// based upload. | [
"SetSuccessStatusAction",
"-",
"Sets",
"the",
"status",
"success",
"code",
"of",
"the",
"object",
"for",
"this",
"policy",
"based",
"upload",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L171-L185 | train |
minio/minio-go | post-policy.go | addNewPolicy | func (p *PostPolicy) addNewPolicy(policyCond policyCondition) error {
if policyCond.matchType == "" || policyCond.condition == "" || policyCond.value == "" {
return ErrInvalidArgument("Policy fields are empty.")
}
p.conditions = append(p.conditions, policyCond)
return nil
} | go | func (p *PostPolicy) addNewPolicy(policyCond policyCondition) error {
if policyCond.matchType == "" || policyCond.condition == "" || policyCond.value == "" {
return ErrInvalidArgument("Policy fields are empty.")
}
p.conditions = append(p.conditions, policyCond)
return nil
} | [
"func",
"(",
"p",
"*",
"PostPolicy",
")",
"addNewPolicy",
"(",
"policyCond",
"policyCondition",
")",
"error",
"{",
"if",
"policyCond",
".",
"matchType",
"==",
"\"",
"\"",
"||",
"policyCond",
".",
"condition",
"==",
"\"",
"\"",
"||",
"policyCond",
".",
"val... | // addNewPolicy - internal helper to validate adding new policies. | [
"addNewPolicy",
"-",
"internal",
"helper",
"to",
"validate",
"adding",
"new",
"policies",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L232-L238 | train |
minio/minio-go | post-policy.go | marshalJSON | func (p PostPolicy) marshalJSON() []byte {
expirationStr := `"expiration":"` + p.expiration.Format(expirationDateFormat) + `"`
var conditionsStr string
conditions := []string{}
for _, po := range p.conditions {
conditions = append(conditions, fmt.Sprintf("[\"%s\",\"%s\",\"%s\"]", po.matchType, po.condition, po.value))
}
if p.contentLengthRange.min != 0 || p.contentLengthRange.max != 0 {
conditions = append(conditions, fmt.Sprintf("[\"content-length-range\", %d, %d]",
p.contentLengthRange.min, p.contentLengthRange.max))
}
if len(conditions) > 0 {
conditionsStr = `"conditions":[` + strings.Join(conditions, ",") + "]"
}
retStr := "{"
retStr = retStr + expirationStr + ","
retStr = retStr + conditionsStr
retStr = retStr + "}"
return []byte(retStr)
} | go | func (p PostPolicy) marshalJSON() []byte {
expirationStr := `"expiration":"` + p.expiration.Format(expirationDateFormat) + `"`
var conditionsStr string
conditions := []string{}
for _, po := range p.conditions {
conditions = append(conditions, fmt.Sprintf("[\"%s\",\"%s\",\"%s\"]", po.matchType, po.condition, po.value))
}
if p.contentLengthRange.min != 0 || p.contentLengthRange.max != 0 {
conditions = append(conditions, fmt.Sprintf("[\"content-length-range\", %d, %d]",
p.contentLengthRange.min, p.contentLengthRange.max))
}
if len(conditions) > 0 {
conditionsStr = `"conditions":[` + strings.Join(conditions, ",") + "]"
}
retStr := "{"
retStr = retStr + expirationStr + ","
retStr = retStr + conditionsStr
retStr = retStr + "}"
return []byte(retStr)
} | [
"func",
"(",
"p",
"PostPolicy",
")",
"marshalJSON",
"(",
")",
"[",
"]",
"byte",
"{",
"expirationStr",
":=",
"`\"expiration\":\"`",
"+",
"p",
".",
"expiration",
".",
"Format",
"(",
"expirationDateFormat",
")",
"+",
"`\"`",
"\n",
"var",
"conditionsStr",
"strin... | // marshalJSON - Provides Marshalled JSON in bytes. | [
"marshalJSON",
"-",
"Provides",
"Marshalled",
"JSON",
"in",
"bytes",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L246-L265 | train |
minio/minio-go | pkg/policy/bucket-policy.go | IsValidBucketPolicy | func (p BucketPolicy) IsValidBucketPolicy() bool {
switch p {
case BucketPolicyNone, BucketPolicyReadOnly, BucketPolicyReadWrite, BucketPolicyWriteOnly:
return true
}
return false
} | go | func (p BucketPolicy) IsValidBucketPolicy() bool {
switch p {
case BucketPolicyNone, BucketPolicyReadOnly, BucketPolicyReadWrite, BucketPolicyWriteOnly:
return true
}
return false
} | [
"func",
"(",
"p",
"BucketPolicy",
")",
"IsValidBucketPolicy",
"(",
")",
"bool",
"{",
"switch",
"p",
"{",
"case",
"BucketPolicyNone",
",",
"BucketPolicyReadOnly",
",",
"BucketPolicyReadWrite",
",",
"BucketPolicyWriteOnly",
":",
"return",
"true",
"\n",
"}",
"\n",
... | // IsValidBucketPolicy - returns true if policy is valid and supported, false otherwise. | [
"IsValidBucketPolicy",
"-",
"returns",
"true",
"if",
"policy",
"is",
"valid",
"and",
"supported",
"false",
"otherwise",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L41-L47 | train |
minio/minio-go | pkg/policy/bucket-policy.go | UnmarshalJSON | func (u *User) UnmarshalJSON(data []byte) error {
// Try to unmarshal data in a struct equal to User, we need it
// to avoid infinite recursive call of this function
type AliasUser User
var au AliasUser
err := json.Unmarshal(data, &au)
if err == nil {
*u = User(au)
return nil
}
// Data type is not known, check if it is a json string
// which contains a star, which is permitted in the spec
var str string
err = json.Unmarshal(data, &str)
if err == nil {
if str != "*" {
return errors.New("unrecognized Principal field")
}
*u = User{AWS: set.CreateStringSet("*")}
return nil
}
return err
} | go | func (u *User) UnmarshalJSON(data []byte) error {
// Try to unmarshal data in a struct equal to User, we need it
// to avoid infinite recursive call of this function
type AliasUser User
var au AliasUser
err := json.Unmarshal(data, &au)
if err == nil {
*u = User(au)
return nil
}
// Data type is not known, check if it is a json string
// which contains a star, which is permitted in the spec
var str string
err = json.Unmarshal(data, &str)
if err == nil {
if str != "*" {
return errors.New("unrecognized Principal field")
}
*u = User{AWS: set.CreateStringSet("*")}
return nil
}
return err
} | [
"func",
"(",
"u",
"*",
"User",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"// Try to unmarshal data in a struct equal to User, we need it",
"// to avoid infinite recursive call of this function",
"type",
"AliasUser",
"User",
"\n",
"var",
"au",... | // UnmarshalJSON is a custom json unmarshaler for Principal field,
// the reason is that Principal can take a json struct represented by
// User string but it can also take a string. | [
"UnmarshalJSON",
"is",
"a",
"custom",
"json",
"unmarshaler",
"for",
"Principal",
"field",
"the",
"reason",
"is",
"that",
"Principal",
"can",
"take",
"a",
"json",
"struct",
"represented",
"by",
"User",
"string",
"but",
"it",
"can",
"also",
"take",
"a",
"strin... | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L90-L112 | train |
minio/minio-go | pkg/policy/bucket-policy.go | isValidStatement | func isValidStatement(statement Statement, bucketName string) bool {
if statement.Actions.Intersection(validActions).IsEmpty() {
return false
}
if statement.Effect != "Allow" {
return false
}
if statement.Principal.AWS == nil || !statement.Principal.AWS.Contains("*") {
return false
}
bucketResource := awsResourcePrefix + bucketName
if statement.Resources.Contains(bucketResource) {
return true
}
if statement.Resources.FuncMatch(startsWithFunc, bucketResource+"/").IsEmpty() {
return false
}
return true
} | go | func isValidStatement(statement Statement, bucketName string) bool {
if statement.Actions.Intersection(validActions).IsEmpty() {
return false
}
if statement.Effect != "Allow" {
return false
}
if statement.Principal.AWS == nil || !statement.Principal.AWS.Contains("*") {
return false
}
bucketResource := awsResourcePrefix + bucketName
if statement.Resources.Contains(bucketResource) {
return true
}
if statement.Resources.FuncMatch(startsWithFunc, bucketResource+"/").IsEmpty() {
return false
}
return true
} | [
"func",
"isValidStatement",
"(",
"statement",
"Statement",
",",
"bucketName",
"string",
")",
"bool",
"{",
"if",
"statement",
".",
"Actions",
".",
"Intersection",
"(",
"validActions",
")",
".",
"IsEmpty",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
... | // isValidStatement - returns whether given statement is valid to process for given bucket name. | [
"isValidStatement",
"-",
"returns",
"whether",
"given",
"statement",
"is",
"valid",
"to",
"process",
"for",
"given",
"bucket",
"name",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L131-L154 | train |
minio/minio-go | pkg/policy/bucket-policy.go | newBucketStatement | func newBucketStatement(policy BucketPolicy, bucketName string, prefix string) (statements []Statement) {
statements = []Statement{}
if policy == BucketPolicyNone || bucketName == "" {
return statements
}
bucketResource := set.CreateStringSet(awsResourcePrefix + bucketName)
statement := Statement{
Actions: commonBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
statements = append(statements, statement)
if policy == BucketPolicyReadOnly || policy == BucketPolicyReadWrite {
statement = Statement{
Actions: readOnlyBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
if prefix != "" {
condKeyMap := make(ConditionKeyMap)
condKeyMap.Add("s3:prefix", set.CreateStringSet(prefix))
condMap := make(ConditionMap)
condMap.Add("StringEquals", condKeyMap)
statement.Conditions = condMap
}
statements = append(statements, statement)
}
if policy == BucketPolicyWriteOnly || policy == BucketPolicyReadWrite {
statement = Statement{
Actions: writeOnlyBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
statements = append(statements, statement)
}
return statements
} | go | func newBucketStatement(policy BucketPolicy, bucketName string, prefix string) (statements []Statement) {
statements = []Statement{}
if policy == BucketPolicyNone || bucketName == "" {
return statements
}
bucketResource := set.CreateStringSet(awsResourcePrefix + bucketName)
statement := Statement{
Actions: commonBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
statements = append(statements, statement)
if policy == BucketPolicyReadOnly || policy == BucketPolicyReadWrite {
statement = Statement{
Actions: readOnlyBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
if prefix != "" {
condKeyMap := make(ConditionKeyMap)
condKeyMap.Add("s3:prefix", set.CreateStringSet(prefix))
condMap := make(ConditionMap)
condMap.Add("StringEquals", condKeyMap)
statement.Conditions = condMap
}
statements = append(statements, statement)
}
if policy == BucketPolicyWriteOnly || policy == BucketPolicyReadWrite {
statement = Statement{
Actions: writeOnlyBucketActions,
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: bucketResource,
Sid: "",
}
statements = append(statements, statement)
}
return statements
} | [
"func",
"newBucketStatement",
"(",
"policy",
"BucketPolicy",
",",
"bucketName",
"string",
",",
"prefix",
"string",
")",
"(",
"statements",
"[",
"]",
"Statement",
")",
"{",
"statements",
"=",
"[",
"]",
"Statement",
"{",
"}",
"\n",
"if",
"policy",
"==",
"Buc... | // Returns new statements with bucket actions for given policy. | [
"Returns",
"new",
"statements",
"with",
"bucket",
"actions",
"for",
"given",
"policy",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L157-L204 | train |
minio/minio-go | pkg/policy/bucket-policy.go | newObjectStatement | func newObjectStatement(policy BucketPolicy, bucketName string, prefix string) (statements []Statement) {
statements = []Statement{}
if policy == BucketPolicyNone || bucketName == "" {
return statements
}
statement := Statement{
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: set.CreateStringSet(awsResourcePrefix + bucketName + "/" + prefix + "*"),
Sid: "",
}
if policy == BucketPolicyReadOnly {
statement.Actions = readOnlyObjectActions
} else if policy == BucketPolicyWriteOnly {
statement.Actions = writeOnlyObjectActions
} else if policy == BucketPolicyReadWrite {
statement.Actions = readWriteObjectActions
}
statements = append(statements, statement)
return statements
} | go | func newObjectStatement(policy BucketPolicy, bucketName string, prefix string) (statements []Statement) {
statements = []Statement{}
if policy == BucketPolicyNone || bucketName == "" {
return statements
}
statement := Statement{
Effect: "Allow",
Principal: User{AWS: set.CreateStringSet("*")},
Resources: set.CreateStringSet(awsResourcePrefix + bucketName + "/" + prefix + "*"),
Sid: "",
}
if policy == BucketPolicyReadOnly {
statement.Actions = readOnlyObjectActions
} else if policy == BucketPolicyWriteOnly {
statement.Actions = writeOnlyObjectActions
} else if policy == BucketPolicyReadWrite {
statement.Actions = readWriteObjectActions
}
statements = append(statements, statement)
return statements
} | [
"func",
"newObjectStatement",
"(",
"policy",
"BucketPolicy",
",",
"bucketName",
"string",
",",
"prefix",
"string",
")",
"(",
"statements",
"[",
"]",
"Statement",
")",
"{",
"statements",
"=",
"[",
"]",
"Statement",
"{",
"}",
"\n",
"if",
"policy",
"==",
"Buc... | // Returns new statements contains object actions for given policy. | [
"Returns",
"new",
"statements",
"contains",
"object",
"actions",
"for",
"given",
"policy",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L207-L230 | train |
minio/minio-go | pkg/policy/bucket-policy.go | newStatements | func newStatements(policy BucketPolicy, bucketName string, prefix string) (statements []Statement) {
statements = []Statement{}
ns := newBucketStatement(policy, bucketName, prefix)
statements = append(statements, ns...)
ns = newObjectStatement(policy, bucketName, prefix)
statements = append(statements, ns...)
return statements
} | go | func newStatements(policy BucketPolicy, bucketName string, prefix string) (statements []Statement) {
statements = []Statement{}
ns := newBucketStatement(policy, bucketName, prefix)
statements = append(statements, ns...)
ns = newObjectStatement(policy, bucketName, prefix)
statements = append(statements, ns...)
return statements
} | [
"func",
"newStatements",
"(",
"policy",
"BucketPolicy",
",",
"bucketName",
"string",
",",
"prefix",
"string",
")",
"(",
"statements",
"[",
"]",
"Statement",
")",
"{",
"statements",
"=",
"[",
"]",
"Statement",
"{",
"}",
"\n",
"ns",
":=",
"newBucketStatement",... | // Returns new statements for given policy, bucket and prefix. | [
"Returns",
"new",
"statements",
"for",
"given",
"policy",
"bucket",
"and",
"prefix",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L233-L242 | train |
minio/minio-go | pkg/policy/bucket-policy.go | getInUsePolicy | func getInUsePolicy(statements []Statement, bucketName string, prefix string) (readOnlyInUse, writeOnlyInUse bool) {
resourcePrefix := awsResourcePrefix + bucketName + "/"
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
for _, s := range statements {
if !s.Resources.Contains(objectResource) && !s.Resources.FuncMatch(startsWithFunc, resourcePrefix).IsEmpty() {
if s.Actions.Intersection(readOnlyObjectActions).Equals(readOnlyObjectActions) {
readOnlyInUse = true
}
if s.Actions.Intersection(writeOnlyObjectActions).Equals(writeOnlyObjectActions) {
writeOnlyInUse = true
}
}
if readOnlyInUse && writeOnlyInUse {
break
}
}
return readOnlyInUse, writeOnlyInUse
} | go | func getInUsePolicy(statements []Statement, bucketName string, prefix string) (readOnlyInUse, writeOnlyInUse bool) {
resourcePrefix := awsResourcePrefix + bucketName + "/"
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
for _, s := range statements {
if !s.Resources.Contains(objectResource) && !s.Resources.FuncMatch(startsWithFunc, resourcePrefix).IsEmpty() {
if s.Actions.Intersection(readOnlyObjectActions).Equals(readOnlyObjectActions) {
readOnlyInUse = true
}
if s.Actions.Intersection(writeOnlyObjectActions).Equals(writeOnlyObjectActions) {
writeOnlyInUse = true
}
}
if readOnlyInUse && writeOnlyInUse {
break
}
}
return readOnlyInUse, writeOnlyInUse
} | [
"func",
"getInUsePolicy",
"(",
"statements",
"[",
"]",
"Statement",
",",
"bucketName",
"string",
",",
"prefix",
"string",
")",
"(",
"readOnlyInUse",
",",
"writeOnlyInUse",
"bool",
")",
"{",
"resourcePrefix",
":=",
"awsResourcePrefix",
"+",
"bucketName",
"+",
"\"... | // Returns whether given bucket statements are used by other than given prefix statements. | [
"Returns",
"whether",
"given",
"bucket",
"statements",
"are",
"used",
"by",
"other",
"than",
"given",
"prefix",
"statements",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L245-L265 | train |
minio/minio-go | pkg/policy/bucket-policy.go | removeObjectActions | func removeObjectActions(statement Statement, objectResource string) Statement {
if statement.Conditions == nil {
if len(statement.Resources) > 1 {
statement.Resources.Remove(objectResource)
} else {
statement.Actions = statement.Actions.Difference(readOnlyObjectActions)
statement.Actions = statement.Actions.Difference(writeOnlyObjectActions)
}
}
return statement
} | go | func removeObjectActions(statement Statement, objectResource string) Statement {
if statement.Conditions == nil {
if len(statement.Resources) > 1 {
statement.Resources.Remove(objectResource)
} else {
statement.Actions = statement.Actions.Difference(readOnlyObjectActions)
statement.Actions = statement.Actions.Difference(writeOnlyObjectActions)
}
}
return statement
} | [
"func",
"removeObjectActions",
"(",
"statement",
"Statement",
",",
"objectResource",
"string",
")",
"Statement",
"{",
"if",
"statement",
".",
"Conditions",
"==",
"nil",
"{",
"if",
"len",
"(",
"statement",
".",
"Resources",
")",
">",
"1",
"{",
"statement",
".... | // Removes object actions in given statement. | [
"Removes",
"object",
"actions",
"in",
"given",
"statement",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L268-L279 | train |
minio/minio-go | pkg/policy/bucket-policy.go | removeBucketActions | func removeBucketActions(statement Statement, prefix string, bucketResource string, readOnlyInUse, writeOnlyInUse bool) Statement {
removeReadOnly := func() {
if !statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) {
return
}
if statement.Conditions == nil {
statement.Actions = statement.Actions.Difference(readOnlyBucketActions)
return
}
if prefix != "" {
stringEqualsValue := statement.Conditions["StringEquals"]
values := set.NewStringSet()
if stringEqualsValue != nil {
values = stringEqualsValue["s3:prefix"]
if values == nil {
values = set.NewStringSet()
}
}
values.Remove(prefix)
if stringEqualsValue != nil {
if values.IsEmpty() {
delete(stringEqualsValue, "s3:prefix")
}
if len(stringEqualsValue) == 0 {
delete(statement.Conditions, "StringEquals")
}
}
if len(statement.Conditions) == 0 {
statement.Conditions = nil
statement.Actions = statement.Actions.Difference(readOnlyBucketActions)
}
}
}
removeWriteOnly := func() {
if statement.Conditions == nil {
statement.Actions = statement.Actions.Difference(writeOnlyBucketActions)
}
}
if len(statement.Resources) > 1 {
statement.Resources.Remove(bucketResource)
} else {
if !readOnlyInUse {
removeReadOnly()
}
if !writeOnlyInUse {
removeWriteOnly()
}
}
return statement
} | go | func removeBucketActions(statement Statement, prefix string, bucketResource string, readOnlyInUse, writeOnlyInUse bool) Statement {
removeReadOnly := func() {
if !statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) {
return
}
if statement.Conditions == nil {
statement.Actions = statement.Actions.Difference(readOnlyBucketActions)
return
}
if prefix != "" {
stringEqualsValue := statement.Conditions["StringEquals"]
values := set.NewStringSet()
if stringEqualsValue != nil {
values = stringEqualsValue["s3:prefix"]
if values == nil {
values = set.NewStringSet()
}
}
values.Remove(prefix)
if stringEqualsValue != nil {
if values.IsEmpty() {
delete(stringEqualsValue, "s3:prefix")
}
if len(stringEqualsValue) == 0 {
delete(statement.Conditions, "StringEquals")
}
}
if len(statement.Conditions) == 0 {
statement.Conditions = nil
statement.Actions = statement.Actions.Difference(readOnlyBucketActions)
}
}
}
removeWriteOnly := func() {
if statement.Conditions == nil {
statement.Actions = statement.Actions.Difference(writeOnlyBucketActions)
}
}
if len(statement.Resources) > 1 {
statement.Resources.Remove(bucketResource)
} else {
if !readOnlyInUse {
removeReadOnly()
}
if !writeOnlyInUse {
removeWriteOnly()
}
}
return statement
} | [
"func",
"removeBucketActions",
"(",
"statement",
"Statement",
",",
"prefix",
"string",
",",
"bucketResource",
"string",
",",
"readOnlyInUse",
",",
"writeOnlyInUse",
"bool",
")",
"Statement",
"{",
"removeReadOnly",
":=",
"func",
"(",
")",
"{",
"if",
"!",
"stateme... | // Removes bucket actions for given policy in given statement. | [
"Removes",
"bucket",
"actions",
"for",
"given",
"policy",
"in",
"given",
"statement",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L282-L340 | train |
minio/minio-go | pkg/policy/bucket-policy.go | appendStatement | func appendStatement(statements []Statement, statement Statement) []Statement {
for i, s := range statements {
if s.Actions.Equals(statement.Actions) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Equals(statement.Principal.AWS) &&
reflect.DeepEqual(s.Conditions, statement.Conditions) {
statements[i].Resources = s.Resources.Union(statement.Resources)
return statements
} else if s.Resources.Equals(statement.Resources) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Equals(statement.Principal.AWS) &&
reflect.DeepEqual(s.Conditions, statement.Conditions) {
statements[i].Actions = s.Actions.Union(statement.Actions)
return statements
}
if s.Resources.Intersection(statement.Resources).Equals(statement.Resources) &&
s.Actions.Intersection(statement.Actions).Equals(statement.Actions) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Intersection(statement.Principal.AWS).Equals(statement.Principal.AWS) {
if reflect.DeepEqual(s.Conditions, statement.Conditions) {
return statements
}
if s.Conditions != nil && statement.Conditions != nil {
if s.Resources.Equals(statement.Resources) {
statements[i].Conditions = mergeConditionMap(s.Conditions, statement.Conditions)
return statements
}
}
}
}
if !(statement.Actions.IsEmpty() && statement.Resources.IsEmpty()) {
return append(statements, statement)
}
return statements
} | go | func appendStatement(statements []Statement, statement Statement) []Statement {
for i, s := range statements {
if s.Actions.Equals(statement.Actions) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Equals(statement.Principal.AWS) &&
reflect.DeepEqual(s.Conditions, statement.Conditions) {
statements[i].Resources = s.Resources.Union(statement.Resources)
return statements
} else if s.Resources.Equals(statement.Resources) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Equals(statement.Principal.AWS) &&
reflect.DeepEqual(s.Conditions, statement.Conditions) {
statements[i].Actions = s.Actions.Union(statement.Actions)
return statements
}
if s.Resources.Intersection(statement.Resources).Equals(statement.Resources) &&
s.Actions.Intersection(statement.Actions).Equals(statement.Actions) &&
s.Effect == statement.Effect &&
s.Principal.AWS.Intersection(statement.Principal.AWS).Equals(statement.Principal.AWS) {
if reflect.DeepEqual(s.Conditions, statement.Conditions) {
return statements
}
if s.Conditions != nil && statement.Conditions != nil {
if s.Resources.Equals(statement.Resources) {
statements[i].Conditions = mergeConditionMap(s.Conditions, statement.Conditions)
return statements
}
}
}
}
if !(statement.Actions.IsEmpty() && statement.Resources.IsEmpty()) {
return append(statements, statement)
}
return statements
} | [
"func",
"appendStatement",
"(",
"statements",
"[",
"]",
"Statement",
",",
"statement",
"Statement",
")",
"[",
"]",
"Statement",
"{",
"for",
"i",
",",
"s",
":=",
"range",
"statements",
"{",
"if",
"s",
".",
"Actions",
".",
"Equals",
"(",
"statement",
".",
... | // Appends given statement into statement list to have unique statements.
// - If statement already exists in statement list, it ignores.
// - If statement exists with different conditions, they are merged.
// - Else the statement is appended to statement list. | [
"Appends",
"given",
"statement",
"into",
"statement",
"list",
"to",
"have",
"unique",
"statements",
".",
"-",
"If",
"statement",
"already",
"exists",
"in",
"statement",
"list",
"it",
"ignores",
".",
"-",
"If",
"statement",
"exists",
"with",
"different",
"condi... | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L436-L473 | train |
minio/minio-go | pkg/policy/bucket-policy.go | appendStatements | func appendStatements(statements []Statement, appendStatements []Statement) []Statement {
for _, s := range appendStatements {
statements = appendStatement(statements, s)
}
return statements
} | go | func appendStatements(statements []Statement, appendStatements []Statement) []Statement {
for _, s := range appendStatements {
statements = appendStatement(statements, s)
}
return statements
} | [
"func",
"appendStatements",
"(",
"statements",
"[",
"]",
"Statement",
",",
"appendStatements",
"[",
"]",
"Statement",
")",
"[",
"]",
"Statement",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"appendStatements",
"{",
"statements",
"=",
"appendStatement",
"(",
"s... | // Appends two statement lists. | [
"Appends",
"two",
"statement",
"lists",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L476-L482 | train |
minio/minio-go | pkg/policy/bucket-policy.go | getBucketPolicy | func getBucketPolicy(statement Statement, prefix string) (commonFound, readOnly, writeOnly bool) {
if !(statement.Effect == "Allow" && statement.Principal.AWS.Contains("*")) {
return commonFound, readOnly, writeOnly
}
if statement.Actions.Intersection(commonBucketActions).Equals(commonBucketActions) &&
statement.Conditions == nil {
commonFound = true
}
if statement.Actions.Intersection(writeOnlyBucketActions).Equals(writeOnlyBucketActions) &&
statement.Conditions == nil {
writeOnly = true
}
if statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) {
if prefix != "" && statement.Conditions != nil {
if stringEqualsValue, ok := statement.Conditions["StringEquals"]; ok {
if s3PrefixValues, ok := stringEqualsValue["s3:prefix"]; ok {
if s3PrefixValues.Contains(prefix) {
readOnly = true
}
}
} else if stringNotEqualsValue, ok := statement.Conditions["StringNotEquals"]; ok {
if s3PrefixValues, ok := stringNotEqualsValue["s3:prefix"]; ok {
if !s3PrefixValues.Contains(prefix) {
readOnly = true
}
}
}
} else if prefix == "" && statement.Conditions == nil {
readOnly = true
} else if prefix != "" && statement.Conditions == nil {
readOnly = true
}
}
return commonFound, readOnly, writeOnly
} | go | func getBucketPolicy(statement Statement, prefix string) (commonFound, readOnly, writeOnly bool) {
if !(statement.Effect == "Allow" && statement.Principal.AWS.Contains("*")) {
return commonFound, readOnly, writeOnly
}
if statement.Actions.Intersection(commonBucketActions).Equals(commonBucketActions) &&
statement.Conditions == nil {
commonFound = true
}
if statement.Actions.Intersection(writeOnlyBucketActions).Equals(writeOnlyBucketActions) &&
statement.Conditions == nil {
writeOnly = true
}
if statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) {
if prefix != "" && statement.Conditions != nil {
if stringEqualsValue, ok := statement.Conditions["StringEquals"]; ok {
if s3PrefixValues, ok := stringEqualsValue["s3:prefix"]; ok {
if s3PrefixValues.Contains(prefix) {
readOnly = true
}
}
} else if stringNotEqualsValue, ok := statement.Conditions["StringNotEquals"]; ok {
if s3PrefixValues, ok := stringNotEqualsValue["s3:prefix"]; ok {
if !s3PrefixValues.Contains(prefix) {
readOnly = true
}
}
}
} else if prefix == "" && statement.Conditions == nil {
readOnly = true
} else if prefix != "" && statement.Conditions == nil {
readOnly = true
}
}
return commonFound, readOnly, writeOnly
} | [
"func",
"getBucketPolicy",
"(",
"statement",
"Statement",
",",
"prefix",
"string",
")",
"(",
"commonFound",
",",
"readOnly",
",",
"writeOnly",
"bool",
")",
"{",
"if",
"!",
"(",
"statement",
".",
"Effect",
"==",
"\"",
"\"",
"&&",
"statement",
".",
"Principa... | // Returns policy of given bucket statement. | [
"Returns",
"policy",
"of",
"given",
"bucket",
"statement",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L485-L523 | train |
minio/minio-go | pkg/policy/bucket-policy.go | getObjectPolicy | func getObjectPolicy(statement Statement) (readOnly bool, writeOnly bool) {
if statement.Effect == "Allow" &&
statement.Principal.AWS.Contains("*") &&
statement.Conditions == nil {
if statement.Actions.Intersection(readOnlyObjectActions).Equals(readOnlyObjectActions) {
readOnly = true
}
if statement.Actions.Intersection(writeOnlyObjectActions).Equals(writeOnlyObjectActions) {
writeOnly = true
}
}
return readOnly, writeOnly
} | go | func getObjectPolicy(statement Statement) (readOnly bool, writeOnly bool) {
if statement.Effect == "Allow" &&
statement.Principal.AWS.Contains("*") &&
statement.Conditions == nil {
if statement.Actions.Intersection(readOnlyObjectActions).Equals(readOnlyObjectActions) {
readOnly = true
}
if statement.Actions.Intersection(writeOnlyObjectActions).Equals(writeOnlyObjectActions) {
writeOnly = true
}
}
return readOnly, writeOnly
} | [
"func",
"getObjectPolicy",
"(",
"statement",
"Statement",
")",
"(",
"readOnly",
"bool",
",",
"writeOnly",
"bool",
")",
"{",
"if",
"statement",
".",
"Effect",
"==",
"\"",
"\"",
"&&",
"statement",
".",
"Principal",
".",
"AWS",
".",
"Contains",
"(",
"\"",
"... | // Returns policy of given object statement. | [
"Returns",
"policy",
"of",
"given",
"object",
"statement",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L526-L539 | train |
minio/minio-go | pkg/policy/bucket-policy.go | GetPolicy | func GetPolicy(statements []Statement, bucketName string, prefix string) BucketPolicy {
bucketResource := awsResourcePrefix + bucketName
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
bucketCommonFound := false
bucketReadOnly := false
bucketWriteOnly := false
matchedResource := ""
objReadOnly := false
objWriteOnly := false
for _, s := range statements {
matchedObjResources := set.NewStringSet()
if s.Resources.Contains(objectResource) {
matchedObjResources.Add(objectResource)
} else {
matchedObjResources = s.Resources.FuncMatch(resourceMatch, objectResource)
}
if !matchedObjResources.IsEmpty() {
readOnly, writeOnly := getObjectPolicy(s)
for resource := range matchedObjResources {
if len(matchedResource) < len(resource) {
objReadOnly = readOnly
objWriteOnly = writeOnly
matchedResource = resource
} else if len(matchedResource) == len(resource) {
objReadOnly = objReadOnly || readOnly
objWriteOnly = objWriteOnly || writeOnly
matchedResource = resource
}
}
}
if s.Resources.Contains(bucketResource) {
commonFound, readOnly, writeOnly := getBucketPolicy(s, prefix)
bucketCommonFound = bucketCommonFound || commonFound
bucketReadOnly = bucketReadOnly || readOnly
bucketWriteOnly = bucketWriteOnly || writeOnly
}
}
policy := BucketPolicyNone
if bucketCommonFound {
if bucketReadOnly && bucketWriteOnly && objReadOnly && objWriteOnly {
policy = BucketPolicyReadWrite
} else if bucketReadOnly && objReadOnly {
policy = BucketPolicyReadOnly
} else if bucketWriteOnly && objWriteOnly {
policy = BucketPolicyWriteOnly
}
}
return policy
} | go | func GetPolicy(statements []Statement, bucketName string, prefix string) BucketPolicy {
bucketResource := awsResourcePrefix + bucketName
objectResource := awsResourcePrefix + bucketName + "/" + prefix + "*"
bucketCommonFound := false
bucketReadOnly := false
bucketWriteOnly := false
matchedResource := ""
objReadOnly := false
objWriteOnly := false
for _, s := range statements {
matchedObjResources := set.NewStringSet()
if s.Resources.Contains(objectResource) {
matchedObjResources.Add(objectResource)
} else {
matchedObjResources = s.Resources.FuncMatch(resourceMatch, objectResource)
}
if !matchedObjResources.IsEmpty() {
readOnly, writeOnly := getObjectPolicy(s)
for resource := range matchedObjResources {
if len(matchedResource) < len(resource) {
objReadOnly = readOnly
objWriteOnly = writeOnly
matchedResource = resource
} else if len(matchedResource) == len(resource) {
objReadOnly = objReadOnly || readOnly
objWriteOnly = objWriteOnly || writeOnly
matchedResource = resource
}
}
}
if s.Resources.Contains(bucketResource) {
commonFound, readOnly, writeOnly := getBucketPolicy(s, prefix)
bucketCommonFound = bucketCommonFound || commonFound
bucketReadOnly = bucketReadOnly || readOnly
bucketWriteOnly = bucketWriteOnly || writeOnly
}
}
policy := BucketPolicyNone
if bucketCommonFound {
if bucketReadOnly && bucketWriteOnly && objReadOnly && objWriteOnly {
policy = BucketPolicyReadWrite
} else if bucketReadOnly && objReadOnly {
policy = BucketPolicyReadOnly
} else if bucketWriteOnly && objWriteOnly {
policy = BucketPolicyWriteOnly
}
}
return policy
} | [
"func",
"GetPolicy",
"(",
"statements",
"[",
"]",
"Statement",
",",
"bucketName",
"string",
",",
"prefix",
"string",
")",
"BucketPolicy",
"{",
"bucketResource",
":=",
"awsResourcePrefix",
"+",
"bucketName",
"\n",
"objectResource",
":=",
"awsResourcePrefix",
"+",
"... | // GetPolicy - Returns policy of given bucket name, prefix in given statements. | [
"GetPolicy",
"-",
"Returns",
"policy",
"of",
"given",
"bucket",
"name",
"prefix",
"in",
"given",
"statements",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L542-L594 | train |
minio/minio-go | pkg/policy/bucket-policy.go | GetPolicies | func GetPolicies(statements []Statement, bucketName, prefix string) map[string]BucketPolicy {
policyRules := map[string]BucketPolicy{}
objResources := set.NewStringSet()
// Search all resources related to objects policy
for _, s := range statements {
for r := range s.Resources {
if strings.HasPrefix(r, awsResourcePrefix+bucketName+"/"+prefix) {
objResources.Add(r)
}
}
}
// Pretend that policy resource as an actual object and fetch its policy
for r := range objResources {
// Put trailing * if exists in asterisk
asterisk := ""
if strings.HasSuffix(r, "*") {
r = r[:len(r)-1]
asterisk = "*"
}
var objectPath string
if len(r) >= len(awsResourcePrefix+bucketName)+1 {
objectPath = r[len(awsResourcePrefix+bucketName)+1:]
}
p := GetPolicy(statements, bucketName, objectPath)
policyRules[bucketName+"/"+objectPath+asterisk] = p
}
return policyRules
} | go | func GetPolicies(statements []Statement, bucketName, prefix string) map[string]BucketPolicy {
policyRules := map[string]BucketPolicy{}
objResources := set.NewStringSet()
// Search all resources related to objects policy
for _, s := range statements {
for r := range s.Resources {
if strings.HasPrefix(r, awsResourcePrefix+bucketName+"/"+prefix) {
objResources.Add(r)
}
}
}
// Pretend that policy resource as an actual object and fetch its policy
for r := range objResources {
// Put trailing * if exists in asterisk
asterisk := ""
if strings.HasSuffix(r, "*") {
r = r[:len(r)-1]
asterisk = "*"
}
var objectPath string
if len(r) >= len(awsResourcePrefix+bucketName)+1 {
objectPath = r[len(awsResourcePrefix+bucketName)+1:]
}
p := GetPolicy(statements, bucketName, objectPath)
policyRules[bucketName+"/"+objectPath+asterisk] = p
}
return policyRules
} | [
"func",
"GetPolicies",
"(",
"statements",
"[",
"]",
"Statement",
",",
"bucketName",
",",
"prefix",
"string",
")",
"map",
"[",
"string",
"]",
"BucketPolicy",
"{",
"policyRules",
":=",
"map",
"[",
"string",
"]",
"BucketPolicy",
"{",
"}",
"\n",
"objResources",
... | // GetPolicies - returns a map of policies of given bucket name, prefix in given statements. | [
"GetPolicies",
"-",
"returns",
"a",
"map",
"of",
"policies",
"of",
"given",
"bucket",
"name",
"prefix",
"in",
"given",
"statements",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L597-L625 | train |
minio/minio-go | pkg/policy/bucket-policy.go | SetPolicy | func SetPolicy(statements []Statement, policy BucketPolicy, bucketName string, prefix string) []Statement {
out := removeStatements(statements, bucketName, prefix)
// fmt.Println("out = ")
// printstatement(out)
ns := newStatements(policy, bucketName, prefix)
// fmt.Println("ns = ")
// printstatement(ns)
rv := appendStatements(out, ns)
// fmt.Println("rv = ")
// printstatement(rv)
return rv
} | go | func SetPolicy(statements []Statement, policy BucketPolicy, bucketName string, prefix string) []Statement {
out := removeStatements(statements, bucketName, prefix)
// fmt.Println("out = ")
// printstatement(out)
ns := newStatements(policy, bucketName, prefix)
// fmt.Println("ns = ")
// printstatement(ns)
rv := appendStatements(out, ns)
// fmt.Println("rv = ")
// printstatement(rv)
return rv
} | [
"func",
"SetPolicy",
"(",
"statements",
"[",
"]",
"Statement",
",",
"policy",
"BucketPolicy",
",",
"bucketName",
"string",
",",
"prefix",
"string",
")",
"[",
"]",
"Statement",
"{",
"out",
":=",
"removeStatements",
"(",
"statements",
",",
"bucketName",
",",
"... | // SetPolicy - Returns new statements containing policy of given bucket name and prefix are appended. | [
"SetPolicy",
"-",
"Returns",
"new",
"statements",
"containing",
"policy",
"of",
"given",
"bucket",
"name",
"and",
"prefix",
"are",
"appended",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L628-L641 | train |
minio/minio-go | pkg/policy/bucket-policy.go | resourceMatch | func resourceMatch(pattern, resource string) bool {
if pattern == "" {
return resource == pattern
}
if pattern == "*" {
return true
}
parts := strings.Split(pattern, "*")
if len(parts) == 1 {
return resource == pattern
}
tGlob := strings.HasSuffix(pattern, "*")
end := len(parts) - 1
if !strings.HasPrefix(resource, parts[0]) {
return false
}
for i := 1; i < end; i++ {
if !strings.Contains(resource, parts[i]) {
return false
}
idx := strings.Index(resource, parts[i]) + len(parts[i])
resource = resource[idx:]
}
return tGlob || strings.HasSuffix(resource, parts[end])
} | go | func resourceMatch(pattern, resource string) bool {
if pattern == "" {
return resource == pattern
}
if pattern == "*" {
return true
}
parts := strings.Split(pattern, "*")
if len(parts) == 1 {
return resource == pattern
}
tGlob := strings.HasSuffix(pattern, "*")
end := len(parts) - 1
if !strings.HasPrefix(resource, parts[0]) {
return false
}
for i := 1; i < end; i++ {
if !strings.Contains(resource, parts[i]) {
return false
}
idx := strings.Index(resource, parts[i]) + len(parts[i])
resource = resource[idx:]
}
return tGlob || strings.HasSuffix(resource, parts[end])
} | [
"func",
"resourceMatch",
"(",
"pattern",
",",
"resource",
"string",
")",
"bool",
"{",
"if",
"pattern",
"==",
"\"",
"\"",
"{",
"return",
"resource",
"==",
"pattern",
"\n",
"}",
"\n",
"if",
"pattern",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
... | // Match function matches wild cards in 'pattern' for resource. | [
"Match",
"function",
"matches",
"wild",
"cards",
"in",
"pattern",
"for",
"resource",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L644-L668 | train |
minio/minio-go | api-put-object-context.go | PutObjectWithContext | func (c Client) PutObjectWithContext(ctx context.Context, bucketName, objectName string, reader io.Reader, objectSize int64,
opts PutObjectOptions) (n int64, err error) {
err = opts.validate()
if err != nil {
return 0, err
}
return c.putObjectCommon(ctx, bucketName, objectName, reader, objectSize, opts)
} | go | func (c Client) PutObjectWithContext(ctx context.Context, bucketName, objectName string, reader io.Reader, objectSize int64,
opts PutObjectOptions) (n int64, err error) {
err = opts.validate()
if err != nil {
return 0, err
}
return c.putObjectCommon(ctx, bucketName, objectName, reader, objectSize, opts)
} | [
"func",
"(",
"c",
"Client",
")",
"PutObjectWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
",",
"objectName",
"string",
",",
"reader",
"io",
".",
"Reader",
",",
"objectSize",
"int64",
",",
"opts",
"PutObjectOptions",
")",
"(",
"n",
... | // PutObjectWithContext - Identical to PutObject call, but accepts context to facilitate request cancellation. | [
"PutObjectWithContext",
"-",
"Identical",
"to",
"PutObject",
"call",
"but",
"accepts",
"context",
"to",
"facilitate",
"request",
"cancellation",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-put-object-context.go#L26-L33 | train |
minio/minio-go | api-get-object-context.go | GetObjectWithContext | func (c Client) GetObjectWithContext(ctx context.Context, bucketName, objectName string, opts GetObjectOptions) (*Object, error) {
return c.getObjectWithContext(ctx, bucketName, objectName, opts)
} | go | func (c Client) GetObjectWithContext(ctx context.Context, bucketName, objectName string, opts GetObjectOptions) (*Object, error) {
return c.getObjectWithContext(ctx, bucketName, objectName, opts)
} | [
"func",
"(",
"c",
"Client",
")",
"GetObjectWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
",",
"objectName",
"string",
",",
"opts",
"GetObjectOptions",
")",
"(",
"*",
"Object",
",",
"error",
")",
"{",
"return",
"c",
".",
"getObject... | // GetObjectWithContext - returns an seekable, readable object.
// The options can be used to specify the GET request further. | [
"GetObjectWithContext",
"-",
"returns",
"an",
"seekable",
"readable",
"object",
".",
"The",
"options",
"can",
"be",
"used",
"to",
"specify",
"the",
"GET",
"request",
"further",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-object-context.go#L24-L26 | train |
minio/minio-go | api-get-lifecycle.go | GetBucketLifecycle | func (c Client) GetBucketLifecycle(bucketName string) (string, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return "", err
}
bucketLifecycle, err := c.getBucketLifecycle(bucketName)
if err != nil {
errResponse := ToErrorResponse(err)
if errResponse.Code == "NoSuchLifecycleConfiguration" {
return "", nil
}
return "", err
}
return bucketLifecycle, nil
} | go | func (c Client) GetBucketLifecycle(bucketName string) (string, error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return "", err
}
bucketLifecycle, err := c.getBucketLifecycle(bucketName)
if err != nil {
errResponse := ToErrorResponse(err)
if errResponse.Code == "NoSuchLifecycleConfiguration" {
return "", nil
}
return "", err
}
return bucketLifecycle, nil
} | [
"func",
"(",
"c",
"Client",
")",
"GetBucketLifecycle",
"(",
"bucketName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Input validation.",
"if",
"err",
":=",
"s3utils",
".",
"CheckValidBucketName",
"(",
"bucketName",
")",
";",
"err",
"!=",
"nil"... | // GetBucketLifecycle - get bucket lifecycle. | [
"GetBucketLifecycle",
"-",
"get",
"bucket",
"lifecycle",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-lifecycle.go#L30-L44 | train |
minio/minio-go | api-get-lifecycle.go | getBucketLifecycle | func (c Client) getBucketLifecycle(bucketName string) (string, error) {
// Get resources properly escaped and lined up before
// using them in http request.
urlValues := make(url.Values)
urlValues.Set("lifecycle", "")
// Execute GET on bucket to get lifecycle.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
})
defer closeResponse(resp)
if err != nil {
return "", err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return "", httpRespToErrorResponse(resp, bucketName, "")
}
}
bucketLifecycleBuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
lifecycle := string(bucketLifecycleBuf)
return lifecycle, err
} | go | func (c Client) getBucketLifecycle(bucketName string) (string, error) {
// Get resources properly escaped and lined up before
// using them in http request.
urlValues := make(url.Values)
urlValues.Set("lifecycle", "")
// Execute GET on bucket to get lifecycle.
resp, err := c.executeMethod(context.Background(), "GET", requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
})
defer closeResponse(resp)
if err != nil {
return "", err
}
if resp != nil {
if resp.StatusCode != http.StatusOK {
return "", httpRespToErrorResponse(resp, bucketName, "")
}
}
bucketLifecycleBuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
lifecycle := string(bucketLifecycleBuf)
return lifecycle, err
} | [
"func",
"(",
"c",
"Client",
")",
"getBucketLifecycle",
"(",
"bucketName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Get resources properly escaped and lined up before",
"// using them in http request.",
"urlValues",
":=",
"make",
"(",
"url",
".",
"Valu... | // Request server for current bucket lifecycle. | [
"Request",
"server",
"for",
"current",
"bucket",
"lifecycle",
"."
] | 68eef499b4c530409962a5d1a12fa8c848587761 | https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-lifecycle.go#L47-L77 | train |
vsergeev/btckeygenie | btckey/btckey.go | derive | func (priv *PrivateKey) derive() (pub *PublicKey) {
/* See Certicom's SEC1 3.2.1, pg.23 */
/* Derive public key from Q = d*G */
Q := secp256k1.ScalarBaseMult(priv.D)
/* Check that Q is on the curve */
if !secp256k1.IsOnCurve(Q) {
panic("Catastrophic math logic failure in public key derivation.")
}
priv.X = Q.X
priv.Y = Q.Y
return &priv.PublicKey
} | go | func (priv *PrivateKey) derive() (pub *PublicKey) {
/* See Certicom's SEC1 3.2.1, pg.23 */
/* Derive public key from Q = d*G */
Q := secp256k1.ScalarBaseMult(priv.D)
/* Check that Q is on the curve */
if !secp256k1.IsOnCurve(Q) {
panic("Catastrophic math logic failure in public key derivation.")
}
priv.X = Q.X
priv.Y = Q.Y
return &priv.PublicKey
} | [
"func",
"(",
"priv",
"*",
"PrivateKey",
")",
"derive",
"(",
")",
"(",
"pub",
"*",
"PublicKey",
")",
"{",
"/* See Certicom's SEC1 3.2.1, pg.23 */",
"/* Derive public key from Q = d*G */",
"Q",
":=",
"secp256k1",
".",
"ScalarBaseMult",
"(",
"priv",
".",
"D",
")",
... | // derive derives a Bitcoin public key from a Bitcoin private key. | [
"derive",
"derives",
"a",
"Bitcoin",
"public",
"key",
"from",
"a",
"Bitcoin",
"private",
"key",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L54-L69 | train |
vsergeev/btckeygenie | btckey/btckey.go | GenerateKey | func GenerateKey(rand io.Reader) (priv PrivateKey, err error) {
/* See Certicom's SEC1 3.2.1, pg.23 */
/* See NSA's Suite B Implementer’s Guide to FIPS 186-3 (ECDSA) A.1.1, pg.18 */
/* Select private key d randomly from [1, n) */
/* Read N bit length random bytes + 64 extra bits */
b := make([]byte, secp256k1.N.BitLen()/8+8)
_, err = io.ReadFull(rand, b)
if err != nil {
return priv, fmt.Errorf("Reading random reader: %v", err)
}
d := new(big.Int).SetBytes(b)
/* Mod n-1 to shift d into [0, n-1) range */
d.Mod(d, new(big.Int).Sub(secp256k1.N, big.NewInt(1)))
/* Add one to shift d to [1, n) range */
d.Add(d, big.NewInt(1))
priv.D = d
/* Derive public key from private key */
priv.derive()
return priv, nil
} | go | func GenerateKey(rand io.Reader) (priv PrivateKey, err error) {
/* See Certicom's SEC1 3.2.1, pg.23 */
/* See NSA's Suite B Implementer’s Guide to FIPS 186-3 (ECDSA) A.1.1, pg.18 */
/* Select private key d randomly from [1, n) */
/* Read N bit length random bytes + 64 extra bits */
b := make([]byte, secp256k1.N.BitLen()/8+8)
_, err = io.ReadFull(rand, b)
if err != nil {
return priv, fmt.Errorf("Reading random reader: %v", err)
}
d := new(big.Int).SetBytes(b)
/* Mod n-1 to shift d into [0, n-1) range */
d.Mod(d, new(big.Int).Sub(secp256k1.N, big.NewInt(1)))
/* Add one to shift d to [1, n) range */
d.Add(d, big.NewInt(1))
priv.D = d
/* Derive public key from private key */
priv.derive()
return priv, nil
} | [
"func",
"GenerateKey",
"(",
"rand",
"io",
".",
"Reader",
")",
"(",
"priv",
"PrivateKey",
",",
"err",
"error",
")",
"{",
"/* See Certicom's SEC1 3.2.1, pg.23 */",
"/* See NSA's Suite B Implementer’s Guide to FIPS 186-3 (ECDSA) A.1.1, pg.18 */",
"/* Select private key d randomly fr... | // GenerateKey generates a public and private key pair using random source rand. | [
"GenerateKey",
"generates",
"a",
"public",
"and",
"private",
"key",
"pair",
"using",
"random",
"source",
"rand",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L72-L98 | train |
vsergeev/btckeygenie | btckey/btckey.go | b58decode | func b58decode(s string) (b []byte, err error) {
/* See https://en.bitcoin.it/wiki/Base58Check_encoding */
const BITCOIN_BASE58_TABLE = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
/* Initialize */
x := big.NewInt(0)
m := big.NewInt(58)
/* Convert string to big int */
for i := 0; i < len(s); i++ {
b58index := strings.IndexByte(BITCOIN_BASE58_TABLE, s[i])
if b58index == -1 {
return nil, fmt.Errorf("Invalid base-58 character encountered: '%c', index %d.", s[i], i)
}
b58value := big.NewInt(int64(b58index))
x.Mul(x, m)
x.Add(x, b58value)
}
/* Convert big int to big endian bytes */
b = x.Bytes()
return b, nil
} | go | func b58decode(s string) (b []byte, err error) {
/* See https://en.bitcoin.it/wiki/Base58Check_encoding */
const BITCOIN_BASE58_TABLE = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
/* Initialize */
x := big.NewInt(0)
m := big.NewInt(58)
/* Convert string to big int */
for i := 0; i < len(s); i++ {
b58index := strings.IndexByte(BITCOIN_BASE58_TABLE, s[i])
if b58index == -1 {
return nil, fmt.Errorf("Invalid base-58 character encountered: '%c', index %d.", s[i], i)
}
b58value := big.NewInt(int64(b58index))
x.Mul(x, m)
x.Add(x, b58value)
}
/* Convert big int to big endian bytes */
b = x.Bytes()
return b, nil
} | [
"func",
"b58decode",
"(",
"s",
"string",
")",
"(",
"b",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"/* See https://en.bitcoin.it/wiki/Base58Check_encoding */",
"const",
"BITCOIN_BASE58_TABLE",
"=",
"\"",
"\"",
"\n\n",
"/* Initialize */",
"x",
":=",
"big",
... | // b58decode decodes a base-58 encoded string into a byte slice b. | [
"b58decode",
"decodes",
"a",
"base",
"-",
"58",
"encoded",
"string",
"into",
"a",
"byte",
"slice",
"b",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L131-L155 | train |
vsergeev/btckeygenie | btckey/btckey.go | b58checkdecode | func b58checkdecode(s string) (ver uint8, b []byte, err error) {
/* Decode base58 string */
b, err = b58decode(s)
if err != nil {
return 0, nil, err
}
/* Add leading zero bytes */
for i := 0; i < len(s); i++ {
if s[i] != '1' {
break
}
b = append([]byte{0x00}, b...)
}
/* Verify checksum */
if len(b) < 5 {
return 0, nil, fmt.Errorf("Invalid base-58 check string: missing checksum.")
}
/* Create a new SHA256 context */
sha256_h := sha256.New()
/* SHA256 Hash #1 */
sha256_h.Reset()
sha256_h.Write(b[:len(b)-4])
hash1 := sha256_h.Sum(nil)
/* SHA256 Hash #2 */
sha256_h.Reset()
sha256_h.Write(hash1)
hash2 := sha256_h.Sum(nil)
/* Compare checksum */
if bytes.Compare(hash2[0:4], b[len(b)-4:]) != 0 {
return 0, nil, fmt.Errorf("Invalid base-58 check string: invalid checksum.")
}
/* Strip checksum bytes */
b = b[:len(b)-4]
/* Extract and strip version */
ver = b[0]
b = b[1:]
return ver, b, nil
} | go | func b58checkdecode(s string) (ver uint8, b []byte, err error) {
/* Decode base58 string */
b, err = b58decode(s)
if err != nil {
return 0, nil, err
}
/* Add leading zero bytes */
for i := 0; i < len(s); i++ {
if s[i] != '1' {
break
}
b = append([]byte{0x00}, b...)
}
/* Verify checksum */
if len(b) < 5 {
return 0, nil, fmt.Errorf("Invalid base-58 check string: missing checksum.")
}
/* Create a new SHA256 context */
sha256_h := sha256.New()
/* SHA256 Hash #1 */
sha256_h.Reset()
sha256_h.Write(b[:len(b)-4])
hash1 := sha256_h.Sum(nil)
/* SHA256 Hash #2 */
sha256_h.Reset()
sha256_h.Write(hash1)
hash2 := sha256_h.Sum(nil)
/* Compare checksum */
if bytes.Compare(hash2[0:4], b[len(b)-4:]) != 0 {
return 0, nil, fmt.Errorf("Invalid base-58 check string: invalid checksum.")
}
/* Strip checksum bytes */
b = b[:len(b)-4]
/* Extract and strip version */
ver = b[0]
b = b[1:]
return ver, b, nil
} | [
"func",
"b58checkdecode",
"(",
"s",
"string",
")",
"(",
"ver",
"uint8",
",",
"b",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"/* Decode base58 string */",
"b",
",",
"err",
"=",
"b58decode",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // b58checkdecode decodes base-58 check encoded string s into a version ver and byte slice b. | [
"b58checkdecode",
"decodes",
"base",
"-",
"58",
"check",
"encoded",
"string",
"s",
"into",
"a",
"version",
"ver",
"and",
"byte",
"slice",
"b",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L197-L243 | train |
vsergeev/btckeygenie | btckey/btckey.go | ToBytes | func (priv *PrivateKey) ToBytes() (b []byte) {
d := priv.D.Bytes()
/* Pad D to 32 bytes */
padded_d := append(bytes.Repeat([]byte{0x00}, 32-len(d)), d...)
return padded_d
} | go | func (priv *PrivateKey) ToBytes() (b []byte) {
d := priv.D.Bytes()
/* Pad D to 32 bytes */
padded_d := append(bytes.Repeat([]byte{0x00}, 32-len(d)), d...)
return padded_d
} | [
"func",
"(",
"priv",
"*",
"PrivateKey",
")",
"ToBytes",
"(",
")",
"(",
"b",
"[",
"]",
"byte",
")",
"{",
"d",
":=",
"priv",
".",
"D",
".",
"Bytes",
"(",
")",
"\n\n",
"/* Pad D to 32 bytes */",
"padded_d",
":=",
"append",
"(",
"bytes",
".",
"Repeat",
... | // ToBytes converts a Bitcoin private key to a 32-byte byte slice. | [
"ToBytes",
"converts",
"a",
"Bitcoin",
"private",
"key",
"to",
"a",
"32",
"-",
"byte",
"byte",
"slice",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L278-L285 | train |
vsergeev/btckeygenie | btckey/btckey.go | FromBytes | func (priv *PrivateKey) FromBytes(b []byte) (err error) {
if len(b) != 32 {
return fmt.Errorf("Invalid private key bytes length %d, expected 32.", len(b))
}
priv.D = new(big.Int).SetBytes(b)
/* Derive public key from private key */
priv.derive()
return nil
} | go | func (priv *PrivateKey) FromBytes(b []byte) (err error) {
if len(b) != 32 {
return fmt.Errorf("Invalid private key bytes length %d, expected 32.", len(b))
}
priv.D = new(big.Int).SetBytes(b)
/* Derive public key from private key */
priv.derive()
return nil
} | [
"func",
"(",
"priv",
"*",
"PrivateKey",
")",
"FromBytes",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"b",
")",
"!=",
"32",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"b",
")",... | // FromBytes converts a 32-byte byte slice to a Bitcoin private key and derives the corresponding Bitcoin public key. | [
"FromBytes",
"converts",
"a",
"32",
"-",
"byte",
"byte",
"slice",
"to",
"a",
"Bitcoin",
"private",
"key",
"and",
"derives",
"the",
"corresponding",
"Bitcoin",
"public",
"key",
"."
] | 413cbe3261adadbc974cecdbb4ea0b86c813c1a0 | https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L288-L299 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.