preface
This is my participation more challenge the 10th day, everybody is good, I am a composer of the day in the previous chapter we introduced the commonly used middleware development, believe that you have a new knowledge of the middleware and the management of the resource file upload and download, on the server is necessary function, in this section, we develop a upload users face interface development, file management basic function ~
1. Introduction to Minio
Object Storage System, similar to Ali Oss
Features:
1. High performance
2. Scalability
3. Cloud native support
4. Open full source code + enterprise support
5. Compatible with Amazon S3
6. Very easy to use
Minio website
Diagram:
1. Preparatory work
In the previous article we talked a lot about how to configure routing and yamL configuration file Settings and read. This article is not about doing this by hand, but more about implementing this feature, so you need to prepare for the early stages:
- Write the route to upload the file, and write the controller function
- To configure the struct field (config/config.go) of minio in YAML, see
minio:
endpoint: "127.0.0.1:9000"
accessKeyID: "minioadmin"
secretAccessKey: "minioadmin"
Copy the code
3. Install the minio official website installation document, recommended docker installation :docs.minio.org.cn/docs/
4. Try the minio interface: http://127.0.0.1:9000/
2. Write miniO initialization links
(1). In the initialize/minio
package initialize
import (
"github.com/minio/minio-go"
_ "github.com/minio/minio-go/pkg/encrypt"
"go_gin/global"
"go_gin/utils"
"log"
)
func InitMinIO(a) {
minioInfo := global.Settings.MinioInfo
// Initialize the minio client object. False: Disables HTTPS certificate verification
minioClient, err := minio.New(minioInfo.Endpoint, minioInfo.AccessKeyID, minioInfo.SecretAccessKey, false )
iferr ! =nil {
log.Fatalln(err)
}
// The client is registered in a global variable
global.MinioClient = minioClient
// Create a bucket named userheader.
utils.CreateMinoBuket("userheader")}Copy the code
CreateMinoBuket() {utils.CreateMinoBuket() {utils.CreateMinoBuket()
(2). Add global.minioclient \
In the global. GlobalVar
MinioClient *minio.Client
Copy the code
(3). Call in main.go
// initialize minIO
initialize.InitMinIO()
Copy the code
3. Write minio operation functions
Write in utils/minio.go
package utils
import (
"fmt"
"github.com/minio/minio-go"
"github.com/minio/minio-go/v6/pkg/policy"
"go.uber.org/zap"
"go_gin/global"
"io"
"net/url"
"time"
)
// CreateMinoBuket creates a minio bucket
func CreateMinoBuket(bucketName string) {
location := "us-east-1"
err := global.MinioClient.MakeBucket(bucketName, location)
iferr ! =nil {
// Check whether the bucket already exists.
exists, err := global.MinioClient.BucketExists(bucketName)
fmt.Println(exists)
if err == nil && exists {
fmt.Printf("We already own %s\n", bucketName)
} else {
fmt.Println(err, exists)
return}}//
err = global.MinioClient.SetBucketPolicy(bucketName, policy.BucketPolicyReadWrite)
iferr ! =nil {
fmt.Println(err)
return
}
fmt.Printf("Successfully created %s\n", bucketName)
}
// UploadFile UploadFile to a bucket specified by minio
func UploadFile(bucketName, objectName string, reader io.Reader, objectSize int64) (ok bool) {
n, err := global.MinioClient.PutObject(bucketName, objectName, reader, objectSize, minio.PutObjectOptions{ContentType: "application/octet-stream"})
iferr ! =nil {
fmt.Println(err)
return false
}
fmt.Println("Successfully uploaded bytes: ", n)
return true
}
// GetFileUrl gets the file URL
func GetFileUrl(bucketName string, fileName string, expires time.Duration) string {
//time.Second*24*60*60
reqParams := make(url.Values)
presignedURL, err := global.MinioClient.PresignedGetObject(bucketName, fileName, expires, reqParams)
iferr ! =nil {
zap.L().Error(err.Error())
return ""
}
return fmt.Sprintf("%s", presignedURL)
}
Copy the code
CreateMinoBuket creates a bucket at minio. UploadFile uploads a file. GetFileUrl obtains the URL of the downloaded file
4. Write an interface for uploading profile pictures
The controller/user. Go
// PutHeaderImage uploads the user profile picture
func PutHeaderImage(c *gin.Context) {
file, _ := c.FormFile("file")
fileObj, err := file.Open()
iferr ! =nil {
fmt.Println(err)
return
}
// Upload the file to the corresponding bucket of minio
ok := utils.UploadFile("userheader", file.Filename, fileObj, file.Size)
if! ok { Response.Err(c,401.401."Avatar uploading failed"."")
return
}
headerUrl := utils.GetFileUrl("userheader", file.Filename, time.Second*24*60*60)
if headerUrl == "" {
Response.Success(c, 400."Failed to obtain user profile picture"."headerMap")
return
}
//TODO stores the user's avatar address to head_URL in the corresponding user table
Response.Success(c, 200."Avatar uploaded successfully".map[string]interface{} {"userheaderUrl": headerUrl,
})
}
Copy the code
What can be improved:
- When you get the url of your avatar, you should store the address in mysql
- File name plus UUID to prevent overwriting
Ps: Don’t forget to add a route to the Container.
Finally – verification of results
(1). Request to upload file route in Postman:The request is made on the browser with the value of userheaderUrl and the file is downloaded successfully (2). View in minio:
http://127.0.0.1:9000/ Minio successfully added the upload file
If you found any of these articles useful, please give them a thumbs up and leave a comment