Skip to content

Commit

Permalink
增加网络链接文件类型错误提示,优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
ygxbnet committed Jan 29, 2024
1 parent 17aa996 commit 258b3dd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
3 changes: 2 additions & 1 deletion internal/httpapi/httpapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
)

var userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"
var apiPath = "/api/v1/upload"

// UploadImageToLsky 上传图片到Lsky,返回相关信息
func UploadImageToLsky(data io.Reader, imageName string, serverURL string, authToken string) (response *http.Response, error error) {
Expand All @@ -27,7 +28,7 @@ func UploadImageToLsky(data io.Reader, imageName string, serverURL string, authT

// 请求http
client := &http.Client{}
req, err := http.NewRequest("POST", serverURL+"/api/v1/upload", &bufReader)
req, err := http.NewRequest("POST", serverURL+apiPath, &bufReader)
if err != nil {
return nil, err
}
Expand Down
15 changes: 10 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (

// PATH 注意在开发时需要将路径传入
//
// 例如:-path C:\YGXB\Project\upload
// 例如:-path C:\xxx\xxx
var PATH = flag.String("path", "", "程序路径")

var configData config.Result
Expand All @@ -41,6 +41,7 @@ func main() {
// 开发时运行路径与项目路径不同,需使用手动传入的 config.yml 地址
programPath = *PATH
}
// 解析配置
configData = config.Parse(programPath)

// 得到URL地址
Expand All @@ -51,17 +52,21 @@ func main() {
var getData io.Reader
var imageName string

// 读取图片文件
if url[0:4] == "http" { // 判断是否为网络图片
// 读取图片文件,判断是否为网络图片
if url[0:4] == "http" {
// 文件为网络图片
data, err := httpapi.GetNetworkImageData(url)
defer data.Close()

// 解析图片类型
imageType := "webp"
buff, err := io.ReadAll(data)
fileType := http.DetectContentType(buff)
if fileType[:5] == "image" { // 格式:image/jpeg
if fileType[:5] == "image" { // fileType例子:image/jpeg
imageType = fileType[6:]
} else {
fmt.Println("❗输入的网络链接不是图片,请检查链接是否正确\n", string(buff)[:1000])
os.Exit(1)
}

imageName = fmt.Sprintf("%s.%s", time.Now().Format("2006-01-02 15:04:05"), imageType)
Expand Down Expand Up @@ -98,7 +103,7 @@ func main() {
if response.StatusCode == 200 {
if gjson.Parse(string(returnMessage)).Get("status").String() == "true" {
// 成功上传
fmt.Println(gjson.Parse(string(returnMessage)).Get("data").Get("links").Get("url").String())
fmt.Println(gjson.Parse(string(returnMessage)).Get("data.links.url").String())
} else {
// 上传失败
fmt.Println("❗上传图片失败 服务器返回信息:", string(returnMessage))
Expand Down

0 comments on commit 258b3dd

Please sign in to comment.