id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
148,700
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", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Execute GET on bucket to list objects.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "queryValues", ":", "urlValues", ",", "contentSHA256Hex", ":", "emptySHA256Hex", ",", "}", ")", "\n\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "\"", "\"", ",", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "bucketPolicyBuf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "policy", ":=", "string", "(", "bucketPolicyBuf", ")", "\n", "return", "policy", ",", "err", "\n", "}" ]
// 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
148,701
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", "+", "chunkDataSize", "+", "crlfLen", "\n", "}" ]
// 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
148,702
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", ".", "Format", "(", "iso8601DateFormat", ")", ",", "getScope", "(", "region", ",", "t", ")", ",", "previousSig", ",", "emptySHA256", ",", "hex", ".", "EncodeToString", "(", "sum256", "(", "chunkData", ")", ")", ",", "}", "\n\n", "return", "strings", ".", "Join", "(", "stringToSignParts", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// 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
148,703
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", "(", "\"", "\"", ",", "streamingSignAlgorithm", ")", "\n", "if", "sessionToken", "!=", "\"", "\"", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "sessionToken", ")", "\n", "}", "\n\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "timestamp", ".", "Format", "(", "iso8601DateFormat", ")", ")", "\n", "// Set content length with streaming signature for each chunk included.", "req", ".", "ContentLength", "=", "getStreamLength", "(", "dataLen", ",", "int64", "(", "payloadChunkSize", ")", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "dataLen", ",", "10", ")", ")", "\n", "}" ]
// 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
148,704
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", "(", "reqTime", ",", "region", ",", "previousSignature", ",", "chunkData", ")", "\n", "signingKey", ":=", "getSigningKey", "(", "secretAccessKey", ",", "region", ",", "reqTime", ")", "\n", "return", "getSignature", "(", "signingKey", ",", "chunkStringToSign", ")", "\n", "}" ]
// 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
148,705
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 string to sign from canonical request.", "stringToSign", ":=", "getStringToSignV4", "(", "s", ".", "reqTime", ",", "s", ".", "region", ",", "canonicalRequest", ")", "\n\n", "signingKey", ":=", "getSigningKey", "(", "s", ".", "secretAccessKey", ",", "s", ".", "region", ",", "s", ".", "reqTime", ")", "\n\n", "// Calculate signature.", "s", ".", "seedSignature", "=", "getSignature", "(", "signingKey", ",", "stringToSign", ")", "\n", "}" ]
// 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
148,706
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", ",", "s", ".", "region", ",", "s", ".", "prevSignature", ",", "s", ".", "secretAccessKey", ")", "\n\n", "// For next chunk signature computation", "s", ".", "prevSignature", "=", "signature", "\n\n", "// Write chunk header into streaming buffer", "chunkHdr", ":=", "buildChunkHeader", "(", "int64", "(", "chunkLen", ")", ",", "signature", ")", "\n", "s", ".", "buf", ".", "Write", "(", "chunkHdr", ")", "\n\n", "// Write chunk data into streaming buffer", "s", ".", "buf", ".", "Write", "(", "s", ".", "chunkBuf", "[", ":", "chunkLen", "]", ")", "\n\n", "// Write the chunk trailer.", "s", ".", "buf", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\\r", "\\n", "\"", ")", ")", "\n\n", "// Reset chunkBufLen for next chunk read.", "s", ".", "chunkBufLen", "=", "0", "\n", "s", ".", "chunkNum", "++", "\n", "}" ]
// 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
148,707
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", "authParts", ":=", "[", "]", "string", "{", "signV4Algorithm", "+", "\"", "\"", "+", "credential", ",", "\"", "\"", "+", "getSignedHeaders", "(", "*", "req", ",", "ignoredStreamingHeaders", ")", ",", "\"", "\"", "+", "s", ".", "seedSignature", ",", "}", "\n\n", "// Set authorization header.", "auth", ":=", "strings", ".", "Join", "(", "authParts", ",", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "auth", ")", "\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
148,708
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", "{", "// Set headers needed for streaming signature.", "prepareStreamingRequest", "(", "req", ",", "sessionToken", ",", "dataLen", ",", "reqTime", ")", "\n\n", "if", "req", ".", "Body", "==", "nil", "{", "req", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ")", "\n", "}", "\n\n", "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", ")", ",", "}", "\n\n", "// Add the request headers required for chunk upload signing.", "// Compute the seed signature.", "stReader", ".", "setSeedSignature", "(", "req", ")", "\n\n", "// Set the authorization header with the seed signature.", "stReader", ".", "setStreamingAuthHeader", "(", "req", ")", "\n\n", "// Set seed signature as prevSignature for subsequent", "// streaming signing process.", "stReader", ".", "prevSignature", "=", "stReader", ".", "seedSignature", "\n", "req", ".", "Body", "=", "stReader", "\n\n", "return", "req", "\n", "}" ]
// 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
148,709
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", ":", "// 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", "\n", "for", "{", "n1", ",", "err", ":=", "s", ".", "baseReadCloser", ".", "Read", "(", "s", ".", "chunkBuf", "[", "s", ".", "chunkBufLen", ":", "]", ")", "\n", "// 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", "\n", "s", ".", "bytesRead", "+=", "int64", "(", "n1", ")", "\n\n", "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", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "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", "\n\n", "// bytes read from baseReader different than", "// content length provided.", "if", "s", ".", "bytesRead", "!=", "s", ".", "contentLen", "{", "return", "0", ",", "io", ".", "ErrUnexpectedEOF", "\n", "}", "\n\n", "// Sign the chunk and write it to s.buf.", "s", ".", "signChunk", "(", "0", ")", "\n", "break", "\n", "}", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "}", "\n", "}", "\n", "return", "s", ".", "buf", ".", "Read", "(", "buf", ")", "\n", "}" ]
// 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
148,710
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", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "BucketNotification", "{", "}", ",", "err", "\n", "}", "\n", "notification", ",", "err", ":=", "c", ".", "getBucketNotification", "(", "bucketName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "BucketNotification", "{", "}", ",", "err", "\n", "}", "\n", "return", "notification", ",", "nil", "\n", "}" ]
// 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
148,711
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", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Execute GET on bucket to list objects.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "queryValues", ":", "urlValues", ",", "contentSHA256Hex", ":", "emptySHA256Hex", ",", "}", ")", "\n\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "BucketNotification", "{", "}", ",", "err", "\n", "}", "\n", "return", "processBucketNotificationResponse", "(", "bucketName", ",", "resp", ")", "\n\n", "}" ]
// Request server for notification rules.
[ "Request", "server", "for", "notification", "rules", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-notification.go#L46-L63
148,712
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", ":=", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "return", "BucketNotification", "{", "}", ",", "errResponse", "\n", "}", "\n", "var", "bucketNotification", "BucketNotification", "\n", "err", ":=", "xmlDecoder", "(", "resp", ".", "Body", ",", "&", "bucketNotification", ")", "\n", "if", "err", "!=", "nil", "{", "return", "BucketNotification", "{", "}", ",", "err", "\n", "}", "\n", "return", "bucketNotification", ",", "nil", "\n", "}" ]
// 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
148,713
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(), &notificationInfo); 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(), &notificationInfo); 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", "{", "notificationInfoCh", ":=", "make", "(", "chan", "NotificationInfo", ",", "1", ")", "\n", "// Only success, start a routine to start reading line by line.", "go", "func", "(", "notificationInfoCh", "chan", "<-", "NotificationInfo", ")", "{", "defer", "close", "(", "notificationInfoCh", ")", "\n\n", "// Validate the bucket name.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "notificationInfoCh", "<-", "NotificationInfo", "{", "Err", ":", "err", ",", "}", "\n", "return", "\n", "}", "\n\n", "// Check ARN partition to verify if listening bucket is supported", "if", "s3utils", ".", "IsAmazonEndpoint", "(", "*", "c", ".", "endpointURL", ")", "||", "s3utils", ".", "IsGoogleEndpoint", "(", "*", "c", ".", "endpointURL", ")", "{", "notificationInfoCh", "<-", "NotificationInfo", "{", "Err", ":", "ErrAPINotSupported", "(", "\"", "\"", ")", ",", "}", "\n", "return", "\n", "}", "\n\n", "// Continuously run and listen on bucket notification.", "// Create a done channel to control 'ListObjects' go routine.", "retryDoneCh", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n\n", "// Indicate to our routine to exit cleanly upon return.", "defer", "close", "(", "retryDoneCh", ")", "\n\n", "// Wait on the jitter retry loop.", "for", "range", "c", ".", "newRetryTimerContinous", "(", "time", ".", "Second", ",", "time", ".", "Second", "*", "30", ",", "MaxJitter", ",", "retryDoneCh", ")", "{", "urlValues", ":=", "make", "(", "url", ".", "Values", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "prefix", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "suffix", ")", "\n", "urlValues", "[", "\"", "\"", "]", "=", "events", "\n\n", "// Execute GET on bucket to list objects.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "queryValues", ":", "urlValues", ",", "contentSHA256Hex", ":", "emptySHA256Hex", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "notificationInfoCh", "<-", "NotificationInfo", "{", "Err", ":", "err", ",", "}", "\n", "return", "\n", "}", "\n\n", "// Validate http response, upon error return quickly.", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "errResponse", ":=", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "notificationInfoCh", "<-", "NotificationInfo", "{", "Err", ":", "errResponse", ",", "}", "\n", "return", "\n", "}", "\n\n", "// Initialize a new bufio scanner, to read line by line.", "bio", ":=", "bufio", ".", "NewScanner", "(", "resp", ".", "Body", ")", "\n\n", "// Close the response body.", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "// Unmarshal each line, returns marshalled values.", "for", "bio", ".", "Scan", "(", ")", "{", "var", "notificationInfo", "NotificationInfo", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "bio", ".", "Bytes", "(", ")", ",", "&", "notificationInfo", ")", ";", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "// Send notificationInfo", "select", "{", "case", "notificationInfoCh", "<-", "notificationInfo", ":", "case", "<-", "doneCh", ":", "return", "\n", "}", "\n", "}", "\n", "// 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", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", "notificationInfoCh", ")", "\n\n", "// Returns the notification info channel, for caller to start reading from.", "return", "notificationInfoCh", "\n", "}" ]
// ListenBucketNotification - listen on bucket notifications.
[ "ListenBucketNotification", "-", "listen", "on", "bucket", "notifications", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-notification.go#L138-L228
148,714
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", "s", ".", "IsStreamingV4", "(", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// 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
148,715
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
148,716
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", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Code", ")", "\n", "}", "\n", "return", "msg", "\n", "}", "\n", "return", "e", ".", "Message", "\n", "}" ]
// 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
148,717
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", ":", "bucketName", ",", "}", "\n", "}" ]
// 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
148,718
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", "ErrorResponse", "{", "StatusCode", ":", "http", ".", "StatusBadRequest", ",", "Code", ":", "\"", "\"", ",", "Message", ":", "msg", ",", "BucketName", ":", "bucketName", ",", "Key", ":", "objectName", ",", "}", "\n", "}" ]
// 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
148,719
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", ".", "StatusBadRequest", ",", "Code", ":", "\"", "\"", ",", "Message", ":", "msg", ",", "BucketName", ":", "bucketName", ",", "Key", ":", "objectName", ",", "}", "\n", "}" ]
// 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
148,720
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", "{", "StatusCode", ":", "http", ".", "StatusBadRequest", ",", "Code", ":", "\"", "\"", ",", "Message", ":", "msg", ",", "BucketName", ":", "bucketName", ",", "Key", ":", "objectName", ",", "}", "\n", "}" ]
// 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
148,721
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", ":", "\"", "\"", ",", "}", "\n", "}" ]
// 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
148,722
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", ":", "\"", "\"", ",", "}", "\n", "}" ]
// 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
148,723
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", ":", "\"", "\"", ",", "}", "\n", "}" ]
// 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
148,724
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", "(", "reqHost", ",", "\"", "\"", ")", "\n", "if", "dotPos", ">", "-", "1", "{", "bucketName", ":=", "reqHost", "[", ":", "dotPos", "]", "\n", "path", "=", "\"", "\"", "+", "bucketName", "\n", "path", "+=", "req", ".", "URL", ".", "Path", "\n", "path", "=", "s3utils", ".", "EncodePath", "(", "path", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "path", "=", "s3utils", ".", "EncodePath", "(", "req", ".", "URL", ".", "Path", ")", "\n", "return", "\n", "}" ]
// 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
148,725
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", "(", "[", "]", "byte", "(", "policyBase64", ")", ")", "\n", "signature", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "hm", ".", "Sum", "(", "nil", ")", ")", "\n", "return", "signature", "\n", "}" ]
// 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
148,726
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", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "+", "\"", "\\n", "\"", ")", "\n", "buf", ".", "WriteString", "(", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "+", "\"", "\\n", "\"", ")", "\n", "buf", ".", "WriteString", "(", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "+", "\"", "\\n", "\"", ")", "\n", "}" ]
// 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
148,727
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", ")", "\n", "for", "k", ",", "vv", ":=", "range", "req", ".", "Header", "{", "// All the AMZ headers should be lowercase", "lk", ":=", "strings", ".", "ToLower", "(", "k", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "lk", ",", "\"", "\"", ")", "{", "protoHeaders", "=", "append", "(", "protoHeaders", ",", "lk", ")", "\n", "vals", "[", "lk", "]", "=", "vv", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "protoHeaders", ")", "\n", "for", "_", ",", "k", ":=", "range", "protoHeaders", "{", "buf", ".", "WriteString", "(", "k", ")", "\n", "buf", ".", "WriteByte", "(", "':'", ")", "\n", "for", "idx", ",", "v", ":=", "range", "vals", "[", "k", "]", "{", "if", "idx", ">", "0", "{", "buf", ".", "WriteByte", "(", "','", ")", "\n", "}", "\n", "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", ")", "\n", "}", "else", "{", "buf", ".", "WriteString", "(", "v", ")", "\n", "}", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "'\\n'", ")", "\n", "}", "\n", "}" ]
// 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
148,728
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", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "getClientGrantsTokenExpiry", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "New", "(", "&", "STSClientGrants", "{", "Client", ":", "&", "http", ".", "Client", "{", "Transport", ":", "http", ".", "DefaultTransport", ",", "}", ",", "stsEndpoint", ":", "stsEndpoint", ",", "getClientGrantsTokenExpiry", ":", "getClientGrantsTokenExpiry", ",", "}", ")", ",", "nil", "\n", "}" ]
// 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
148,729
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", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Execute DELETE on objectName.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "objectName", ":", "objectName", ",", "contentSHA256Hex", ":", "emptySHA256Hex", ",", "}", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "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", ")", "\n", "}", "\n", "}", "\n\n", "// DeleteObject always responds with http '204' even for", "// objects which do not exist. So no need to handle them", "// specifically.", "return", "nil", "\n", "}" ]
// 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
148,730
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", "(", "rmObjects", ",", "deleteObject", "{", "Key", ":", "obj", "}", ")", "\n", "}", "\n", "xmlBytes", ",", "_", ":=", "xml", ".", "Marshal", "(", "deleteMultiObjects", "{", "Objects", ":", "rmObjects", ",", "Quiet", ":", "true", "}", ")", "\n", "return", "xmlBytes", "\n", "}" ]
// 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
148,731
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", "RemoveObjectError", ",", "1", ")", "\n\n", "// Validate if bucket name is valid.", "if", "err", ":=", "s3utils", ".", "CheckValidBucketName", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "defer", "close", "(", "errorCh", ")", "\n", "errorCh", "<-", "RemoveObjectError", "{", "Err", ":", "err", ",", "}", "\n", "return", "errorCh", "\n", "}", "\n", "// Validate objects channel to be properly allocated.", "if", "objectsCh", "==", "nil", "{", "defer", "close", "(", "errorCh", ")", "\n", "errorCh", "<-", "RemoveObjectError", "{", "Err", ":", "ErrInvalidArgument", "(", "\"", "\"", ")", ",", "}", "\n", "return", "errorCh", "\n", "}", "\n\n", "// Generate and call MultiDelete S3 requests based on entries received from objectsCh", "go", "func", "(", "errorCh", "chan", "<-", "RemoveObjectError", ")", "{", "maxEntries", ":=", "1000", "\n", "finish", ":=", "false", "\n", "urlValues", ":=", "make", "(", "url", ".", "Values", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Close error channel when Multi delete finishes.", "defer", "close", "(", "errorCh", ")", "\n\n", "// Loop over entries by 1000 and call MultiDelete requests", "for", "{", "if", "finish", "{", "break", "\n", "}", "\n", "count", ":=", "0", "\n", "var", "batch", "[", "]", "string", "\n\n", "// Try to gather 1000 entries", "for", "object", ":=", "range", "objectsCh", "{", "batch", "=", "append", "(", "batch", ",", "object", ")", "\n", "if", "count", "++", ";", "count", ">=", "maxEntries", "{", "break", "\n", "}", "\n", "}", "\n", "if", "count", "==", "0", "{", "// Multi Objects Delete API doesn't accept empty object list, quit immediately", "break", "\n", "}", "\n", "if", "count", "<", "maxEntries", "{", "// We didn't have 1000 entries, so this is the last batch", "finish", "=", "true", "\n", "}", "\n\n", "// Generate remove multi objects XML request", "removeBytes", ":=", "generateRemoveMultiObjectsRequest", "(", "batch", ")", "\n", "// Execute GET on bucket to list objects.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "ctx", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "queryValues", ":", "urlValues", ",", "contentBody", ":", "bytes", ".", "NewReader", "(", "removeBytes", ")", ",", "contentLength", ":", "int64", "(", "len", "(", "removeBytes", ")", ")", ",", "contentMD5Base64", ":", "sumMD5Base64", "(", "removeBytes", ")", ",", "contentSHA256Hex", ":", "sum256Hex", "(", "removeBytes", ")", ",", "}", ")", "\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "e", ":=", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "errorCh", "<-", "RemoveObjectError", "{", "ObjectName", ":", "\"", "\"", ",", "Err", ":", "e", "}", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "for", "_", ",", "b", ":=", "range", "batch", "{", "errorCh", "<-", "RemoveObjectError", "{", "ObjectName", ":", "b", ",", "Err", ":", "err", "}", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// Process multiobjects remove xml response", "processRemoveMultiObjectsResponse", "(", "resp", ".", "Body", ",", "batch", ",", "errorCh", ")", "\n\n", "closeResponse", "(", "resp", ")", "\n", "}", "\n", "}", "(", "errorCh", ")", "\n", "return", "errorCh", "\n", "}" ]
// 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
148,732
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", "(", ")", ",", "bucketName", ",", "objectsCh", ")", "\n", "}" ]
// 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
148,733
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", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Find multipart upload ids of the object to be aborted.", "uploadIDs", ",", "err", ":=", "c", ".", "findUploadIDs", "(", "bucketName", ",", "objectName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "uploadID", ":=", "range", "uploadIDs", "{", "// abort incomplete multipart upload, based on the upload id passed.", "err", ":=", "c", ".", "abortMultipartUpload", "(", "context", ".", "Background", "(", ")", ",", "bucketName", ",", "objectName", ",", "uploadID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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
148,734
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", "(", "bucketName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s3utils", ".", "CheckValidObjectName", "(", "objectName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Initialize url queries.", "urlValues", ":=", "make", "(", "url", ".", "Values", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "uploadID", ")", "\n\n", "// Execute DELETE on multipart upload.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "ctx", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "objectName", ":", "objectName", ",", "queryValues", ":", "urlValues", ",", "contentSHA256Hex", ":", "emptySHA256Hex", ",", "}", ")", "\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusNoContent", "{", "// Abort has no response body, handle it for any errors.", "var", "errorResponse", "ErrorResponse", "\n", "switch", "resp", ".", "StatusCode", "{", "case", "http", ".", "StatusNotFound", ":", "// This is needed specifically for abort and it cannot", "// be converged into default case.", "errorResponse", "=", "ErrorResponse", "{", "Code", ":", "\"", "\"", ",", "Message", ":", "\"", "\"", ",", "BucketName", ":", "bucketName", ",", "Key", ":", "objectName", ",", "RequestID", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "HostID", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "Region", ":", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "}", "\n", "default", ":", "return", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "objectName", ")", "\n", "}", "\n", "return", "errorResponse", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
148,735
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
148,736
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", "[", "string", "]", "string", ")", "\n", "return", "p", "\n", "}" ]
// NewPostPolicy - Instantiate new post policy.
[ "NewPostPolicy", "-", "Instantiate", "new", "post", "policy", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/post-policy.go#L66-L71
148,737
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", "=", "t", "\n", "return", "nil", "\n", "}" ]
// 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
148,738
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", "(", "\"", "\"", ")", "\n", "}", "\n", "policyCond", ":=", "policyCondition", "{", "matchType", ":", "\"", "\"", ",", "condition", ":", "\"", "\"", ",", "value", ":", "key", ",", "}", "\n", "if", "err", ":=", "p", ".", "addNewPolicy", "(", "policyCond", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "formData", "[", "\"", "\"", "]", "=", "key", "\n", "return", "nil", "\n", "}" ]
// 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
148,739
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", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "policyCond", ":=", "policyCondition", "{", "matchType", ":", "\"", "\"", ",", "condition", ":", "\"", "\"", ",", "value", ":", "keyStartsWith", ",", "}", "\n", "if", "err", ":=", "p", ".", "addNewPolicy", "(", "policyCond", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "formData", "[", "\"", "\"", "]", "=", "keyStartsWith", "\n", "return", "nil", "\n", "}" ]
// 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
148,740
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", "(", "\"", "\"", ")", "\n", "}", "\n", "policyCond", ":=", "policyCondition", "{", "matchType", ":", "\"", "\"", ",", "condition", ":", "\"", "\"", ",", "value", ":", "bucketName", ",", "}", "\n", "if", "err", ":=", "p", ".", "addNewPolicy", "(", "policyCond", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "formData", "[", "\"", "\"", "]", "=", "bucketName", "\n", "return", "nil", "\n", "}" ]
// 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
148,741
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", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "policyCond", ":=", "policyCondition", "{", "matchType", ":", "\"", "\"", ",", "condition", ":", "\"", "\"", ",", "value", ":", "contentType", ",", "}", "\n", "if", "err", ":=", "p", ".", "addNewPolicy", "(", "policyCond", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "formData", "[", "\"", "\"", "]", "=", "contentType", "\n", "return", "nil", "\n", "}" ]
// 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
148,742
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", "{", "return", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "max", "<", "0", "{", "return", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "contentLengthRange", ".", "min", "=", "min", "\n", "p", ".", "contentLengthRange", ".", "max", "=", "max", "\n", "return", "nil", "\n", "}" ]
// 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
148,743
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", "(", "\"", "\"", ")", "\n", "}", "\n", "policyCond", ":=", "policyCondition", "{", "matchType", ":", "\"", "\"", ",", "condition", ":", "\"", "\"", ",", "value", ":", "status", ",", "}", "\n", "if", "err", ":=", "p", ".", "addNewPolicy", "(", "policyCond", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "formData", "[", "\"", "\"", "]", "=", "status", "\n", "return", "nil", "\n", "}" ]
// 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
148,744
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", ".", "value", "==", "\"", "\"", "{", "return", "ErrInvalidArgument", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "conditions", "=", "append", "(", "p", ".", "conditions", ",", "policyCond", ")", "\n", "return", "nil", "\n", "}" ]
// 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
148,745
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", "string", "\n", "conditions", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "po", ":=", "range", "p", ".", "conditions", "{", "conditions", "=", "append", "(", "conditions", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "po", ".", "matchType", ",", "po", ".", "condition", ",", "po", ".", "value", ")", ")", "\n", "}", "\n", "if", "p", ".", "contentLengthRange", ".", "min", "!=", "0", "||", "p", ".", "contentLengthRange", ".", "max", "!=", "0", "{", "conditions", "=", "append", "(", "conditions", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "p", ".", "contentLengthRange", ".", "min", ",", "p", ".", "contentLengthRange", ".", "max", ")", ")", "\n", "}", "\n", "if", "len", "(", "conditions", ")", ">", "0", "{", "conditionsStr", "=", "`\"conditions\":[`", "+", "strings", ".", "Join", "(", "conditions", ",", "\"", "\"", ")", "+", "\"", "\"", "\n", "}", "\n", "retStr", ":=", "\"", "\"", "\n", "retStr", "=", "retStr", "+", "expirationStr", "+", "\"", "\"", "\n", "retStr", "=", "retStr", "+", "conditionsStr", "\n", "retStr", "=", "retStr", "+", "\"", "\"", "\n", "return", "[", "]", "byte", "(", "retStr", ")", "\n", "}" ]
// 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
148,746
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", "return", "false", "\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
148,747
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", "AliasUser", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "au", ")", "\n", "if", "err", "==", "nil", "{", "*", "u", "=", "User", "(", "au", ")", "\n", "return", "nil", "\n", "}", "\n", "// 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", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "str", ")", "\n", "if", "err", "==", "nil", "{", "if", "str", "!=", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "*", "u", "=", "User", "{", "AWS", ":", "set", ".", "CreateStringSet", "(", "\"", "\"", ")", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// 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", "string", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L90-L112
148,748
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", "if", "statement", ".", "Effect", "!=", "\"", "\"", "{", "return", "false", "\n", "}", "\n\n", "if", "statement", ".", "Principal", ".", "AWS", "==", "nil", "||", "!", "statement", ".", "Principal", ".", "AWS", ".", "Contains", "(", "\"", "\"", ")", "{", "return", "false", "\n", "}", "\n\n", "bucketResource", ":=", "awsResourcePrefix", "+", "bucketName", "\n", "if", "statement", ".", "Resources", ".", "Contains", "(", "bucketResource", ")", "{", "return", "true", "\n", "}", "\n\n", "if", "statement", ".", "Resources", ".", "FuncMatch", "(", "startsWithFunc", ",", "bucketResource", "+", "\"", "\"", ")", ".", "IsEmpty", "(", ")", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\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
148,749
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", "==", "BucketPolicyNone", "||", "bucketName", "==", "\"", "\"", "{", "return", "statements", "\n", "}", "\n\n", "bucketResource", ":=", "set", ".", "CreateStringSet", "(", "awsResourcePrefix", "+", "bucketName", ")", "\n\n", "statement", ":=", "Statement", "{", "Actions", ":", "commonBucketActions", ",", "Effect", ":", "\"", "\"", ",", "Principal", ":", "User", "{", "AWS", ":", "set", ".", "CreateStringSet", "(", "\"", "\"", ")", "}", ",", "Resources", ":", "bucketResource", ",", "Sid", ":", "\"", "\"", ",", "}", "\n", "statements", "=", "append", "(", "statements", ",", "statement", ")", "\n\n", "if", "policy", "==", "BucketPolicyReadOnly", "||", "policy", "==", "BucketPolicyReadWrite", "{", "statement", "=", "Statement", "{", "Actions", ":", "readOnlyBucketActions", ",", "Effect", ":", "\"", "\"", ",", "Principal", ":", "User", "{", "AWS", ":", "set", ".", "CreateStringSet", "(", "\"", "\"", ")", "}", ",", "Resources", ":", "bucketResource", ",", "Sid", ":", "\"", "\"", ",", "}", "\n", "if", "prefix", "!=", "\"", "\"", "{", "condKeyMap", ":=", "make", "(", "ConditionKeyMap", ")", "\n", "condKeyMap", ".", "Add", "(", "\"", "\"", ",", "set", ".", "CreateStringSet", "(", "prefix", ")", ")", "\n", "condMap", ":=", "make", "(", "ConditionMap", ")", "\n", "condMap", ".", "Add", "(", "\"", "\"", ",", "condKeyMap", ")", "\n", "statement", ".", "Conditions", "=", "condMap", "\n", "}", "\n", "statements", "=", "append", "(", "statements", ",", "statement", ")", "\n", "}", "\n\n", "if", "policy", "==", "BucketPolicyWriteOnly", "||", "policy", "==", "BucketPolicyReadWrite", "{", "statement", "=", "Statement", "{", "Actions", ":", "writeOnlyBucketActions", ",", "Effect", ":", "\"", "\"", ",", "Principal", ":", "User", "{", "AWS", ":", "set", ".", "CreateStringSet", "(", "\"", "\"", ")", "}", ",", "Resources", ":", "bucketResource", ",", "Sid", ":", "\"", "\"", ",", "}", "\n", "statements", "=", "append", "(", "statements", ",", "statement", ")", "\n", "}", "\n\n", "return", "statements", "\n", "}" ]
// 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
148,750
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", "==", "BucketPolicyNone", "||", "bucketName", "==", "\"", "\"", "{", "return", "statements", "\n", "}", "\n\n", "statement", ":=", "Statement", "{", "Effect", ":", "\"", "\"", ",", "Principal", ":", "User", "{", "AWS", ":", "set", ".", "CreateStringSet", "(", "\"", "\"", ")", "}", ",", "Resources", ":", "set", ".", "CreateStringSet", "(", "awsResourcePrefix", "+", "bucketName", "+", "\"", "\"", "+", "prefix", "+", "\"", "\"", ")", ",", "Sid", ":", "\"", "\"", ",", "}", "\n\n", "if", "policy", "==", "BucketPolicyReadOnly", "{", "statement", ".", "Actions", "=", "readOnlyObjectActions", "\n", "}", "else", "if", "policy", "==", "BucketPolicyWriteOnly", "{", "statement", ".", "Actions", "=", "writeOnlyObjectActions", "\n", "}", "else", "if", "policy", "==", "BucketPolicyReadWrite", "{", "statement", ".", "Actions", "=", "readWriteObjectActions", "\n", "}", "\n\n", "statements", "=", "append", "(", "statements", ",", "statement", ")", "\n", "return", "statements", "\n", "}" ]
// 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
148,751
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", "(", "policy", ",", "bucketName", ",", "prefix", ")", "\n", "statements", "=", "append", "(", "statements", ",", "ns", "...", ")", "\n\n", "ns", "=", "newObjectStatement", "(", "policy", ",", "bucketName", ",", "prefix", ")", "\n", "statements", "=", "append", "(", "statements", ",", "ns", "...", ")", "\n\n", "return", "statements", "\n", "}" ]
// 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
148,752
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", "+", "\"", "\"", "\n", "objectResource", ":=", "awsResourcePrefix", "+", "bucketName", "+", "\"", "\"", "+", "prefix", "+", "\"", "\"", "\n\n", "for", "_", ",", "s", ":=", "range", "statements", "{", "if", "!", "s", ".", "Resources", ".", "Contains", "(", "objectResource", ")", "&&", "!", "s", ".", "Resources", ".", "FuncMatch", "(", "startsWithFunc", ",", "resourcePrefix", ")", ".", "IsEmpty", "(", ")", "{", "if", "s", ".", "Actions", ".", "Intersection", "(", "readOnlyObjectActions", ")", ".", "Equals", "(", "readOnlyObjectActions", ")", "{", "readOnlyInUse", "=", "true", "\n", "}", "\n\n", "if", "s", ".", "Actions", ".", "Intersection", "(", "writeOnlyObjectActions", ")", ".", "Equals", "(", "writeOnlyObjectActions", ")", "{", "writeOnlyInUse", "=", "true", "\n", "}", "\n", "}", "\n", "if", "readOnlyInUse", "&&", "writeOnlyInUse", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "readOnlyInUse", ",", "writeOnlyInUse", "\n", "}" ]
// 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
148,753
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", ".", "Resources", ".", "Remove", "(", "objectResource", ")", "\n", "}", "else", "{", "statement", ".", "Actions", "=", "statement", ".", "Actions", ".", "Difference", "(", "readOnlyObjectActions", ")", "\n", "statement", ".", "Actions", "=", "statement", ".", "Actions", ".", "Difference", "(", "writeOnlyObjectActions", ")", "\n", "}", "\n", "}", "\n\n", "return", "statement", "\n", "}" ]
// 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
148,754
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", "!", "statement", ".", "Actions", ".", "Intersection", "(", "readOnlyBucketActions", ")", ".", "Equals", "(", "readOnlyBucketActions", ")", "{", "return", "\n", "}", "\n\n", "if", "statement", ".", "Conditions", "==", "nil", "{", "statement", ".", "Actions", "=", "statement", ".", "Actions", ".", "Difference", "(", "readOnlyBucketActions", ")", "\n", "return", "\n", "}", "\n\n", "if", "prefix", "!=", "\"", "\"", "{", "stringEqualsValue", ":=", "statement", ".", "Conditions", "[", "\"", "\"", "]", "\n", "values", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "if", "stringEqualsValue", "!=", "nil", "{", "values", "=", "stringEqualsValue", "[", "\"", "\"", "]", "\n", "if", "values", "==", "nil", "{", "values", "=", "set", ".", "NewStringSet", "(", ")", "\n", "}", "\n", "}", "\n\n", "values", ".", "Remove", "(", "prefix", ")", "\n\n", "if", "stringEqualsValue", "!=", "nil", "{", "if", "values", ".", "IsEmpty", "(", ")", "{", "delete", "(", "stringEqualsValue", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "stringEqualsValue", ")", "==", "0", "{", "delete", "(", "statement", ".", "Conditions", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "statement", ".", "Conditions", ")", "==", "0", "{", "statement", ".", "Conditions", "=", "nil", "\n", "statement", ".", "Actions", "=", "statement", ".", "Actions", ".", "Difference", "(", "readOnlyBucketActions", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "removeWriteOnly", ":=", "func", "(", ")", "{", "if", "statement", ".", "Conditions", "==", "nil", "{", "statement", ".", "Actions", "=", "statement", ".", "Actions", ".", "Difference", "(", "writeOnlyBucketActions", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "statement", ".", "Resources", ")", ">", "1", "{", "statement", ".", "Resources", ".", "Remove", "(", "bucketResource", ")", "\n", "}", "else", "{", "if", "!", "readOnlyInUse", "{", "removeReadOnly", "(", ")", "\n", "}", "\n\n", "if", "!", "writeOnlyInUse", "{", "removeWriteOnly", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "statement", "\n", "}" ]
// 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
148,755
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", ".", "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", ")", "\n", "return", "statements", "\n", "}", "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", ")", "\n", "return", "statements", "\n", "}", "\n\n", "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", "\n", "}", "\n", "if", "s", ".", "Conditions", "!=", "nil", "&&", "statement", ".", "Conditions", "!=", "nil", "{", "if", "s", ".", "Resources", ".", "Equals", "(", "statement", ".", "Resources", ")", "{", "statements", "[", "i", "]", ".", "Conditions", "=", "mergeConditionMap", "(", "s", ".", "Conditions", ",", "statement", ".", "Conditions", ")", "\n", "return", "statements", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "!", "(", "statement", ".", "Actions", ".", "IsEmpty", "(", ")", "&&", "statement", ".", "Resources", ".", "IsEmpty", "(", ")", ")", "{", "return", "append", "(", "statements", ",", "statement", ")", "\n", "}", "\n\n", "return", "statements", "\n", "}" ]
// 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", "conditions", "they", "are", "merged", ".", "-", "Else", "the", "statement", "is", "appended", "to", "statement", "list", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L436-L473
148,756
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", "(", "statements", ",", "s", ")", "\n", "}", "\n\n", "return", "statements", "\n", "}" ]
// Appends two statement lists.
[ "Appends", "two", "statement", "lists", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/pkg/policy/bucket-policy.go#L476-L482
148,757
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", ".", "Principal", ".", "AWS", ".", "Contains", "(", "\"", "\"", ")", ")", "{", "return", "commonFound", ",", "readOnly", ",", "writeOnly", "\n", "}", "\n\n", "if", "statement", ".", "Actions", ".", "Intersection", "(", "commonBucketActions", ")", ".", "Equals", "(", "commonBucketActions", ")", "&&", "statement", ".", "Conditions", "==", "nil", "{", "commonFound", "=", "true", "\n", "}", "\n\n", "if", "statement", ".", "Actions", ".", "Intersection", "(", "writeOnlyBucketActions", ")", ".", "Equals", "(", "writeOnlyBucketActions", ")", "&&", "statement", ".", "Conditions", "==", "nil", "{", "writeOnly", "=", "true", "\n", "}", "\n\n", "if", "statement", ".", "Actions", ".", "Intersection", "(", "readOnlyBucketActions", ")", ".", "Equals", "(", "readOnlyBucketActions", ")", "{", "if", "prefix", "!=", "\"", "\"", "&&", "statement", ".", "Conditions", "!=", "nil", "{", "if", "stringEqualsValue", ",", "ok", ":=", "statement", ".", "Conditions", "[", "\"", "\"", "]", ";", "ok", "{", "if", "s3PrefixValues", ",", "ok", ":=", "stringEqualsValue", "[", "\"", "\"", "]", ";", "ok", "{", "if", "s3PrefixValues", ".", "Contains", "(", "prefix", ")", "{", "readOnly", "=", "true", "\n", "}", "\n", "}", "\n", "}", "else", "if", "stringNotEqualsValue", ",", "ok", ":=", "statement", ".", "Conditions", "[", "\"", "\"", "]", ";", "ok", "{", "if", "s3PrefixValues", ",", "ok", ":=", "stringNotEqualsValue", "[", "\"", "\"", "]", ";", "ok", "{", "if", "!", "s3PrefixValues", ".", "Contains", "(", "prefix", ")", "{", "readOnly", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "if", "prefix", "==", "\"", "\"", "&&", "statement", ".", "Conditions", "==", "nil", "{", "readOnly", "=", "true", "\n", "}", "else", "if", "prefix", "!=", "\"", "\"", "&&", "statement", ".", "Conditions", "==", "nil", "{", "readOnly", "=", "true", "\n", "}", "\n", "}", "\n\n", "return", "commonFound", ",", "readOnly", ",", "writeOnly", "\n", "}" ]
// 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
148,758
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", "(", "\"", "\"", ")", "&&", "statement", ".", "Conditions", "==", "nil", "{", "if", "statement", ".", "Actions", ".", "Intersection", "(", "readOnlyObjectActions", ")", ".", "Equals", "(", "readOnlyObjectActions", ")", "{", "readOnly", "=", "true", "\n", "}", "\n", "if", "statement", ".", "Actions", ".", "Intersection", "(", "writeOnlyObjectActions", ")", ".", "Equals", "(", "writeOnlyObjectActions", ")", "{", "writeOnly", "=", "true", "\n", "}", "\n", "}", "\n\n", "return", "readOnly", ",", "writeOnly", "\n", "}" ]
// 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
148,759
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", "+", "bucketName", "+", "\"", "\"", "+", "prefix", "+", "\"", "\"", "\n\n", "bucketCommonFound", ":=", "false", "\n", "bucketReadOnly", ":=", "false", "\n", "bucketWriteOnly", ":=", "false", "\n", "matchedResource", ":=", "\"", "\"", "\n", "objReadOnly", ":=", "false", "\n", "objWriteOnly", ":=", "false", "\n\n", "for", "_", ",", "s", ":=", "range", "statements", "{", "matchedObjResources", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "if", "s", ".", "Resources", ".", "Contains", "(", "objectResource", ")", "{", "matchedObjResources", ".", "Add", "(", "objectResource", ")", "\n", "}", "else", "{", "matchedObjResources", "=", "s", ".", "Resources", ".", "FuncMatch", "(", "resourceMatch", ",", "objectResource", ")", "\n", "}", "\n", "if", "!", "matchedObjResources", ".", "IsEmpty", "(", ")", "{", "readOnly", ",", "writeOnly", ":=", "getObjectPolicy", "(", "s", ")", "\n", "for", "resource", ":=", "range", "matchedObjResources", "{", "if", "len", "(", "matchedResource", ")", "<", "len", "(", "resource", ")", "{", "objReadOnly", "=", "readOnly", "\n", "objWriteOnly", "=", "writeOnly", "\n", "matchedResource", "=", "resource", "\n", "}", "else", "if", "len", "(", "matchedResource", ")", "==", "len", "(", "resource", ")", "{", "objReadOnly", "=", "objReadOnly", "||", "readOnly", "\n", "objWriteOnly", "=", "objWriteOnly", "||", "writeOnly", "\n", "matchedResource", "=", "resource", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "s", ".", "Resources", ".", "Contains", "(", "bucketResource", ")", "{", "commonFound", ",", "readOnly", ",", "writeOnly", ":=", "getBucketPolicy", "(", "s", ",", "prefix", ")", "\n", "bucketCommonFound", "=", "bucketCommonFound", "||", "commonFound", "\n", "bucketReadOnly", "=", "bucketReadOnly", "||", "readOnly", "\n", "bucketWriteOnly", "=", "bucketWriteOnly", "||", "writeOnly", "\n", "}", "\n", "}", "\n\n", "policy", ":=", "BucketPolicyNone", "\n", "if", "bucketCommonFound", "{", "if", "bucketReadOnly", "&&", "bucketWriteOnly", "&&", "objReadOnly", "&&", "objWriteOnly", "{", "policy", "=", "BucketPolicyReadWrite", "\n", "}", "else", "if", "bucketReadOnly", "&&", "objReadOnly", "{", "policy", "=", "BucketPolicyReadOnly", "\n", "}", "else", "if", "bucketWriteOnly", "&&", "objWriteOnly", "{", "policy", "=", "BucketPolicyWriteOnly", "\n", "}", "\n", "}", "\n\n", "return", "policy", "\n", "}" ]
// 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
148,760
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", ":=", "set", ".", "NewStringSet", "(", ")", "\n", "// 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", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Pretend that policy resource as an actual object and fetch its policy", "for", "r", ":=", "range", "objResources", "{", "// Put trailing * if exists in asterisk", "asterisk", ":=", "\"", "\"", "\n", "if", "strings", ".", "HasSuffix", "(", "r", ",", "\"", "\"", ")", "{", "r", "=", "r", "[", ":", "len", "(", "r", ")", "-", "1", "]", "\n", "asterisk", "=", "\"", "\"", "\n", "}", "\n", "var", "objectPath", "string", "\n", "if", "len", "(", "r", ")", ">=", "len", "(", "awsResourcePrefix", "+", "bucketName", ")", "+", "1", "{", "objectPath", "=", "r", "[", "len", "(", "awsResourcePrefix", "+", "bucketName", ")", "+", "1", ":", "]", "\n", "}", "\n", "p", ":=", "GetPolicy", "(", "statements", ",", "bucketName", ",", "objectPath", ")", "\n", "policyRules", "[", "bucketName", "+", "\"", "\"", "+", "objectPath", "+", "asterisk", "]", "=", "p", "\n", "}", "\n", "return", "policyRules", "\n", "}" ]
// 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
148,761
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", ",", "prefix", ")", "\n", "// fmt.Println(\"out = \")", "// printstatement(out)", "ns", ":=", "newStatements", "(", "policy", ",", "bucketName", ",", "prefix", ")", "\n", "// fmt.Println(\"ns = \")", "// printstatement(ns)", "rv", ":=", "appendStatements", "(", "out", ",", "ns", ")", "\n", "// fmt.Println(\"rv = \")", "// printstatement(rv)", "return", "rv", "\n", "}" ]
// 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
148,762
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", "}", "\n", "parts", ":=", "strings", ".", "Split", "(", "pattern", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "==", "1", "{", "return", "resource", "==", "pattern", "\n", "}", "\n", "tGlob", ":=", "strings", ".", "HasSuffix", "(", "pattern", ",", "\"", "\"", ")", "\n", "end", ":=", "len", "(", "parts", ")", "-", "1", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "resource", ",", "parts", "[", "0", "]", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "1", ";", "i", "<", "end", ";", "i", "++", "{", "if", "!", "strings", ".", "Contains", "(", "resource", ",", "parts", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "idx", ":=", "strings", ".", "Index", "(", "resource", ",", "parts", "[", "i", "]", ")", "+", "len", "(", "parts", "[", "i", "]", ")", "\n", "resource", "=", "resource", "[", "idx", ":", "]", "\n", "}", "\n", "return", "tGlob", "||", "strings", ".", "HasSuffix", "(", "resource", ",", "parts", "[", "end", "]", ")", "\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
148,763
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", "int64", ",", "err", "error", ")", "{", "err", "=", "opts", ".", "validate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "c", ".", "putObjectCommon", "(", "ctx", ",", "bucketName", ",", "objectName", ",", "reader", ",", "objectSize", ",", "opts", ")", "\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
148,764
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", ".", "getObjectWithContext", "(", "ctx", ",", "bucketName", ",", "objectName", ",", "opts", ")", "\n", "}" ]
// 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
148,765
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", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "bucketLifecycle", ",", "err", ":=", "c", ".", "getBucketLifecycle", "(", "bucketName", ")", "\n", "if", "err", "!=", "nil", "{", "errResponse", ":=", "ToErrorResponse", "(", "err", ")", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "bucketLifecycle", ",", "nil", "\n", "}" ]
// GetBucketLifecycle - get bucket lifecycle.
[ "GetBucketLifecycle", "-", "get", "bucket", "lifecycle", "." ]
68eef499b4c530409962a5d1a12fa8c848587761
https://github.com/minio/minio-go/blob/68eef499b4c530409962a5d1a12fa8c848587761/api-get-lifecycle.go#L30-L44
148,766
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", ".", "Values", ")", "\n", "urlValues", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Execute GET on bucket to get lifecycle.", "resp", ",", "err", ":=", "c", ".", "executeMethod", "(", "context", ".", "Background", "(", ")", ",", "\"", "\"", ",", "requestMetadata", "{", "bucketName", ":", "bucketName", ",", "queryValues", ":", "urlValues", ",", "}", ")", "\n\n", "defer", "closeResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "resp", "!=", "nil", "{", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "\"", "\"", ",", "httpRespToErrorResponse", "(", "resp", ",", "bucketName", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "bucketLifecycleBuf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "lifecycle", ":=", "string", "(", "bucketLifecycleBuf", ")", "\n", "return", "lifecycle", ",", "err", "\n", "}" ]
// 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
148,767
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", ")", "\n\n", "/* Check that Q is on the curve */", "if", "!", "secp256k1", ".", "IsOnCurve", "(", "Q", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "priv", ".", "X", "=", "Q", ".", "X", "\n", "priv", ".", "Y", "=", "Q", ".", "Y", "\n\n", "return", "&", "priv", ".", "PublicKey", "\n", "}" ]
// 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
148,768
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 from [1, n) */", "/* Read N bit length random bytes + 64 extra bits */", "b", ":=", "make", "(", "[", "]", "byte", ",", "secp256k1", ".", "N", ".", "BitLen", "(", ")", "/", "8", "+", "8", ")", "\n", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "rand", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "priv", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "d", ":=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "b", ")", "\n\n", "/* Mod n-1 to shift d into [0, n-1) range */", "d", ".", "Mod", "(", "d", ",", "new", "(", "big", ".", "Int", ")", ".", "Sub", "(", "secp256k1", ".", "N", ",", "big", ".", "NewInt", "(", "1", ")", ")", ")", "\n", "/* Add one to shift d to [1, n) range */", "d", ".", "Add", "(", "d", ",", "big", ".", "NewInt", "(", "1", ")", ")", "\n\n", "priv", ".", "D", "=", "d", "\n\n", "/* Derive public key from private key */", "priv", ".", "derive", "(", ")", "\n\n", "return", "priv", ",", "nil", "\n", "}" ]
// 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
148,769
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", ".", "NewInt", "(", "0", ")", "\n", "m", ":=", "big", ".", "NewInt", "(", "58", ")", "\n\n", "/* Convert string to big int */", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "b58index", ":=", "strings", ".", "IndexByte", "(", "BITCOIN_BASE58_TABLE", ",", "s", "[", "i", "]", ")", "\n", "if", "b58index", "==", "-", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", "[", "i", "]", ",", "i", ")", "\n", "}", "\n", "b58value", ":=", "big", ".", "NewInt", "(", "int64", "(", "b58index", ")", ")", "\n", "x", ".", "Mul", "(", "x", ",", "m", ")", "\n", "x", ".", "Add", "(", "x", ",", "b58value", ")", "\n", "}", "\n\n", "/* Convert big int to big endian bytes */", "b", "=", "x", ".", "Bytes", "(", ")", "\n\n", "return", "b", ",", "nil", "\n", "}" ]
// 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
148,770
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", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n\n", "/* Add leading zero bytes */", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "if", "s", "[", "i", "]", "!=", "'1'", "{", "break", "\n", "}", "\n", "b", "=", "append", "(", "[", "]", "byte", "{", "0x00", "}", ",", "b", "...", ")", "\n", "}", "\n\n", "/* Verify checksum */", "if", "len", "(", "b", ")", "<", "5", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "/* Create a new SHA256 context */", "sha256_h", ":=", "sha256", ".", "New", "(", ")", "\n\n", "/* SHA256 Hash #1 */", "sha256_h", ".", "Reset", "(", ")", "\n", "sha256_h", ".", "Write", "(", "b", "[", ":", "len", "(", "b", ")", "-", "4", "]", ")", "\n", "hash1", ":=", "sha256_h", ".", "Sum", "(", "nil", ")", "\n\n", "/* SHA256 Hash #2 */", "sha256_h", ".", "Reset", "(", ")", "\n", "sha256_h", ".", "Write", "(", "hash1", ")", "\n", "hash2", ":=", "sha256_h", ".", "Sum", "(", "nil", ")", "\n\n", "/* Compare checksum */", "if", "bytes", ".", "Compare", "(", "hash2", "[", "0", ":", "4", "]", ",", "b", "[", "len", "(", "b", ")", "-", "4", ":", "]", ")", "!=", "0", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "/* Strip checksum bytes */", "b", "=", "b", "[", ":", "len", "(", "b", ")", "-", "4", "]", "\n\n", "/* Extract and strip version */", "ver", "=", "b", "[", "0", "]", "\n", "b", "=", "b", "[", "1", ":", "]", "\n\n", "return", "ver", ",", "b", ",", "nil", "\n", "}" ]
// 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
148,771
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", "(", "[", "]", "byte", "{", "0x00", "}", ",", "32", "-", "len", "(", "d", ")", ")", ",", "d", "...", ")", "\n\n", "return", "padded_d", "\n", "}" ]
// 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
148,772
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", ")", ")", "\n", "}", "\n\n", "priv", ".", "D", "=", "new", "(", "big", ".", "Int", ")", ".", "SetBytes", "(", "b", ")", "\n\n", "/* Derive public key from private key */", "priv", ".", "derive", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// 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
148,773
vsergeev/btckeygenie
btckey/btckey.go
ToWIF
func (priv *PrivateKey) ToWIF() (wif string) { /* See https://en.bitcoin.it/wiki/Wallet_import_format */ /* Convert the private key to bytes */ priv_bytes := priv.ToBytes() /* Convert bytes to base-58 check encoded string with version 0x80 */ wif = b58checkencode(0x80, priv_bytes) return wif }
go
func (priv *PrivateKey) ToWIF() (wif string) { /* See https://en.bitcoin.it/wiki/Wallet_import_format */ /* Convert the private key to bytes */ priv_bytes := priv.ToBytes() /* Convert bytes to base-58 check encoded string with version 0x80 */ wif = b58checkencode(0x80, priv_bytes) return wif }
[ "func", "(", "priv", "*", "PrivateKey", ")", "ToWIF", "(", ")", "(", "wif", "string", ")", "{", "/* See https://en.bitcoin.it/wiki/Wallet_import_format */", "/* Convert the private key to bytes */", "priv_bytes", ":=", "priv", ".", "ToBytes", "(", ")", "\n\n", "/* Convert bytes to base-58 check encoded string with version 0x80 */", "wif", "=", "b58checkencode", "(", "0x80", ",", "priv_bytes", ")", "\n\n", "return", "wif", "\n", "}" ]
// ToWIF converts a Bitcoin private key to a Wallet Import Format string.
[ "ToWIF", "converts", "a", "Bitcoin", "private", "key", "to", "a", "Wallet", "Import", "Format", "string", "." ]
413cbe3261adadbc974cecdbb4ea0b86c813c1a0
https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L302-L312
148,774
vsergeev/btckeygenie
btckey/btckey.go
ToWIFC
func (priv *PrivateKey) ToWIFC() (wifc string) { /* See https://en.bitcoin.it/wiki/Wallet_import_format */ /* Convert the private key to bytes */ priv_bytes := priv.ToBytes() /* Append 0x01 to tell Bitcoin wallet to use compressed public keys */ priv_bytes = append(priv_bytes, []byte{0x01}...) /* Convert bytes to base-58 check encoded string with version 0x80 */ wifc = b58checkencode(0x80, priv_bytes) return wifc }
go
func (priv *PrivateKey) ToWIFC() (wifc string) { /* See https://en.bitcoin.it/wiki/Wallet_import_format */ /* Convert the private key to bytes */ priv_bytes := priv.ToBytes() /* Append 0x01 to tell Bitcoin wallet to use compressed public keys */ priv_bytes = append(priv_bytes, []byte{0x01}...) /* Convert bytes to base-58 check encoded string with version 0x80 */ wifc = b58checkencode(0x80, priv_bytes) return wifc }
[ "func", "(", "priv", "*", "PrivateKey", ")", "ToWIFC", "(", ")", "(", "wifc", "string", ")", "{", "/* See https://en.bitcoin.it/wiki/Wallet_import_format */", "/* Convert the private key to bytes */", "priv_bytes", ":=", "priv", ".", "ToBytes", "(", ")", "\n\n", "/* Append 0x01 to tell Bitcoin wallet to use compressed public keys */", "priv_bytes", "=", "append", "(", "priv_bytes", ",", "[", "]", "byte", "{", "0x01", "}", "...", ")", "\n\n", "/* Convert bytes to base-58 check encoded string with version 0x80 */", "wifc", "=", "b58checkencode", "(", "0x80", ",", "priv_bytes", ")", "\n\n", "return", "wifc", "\n", "}" ]
// ToWIFC converts a Bitcoin private key to a Wallet Import Format string with the public key compressed flag.
[ "ToWIFC", "converts", "a", "Bitcoin", "private", "key", "to", "a", "Wallet", "Import", "Format", "string", "with", "the", "public", "key", "compressed", "flag", "." ]
413cbe3261adadbc974cecdbb4ea0b86c813c1a0
https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L315-L328
148,775
vsergeev/btckeygenie
btckey/btckey.go
FromWIF
func (priv *PrivateKey) FromWIF(wif string) (err error) { /* See https://en.bitcoin.it/wiki/Wallet_import_format */ /* Base58 Check Decode the WIF string */ ver, priv_bytes, err := b58checkdecode(wif) if err != nil { return err } /* Check that the version byte is 0x80 */ if ver != 0x80 { return fmt.Errorf("Invalid WIF version 0x%02x, expected 0x80.", ver) } /* If the private key bytes length is 33, check that suffix byte is 0x01 (for compression) and strip it off */ if len(priv_bytes) == 33 { if priv_bytes[len(priv_bytes)-1] != 0x01 { return fmt.Errorf("Invalid private key, unknown suffix byte 0x%02x.", priv_bytes[len(priv_bytes)-1]) } priv_bytes = priv_bytes[0:32] } /* Convert from bytes to a private key */ err = priv.FromBytes(priv_bytes) if err != nil { return err } /* Derive public key from private key */ priv.derive() return nil }
go
func (priv *PrivateKey) FromWIF(wif string) (err error) { /* See https://en.bitcoin.it/wiki/Wallet_import_format */ /* Base58 Check Decode the WIF string */ ver, priv_bytes, err := b58checkdecode(wif) if err != nil { return err } /* Check that the version byte is 0x80 */ if ver != 0x80 { return fmt.Errorf("Invalid WIF version 0x%02x, expected 0x80.", ver) } /* If the private key bytes length is 33, check that suffix byte is 0x01 (for compression) and strip it off */ if len(priv_bytes) == 33 { if priv_bytes[len(priv_bytes)-1] != 0x01 { return fmt.Errorf("Invalid private key, unknown suffix byte 0x%02x.", priv_bytes[len(priv_bytes)-1]) } priv_bytes = priv_bytes[0:32] } /* Convert from bytes to a private key */ err = priv.FromBytes(priv_bytes) if err != nil { return err } /* Derive public key from private key */ priv.derive() return nil }
[ "func", "(", "priv", "*", "PrivateKey", ")", "FromWIF", "(", "wif", "string", ")", "(", "err", "error", ")", "{", "/* See https://en.bitcoin.it/wiki/Wallet_import_format */", "/* Base58 Check Decode the WIF string */", "ver", ",", "priv_bytes", ",", "err", ":=", "b58checkdecode", "(", "wif", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "/* Check that the version byte is 0x80 */", "if", "ver", "!=", "0x80", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ver", ")", "\n", "}", "\n\n", "/* If the private key bytes length is 33, check that suffix byte is 0x01 (for compression) and strip it off */", "if", "len", "(", "priv_bytes", ")", "==", "33", "{", "if", "priv_bytes", "[", "len", "(", "priv_bytes", ")", "-", "1", "]", "!=", "0x01", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "priv_bytes", "[", "len", "(", "priv_bytes", ")", "-", "1", "]", ")", "\n", "}", "\n", "priv_bytes", "=", "priv_bytes", "[", "0", ":", "32", "]", "\n", "}", "\n\n", "/* Convert from bytes to a private key */", "err", "=", "priv", ".", "FromBytes", "(", "priv_bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "/* Derive public key from private key */", "priv", ".", "derive", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// FromWIF converts a Wallet Import Format string to a Bitcoin private key and derives the corresponding Bitcoin public key.
[ "FromWIF", "converts", "a", "Wallet", "Import", "Format", "string", "to", "a", "Bitcoin", "private", "key", "and", "derives", "the", "corresponding", "Bitcoin", "public", "key", "." ]
413cbe3261adadbc974cecdbb4ea0b86c813c1a0
https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L331-L363
148,776
vsergeev/btckeygenie
btckey/btckey.go
ToBytesUncompressed
func (pub *PublicKey) ToBytesUncompressed() (b []byte) { /* See Certicom SEC1 2.3.3, pg. 10 */ x := pub.X.Bytes() y := pub.Y.Bytes() /* Pad X and Y coordinate bytes to 32-bytes */ padded_x := append(bytes.Repeat([]byte{0x00}, 32-len(x)), x...) padded_y := append(bytes.Repeat([]byte{0x00}, 32-len(y)), y...) /* Add prefix 0x04 for uncompressed coordinates */ return append([]byte{0x04}, append(padded_x, padded_y...)...) }
go
func (pub *PublicKey) ToBytesUncompressed() (b []byte) { /* See Certicom SEC1 2.3.3, pg. 10 */ x := pub.X.Bytes() y := pub.Y.Bytes() /* Pad X and Y coordinate bytes to 32-bytes */ padded_x := append(bytes.Repeat([]byte{0x00}, 32-len(x)), x...) padded_y := append(bytes.Repeat([]byte{0x00}, 32-len(y)), y...) /* Add prefix 0x04 for uncompressed coordinates */ return append([]byte{0x04}, append(padded_x, padded_y...)...) }
[ "func", "(", "pub", "*", "PublicKey", ")", "ToBytesUncompressed", "(", ")", "(", "b", "[", "]", "byte", ")", "{", "/* See Certicom SEC1 2.3.3, pg. 10 */", "x", ":=", "pub", ".", "X", ".", "Bytes", "(", ")", "\n", "y", ":=", "pub", ".", "Y", ".", "Bytes", "(", ")", "\n\n", "/* Pad X and Y coordinate bytes to 32-bytes */", "padded_x", ":=", "append", "(", "bytes", ".", "Repeat", "(", "[", "]", "byte", "{", "0x00", "}", ",", "32", "-", "len", "(", "x", ")", ")", ",", "x", "...", ")", "\n", "padded_y", ":=", "append", "(", "bytes", ".", "Repeat", "(", "[", "]", "byte", "{", "0x00", "}", ",", "32", "-", "len", "(", "y", ")", ")", ",", "y", "...", ")", "\n\n", "/* Add prefix 0x04 for uncompressed coordinates */", "return", "append", "(", "[", "]", "byte", "{", "0x04", "}", ",", "append", "(", "padded_x", ",", "padded_y", "...", ")", "...", ")", "\n", "}" ]
// ToBytesUncompressed converts a Bitcoin public key to a 65-byte byte slice without point compression.
[ "ToBytesUncompressed", "converts", "a", "Bitcoin", "public", "key", "to", "a", "65", "-", "byte", "byte", "slice", "without", "point", "compression", "." ]
413cbe3261adadbc974cecdbb4ea0b86c813c1a0
https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L387-L399
148,777
vsergeev/btckeygenie
btckey/btckey.go
ToAddress
func (pub *PublicKey) ToAddress() (address string) { /* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */ /* Convert the public key to bytes */ pub_bytes := pub.ToBytes() /* SHA256 Hash */ sha256_h := sha256.New() sha256_h.Reset() sha256_h.Write(pub_bytes) pub_hash_1 := sha256_h.Sum(nil) /* RIPEMD-160 Hash */ ripemd160_h := ripemd160.New() ripemd160_h.Reset() ripemd160_h.Write(pub_hash_1) pub_hash_2 := ripemd160_h.Sum(nil) /* Convert hash bytes to base58 check encoded sequence */ address = b58checkencode(0x00, pub_hash_2) return address }
go
func (pub *PublicKey) ToAddress() (address string) { /* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */ /* Convert the public key to bytes */ pub_bytes := pub.ToBytes() /* SHA256 Hash */ sha256_h := sha256.New() sha256_h.Reset() sha256_h.Write(pub_bytes) pub_hash_1 := sha256_h.Sum(nil) /* RIPEMD-160 Hash */ ripemd160_h := ripemd160.New() ripemd160_h.Reset() ripemd160_h.Write(pub_hash_1) pub_hash_2 := ripemd160_h.Sum(nil) /* Convert hash bytes to base58 check encoded sequence */ address = b58checkencode(0x00, pub_hash_2) return address }
[ "func", "(", "pub", "*", "PublicKey", ")", "ToAddress", "(", ")", "(", "address", "string", ")", "{", "/* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */", "/* Convert the public key to bytes */", "pub_bytes", ":=", "pub", ".", "ToBytes", "(", ")", "\n\n", "/* SHA256 Hash */", "sha256_h", ":=", "sha256", ".", "New", "(", ")", "\n", "sha256_h", ".", "Reset", "(", ")", "\n", "sha256_h", ".", "Write", "(", "pub_bytes", ")", "\n", "pub_hash_1", ":=", "sha256_h", ".", "Sum", "(", "nil", ")", "\n\n", "/* RIPEMD-160 Hash */", "ripemd160_h", ":=", "ripemd160", ".", "New", "(", ")", "\n", "ripemd160_h", ".", "Reset", "(", ")", "\n", "ripemd160_h", ".", "Write", "(", "pub_hash_1", ")", "\n", "pub_hash_2", ":=", "ripemd160_h", ".", "Sum", "(", "nil", ")", "\n\n", "/* Convert hash bytes to base58 check encoded sequence */", "address", "=", "b58checkencode", "(", "0x00", ",", "pub_hash_2", ")", "\n\n", "return", "address", "\n", "}" ]
// ToAddress converts a Bitcoin public key to a compressed Bitcoin address string.
[ "ToAddress", "converts", "a", "Bitcoin", "public", "key", "to", "a", "compressed", "Bitcoin", "address", "string", "." ]
413cbe3261adadbc974cecdbb4ea0b86c813c1a0
https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/btckey.go#L447-L469
148,778
vsergeev/btckeygenie
btckey/elliptic.go
format
func (p *Point) format() string { if p.X == nil && p.Y == nil { return "(inf,inf)" } return fmt.Sprintf("(%s,%s)", hex.EncodeToString(p.X.Bytes()), hex.EncodeToString(p.Y.Bytes())) }
go
func (p *Point) format() string { if p.X == nil && p.Y == nil { return "(inf,inf)" } return fmt.Sprintf("(%s,%s)", hex.EncodeToString(p.X.Bytes()), hex.EncodeToString(p.Y.Bytes())) }
[ "func", "(", "p", "*", "Point", ")", "format", "(", ")", "string", "{", "if", "p", ".", "X", "==", "nil", "&&", "p", ".", "Y", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hex", ".", "EncodeToString", "(", "p", ".", "X", ".", "Bytes", "(", ")", ")", ",", "hex", ".", "EncodeToString", "(", "p", ".", "Y", ".", "Bytes", "(", ")", ")", ")", "\n", "}" ]
// format formats the bytes of a point for debugging.
[ "format", "formats", "the", "bytes", "of", "a", "point", "for", "debugging", "." ]
413cbe3261adadbc974cecdbb4ea0b86c813c1a0
https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/elliptic.go#L43-L48
148,779
vsergeev/btckeygenie
btckey/elliptic.go
IsOnCurve
func (ec *EllipticCurve) IsOnCurve(P Point) bool { if ec.IsInfinity(P) { return false } /* y**2 = x**3 + a*x + b % p */ lhs := mulMod(P.Y, P.Y, ec.P) rhs := addMod( addMod( expMod(P.X, big.NewInt(3), ec.P), mulMod(ec.A, P.X, ec.P), ec.P), ec.B, ec.P) if lhs.Cmp(rhs) == 0 { return true } return false }
go
func (ec *EllipticCurve) IsOnCurve(P Point) bool { if ec.IsInfinity(P) { return false } /* y**2 = x**3 + a*x + b % p */ lhs := mulMod(P.Y, P.Y, ec.P) rhs := addMod( addMod( expMod(P.X, big.NewInt(3), ec.P), mulMod(ec.A, P.X, ec.P), ec.P), ec.B, ec.P) if lhs.Cmp(rhs) == 0 { return true } return false }
[ "func", "(", "ec", "*", "EllipticCurve", ")", "IsOnCurve", "(", "P", "Point", ")", "bool", "{", "if", "ec", ".", "IsInfinity", "(", "P", ")", "{", "return", "false", "\n", "}", "\n\n", "/* y**2 = x**3 + a*x + b % p */", "lhs", ":=", "mulMod", "(", "P", ".", "Y", ",", "P", ".", "Y", ",", "ec", ".", "P", ")", "\n", "rhs", ":=", "addMod", "(", "addMod", "(", "expMod", "(", "P", ".", "X", ",", "big", ".", "NewInt", "(", "3", ")", ",", "ec", ".", "P", ")", ",", "mulMod", "(", "ec", ".", "A", ",", "P", ".", "X", ",", "ec", ".", "P", ")", ",", "ec", ".", "P", ")", ",", "ec", ".", "B", ",", "ec", ".", "P", ")", "\n\n", "if", "lhs", ".", "Cmp", "(", "rhs", ")", "==", "0", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// IsOnCurve checks if point P is on EllipticCurve ec.
[ "IsOnCurve", "checks", "if", "point", "P", "is", "on", "EllipticCurve", "ec", "." ]
413cbe3261adadbc974cecdbb4ea0b86c813c1a0
https://github.com/vsergeev/btckeygenie/blob/413cbe3261adadbc974cecdbb4ea0b86c813c1a0/btckey/elliptic.go#L128-L146
148,780
gocarina/gocsv
csv.go
LazyCSVReader
func LazyCSVReader(in io.Reader) CSVReader { csvReader := csv.NewReader(in) csvReader.LazyQuotes = true csvReader.TrimLeadingSpace = true return csvReader }
go
func LazyCSVReader(in io.Reader) CSVReader { csvReader := csv.NewReader(in) csvReader.LazyQuotes = true csvReader.TrimLeadingSpace = true return csvReader }
[ "func", "LazyCSVReader", "(", "in", "io", ".", "Reader", ")", "CSVReader", "{", "csvReader", ":=", "csv", ".", "NewReader", "(", "in", ")", "\n", "csvReader", ".", "LazyQuotes", "=", "true", "\n", "csvReader", ".", "TrimLeadingSpace", "=", "true", "\n", "return", "csvReader", "\n", "}" ]
// LazyCSVReader returns a lazy CSV reader, with LazyQuotes and TrimLeadingSpace.
[ "LazyCSVReader", "returns", "a", "lazy", "CSV", "reader", "with", "LazyQuotes", "and", "TrimLeadingSpace", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L72-L77
148,781
gocarina/gocsv
csv.go
MarshalString
func MarshalString(in interface{}) (out string, err error) { bufferString := bytes.NewBufferString(out) if err := Marshal(in, bufferString); err != nil { return "", err } return bufferString.String(), nil }
go
func MarshalString(in interface{}) (out string, err error) { bufferString := bytes.NewBufferString(out) if err := Marshal(in, bufferString); err != nil { return "", err } return bufferString.String(), nil }
[ "func", "MarshalString", "(", "in", "interface", "{", "}", ")", "(", "out", "string", ",", "err", "error", ")", "{", "bufferString", ":=", "bytes", ".", "NewBufferString", "(", "out", ")", "\n", "if", "err", ":=", "Marshal", "(", "in", ",", "bufferString", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "bufferString", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// MarshalString returns the CSV string from the interface.
[ "MarshalString", "returns", "the", "CSV", "string", "from", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L97-L103
148,782
gocarina/gocsv
csv.go
MarshalBytes
func MarshalBytes(in interface{}) (out []byte, err error) { bufferString := bytes.NewBuffer(out) if err := Marshal(in, bufferString); err != nil { return nil, err } return bufferString.Bytes(), nil }
go
func MarshalBytes(in interface{}) (out []byte, err error) { bufferString := bytes.NewBuffer(out) if err := Marshal(in, bufferString); err != nil { return nil, err } return bufferString.Bytes(), nil }
[ "func", "MarshalBytes", "(", "in", "interface", "{", "}", ")", "(", "out", "[", "]", "byte", ",", "err", "error", ")", "{", "bufferString", ":=", "bytes", ".", "NewBuffer", "(", "out", ")", "\n", "if", "err", ":=", "Marshal", "(", "in", ",", "bufferString", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "bufferString", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// MarshalBytes returns the CSV bytes from the interface.
[ "MarshalBytes", "returns", "the", "CSV", "bytes", "from", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L106-L112
148,783
gocarina/gocsv
csv.go
MarshalCSV
func MarshalCSV(in interface{}, out *SafeCSVWriter) (err error) { return writeTo(out, in, false) }
go
func MarshalCSV(in interface{}, out *SafeCSVWriter) (err error) { return writeTo(out, in, false) }
[ "func", "MarshalCSV", "(", "in", "interface", "{", "}", ",", "out", "*", "SafeCSVWriter", ")", "(", "err", "error", ")", "{", "return", "writeTo", "(", "out", ",", "in", ",", "false", ")", "\n", "}" ]
// MarshalCSV returns the CSV in writer from the interface.
[ "MarshalCSV", "returns", "the", "CSV", "in", "writer", "from", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L132-L134
148,784
gocarina/gocsv
csv.go
MarshalCSVWithoutHeaders
func MarshalCSVWithoutHeaders(in interface{}, out *SafeCSVWriter) (err error) { return writeTo(out, in, true) }
go
func MarshalCSVWithoutHeaders(in interface{}, out *SafeCSVWriter) (err error) { return writeTo(out, in, true) }
[ "func", "MarshalCSVWithoutHeaders", "(", "in", "interface", "{", "}", ",", "out", "*", "SafeCSVWriter", ")", "(", "err", "error", ")", "{", "return", "writeTo", "(", "out", ",", "in", ",", "true", ")", "\n", "}" ]
// MarshalCSVWithoutHeaders returns the CSV in writer from the interface.
[ "MarshalCSVWithoutHeaders", "returns", "the", "CSV", "in", "writer", "from", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L137-L139
148,785
gocarina/gocsv
csv.go
UnmarshalString
func UnmarshalString(in string, out interface{}) error { return Unmarshal(strings.NewReader(in), out) }
go
func UnmarshalString(in string, out interface{}) error { return Unmarshal(strings.NewReader(in), out) }
[ "func", "UnmarshalString", "(", "in", "string", ",", "out", "interface", "{", "}", ")", "error", "{", "return", "Unmarshal", "(", "strings", ".", "NewReader", "(", "in", ")", ",", "out", ")", "\n", "}" ]
// UnmarshalString parses the CSV from the string in the interface.
[ "UnmarshalString", "parses", "the", "CSV", "from", "the", "string", "in", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L150-L152
148,786
gocarina/gocsv
csv.go
UnmarshalBytes
func UnmarshalBytes(in []byte, out interface{}) error { return Unmarshal(bytes.NewReader(in), out) }
go
func UnmarshalBytes(in []byte, out interface{}) error { return Unmarshal(bytes.NewReader(in), out) }
[ "func", "UnmarshalBytes", "(", "in", "[", "]", "byte", ",", "out", "interface", "{", "}", ")", "error", "{", "return", "Unmarshal", "(", "bytes", ".", "NewReader", "(", "in", ")", ",", "out", ")", "\n", "}" ]
// UnmarshalBytes parses the CSV from the bytes in the interface.
[ "UnmarshalBytes", "parses", "the", "CSV", "from", "the", "bytes", "in", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L155-L157
148,787
gocarina/gocsv
csv.go
Unmarshal
func Unmarshal(in io.Reader, out interface{}) error { return readTo(newDecoder(in), out) }
go
func Unmarshal(in io.Reader, out interface{}) error { return readTo(newDecoder(in), out) }
[ "func", "Unmarshal", "(", "in", "io", ".", "Reader", ",", "out", "interface", "{", "}", ")", "error", "{", "return", "readTo", "(", "newDecoder", "(", "in", ")", ",", "out", ")", "\n", "}" ]
// Unmarshal parses the CSV from the reader in the interface.
[ "Unmarshal", "parses", "the", "CSV", "from", "the", "reader", "in", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L160-L162
148,788
gocarina/gocsv
csv.go
UnmarshalWithoutHeaders
func UnmarshalWithoutHeaders(in io.Reader, out interface{}) error { return readToWithoutHeaders(newDecoder(in), out) }
go
func UnmarshalWithoutHeaders(in io.Reader, out interface{}) error { return readToWithoutHeaders(newDecoder(in), out) }
[ "func", "UnmarshalWithoutHeaders", "(", "in", "io", ".", "Reader", ",", "out", "interface", "{", "}", ")", "error", "{", "return", "readToWithoutHeaders", "(", "newDecoder", "(", "in", ")", ",", "out", ")", "\n", "}" ]
// UnmarshalWithoutHeaders parses the CSV from the reader in the interface.
[ "UnmarshalWithoutHeaders", "parses", "the", "CSV", "from", "the", "reader", "in", "the", "interface", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L165-L167
148,789
gocarina/gocsv
csv.go
UnmarshalToChan
func UnmarshalToChan(in io.Reader, c interface{}) error { if c == nil { return fmt.Errorf("goscv: channel is %v", c) } return readEach(newDecoder(in), c) }
go
func UnmarshalToChan(in io.Reader, c interface{}) error { if c == nil { return fmt.Errorf("goscv: channel is %v", c) } return readEach(newDecoder(in), c) }
[ "func", "UnmarshalToChan", "(", "in", "io", ".", "Reader", ",", "c", "interface", "{", "}", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ")", "\n", "}", "\n", "return", "readEach", "(", "newDecoder", "(", "in", ")", ",", "c", ")", "\n", "}" ]
// UnmarshalToChan parses the CSV from the reader and send each value in the chan c. // The channel must have a concrete type.
[ "UnmarshalToChan", "parses", "the", "CSV", "from", "the", "reader", "and", "send", "each", "value", "in", "the", "chan", "c", ".", "The", "channel", "must", "have", "a", "concrete", "type", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L186-L191
148,790
gocarina/gocsv
csv.go
UnmarshalDecoderToChan
func UnmarshalDecoderToChan(in SimpleDecoder, c interface{}) error { if c == nil { return fmt.Errorf("goscv: channel is %v", c) } return readEach(in, c) }
go
func UnmarshalDecoderToChan(in SimpleDecoder, c interface{}) error { if c == nil { return fmt.Errorf("goscv: channel is %v", c) } return readEach(in, c) }
[ "func", "UnmarshalDecoderToChan", "(", "in", "SimpleDecoder", ",", "c", "interface", "{", "}", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ")", "\n", "}", "\n", "return", "readEach", "(", "in", ",", "c", ")", "\n", "}" ]
// UnmarshalDecoderToChan parses the CSV from the decoder and send each value in the chan c. // The channel must have a concrete type.
[ "UnmarshalDecoderToChan", "parses", "the", "CSV", "from", "the", "decoder", "and", "send", "each", "value", "in", "the", "chan", "c", ".", "The", "channel", "must", "have", "a", "concrete", "type", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L195-L200
148,791
gocarina/gocsv
csv.go
UnmarshalStringToChan
func UnmarshalStringToChan(in string, c interface{}) error { return UnmarshalToChan(strings.NewReader(in), c) }
go
func UnmarshalStringToChan(in string, c interface{}) error { return UnmarshalToChan(strings.NewReader(in), c) }
[ "func", "UnmarshalStringToChan", "(", "in", "string", ",", "c", "interface", "{", "}", ")", "error", "{", "return", "UnmarshalToChan", "(", "strings", ".", "NewReader", "(", "in", ")", ",", "c", ")", "\n", "}" ]
// UnmarshalStringToChan parses the CSV from the string and send each value in the chan c. // The channel must have a concrete type.
[ "UnmarshalStringToChan", "parses", "the", "CSV", "from", "the", "string", "and", "send", "each", "value", "in", "the", "chan", "c", ".", "The", "channel", "must", "have", "a", "concrete", "type", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L204-L206
148,792
gocarina/gocsv
csv.go
UnmarshalBytesToChan
func UnmarshalBytesToChan(in []byte, c interface{}) error { return UnmarshalToChan(bytes.NewReader(in), c) }
go
func UnmarshalBytesToChan(in []byte, c interface{}) error { return UnmarshalToChan(bytes.NewReader(in), c) }
[ "func", "UnmarshalBytesToChan", "(", "in", "[", "]", "byte", ",", "c", "interface", "{", "}", ")", "error", "{", "return", "UnmarshalToChan", "(", "bytes", ".", "NewReader", "(", "in", ")", ",", "c", ")", "\n", "}" ]
// UnmarshalBytesToChan parses the CSV from the bytes and send each value in the chan c. // The channel must have a concrete type.
[ "UnmarshalBytesToChan", "parses", "the", "CSV", "from", "the", "bytes", "and", "send", "each", "value", "in", "the", "chan", "c", ".", "The", "channel", "must", "have", "a", "concrete", "type", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L210-L212
148,793
gocarina/gocsv
csv.go
CSVToMap
func CSVToMap(in io.Reader) (map[string]string, error) { decoder := newDecoder(in) header, err := decoder.getCSVRow() if err != nil { return nil, err } if len(header) != 2 { return nil, fmt.Errorf("maps can only be created for csv of two columns") } m := make(map[string]string) for { line, err := decoder.getCSVRow() if err == io.EOF { break } else if err != nil { return nil, err } m[line[0]] = line[1] } return m, nil }
go
func CSVToMap(in io.Reader) (map[string]string, error) { decoder := newDecoder(in) header, err := decoder.getCSVRow() if err != nil { return nil, err } if len(header) != 2 { return nil, fmt.Errorf("maps can only be created for csv of two columns") } m := make(map[string]string) for { line, err := decoder.getCSVRow() if err == io.EOF { break } else if err != nil { return nil, err } m[line[0]] = line[1] } return m, nil }
[ "func", "CSVToMap", "(", "in", "io", ".", "Reader", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "decoder", ":=", "newDecoder", "(", "in", ")", "\n", "header", ",", "err", ":=", "decoder", ".", "getCSVRow", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "header", ")", "!=", "2", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "m", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "{", "line", ",", "err", ":=", "decoder", ".", "getCSVRow", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "m", "[", "line", "[", "0", "]", "]", "=", "line", "[", "1", "]", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// CSVToMap creates a simple map from a CSV of 2 columns.
[ "CSVToMap", "creates", "a", "simple", "map", "from", "a", "CSV", "of", "2", "columns", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L283-L303
148,794
gocarina/gocsv
csv.go
CSVToMaps
func CSVToMaps(reader io.Reader) ([]map[string]string, error) { r := csv.NewReader(reader) rows := []map[string]string{} var header []string for { record, err := r.Read() if err == io.EOF { break } if err != nil { return nil, err } if header == nil { header = record } else { dict := map[string]string{} for i := range header { dict[header[i]] = record[i] } rows = append(rows, dict) } } return rows, nil }
go
func CSVToMaps(reader io.Reader) ([]map[string]string, error) { r := csv.NewReader(reader) rows := []map[string]string{} var header []string for { record, err := r.Read() if err == io.EOF { break } if err != nil { return nil, err } if header == nil { header = record } else { dict := map[string]string{} for i := range header { dict[header[i]] = record[i] } rows = append(rows, dict) } } return rows, nil }
[ "func", "CSVToMaps", "(", "reader", "io", ".", "Reader", ")", "(", "[", "]", "map", "[", "string", "]", "string", ",", "error", ")", "{", "r", ":=", "csv", ".", "NewReader", "(", "reader", ")", "\n", "rows", ":=", "[", "]", "map", "[", "string", "]", "string", "{", "}", "\n", "var", "header", "[", "]", "string", "\n", "for", "{", "record", ",", "err", ":=", "r", ".", "Read", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "header", "==", "nil", "{", "header", "=", "record", "\n", "}", "else", "{", "dict", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "header", "{", "dict", "[", "header", "[", "i", "]", "]", "=", "record", "[", "i", "]", "\n", "}", "\n", "rows", "=", "append", "(", "rows", ",", "dict", ")", "\n", "}", "\n", "}", "\n", "return", "rows", ",", "nil", "\n", "}" ]
// CSVToMaps takes a reader and returns an array of dictionaries, using the header row as the keys
[ "CSVToMaps", "takes", "a", "reader", "and", "returns", "an", "array", "of", "dictionaries", "using", "the", "header", "row", "as", "the", "keys" ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/csv.go#L306-L329
148,795
gocarina/gocsv
encode.go
ensureInType
func ensureInType(outType reflect.Type) error { switch outType.Kind() { case reflect.Slice: fallthrough case reflect.Array: return nil } return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported") }
go
func ensureInType(outType reflect.Type) error { switch outType.Kind() { case reflect.Slice: fallthrough case reflect.Array: return nil } return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported") }
[ "func", "ensureInType", "(", "outType", "reflect", ".", "Type", ")", "error", "{", "switch", "outType", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Slice", ":", "fallthrough", "\n", "case", "reflect", ".", "Array", ":", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "outType", ".", "String", "(", ")", "+", "\"", "\"", ")", "\n", "}" ]
// Check if the inType is an array or a slice
[ "Check", "if", "the", "inType", "is", "an", "array", "or", "a", "slice" ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/encode.go#L114-L122
148,796
gocarina/gocsv
decode.go
maybeDoubleHeaderNames
func maybeDoubleHeaderNames(headers []string) error { headerMap := make(map[string]bool, len(headers)) for _, v := range headers { if _, ok := headerMap[v]; ok { return fmt.Errorf("Repeated header name: %v", v) } headerMap[v] = true } return nil }
go
func maybeDoubleHeaderNames(headers []string) error { headerMap := make(map[string]bool, len(headers)) for _, v := range headers { if _, ok := headerMap[v]; ok { return fmt.Errorf("Repeated header name: %v", v) } headerMap[v] = true } return nil }
[ "func", "maybeDoubleHeaderNames", "(", "headers", "[", "]", "string", ")", "error", "{", "headerMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ",", "len", "(", "headers", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "headers", "{", "if", "_", ",", "ok", ":=", "headerMap", "[", "v", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "headerMap", "[", "v", "]", "=", "true", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check that no header name is repeated twice
[ "Check", "that", "no", "header", "name", "is", "repeated", "twice" ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/decode.go#L114-L123
148,797
gocarina/gocsv
decode.go
ensureOutType
func ensureOutType(outType reflect.Type) error { switch outType.Kind() { case reflect.Slice: fallthrough case reflect.Chan: fallthrough case reflect.Array: return nil } return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported") }
go
func ensureOutType(outType reflect.Type) error { switch outType.Kind() { case reflect.Slice: fallthrough case reflect.Chan: fallthrough case reflect.Array: return nil } return fmt.Errorf("cannot use " + outType.String() + ", only slice or array supported") }
[ "func", "ensureOutType", "(", "outType", "reflect", ".", "Type", ")", "error", "{", "switch", "outType", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Slice", ":", "fallthrough", "\n", "case", "reflect", ".", "Chan", ":", "fallthrough", "\n", "case", "reflect", ".", "Array", ":", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "outType", ".", "String", "(", ")", "+", "\"", "\"", ")", "\n", "}" ]
// Check if the outType is an array or a slice
[ "Check", "if", "the", "outType", "is", "an", "array", "or", "a", "slice" ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/decode.go#L304-L314
148,798
gocarina/gocsv
decode.go
ensureOutInnerType
func ensureOutInnerType(outInnerType reflect.Type) error { switch outInnerType.Kind() { case reflect.Struct: return nil } return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported") }
go
func ensureOutInnerType(outInnerType reflect.Type) error { switch outInnerType.Kind() { case reflect.Struct: return nil } return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported") }
[ "func", "ensureOutInnerType", "(", "outInnerType", "reflect", ".", "Type", ")", "error", "{", "switch", "outInnerType", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Struct", ":", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "outInnerType", ".", "String", "(", ")", "+", "\"", "\"", ")", "\n", "}" ]
// Check if the outInnerType is of type struct
[ "Check", "if", "the", "outInnerType", "is", "of", "type", "struct" ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/decode.go#L317-L323
148,799
gocarina/gocsv
unmarshaller.go
NewUnmarshaller
func NewUnmarshaller(reader *csv.Reader, out interface{}) (*Unmarshaller, error) { headers, err := reader.Read() if err != nil { return nil, err } um := &Unmarshaller{reader: reader, outType: reflect.TypeOf(out)} err = validate(um, out, headers) if err != nil { return nil, err } return um, nil }
go
func NewUnmarshaller(reader *csv.Reader, out interface{}) (*Unmarshaller, error) { headers, err := reader.Read() if err != nil { return nil, err } um := &Unmarshaller{reader: reader, outType: reflect.TypeOf(out)} err = validate(um, out, headers) if err != nil { return nil, err } return um, nil }
[ "func", "NewUnmarshaller", "(", "reader", "*", "csv", ".", "Reader", ",", "out", "interface", "{", "}", ")", "(", "*", "Unmarshaller", ",", "error", ")", "{", "headers", ",", "err", ":=", "reader", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "um", ":=", "&", "Unmarshaller", "{", "reader", ":", "reader", ",", "outType", ":", "reflect", ".", "TypeOf", "(", "out", ")", "}", "\n", "err", "=", "validate", "(", "um", ",", "out", ",", "headers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "um", ",", "nil", "\n", "}" ]
// NewUnmarshaller creates an unmarshaller from a csv.Reader and a struct.
[ "NewUnmarshaller", "creates", "an", "unmarshaller", "from", "a", "csv", ".", "Reader", "and", "a", "struct", "." ]
2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724
https://github.com/gocarina/gocsv/blob/2fc85fcf0c07e8bb9123b2104e84cfc2a5b53724/unmarshaller.go#L21-L33