Files
go-common/examples/storage_example.go
2025-11-30 13:15:13 +08:00

72 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-commom/config"
"git.toowon.com/jimmy/go-commom/middleware"
"git.toowon.com/jimmy/go-commom/storage"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config/example.json")
if err != nil {
log.Fatal("Failed to load config:", err)
}
// 创建存储实例使用OSS
// 注意需要先实现OSS SDK集成
ossStorage, err := storage.NewStorage(storage.StorageTypeOSS, cfg)
if err != nil {
log.Printf("Failed to create OSS storage: %v", err)
log.Println("Note: OSS SDK integration is required")
// 继续演示其他功能
} else {
// 创建上传处理器
uploadHandler := storage.NewUploadHandler(storage.UploadHandlerConfig{
Storage: ossStorage,
MaxFileSize: 10 * 1024 * 1024, // 10MB
AllowedExts: []string{".jpg", ".jpeg", ".png", ".gif", ".pdf"},
ObjectPrefix: "uploads/",
})
// 创建代理查看处理器
proxyHandler := storage.NewProxyHandler(ossStorage)
// 创建中间件链
chain := middleware.NewChain(
middleware.CORS(cfg.GetCORS()),
middleware.Timezone,
)
// 注册路由
mux := http.NewServeMux()
mux.Handle("/upload", chain.Then(uploadHandler))
mux.Handle("/file", chain.Then(proxyHandler))
log.Println("Storage server started on :8080")
log.Println("Upload: POST /upload")
log.Println("View: GET /file?key=images/test.jpg")
log.Fatal(http.ListenAndServe(":8080", mux))
}
// 演示MinIO存储
minioStorage, err := storage.NewStorage(storage.StorageTypeMinIO, cfg)
if err != nil {
log.Printf("Failed to create MinIO storage: %v", err)
log.Println("Note: MinIO SDK integration is required")
} else {
log.Printf("MinIO storage created: %v", minioStorage != nil)
}
// 演示对象键生成
objectKey1 := storage.GenerateObjectKey("images/", "test.jpg")
log.Printf("Object key 1: %s", objectKey1)
objectKey2 := storage.GenerateObjectKeyWithDate("images", "test.jpg")
log.Printf("Object key 2: %s", objectKey2)
}