From 2c7094bdb681a19d5608690880f95d3d0b44988f Mon Sep 17 00:00:00 2001 From: Jack Henschel Date: Mon, 14 Sep 2020 21:51:26 +0200 Subject: [PATCH] Allow user to specify protocol for custom endpoint In local setups, such as a Minio [1] instance in a Docker container, the protocol may not always be HTTPS (like for public production endpoints), but instead just plain HTTP. To support this use-case, the user can specify a protocol at the beginning of the custom endpoint URI (either http:// or https://). To maintain backwards compatibility, the protocol defaults to HTTPS. The patch also includes a test case to assert this behavior. [1] https://hub.docker.com/r/minio/minio --- simples3.go | 6 +++++- simples3_test.go | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/simples3.go b/simples3.go index 3e506e8..1f974a8 100644 --- a/simples3.go +++ b/simples3.go @@ -155,7 +155,7 @@ func (s3 *S3) getClient() *http.Client { func (s3 *S3) getURL(bucket string, args ...string) (uri string) { if len(s3.Endpoint) > 0 { - uri = defaultProtocol + s3.Endpoint + "/" + bucket + uri = s3.Endpoint + "/" + bucket } else { uri = fmt.Sprintf(s3.URIFormat, s3.Region, bucket) } @@ -168,8 +168,12 @@ func (s3 *S3) getURL(bucket string, args ...string) (uri string) { // SetEndpoint can be used to the set a custom endpoint for // using an alternate instance compatible with the s3 API. +// If no protocol is included in the URI, defaults to HTTPS. func (s3 *S3) SetEndpoint(uri string) *S3 { if len(uri) > 0 { + if !strings.HasPrefix(uri, "http") { + uri = "https://" + uri + } s3.Endpoint = uri } return s3 diff --git a/simples3_test.go b/simples3_test.go index 9dcd495..8d35991 100644 --- a/simples3_test.go +++ b/simples3_test.go @@ -272,3 +272,25 @@ func TestS3_NewUsingIAM(t *testing.T) { t.Errorf("S3.FileDelete() got = %v", s3) } } + +func TestCustomEndpoint(t *testing.T) { + s3 := New("us-east-1", "AccessKey", "SuperSecretKey") + + // no protocol specified, should default to https + s3.SetEndpoint("example.com") + if s3.getURL("bucket1") != "https://example.com/bucket1" { + t.Errorf("S3.SetEndpoint() got = %v", s3.Endpoint) + } + + // explicit http protocol + s3.SetEndpoint("http://localhost:9000") + if s3.getURL("bucket2") != "http://localhost:9000/bucket2" { + t.Errorf("S3.SetEndpoint() got = %v", s3.Endpoint) + } + + // explicit http protocol + s3.SetEndpoint("https://example.com") + if s3.getURL("bucket3") != "https://example.com/bucket3" { + t.Errorf("S3.SetEndpoint() got = %v", s3.Endpoint) + } +}