1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
|
// main.go
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// 配置结构体
type Config struct {
AWSRegion string
AWSAccessKeyID string
AWSSecretAccessKey string
S3Bucket string
ServerPort string
}
// 上传元数据
type UploadMetadata struct {
ID string `json:"id"`
FileName string `json:"file_name"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
MimeType string `json:"mime_type"`
UploadedAt time.Time `json:"uploaded_at"`
UserID string `json:"user_id"` // 可选:关联用户
}
// 应用主要结构
type App struct {
Config *Config
S3 *s3.S3
Router *gin.Engine
// 实际应用中应该使用数据库存储元数据
Uploads map[string]*UploadMetadata
}
// 初始化应用
func NewApp(config *Config) *App {
// 创建AWS会话
sess, err := session.NewSession(&aws.Config{
Region: aws.String(config.AWSRegion),
Credentials: credentials.NewStaticCredentials(
config.AWSAccessKeyID,
config.AWSSecretAccessKey,
"",
),
})
if err != nil {
log.Fatalf("Failed to create AWS session: %v", err)
}
// 创建S3服务客户端
s3Client := s3.New(sess)
app := &App{
Config: config,
S3: s3Client,
Router: gin.Default(),
Uploads: make(map[string]*UploadMetadata),
}
app.setupRoutes()
return app
}
// 设置路由
func (app *App) setupRoutes() {
app.Router.POST("/api/upload/sign", app.generatePresignedURL)
app.Router.POST("/api/upload/complete", app.completeUpload)
app.Router.GET("/api/upload/:id", app.getUploadMetadata)
}
// 生成预签名URL请求
type GeneratePresignedURLRequest struct {
FileName string `json:"file_name" binding:"required"`
FileType string `json:"file_type" binding:"required"`
}
// 生成预签名URL响应
type GeneratePresignedURLResponse struct {
UploadID string `json:"upload_id"`
URL string `json:"url"`
ExpiresAt int64 `json:"expires_at"`
}
// 生成一次性预签名URL
func (app *App) generatePresignedURL(c *gin.Context) {
var req GeneratePresignedURLRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 生成唯一上传ID和文件名
uploadID := uuid.New().String()
fileExt := getFileExtension(req.FileName)
s3Key := fmt.Sprintf("uploads/%s/%s%s", time.Now().Format("2006/01/02"), uploadID, fileExt)
// 创建预签名PUT请求(一次性使用)
reqs, _ := app.S3.PutObjectRequest(&s3.PutObjectInput{
Bucket: aws.String(app.Config.S3Bucket),
Key: aws.String(s3Key),
// 可以添加ContentType和ContentLength限制
})
// 生成预签名URL,设置15分钟过期和一次性使用
url, headers, err := reqs.PresignRequest(15 * time.Minute)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate presigned URL"})
return
}
// 存储上传元数据(实际应用中应使用数据库)
metadata := &UploadMetadata{
ID: uploadID,
FileName: req.FileName,
FilePath: s3Key,
UploadedAt: time.Now(),
}
app.Uploads[uploadID] = metadata
// 记录headers用于验证(实际应用中应存储这些信息)
_ = headers
c.JSON(http.StatusOK, GeneratePresignedURLResponse{
UploadID: uploadID,
URL: url,
ExpiresAt: time.Now().Add(15 * time.Minute).Unix(),
})
}
// 上传完成请求
type CompleteUploadRequest struct {
UploadID string `json:"upload_id" binding:"required"`
}
// 上传完成响应
type CompleteUploadResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
FileURL string `json:"file_url,omitempty"`
}
// 处理上传完成
func (app *App) completeUpload(c *gin.Context) {
var req CompleteUploadRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 获取上传元数据
metadata, exists := app.Uploads[req.UploadID]
if !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Upload not found"})
return
}
// 验证S3中文件是否存在
exists, err := app.verifyS3File(metadata.FilePath)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to verify file"})
return
}
if !exists {
c.JSON(http.StatusBadRequest, gin.H{"error": "File not found in S3"})
return
}
// 获取文件详细信息
fileInfo, err := app.getS3FileInfo(metadata.FilePath)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get file info"})
return
}
// 更新元数据
metadata.FileSize = fileInfo.Size
metadata.MimeType = fileInfo.ContentType
metadata.UploadedAt = time.Now()
// 在实际应用中,这里应该将元数据保存到数据库
c.JSON(http.StatusOK, CompleteUploadResponse{
Success: true,
Message: "File uploaded successfully",
FileURL: fmt.Sprintf("https://%s.s3.%s.amazonaws.com/%s",
app.Config.S3Bucket, app.Config.AWSRegion, metadata.FilePath),
})
}
// S3文件信息
type S3FileInfo struct {
Size int64
ContentType string
LastModified time.Time
}
// 验证S3中文件是否存在
func (app *App) verifyS3File(key string) (bool, error) {
_, err := app.S3.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(app.Config.S3Bucket),
Key: aws.String(key),
})
if err != nil {
return false, err
}
return true, nil
}
// 获取S3文件信息
func (app *App) getS3FileInfo(key string) (*S3FileInfo, error) {
result, err := app.S3.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(app.Config.S3Bucket),
Key: aws.String(key),
})
if err != nil {
return nil, err
}
return &S3FileInfo{
Size: *result.ContentLength,
ContentType: *result.ContentType,
LastModified: *result.LastModified,
}, nil
}
// 获取上传元数据
func (app *App) getUploadMetadata(c *gin.Context) {
uploadID := c.Param("id")
metadata, exists := app.Uploads[uploadID]
if !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Upload not found"})
return
}
c.JSON(http.StatusOK, metadata)
}
// 获取文件扩展名
func getFileExtension(filename string) string {
for i := len(filename) - 1; i >= 0; i-- {
if filename[i] == '.' {
return filename[i:]
}
}
return ""
}
// 主函数
func main() {
config := &Config{
AWSRegion: "us-east-1",
AWSAccessKeyID: "your-access-key-id",
AWSSecretAccessKey: "your-secret-access-key",
S3Bucket: "your-bucket-name",
ServerPort: "8080",
}
app := NewApp(config)
log.Printf("Server starting on port %s", config.ServerPort)
log.Fatal(app.Router.Run(":" + config.ServerPort))
}
|