feat(iap/apple): 实现苹果IAP非续期订阅功能
Build docker and publish / build (20.15.1) (push) Successful in 6m37s

新增苹果IAP相关接口与逻辑,包括产品列表查询、交易绑定、状态查询和恢复购买功能。移除旧的IAP验证逻辑,重构订阅系统以支持苹果IAP交易记录存储和权益计算。

- 新增/pkg/iap/apple包处理JWS解析和产品映射
- 实现GET /products、POST /attach、POST /restore和GET /status接口
- 新增apple_iap_transactions表存储交易记录
- 更新文档说明配置方式和接口规范
- 移除旧的AppleIAP验证和通知处理逻辑
This commit is contained in:
2025-12-13 20:54:50 -08:00
parent a80d6af035
commit 62186ca672
41 changed files with 1715 additions and 474 deletions
+2
View File
@@ -0,0 +1,2 @@
UH7EpvMzwYDBfQ0nxAS5
ibFUcqkPhyeGvQCBjE07VaYzWH3IpJw9frDudxL6
+67
View File
@@ -0,0 +1,67 @@
#!/bin/bash
# Configuration
LOG_FILE="/root/backup.log"
MYSQL_BACKUP_SCRIPT="/root/backup_mysql.sh"
UPLOADER_BINARY="/root/uploader-linux-amd64"
# MinIO Credentials (can be modified here or passed via env)
MINIO_ENDPOINT="http://107.173.50.22:5017"
MINIO_ACCESS_KEY="WyJYxDobmp9glIXVAteC"
MINIO_SECRET_KEY="TNO0ZJ4AH5QupFwDtiLxavUeMVmz2fo1YXRGsI7c"
MINIO_BUCKET="backup"
# Directories to backup (comma separated)
# Example: "/root/vpn_server,/etc/nginx/conf.d"
DIRS_TO_BACKUP="/root/db_backups,/etc/nginx/conf.d"
echo "========================================================" >> "$LOG_FILE"
echo "[$(date)] Starting Daily Backup Task..." >> "$LOG_FILE"
# 1. Execute MySQL Backup
if [ -f "$MYSQL_BACKUP_SCRIPT" ]; then
echo "[$(date)] Running MySQL backup script..." >> "$LOG_FILE"
# Pass credentials to the MySQL script via environment variables if needed,
# but currently backup_mysql.sh calls uploader internally.
# We should update backup_mysql.sh to use these credentials too, or rely on them being embedded/env.
# For now, let's export them so child processes can see them if they use os.Getenv
export MINIO_ENDPOINT
export MINIO_ACCESS_KEY
export MINIO_SECRET_KEY
export MINIO_BUCKET
bash "$MYSQL_BACKUP_SCRIPT" >> "$LOG_FILE" 2>&1
if [ $? -eq 0 ]; then
echo "[$(date)] MySQL backup script finished." >> "$LOG_FILE"
else
echo "[$(date)] Error: MySQL backup script failed!" >> "$LOG_FILE"
fi
else
echo "[$(date)] Error: MySQL backup script not found at $MYSQL_BACKUP_SCRIPT" >> "$LOG_FILE"
fi
# 2. Execute File/Directory Backup using Go Uploader
if [ -f "$UPLOADER_BINARY" ]; then
echo "[$(date)] Running Directory backup..." >> "$LOG_FILE"
chmod +x "$UPLOADER_BINARY"
# Run uploader with explicit flags
"$UPLOADER_BINARY" \
-dir "$DIRS_TO_BACKUP" \
-bucket "$MINIO_BUCKET" \
-endpoint "$MINIO_ENDPOINT" \
-access-key "$MINIO_ACCESS_KEY" \
-secret-key "$MINIO_SECRET_KEY" \
>> "$LOG_FILE" 2>&1
if [ $? -eq 0 ]; then
echo "[$(date)] Directory backup finished." >> "$LOG_FILE"
else
echo "[$(date)] Error: Directory backup failed!" >> "$LOG_FILE"
fi
else
echo "[$(date)] Error: Uploader binary not found at $UPLOADER_BINARY" >> "$LOG_FILE"
fi
echo "[$(date)] Daily Backup Task Completed." >> "$LOG_FILE"
echo "========================================================" >> "$LOG_FILE"
+76
View File
@@ -0,0 +1,76 @@
#!/bin/bash
# Configuration
CONTAINER_NAME="ppanel-db"
DB_USER="vmanroot"
DB_PASSWORD="vmanrootpassword" # Replace with actual password
DB_NAME="ppanel" # Explicitly specify the database name
BACKUP_DIR="/root/db_backups"
UPLOADER_PATH="/root/uploader-linux-amd64" # Path to your go uploader binary
RETENTION_DAYS=7
# Create backup directory if not exists
mkdir -p "$BACKUP_DIR"
# Generate timestamp
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
FILENAME="mysql_backup_${TIMESTAMP}.sql"
FILEPATH="${BACKUP_DIR}/${FILENAME}"
GZ_FILEPATH="${FILEPATH}.gz"
# 1. Dump MySQL database from Docker container
echo "[$(date)] Starting MySQL backup from container ${CONTAINER_NAME}..."
# Check if container is running
if [ ! "$(docker ps -q -f name=${CONTAINER_NAME})" ]; then
echo "Error: Container ${CONTAINER_NAME} is not running!"
exit 1
fi
# Execute dump
docker exec "$CONTAINER_NAME" /usr/bin/mysqldump -u "$DB_USER" -p"$DB_PASSWORD" --databases "$DB_NAME" --no-tablespaces > "$FILEPATH"
# Check if file size is too small (e.g., < 1KB), which usually indicates an empty dump or error
FILE_SIZE=$(stat -c%s "$FILEPATH" 2>/dev/null || stat -f%z "$FILEPATH")
if [ "$FILE_SIZE" -lt 1024 ]; then
echo "Error: Backup file is too small ($FILE_SIZE bytes). Dump might have failed."
cat "$FILEPATH" # Print content to log for debugging
exit 1
fi
if [ $? -eq 0 ]; then
echo "[$(date)] Database dump successful: ${FILEPATH}"
# 2. Compress the backup
gzip "$FILEPATH"
echo "[$(date)] Compression successful: ${GZ_FILEPATH}"
# 3. Upload to MinIO using the Go uploader
if [ -f "$UPLOADER_PATH" ]; then
echo "[$(date)] Uploading to object storage..."
chmod +x "$UPLOADER_PATH"
"$UPLOADER_PATH" -file "$GZ_FILEPATH" -bucket backup
if [ $? -eq 0 ]; then
echo "[$(date)] Upload successful."
else
echo "[$(date)] Upload failed."
fi
else
echo "Warning: Uploader binary not found at $UPLOADER_PATH. Skipping upload."
fi
# 4. Clean up old local backups (optional)
find "$BACKUP_DIR" -name "mysql_backup_*.sql.gz" -mtime +$RETENTION_DAYS -delete
echo "[$(date)] Cleaned up local backups older than $RETENTION_DAYS days."
else
echo "Error: Database dump failed!"
# Clean up empty file if dump failed
if [ -f "$FILEPATH" ]; then
rm "$FILEPATH"
fi
exit 1
fi
echo "[$(date)] Backup process completed."
+14
View File
@@ -0,0 +1,14 @@
MINIO_ENDPOINT="http://107.173.50.22:5017"
MINIO_ACCESS_KEY="WyJYxDobmp9glIXVAteC"
MINIO_SECRET_KEY="TNO0ZJ4AH5QupFwDtiLxavUeMVmz2fo1YXRGsI7c"
MINIO_BUCKET="backup"
./uploader-linux-amd64 \
-dir /root/vpn_server,/etc/nginx/conf.d \
-endpoint http://107.173.50.22:5017 \
-access-key WyJYxDobmp9glIXVAteC \
-secret-key TNO0ZJ4AH5QupFwDtiLxavUeMVmz2fo1YXRGsI7c \
-bucket backup
+29
View File
@@ -0,0 +1,29 @@
module uploader
go 1.24.4
require (
github.com/joho/godotenv v1.5.1
github.com/minio/minio-go/v7 v7.0.97
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/minio/crc64nvme v1.1.0 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/tinylib/msgp v1.3.0 // indirect
golang.org/x/crypto v0.36.0 // indirect
golang.org/x/net v0.38.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/text v0.26.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+45
View File
@@ -0,0 +1,45 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
github.com/minio/crc64nvme v1.1.0 h1:e/tAguZ+4cw32D+IO/8GSf5UVr9y+3eJcxZI2WOO/7Q=
github.com/minio/crc64nvme v1.1.0/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.97 h1:lqhREPyfgHTB/ciX8k2r8k0D93WaFqxbJX36UZq5occ=
github.com/minio/minio-go/v7 v7.0.97/go.mod h1:re5VXuo0pwEtoNLsNuSr0RrLfT/MBtohwdaSmPPSRSk=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+371
View File
@@ -0,0 +1,371 @@
package main
import (
"archive/zip"
"context"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/joho/godotenv"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// Global variables to be set via ldflags
var (
BuildEndpoint string
BuildAccessKey string
BuildSecretKey string
BuildBucket string
)
func main() {
// Load environment variables from .env file
err := godotenv.Load()
if err != nil {
// Just log, don't fail, as we might rely on flags or build defaults
}
// Parse command line arguments
var filePath string
var dirPaths string
var bucketName string
var interval string
var objectName string
var listBuckets bool
var createBucketFlag bool
// Credential flags
var endpointFlag string
var accessKeyFlag string
var secretKeyFlag string
flag.StringVar(&filePath, "file", "", "Path to the file to upload")
flag.StringVar(&dirPaths, "dir", "", "Comma-separated paths to directories to compress and upload")
flag.StringVar(&bucketName, "bucket", "", "Bucket name")
flag.StringVar(&interval, "interval", "", "Backup interval (e.g., 24h, 60m). If not set, runs once.")
flag.StringVar(&objectName, "name", "", "Object name (optional)")
flag.BoolVar(&listBuckets, "list", false, "List all available buckets")
flag.BoolVar(&createBucketFlag, "create", false, "Create the specified bucket if it doesn't exist")
flag.StringVar(&endpointFlag, "endpoint", "", "MinIO endpoint URL")
flag.StringVar(&accessKeyFlag, "access-key", "", "MinIO access key")
flag.StringVar(&secretKeyFlag, "secret-key", "", "MinIO secret key")
flag.Parse()
// Resolve Configuration: Flag > Env > Build Default
finalEndpoint := resolveConfig(endpointFlag, "MINIO_ENDPOINT", BuildEndpoint)
finalAccessKey := resolveConfig(accessKeyFlag, "MINIO_ACCESS_KEY", BuildAccessKey)
finalSecretKey := resolveConfig(secretKeyFlag, "MINIO_SECRET_KEY", BuildSecretKey)
if bucketName == "" {
bucketName = resolveConfig("", "MINIO_BUCKET", BuildBucket)
}
// Initialize MinIO client
minioClient := initMinioClient(finalEndpoint, finalAccessKey, finalSecretKey)
if listBuckets {
listAllBuckets(minioClient)
return
}
if createBucketFlag {
if bucketName == "" {
fmt.Println("Please specify a bucket name using -bucket")
os.Exit(1)
}
createBucket(minioClient, bucketName)
return
}
// Handle positional arguments for backward compatibility
args := flag.Args()
if len(args) > 0 && filePath == "" && dirPaths == "" {
// Check if argument is a directory
info, err := os.Stat(args[0])
if err == nil && info.IsDir() {
dirPaths = args[0]
} else {
filePath = args[0]
}
}
if len(args) > 1 && bucketName == "" {
bucketName = args[1]
}
if bucketName == "" {
// Try to resolve bucket again if not set via flag
bucketName = resolveConfig("", "MINIO_BUCKET", BuildBucket)
}
if (filePath == "" && dirPaths == "") || bucketName == "" {
fmt.Println("Usage: uploader -file <path> -bucket <bucket>")
fmt.Println(" uploader -dir <path1,path2> -bucket <bucket> [-interval 24h]")
fmt.Println(" uploader -list")
fmt.Println("\nCredentials can be provided via .env file, environment variables, or flags:")
fmt.Println(" -endpoint <url> -access-key <key> -secret-key <secret>")
os.Exit(1)
}
// One-time execution
if interval == "" {
if err := performBackup(minioClient, filePath, dirPaths, bucketName, objectName); err != nil {
log.Fatalln(err)
}
return
}
// Scheduled execution
duration, err := time.ParseDuration(interval)
if err != nil {
log.Fatalf("Invalid interval format: %v\n", err)
}
fmt.Printf("Starting backup service every %s...\n", interval)
ticker := time.NewTicker(duration)
defer ticker.Stop()
// Run immediately first
if err := performBackup(minioClient, filePath, dirPaths, bucketName, objectName); err != nil {
log.Printf("Backup failed: %v\n", err)
}
for range ticker.C {
if err := performBackup(minioClient, filePath, dirPaths, bucketName, objectName); err != nil {
log.Printf("Backup failed: %v\n", err)
}
}
}
func resolveConfig(flagVal, envKey, buildVal string) string {
if flagVal != "" {
return flagVal
}
if envVal := os.Getenv(envKey); envVal != "" {
return envVal
}
return buildVal
}
func initMinioClient(endpoint, accessKey, secretKey string) *minio.Client {
useSSL := true
if strings.HasPrefix(endpoint, "http://") {
endpoint = strings.TrimPrefix(endpoint, "http://")
useSSL = false
} else if strings.HasPrefix(endpoint, "https://") {
endpoint = strings.TrimPrefix(endpoint, "https://")
useSSL = true
}
if endpoint == "" || accessKey == "" || secretKey == "" {
log.Fatal("Error: Credentials must be provided via flags, environment variables, .env file, or build-time defaults.")
}
minioClient, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
Secure: useSSL,
})
if err != nil {
log.Fatalln(err)
}
return minioClient
}
func listAllBuckets(client *minio.Client) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
buckets, err := client.ListBuckets(ctx)
if err != nil {
log.Fatalf("Failed to list buckets: %v\n", err)
}
if len(buckets) == 0 {
fmt.Println("No buckets found.")
return
}
fmt.Println("Available buckets:")
for _, bucket := range buckets {
fmt.Printf("- %s (Created: %s)\n", bucket.Name, bucket.CreationDate)
}
}
func createBucket(client *minio.Client, bucketName string) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err := client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})
if err != nil {
// Check to see if we already own this bucket
exists, errBucketExists := client.BucketExists(ctx, bucketName)
if errBucketExists == nil && exists {
log.Printf("We already own %s\n", bucketName)
} else {
log.Fatalf("Failed to create bucket %s: %v\n", bucketName, err)
}
} else {
log.Printf("Successfully created bucket %s\n", bucketName)
}
}
func performBackup(client *minio.Client, filePath, dirPaths, bucketName, objectName string) error {
// Handle single file upload
if filePath != "" {
if objectName == "" {
objectName = filepath.Base(filePath)
}
fmt.Printf("Uploading %s to %s/%s...\n", filePath, bucketName, objectName)
info, err := client.FPutObject(context.Background(), bucketName, objectName, filePath, minio.PutObjectOptions{})
if err != nil {
return fmt.Errorf("failed to upload file %s: %v", filePath, err)
}
fmt.Printf("Successfully uploaded %s. Size: %d bytes\n", filePath, info.Size)
}
// Handle directory uploads
if dirPaths != "" {
dirs := strings.Split(dirPaths, ",")
for _, dirPath := range dirs {
dirPath = strings.TrimSpace(dirPath)
if dirPath == "" {
continue
}
// Verify directory exists
info, err := os.Stat(dirPath)
if err != nil || !info.IsDir() {
log.Printf("Warning: Skipping invalid directory: %s\n", dirPath)
continue
}
timestamp := time.Now().Format("20060102_150405")
dirName := filepath.Base(dirPath)
if dirName == "." || dirName == "/" {
// Use parent directory name or absolute path hash/sanitized name could be better,
// but for simplicity, let's try to get absolute path base
absPath, _ := filepath.Abs(dirPath)
dirName = filepath.Base(absPath)
}
zipName := fmt.Sprintf("%s_%s.zip", dirName, timestamp)
// Create zip in temp directory
tempFile := filepath.Join(os.TempDir(), zipName)
fmt.Printf("Zipping directory %s to %s...\n", dirPath, tempFile)
if err := zipSource(dirPath, tempFile); err != nil {
log.Printf("Error zipping directory %s: %v\n", dirPath, err)
continue
}
// If object name was specified (and only 1 directory), use it.
// Otherwise (multiple directories), use the zip name to avoid overwriting.
uploadName := zipName
if objectName != "" && len(dirs) == 1 {
uploadName = objectName
}
fmt.Printf("Uploading %s to %s/%s...\n", tempFile, bucketName, uploadName)
uploadInfo, err := client.FPutObject(context.Background(), bucketName, uploadName, tempFile, minio.PutObjectOptions{})
// Clean up temp file
os.Remove(tempFile)
if err != nil {
log.Printf("Error uploading directory %s: %v\n", dirPath, err)
continue
}
fmt.Printf("Successfully uploaded %s. Size: %d bytes\n", dirPath, uploadInfo.Size)
}
}
return nil
}
func zipSource(source, target string) error {
f, err := os.Create(target)
if err != nil {
return err
}
defer f.Close()
writer := zip.NewWriter(f)
defer writer.Close()
return filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
// Instead of failing hard, log the error and skip this file
log.Printf("Warning: Skipping file %s due to error: %v\n", path, err)
return nil
}
// Skip the zip file itself if it's inside the source directory
if path == target {
return nil
}
// Skip sockets, pipes, devices, etc. Only allow regular files and directories.
// info.Mode() & os.ModeType returns the file type bits (excluding permissions)
// 0 means regular file.
mode := info.Mode()
if !mode.IsRegular() && !info.IsDir() {
// Skip non-regular files silently (or with debug log) to avoid "no such device" or "open socket" errors
// Symlinks (ModeSymlink) are also skipped by IsRegular(), which is usually desired for backup consistency unless we specifically want to follow them.
// If we want to support symlinks, we'd need to handle them separately. For now, skipping is safer.
return nil
}
header, err := zip.FileInfoHeader(info)
if err != nil {
log.Printf("Warning: Failed to create zip header for %s: %v\n", path, err)
return nil
}
// Change header name to be relative to the source
relPath, err := filepath.Rel(source, path)
if err != nil {
return err
}
// Use forward slashes for zip compatibility
header.Name = filepath.ToSlash(relPath)
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := writer.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
// If we can't open the file (permission denied etc), skip it
log.Printf("Warning: Failed to open file %s: %v\n", path, err)
return nil
}
defer file.Close()
_, err = io.Copy(writer, file)
if err != nil {
log.Printf("Warning: Failed to write file %s to zip: %v\n", path, err)
return nil
}
return nil
})
}
Binary file not shown.