实例:阿里云oss sdk实践

一、 go环境安装

根据阿里云oss sdk go版的安装文档,如下
https://help.aliyun.com/document_detail/87712.html?spm=a2c4g.11186623.6.918.234b4c07Vjvm94

#!/bin/bash

# 安装go
myhome=`pwd`
export GOROOT=${myhome}/go
export PATH=$PATH:${GOROOT}/bin

wget -q http://xxxxxxx/video_tmp_test/go1.13.7.linux-amd64.tar.gz
tar -xzf go1.13.7.linux-amd64.tar.gz

go version

# 解决go被墙的问题
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct

# 安装阿里云oss模块
go get -v github.com/aliyun/aliyun-oss-go-sdk/oss

# clone
git clone [email protected]:aligame-qa/smallTools.git
mv smallTools/oss/kuaijianUploadOss.go ./

# 编译
go build kuaijianUploadOss.go

# 上传
#./kuaijianUploadOss

#测试用
#./kuaijianUploadOss -b debug -c armeabi-v7a -v 1.5.7 -f /Users/lijingle/Downloads/armeabi-v7a-libvideorecsdkloader.so

二、具体实现

package main

import (
    "flag"
    "fmt"
    "os"

    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func HandleMsg(msg string) {
    fmt.Println(msg)
    os.Exit(-1)
}

func listDir(bucket *oss.Bucket, prefix string) {
    lsRes, err := bucket.ListObjects(oss.Prefix(prefix))
    if err != nil {
        HandleError(err)
    }

    for _, object := range lsRes.Objects {
        fmt.Println("  ", object.Key)
    }
}

func IsFileExists(bucket *oss.Bucket, fname string) (rslt bool) {
    // 判断文件是否存在
    isExist, err := bucket.IsObjectExist(fname)
    if err != nil {
        HandleError(err)
    }
    return isExist
}

var localFile = flag.String("f", "", "本地文件")

func main() {
    fmt.Println("OSS Go SDK Version: ", oss.Version)
    flag.Parse()

    // 参数检查
    if *localFile == "" {
        HandleMsg("参数检查错误: 文件名不能为空")
    }

    // 创建OSSClient实例。
    client, err := oss.New("oss-cn-shanghai.aliyuncs.com", "", "")
    if err != nil {
        HandleError(err)
    }

    bucketName := ""
    remotePath := fmt.Sprintf("video_tmp_test/%s/", "dir1")
    remoteFile := remotePath + "after_upload_file.txt"

    // 获取存储空间。
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    isExist := IsFileExists(bucket, remoteFile)
    fmt.Println("===================判断文件是否存在===================")
    fmt.Printf("IsFileExists=%v\n", isExist)

    fmt.Println("===================上传前文件夹情况:===================")
    listDir(bucket, remotePath)

    fmt.Println("===================开始上传so文件===================")

    // 上传本地文件。
    err = bucket.PutObjectFromFile(remoteFile, *localFile)
    if err != nil {
        HandleError(err)
    }

    fmt.Println("===================上传后文件夹情况:===================")
    listDir(bucket, remotePath)
}

你可能感兴趣的:(实例:阿里云oss sdk实践)