# gcp 用法



下載 json
設定方法
`gcloud auth activate-service-account --key-file={json檔位置}`
or
`export GOOGLE_APPLICATION_CREDENTIALS={json檔位置}`
```go=
package main
import (
"context"
"fmt"
"io"
"net/http"
"path/filepath"
"cloud.google.com/go/storage"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// 設置上傳檔案的路由
router.POST("/upload", func(c *gin.Context) {
// 從請求中獲取檔案
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
// 獲取檔案的擴展名
ext := filepath.Ext(file.Filename)
// 生成唯一的檔案名稱
filename := fmt.Sprintf("%s%s", generateUniqueID(), ext)
// 建立 GCS 客戶端
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
defer client.Close()
// 指定 GCS 儲存桶名稱
bucketName := "meeting-center-storage-test"
// 創建一個新的 GCS 物件
obj := client.Bucket(bucketName).Object(filename)
writer := obj.NewWriter(ctx)
// 打開上傳的檔案
src, err := file.Open()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
defer src.Close()
// 將上傳的檔案複製到 GCS 物件
if _, err := io.Copy(writer, src); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// 關閉 GCS 物件寫入器
if err := writer.Close(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// 返回成功響應
c.JSON(http.StatusOK, gin.H{
"message": "File uploaded successfully",
"filename": filename,
})
})
router.GET("/download/:filename", func(c *gin.Context) {
// 獲取 URL 參數中的檔案名稱
filename := c.Param("filename")
// 建立 GCS 客戶端
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// 指定 GCS 儲存桶名稱
bucketName := "meeting-center-storage-test"
// 獲取 GCS 物件
obj := client.Bucket(bucketName).Object(filename)
// 下載 GCS 物件
reader, err := obj.NewReader(ctx)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
defer reader.Close()
// 將 GCS 物件的內容複製到 HTTP 響應中
c.Writer.Header().Set("Content-Disposition", "attachment; filename="+filename)
c.Writer.Header().Set("Content-Type", "application/octet-stream")
if _, err := io.Copy(c.Writer, reader); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
})
// 啟動服務器
router.Run(":8080")
}
func generateUniqueID() string {
// 生成唯一ID的邏輯,可以根據需要自行實現
// 這裡僅作為示例,返回一個固定的字符串
return "123"
}
```