package service import ( "case-open-api/extend/aliyun" "errors" "fmt" "io" "math/rand" "net/http" "time" ) type UserService struct { } // HandleUserImage 处理用户图片 func (r *UserService) HandleUserImage(wxAvatar string) (ossPath string, err error) { if wxAvatar == "" { return "", nil } // 发送GET请求 resp, err := http.Get(wxAvatar) if err != nil { return "", err } defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) if resp.StatusCode != 200 { return "", errors.New("请求失败") } // 读取响应体 respBody, err := io.ReadAll(resp.Body) if err != nil { return "", err } // 设置文件名字 now := time.Now() dateTimeString := now.Format("20060102150405") // 当前时间字符串 rand.New(rand.NewSource(time.Now().UnixNano())) // 设置随机数 ossPath = "user/avatar/" + dateTimeString + fmt.Sprintf("%d", rand.Intn(9000)+1000) + ".png" // 上传oss _, err = aliyun.PutObjectByte(ossPath, respBody) if err != nil { return "", err } ossPath = "/" + ossPath return ossPath, nil }