test/s3-client.go

92 lines
1.8 KiB
Go

package main
import (
"fmt"
"io/fs"
"log"
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/jszwec/s3fs"
toml "github.com/pelletier/go-toml"
)
//AwsDefaultSection toml default section
type AwsDefaultSection struct {
// attribute should be public ! for go-toml
EndpointURL string `toml:"endpoint_url"`
}
//CustomAwsConfig custom toml config for aws
type CustomAwsConfig struct {
Default AwsDefaultSection `toml:"default"`
}
const bucket = "Computer"
func main() {
customConfig := CustomAwsConfig{}
err := DecodeFile(defaults.SharedConfigFilename(), &customConfig)
handleError(err)
s, err := session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: aws.Config{
Endpoint: &customConfig.Default.EndpointURL,
DisableSSL: aws.Bool(true),
},
})
handleError(err)
s3fs := s3fs.New(s3.New(s), bucket)
stat, err := s3fs.Stat("Documents")
handleError(err)
fmt.Printf("stat : %+v\n", stat)
fmt.Printf("isDir : %+v\n", stat.IsDir())
depth := 2
// print out all files in s3 bucket.
err = fs.WalkDir(s3fs, ".", func(path string, d fs.DirEntry, err error) error {
handleError(err)
arr := strings.Split(path, "/")
if len(arr) > depth {
// return errors.New("Error")
return fs.SkipDir
}
if d.IsDir() {
fmt.Printf("dir: %s/\n", path)
} else {
fmt.Println("file:", path)
}
return nil
})
handleError(err)
}
//DecodeFile call toml.Decode with file
func DecodeFile(fpath string, v interface{}) error {
bs, err := os.Open(fpath)
if err != nil {
return err
}
d := toml.NewDecoder(bs)
err = d.Decode(v)
return err
}
func handleError(err error) {
if err != nil {
log.Fatalf("error -> %+v\n", err)
}
}