Todos os produtos
Search
Central de documentação

Object Storage Service:Acesso a arquivos somente leitura com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

Este tópico descreve como usar a operação File-Like do Object Storage Service (OSS) SDK for Go 2.0 para acessar objetos em um bucket.

Observações

  • Os códigos de exemplo deste tópico usam o ID da região China (Hangzhou), cn-hangzhou, como referência. O endpoint público é o padrão. Para acessar o OSS a partir de outros produtos da Alibaba Cloud na mesma região, use o endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar as credenciais de acesso, consulte Configurar credenciais de acesso.

  • Para baixar um arquivo, você deve ter a permissão oss:GetObject. Para obter mais informações, consulte Conceder permissões personalizadas a um usuário RAM.

Método

A operação File-Like do OSS SDK for Go 2.0 permite acessar objetos em um bucket pelo método ReadOnlyFile.

  • O método ReadOnlyFile oferece os modos de fluxo único e prefetch. Ajuste o número de tarefas paralelas para aumentar a velocidade de leitura.

  • Esse método inclui um mecanismo de reconexão que garante robustez em ambientes de rede complexos.

type ReadOnlyFile struct {
...
}

func (c *Client) OpenFile(ctx context.Context, bucket string, key string, optFns ...func(*OpenOptions)) (file *ReadOnlyFile, err error)

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

ctx

context.Context

Contexto da solicitação.

bucket

string

Nome do bucket.

key

string

Nome do objeto.

optFns

...func(*OpenOptions)

Opcional. Opções configuráveis ao abrir o objeto.

Opções de OpenOptions

Opção

Tipo

Descrição

Offset

int64

Deslocamento inicial ao abrir o objeto. Valor padrão: 0.

VersionId

*string

Número da versão do objeto especificado. Este parâmetro é válido apenas se existirem várias versões do objeto.

RequestPayer

*string

Especifica que, se o pagamento por solicitante estiver ativado, RequestPayer deve ser definido como requester.

EnablePrefetch

bool

Especifica se o modo prefetch deve ser ativado. Por padrão, o modo prefetch está desativado.

PrefetchNum

int

Número de chunks pré-carregados. Valor padrão: 3. Este parâmetro é válido quando o modo prefetch está ativado.

ChunkSize

int64

Tamanho de cada chunk pré-carregado. Valor padrão: 6 MiB. Este parâmetro é válido quando o modo prefetch está ativado.

PrefetchThreshold

int64

Número de bytes lidos sequencialmente antes da ativação do modo prefetch. Valor padrão: 20 MiB. Este parâmetro é válido quando o modo prefetch está ativado.

Parâmetros de resposta

Parâmetro

Tipo

Descrição

file

*ReadOnlyFile

Instância de ReadOnlyFile. Este parâmetro é válido quando o valor de err é nil. Para obter mais informações, consulte ReadOnlyFile.

err

error

Status do ReadOnlyFile. Se ocorrer um erro, o valor de err não será nil.

Métodos comuns do ReadOnlyFile

Método

Descrição

Close() error

Fecha os manipuladores de arquivo para liberar recursos, como memória e sockets ativos.

Read(p []byte) (int, error)

Lê bytes com comprimento len(p) da fonte de dados, armazena-os em p e retorna o número de bytes lidos e os erros encontrados.

Seek(offset int64, whence int) (int64, error)

Define o deslocamento para a próxima leitura ou gravação. Valores válidos para whence: 0: início. 1: deslocamento atual. 2: fim.

Stat() (os.FileInfo, error)

Consulta as informações do objeto, incluindo tamanho, hora da última modificação e metadados.

Importante

Nota: Se o modo prefetch estiver ativado e ocorrerem várias leituras fora de ordem, o modo de fluxo único será usado automaticamente.

Exemplos

Ler todo o objeto usando o modo de fluxo único

package main

import (
	"context"
	"flag"
	"io"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Open the object.
	f, err := client.OpenFile(context.TODO(), bucketName, objectName)

	if err != nil {
		log.Fatalf("failed to open file %v", err)
	}
	defer f.Close()

	// Read the content of the object using io.Copy.
	written, err := io.Copy(io.Discard, f)
	if err != nil {
		log.Fatalf("failed to read file %v", err)
	}

	log.Printf("read %d bytes from file", written)
}

Ler todo o objeto usando o modo prefetch

package main

import (
	"context"
	"flag"
	"io"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Open the object.
	f, err := client.OpenFile(context.TODO(),
		bucketName,
		objectName,
		func(oo *oss.OpenOptions) {
			oo.EnablePrefetch = true // Enable the prefetch mode.
		})

	if err != nil {
		log.Fatalf("failed to open file %v", err)
	}

	defer f.Close()

	// Read the object.
	written, err := io.Copy(io.Discard, f)

	if err != nil {
		log.Fatalf("failed to read file %v", err)
	}

	log.Printf("read %d bytes from file", written)
}

Ler dados restantes de uma posição específica com o método **Seek**

package main

import (
	"context"
	"flag"
	"io"
	"log"
	"net/http"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Open the object.
	f, err := client.OpenFile(context.TODO(), bucketName, objectName)

	if err != nil {
		log.Fatalf("failed to open file %v", err)
	}

	defer f.Close()

	// Query the object information.
	info, _ := f.Stat()

	// Display the basic attributes of the object.
	log.Printf("size:%v, mtime:%v\n", info.Size(), info.ModTime())

	// Query object metadata.
	if header, ok := info.Sys().(http.Header); ok {
		log.Printf("content-type:%v\n", header.Get(oss.HTTPHeaderContentType))
	}

	// Specify the offset when you read the object, such as starting from 123.
	_, err = f.Seek(123, io.SeekStart)
	if err != nil {
		log.Fatalf("failed to seek file %v", err)
	}

	// Read the content of the object using io.Copy.
	written, err := io.Copy(io.Discard, f)

	if err != nil {
		log.Fatalf("failed to read file %v", err)
	}

	log.Printf("read %d bytes from file", written)
}

Referências

  • Para obter mais informações sobre arquivos de classe somente leitura, consulte o Guia do Desenvolvedor.

  • Para obter o código de exemplo completo da operação File-Like, visite o GitHub.

  • Para obter mais informações sobre a operação de API da operação File-Like, visite OpenFile.