Skip to content
Console

Connect to S4 with Go

Uses the AWS SDK for Go v2. Each snippet below is a function you can call directly.

Prerequisites

  1. Create a bucket in the console;
  2. Create a sub-user and AccessKey, and grant the sub-user access to this bucket. A new sub-user has no permissions;
  3. Put the keys in environment variables instead of writing them in code:
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"

Install

go get github.com/aws/aws-sdk-go-v2/service/s3
go get github.com/aws/aws-sdk-go-v2/credentials
go get github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager

The examples on this page were tested on Go 1.27, service/s3 v1.116.0, and feature/s3/transfermanager v0.5.11. The required imports are below; keep only the ones you use:

main.go
import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

Connect to S4

main.go
var bucket = "my-bucket"

func newClient() *s3.Client {
	return s3.New(s3.Options{
		BaseEndpoint: aws.String("https://s3.bitiful.net"),
		Region:       "cn-east-1",
		Credentials: credentials.NewStaticCredentialsProvider(
			os.Getenv("S4_ACCESS_KEY"), os.Getenv("S4_SECRET_KEY"), ""),
	})
}

s3.Client can be used concurrently; create one per process. The EndpointResolverWithOptions shown in older articles is deprecated; use BaseEndpoint.

Upload files

An object with the same name is overwritten directly. If ContentType is left empty, S4 detects it automatically.

main.go
func upload(ctx context.Context, client *s3.Client) error {
	// Upload a text string
	_, err := client.PutObject(ctx, &s3.PutObjectInput{
		Bucket:      aws.String(bucket),
		Key:         aws.String("docs/hello.txt"),
		Body:        strings.NewReader("你好,S4"),
		ContentType: aws.String("text/plain; charset=utf-8"),
	})
	if err != nil {
		return err
	}

	// Upload a local file, setting cache time and custom metadata
	f, err := os.Open("photo.jpg")
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = client.PutObject(ctx, &s3.PutObjectInput{
		Bucket:       aws.String(bucket),
		Key:          aws.String("images/photo.jpg"),
		Body:         f,
		ContentType:  aws.String("image/jpeg"),
		CacheControl: aws.String("max-age=86400"),
		Metadata:     map[string]string{"author": "bitiful"},
	})
	return err
}

Upload large files

Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.

main.go
func uploadLarge(ctx context.Context, client *s3.Client) error {
	f, err := os.Open("video.mp4")
	if err != nil {
		return err
	}
	defer f.Close()

	// Split automatically above 16 MiB, 16 MiB per part, 4 parts uploaded at a time
	tm := transfermanager.New(client, func(o *transfermanager.Options) {
		o.MultipartUploadThreshold = 16 * 1024 * 1024
		o.PartSizeBytes = 16 * 1024 * 1024
		o.Concurrency = 4
	})
	_, err = tm.UploadObject(ctx, &transfermanager.UploadObjectInput{
		Bucket:      aws.String(bucket),
		Key:         aws.String("videos/video.mp4"),
		Body:        f,
		ContentType: aws.String("video/mp4"),
	})
	return err
}

Download files

Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.

main.go
func download(ctx context.Context, client *s3.Client) error {
	out, err := client.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String("videos/video.mp4"),
	})
	if err != nil {
		return err
	}
	defer out.Body.Close()

	f, err := os.Create("video-copy.mp4")
	if err != nil {
		return err
	}
	defer f.Close()
	if _, err = io.Copy(f, out.Body); err != nil {
		return err
	}

	// Read only the first 1 KiB
	part, err := client.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String("videos/video.mp4"),
		Range:  aws.String("bytes=0-1023"),
	})
	if err != nil {
		return err
	}
	defer part.Body.Close()
	fmt.Println(aws.ToString(part.ContentRange))
	return nil
}

List files

Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. Delimiter supports only /.

main.go
func list(ctx context.Context, client *s3.Client) error {
	// List all objects under a prefix, paging automatically
	p := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{
		Bucket: aws.String(bucket),
		Prefix: aws.String("images/"),
	})
	for p.HasMorePages() {
		page, err := p.NextPage(ctx)
		if err != nil {
			return err
		}
		for _, obj := range page.Contents {
			fmt.Println(*obj.Key, *obj.Size, obj.LastModified)
		}
	}

	// List only the top-level directories
	root, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
		Bucket:    aws.String(bucket),
		Delimiter: aws.String("/"),
	})
	if err != nil {
		return err
	}
	for _, d := range root.CommonPrefixes {
		fmt.Println("Directory", *d.Prefix)
	}
	return nil
}

Get file information

Retrieve metadata without downloading the content. You can also use this to check whether an object exists.

main.go
func exists(ctx context.Context, client *s3.Client, key string) (bool, error) {
	_, err := client.HeadObject(ctx, &s3.HeadObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
	})
	var notFound *types.NotFound
	if errors.As(err, &notFound) {
		return false, nil
	}
	return err == nil, err
}

Copy and move

Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append ?move=true to CopySource. It only changes the location without copying data, regardless of file size. See Move and rename objects.

main.go
// The object key in CopySource must be URL-encoded
func copySource(key string) string {
	parts := strings.Split(key, "/")
	for i, p := range parts {
		parts[i] = strings.ReplaceAll(url.PathEscape(p), "+", "%2B")
	}
	return bucket + "/" + strings.Join(parts, "/")
}

func copyObject(ctx context.Context, client *s3.Client, src, dst string) error {
	_, err := client.CopyObject(ctx, &s3.CopyObjectInput{
		Bucket:     aws.String(bucket),
		Key:        aws.String(dst),
		CopySource: aws.String(copySource(src)),
	})
	return err
}

