Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar links simbólicos com o OSS SDK for Go 2.0

Última atualização: Oct 10, 2026

Um link simbólico oferece acesso rápido a um objeto em um bucket e facilita o acesso a objetos usados com frequência. No Object Storage Service (OSS), os links simbólicos funcionam como atalhos de arquivo no Windows, permitindo acessar rapidamente os objetos associados. Este tópico descreve como configurar e consultar links simbólicos usando o OSS SDK for Go.

Observações

  • O código de exemplo deste tópico usa o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o endpoint público acessa recursos em um bucket. Para acessar esses recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre as regiões e endpoints compatíveis com o Object Storage Service (OSS), consulte OSS regions and endpoints.

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

  • Criar links simbólicos exige a permissão oss:PutObject, enquanto consultá-los requer a permissão oss:GetObject. Para mais detalhes, consulte Grant custom policy to RAM users.

Métodos

Configurar links simbólicos

func (c *Client) PutSymlink(ctx context.Context, request *PutSymlinkRequest, optFns ...func(*Options)) (*PutSymlinkResult, error)

Consultar links simbólicos

func (c *Client) GetSymlink(ctx context.Context, request *GetSymlinkRequest, optFns ...func(*Options)) (*GetSymlinkResult, error)

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

ctx

context.Context

Contexto da solicitação. Use-o para especificar a duração total da requisição.

request

*PutSymlinkRequest

Parâmetros para configurar links simbólicos. Para mais detalhes, consulte PutSymlinkRequest.

*GetSymlinkRequest

Parâmetros para consultar links simbólicos. Para mais detalhes, consulte GetSymlinkRequest.

optFns

...func(*Options)

Opcional. Parâmetro no nível da operação. Para mais informações, consulte Options.

Valores de retorno

Valor

Tipo

Descrição

result

*PutSymlinkResult

Valores retornados ao configurar links simbólicos. Este parâmetro é válido quando err é nil. Para mais informações, consulte RestoreObjectResult.

*GetSymlinkResult

Valores retornados ao consultar links simbólicos. Este parâmetro é válido quando err é nil. Para mais informações, consulte GetSymlinkResult.

err

error

Status da solicitação. Se a solicitação falhar, err não será nil.

Código de exemplo

Configurar um link simbólico

O código abaixo exemplifica como configurar um link simbólico.

package main

import (
	"context"
	"flag"
	"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()

	// Specify the name of the symlink.
	var (
		symlinkName = "testsymlink" // The name of the symlink.
	)

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

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

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

	// Check whether the name of the symlink is specified.
	if len(symlinkName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, symlink name required")
	}

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

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

	// Create a request to configure the symlink.
	putRequest := &oss.PutSymlinkRequest{
		Bucket: oss.Ptr(bucketName),  // The name of the bucket
		Key:    oss.Ptr(symlinkName), // Specify the name of the symlink.
		Target: oss.Ptr(objectName),  // Specify the name of the object to which the symbolic link points.
	}

	// Execute the request to configure the symlink.
	putResult, err := client.PutSymlink(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put symlink %v", err)
	}

	// Display the result.
	log.Printf("put symlink result:%#v\n", putResult)
}

Consultar um link simbólico

O exemplo a seguir demonstra como consultar um link simbólico e obter o nome do objeto ao qual ele aponta.

package main

import (
	"context"
	"flag"
	"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.
	symlinkName string // The name of the symlink.
)

// 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(&symlinkName, "symlink", "", "The name of the symlink.")
}

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

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

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

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

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

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

	// Create a request to query the symlink.
	getRequest := &oss.GetSymlinkRequest{
		Bucket: oss.Ptr(bucketName),  // The name of the bucket.
		Key:    oss.Ptr(symlinkName), // The name of the symlink.
	}

	// Execute the query operation and process the result.
	getResult, err := client.GetSymlink(context.TODO(), getRequest)
	if err != nil {
		log.Fatalf("failed to get symlink %v", err)
	}

	// Display the result.
	log.Printf("get symlink target object name:%#v\n", *getResult.Target)
}

Referências

  • Para acessar o código de exemplo completo sobre gerenciamento de links simbólicos, visite put_symlink.go e get_symlink.go.

  • Para mais informações sobre operações relacionadas, consulte Symbolic Links.

  • Para detalhes sobre a operação da API usada na configuração de links simbólicos, acesse PutSymlink.

  • Para detalhes sobre a operação da API usada na consulta de links simbólicos, acesse GetSymlink.