-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
102 lines (89 loc) · 2.3 KB
/
main.go
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
package main
import (
"bytes"
"flag"
"fmt"
"github.com/tidwall/gjson"
"io"
"lsky-upload/internal/config"
"lsky-upload/internal/httpapi"
"lsky-upload/internal/log"
"net/http"
"os"
"path/filepath"
"time"
)
func init() {
// 解析传入参数
flag.Parse()
}
func main() {
// 解析配置
config.Init()
// 得到URL地址
urls := flag.Args()
// URL分类上传到图床
for _, url := range urls {
var getData io.Reader
var imageName string
// 读取图片文件,判断是否为网络图片
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" { // fileType例子:image/jpeg
imageType = fileType[6:]
} else {
log.Error("❗输入的网络链接不是图片,请检查链接是否正确\n", string(buff))
os.Exit(1)
}
// 格式化图片名称
imageName = fmt.Sprintf("%s.%s", time.Now().Format("2006-01-02 15:04:05"), imageType)
if err != nil {
log.Error("❗获取网络图片错误:", err)
return
}
getData = bytes.NewReader(buff)
} else {
imageName = filepath.Base(url)
data, err := os.Open(url)
if err != nil {
log.Error("❗打开文件失败", err)
os.Exit(1)
}
getData = data
}
// 上传图片到图床
response, err := httpapi.UploadImageToLsky(
getData,
imageName,
config.ConfigData.LskyServer,
config.ConfigData.LskyAuthToken)
if err != nil {
log.Error("❗上传图片错误:", err)
return
}
defer response.Body.Close()
returnMessage, err := io.ReadAll(response.Body)
if err != nil {
log.Error("❗读取http返回信息失败:", err)
}
// 处理返回结果
if response.StatusCode == 200 {
if gjson.Parse(string(returnMessage)).Get("status").String() == "true" {
// 成功上传
fmt.Println(gjson.Parse(string(returnMessage)).Get("data.links.url").String())
} else {
// 上传失败
log.Error("❗上传图片失败 服务器返回信息:", string(returnMessage))
}
} else {
// 请求上传图片接口失败
log.Error(fmt.Sprintf("❗请求接口%d \t\n详细信息:%s", response.StatusCode, string(returnMessage)))
}
}
}