// Move / rename: S4 extension, no data copied
func moveObject(ctx context.Context, client *s3.Client, src, dst string) error {
	_, err := client.CopyObject(ctx, &s3.CopyObjectInput{
		Bucket:     aws.String(bucket),
		Key:        aws.String(dst),
		CopySource: aws.String(copySource(src) + "?move=true"),
	})
	return err
}

Delete files

Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.

main.go
func remove(ctx context.Context, client *s3.Client) error {
	// Delete one object
	_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String("docs/hello.txt"),
	})
	if err != nil {
		return err
	}

	// Batch delete, up to 1000 objects at a time
	var ids []types.ObjectIdentifier
	for _, k := range []string{"images/a.jpg", "images/b.jpg"} {
		ids = append(ids, types.ObjectIdentifier{Key: aws.String(k)})
	}
	out, err := client.DeleteObjects(ctx, &s3.DeleteObjectsInput{
		Bucket: aws.String(bucket),
		Delete: &types.Delete{Objects: ids, Quiet: aws.Bool(true)},
	})
	if err != nil {
		return err
	}
	for _, e := range out.Errors {
		fmt.Println(aws.ToString(e.Key), aws.ToString(e.Code), aws.ToString(e.Message))
	}
	return nil
}

Presigned URLs

A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign Content-Type for an upload, the client must send exactly the same value.

main.go
func presign(ctx context.Context, client *s3.Client) (getURL, putURL string, err error) {
	pc := s3.NewPresignClient(client)

	// Download URL, valid for 1 hour, with a specified file name
	get, err := pc.PresignGetObject(ctx, &s3.GetObjectInput{
		Bucket:                     aws.String(bucket),
		Key:                        aws.String("images/photo.jpg"),
		ResponseContentDisposition: aws.String(`attachment; filename="photo.jpg"`),
	}, s3.WithPresignExpires(time.Hour))
	if err != nil {
		return "", "", err
	}

	// Upload URL, valid for 10 minutes; the client sends a PUT to it
	put, err := pc.PresignPutObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String("uploads/avatar.jpg"),
	}, s3.WithPresignExpires(10*time.Minute))
	if err != nil {
		return "", "", err
	}
	return get.URL, put.URL, nil
}

Presigned URLs with extension parameters

Extension parameters such as CoreIX processing parameters, rate limits, and request limits must be added before signing. Appending them after signing returns SignatureDoesNotMatch.

main.go
// WithQuery adds S4 extension parameters to the presigned URL and includes them in the signature
func WithQuery(params map[string]string) func(*s3.PresignOptions) {
	add := middleware.BuildMiddlewareFunc("AddS4Query", func(
		ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler,
	) (middleware.BuildOutput, middleware.Metadata, error) {
		if req, ok := in.Request.(*smithyhttp.Request); ok {
			q := req.URL.Query()
			for k, v := range params {
				q.Set(k, v)
			}
			req.URL.RawQuery = q.Encode()
		}
		return next.HandleBuild(ctx, in)
	})
	return func(po *s3.PresignOptions) {
		po.ClientOptions = append(po.ClientOptions, func(o *s3.Options) {
			o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error {
				return stack.Build.Add(add, middleware.After)
			})
		})
	}
}

func presignWithQuery(ctx context.Context, client *s3.Client) (string, error) {
	req, err := s3.NewPresignClient(client).PresignGetObject(ctx,
		&s3.GetObjectInput{
			Bucket: aws.String(bucket),
			Key:    aws.String("images/photo.jpg"),
		},
		s3.WithPresignExpires(time.Hour),
		WithQuery(map[string]string{
			"w":                      "500",     // CoreIX: width 500 px
			"fmt":                    "webp",    // CoreIX: convert to WebP
			"x-bitiful-limit-rate":   "1048576", // Per-connection rate limit of 1 MiB/s
			"x-bitiful-max-requests": "3",       // At most 3 accesses
		}),
	)
	if err != nil {
		return "", err
	}
	return req.URL, nil
}

Conditional writes

Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See Conditional requests.

main.go
func createOnly(ctx context.Context, client *s3.Client) error {
	// Write only if the object does not exist, to prevent overwriting
	_, err := client.PutObject(ctx, &s3.PutObjectInput{
		Bucket:      aws.String(bucket),
		Key:         aws.String("locks/job"),
		Body:        strings.NewReader("me"),
		IfNoneMatch: aws.String("*"),
	})
	var apiErr smithy.APIError
	if errors.As(err, &apiErr) && apiErr.ErrorCode() == "PreconditionFailed" {
		return errors.New("Object already exists")
	}
	return err
}

Handle errors

For the meaning of each error code, see Error codes and troubleshooting. Rate limiting returns 429 TooManyRequest; catch it and retry with backoff.

main.go
func handleError(ctx context.Context, client *s3.Client) {
	_, err := client.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String("not-exists.txt"),
	})
	var noSuchKey *types.NoSuchKey
	var apiErr smithy.APIError
	switch {
	case errors.As(err, &noSuchKey):
		fmt.Println("Object does not exist")
	case errors.As(err, &apiErr):
		fmt.Println(apiErr.ErrorCode(), apiErr.ErrorMessage())
	case err != nil:
		fmt.Println("Network error: ", err)
	}
}

FAQ

What is the difference between transfermanager and manager

feature/s3/manager is the older multipart upload package, and feature/s3/transfermanager replaces it. Existing code that uses manager can keep using it.

Returns 403 AccessDenied

The sub-user has no permission on this bucket or directory. See Sub-user permissions. Creating and deleting buckets can only be done in the console.

Returns SignatureDoesNotMatch

The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the checklist.

Download speed is low

Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a CDN to serve visitors.