-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
2252 lines (2057 loc) · 70.2 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"embed"
"encoding/json"
"flag"
"io/fs"
"io/ioutil"
"log"
"errors"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"runtime"
"fmt"
"time"
"strings"
"net/url"
"math/rand"
"html/template"
"sync"
"io"
"regexp"
"github.com/natefinch/lumberjack"
"github.com/zu1k/nali/pkg/geoip"
"github.com/zu1k/nali/pkg/ip2region"
"github.com/zu1k/nali/pkg/ipip"
"github.com/zu1k/nali/pkg/qqwry"
"github.com/zu1k/nali/pkg/cdn"
"github.com/zu1k/nali/pkg/zxipv6wry"
"github.com/zu1k/nali/pkg/ip2location"
)
//go:embed static/*
var content embed.FS
var (
dataDir string
dbDir string
admin bool
logDir string
// 错误尝试限制和锁定时间
maxAttempts = 5
lockoutDuration = 10 * time.Minute
authenticationURL = "/admin-auth"
authCredentials = map[string]string{}
lockoutData = struct {
sync.RWMutex
attempts int
lockout time.Time
}{}
// 认证 cookie 的设置
authCookieName = "authenticated"
authCookieValue = "true"
authCookieAge = 10 * time.Minute // 认证 cookie 的有效期
ipCookieName = "auth-ip"
ipCookieValue = "" // 动态设置
)
// 定义查询实例
var (
QQWryPath string
ZXIPv6WryPath string
GeoLite2CityPath string
IPIPFreePath string
Ip2RegionPath string
CdnPath string
Ip2locationPath string
geoip2Instance *geoip.GeoIP
qqwryInstance *qqwry.QQwry
ipipInstance *ipip.IPIPFree
ip2regionInstance *ip2region.Ip2Region
zxipv6wryInstance *zxipv6wry.ZXwry
ip2locationInstance *ip2location.IP2Location
cdnInstance *cdn.CDN
)
func init() {
// 设置时区为上海
loc := time.FixedZone("CST", 8*60*60)
time.Local = loc
}
// 定义API请求的数据结构
type ApiRequest struct {
LongUrl string `json:"longUrl"`
ShortCode string `json:"shortCode"`
Password string `json:"password"`
ClientIP string `json:"client_ip"`
Expiration string `json:"expiration"`
BurnAfterReading string `json:"burn_after_reading"`
Type string `json:"type"`
LastUpdate string `json:"last_update"`
}
// 定义根目录请求的数据结构
type Data struct {
TotalRules int `json:"total_rules"`
TodayNewRules int `json:"today_new_rules"`
LastRuleUpdate string `json:"last_rule_update"`
TotalVisits int `json:"total_visits"`
TodayVisits int `json:"today_visits"`
LastVisitsUpdate string `json:"last_visits_update"`
Email string `json:"email"`
Img string `json:"img"`
}
// ApiResponse 是响应体的结构
type ApiResponse struct {
Type string `json:"type"`
ShortURL string `json:"short_url"`
URLName string `json:"URL_NAME"`
}
//配置文件读取修改,数据中获取指定键的字符串
func getStringValue(data map[string]interface{}, key string, defaultValue string) string {
if value, ok := data[key]; ok {
if strValue, ok := value.(string); ok {
return strValue
}
}
return defaultValue
}
//配置文件读取,数据中获取指定键的数值
func getIntValue(data map[string]interface{}, key string, defaultValue int) int {
if value, ok := data[key]; ok {
if floatValue, ok := value.(float64); ok {
return int(floatValue)
}
}
return defaultValue
}
//初始统计数据文件
func initializeData(dataFilePath string) {
timeFormat := "2006-01-02"
// 设置东八区(北京时间),偏移量为 +8 小时
cst := time.FixedZone("CST", 8*60*60)
// 获取当前时间并转换为东八区时间
now := time.Now().In(cst)
// 格式化日期
today := now.Format(timeFormat)
initialData := Data{
TotalRules: 0,
TodayNewRules: 0,
LastRuleUpdate: today,
TotalVisits: 0,
TodayVisits: 0,
LastVisitsUpdate: today,
Email: os.Getenv("Email"),
Img: "https://pic.rmb.bdstatic.com/bjh/gallery/373e5f5d10577706a529f69cc4997ecd608.jpeg",
}
// 如果short_data.json文件不存在则创建
if _, err := os.Stat(dataFilePath); os.IsNotExist(err) {
file, err := os.Create(dataFilePath)
if err != nil {
log.Fatalf("无法创建统计数据文件: %v", err)
}
defer file.Close()
encoder := json.NewEncoder(file)
if err := encoder.Encode(initialData); err != nil {
log.Fatalf("无法写入初始统计数据: %v", err)
}
} else {
// 如果文件存在,检查缺失字段并补充
file, err := os.OpenFile(dataFilePath, os.O_RDWR, 0644)
if err != nil {
log.Fatalf("无法打开统计数据文件: %v", err)
}
defer file.Close()
var rawData map[string]interface{}
decoder := json.NewDecoder(file)
if err := decoder.Decode(&rawData); err != nil {
log.Fatalf("无法解析统计数据文件: %v", err)
}
existingData := Data{
TotalRules: getIntValue(rawData, "total_rules", initialData.TotalRules),
TodayNewRules: getIntValue(rawData, "today_new_rules", initialData.TodayNewRules),
LastRuleUpdate: getStringValue(rawData, "last_rule_update", initialData.LastRuleUpdate),
TotalVisits: getIntValue(rawData, "total_visits", initialData.TotalVisits),
TodayVisits: getIntValue(rawData, "today_visits", initialData.TodayVisits),
LastVisitsUpdate: getStringValue(rawData, "last_visits_update", initialData.LastVisitsUpdate),
Img: getStringValue(rawData, "img", initialData.Img),
Email: getStringValue(rawData, "email", initialData.Email),
}
if existingData.LastRuleUpdate != today {
existingData.LastRuleUpdate = today
existingData.TodayNewRules = 0
}
if existingData.LastVisitsUpdate != today {
existingData.LastVisitsUpdate = today
existingData.TodayVisits = 0
}
if os.Getenv("Email") != "" && existingData.Email != os.Getenv("Email") {
existingData.Email = os.Getenv("Email")
}
dataFilePath := filepath.Join(dataDir, "short_data.json")
// 统计dataDir目录下的.json文件数量
totalRules := 0
err = filepath.Walk(dataDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && filepath.Ext(info.Name()) == ".json" && info.Name() != filepath.Base(dataFilePath) {
totalRules++
}
return nil
})
if err != nil {
log.Fatalf("无法统计.json文件数量: %v", err)
}
existingData.TotalRules = totalRules
// 将文件内容截断为0并将更新后的数据写入
file.Seek(0, 0)
file.Truncate(0)
// 创建 JSON 编码器并设置缩进将数据写入文件
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
if err := encoder.Encode(existingData); err != nil {
log.Fatalf("无法更新统计数据文件: %v", err)
}
}
}
//随机生成8位字符的后缀
func generateRandomString(n int) string {
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
rand.Seed(time.Now().UnixNano())
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
// getClientIP 从HTTP请求中获取客户端IP地址
func getClientIP(r *http.Request) string {
// 从X-Forwarded-For头部获取IP地址(用于代理服务器后的客户端)
ip := r.Header.Get("X-Forwarded-For")
// 如果X-Forwarded-For为空或未知,则使用RemoteAddr
if ip == "" || strings.ToLower(ip) == "unknown" {
ip = r.RemoteAddr
} else {
// X-Forwarded-For可能返回以逗号分隔的多个IP地址
ips := strings.Split(ip, ",")
ip = strings.TrimSpace(ips[0]) // 使用列表中的第一个IP地址
}
// 检查IP地址是否包含端口号
if strings.Contains(ip, ":") {
if strings.Count(ip, ":") == 1 {
// 处理端口号
ip, _, _ = net.SplitHostPort(ip)
}
}
return ip
}
// 处理API请求
func apiHandler(w http.ResponseWriter, r *http.Request, dataDir string) {
var req ApiRequest
// 解析请求体
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 判断后缀是否包含 "/"
if strings.Contains(req.ShortCode, "/") {
errMsg := map[string]string{"error": "错误!后缀里不能包含 / 符号。"}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(errMsg)
return
}
// 如果没有后缀就随机生成8位字符的后缀
if req.ShortCode == "" {
req.ShortCode = generateRandomString(8)
}
// 不能使用后缀api
if req.ShortCode == "api" {
errMsg := map[string]string{"error": "错误!该后缀是api调用,请使用其他后缀。"}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(errMsg)
return
}
// 不能使用后缀admin
if req.ShortCode == "admin" {
errMsg := map[string]string{"error": "错误!该后缀已经被使用,请使用正确的密码修改或使用其他后缀。"}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(errMsg)
return
}
// 不能使用后缀admin-auth
if req.ShortCode == "admin-auth" {
errMsg := map[string]string{"error": "错误!该后缀已经被使用,请使用正确的密码修改或使用其他后缀。"}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(errMsg)
return
}
// 判断请求里的type的值
if req.Type == "link" || req.Type == "iframe" {
if !strings.HasPrefix(req.LongUrl, "http://") && !strings.HasPrefix(req.LongUrl, "https://") {
req.LongUrl = "http://" + req.LongUrl
}
}
// 生成文件路径
filePath := filepath.Join(dataDir, req.ShortCode+".json")
// 检查文件是否存在
isNewRule := true
_, err := os.Stat(filePath)
if err == nil {
isNewRule = false
// 文件存在,检查密码
existingReq := ApiRequest{}
fileData, err := ioutil.ReadFile(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.Unmarshal(fileData, &existingReq); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 检查密码是否匹配
if existingReq.Password != "" && existingReq.Password != req.Password {
errMsg := map[string]string{"error": "密码错误!该后缀已经被使用,请使用正确的密码修改或使用其他后缀。"}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(errMsg)
return
}
}
// 更新过期时间
expirationMinutesStr := req.Expiration
if expirationMinutesStr != "" {
expirationMinutes, err := strconv.Atoi(expirationMinutesStr)
if err != nil {
http.Error(w, "expiration must be a valid number", http.StatusBadRequest)
return
}
// 手动设置为东八区(上海时区)
loc := time.FixedZone("CST", 8*60*60) // CST: China Standard Time
currentTime := time.Now().In(loc)
// 添加指定分钟数到当前时间
expirationTime := currentTime.Add(time.Duration(expirationMinutes) * time.Minute)
// 更新请求中的expiration字段为格式化后的时间字符串
req.Expiration = expirationTime.Format("2006-01-02 15:04:05")
}
// 新增 last_update 参数到请求中
// 手动设置为东八区(上海时区)
loc := time.FixedZone("CST", 8*60*60) // CST: China Standard Time
lastUpdate := time.Now().In(loc).Format("2006-01-02 15:04:05")
req.LastUpdate = lastUpdate
// 获取客户端 IP 地址
clientIP := getClientIP(r) // Assuming getClientIP function retrieves client IP from request 'r'
req.ClientIP = clientIP
// 将更新后的data作为新的请求
data, err := json.MarshalIndent(req, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 创建或更新JSON文件
dir := filepath.Dir(filePath)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// 将更新后的data写入文件
if err := ioutil.WriteFile(filePath, data, 0644); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 如果是新的规则,更新 short_data.json 中的数据
if isNewRule {
// 读取 short_data.json 文件
shortDataPath := filepath.Join(dataDir, "short_data.json")
shortData, err := ioutil.ReadFile(shortDataPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 解析 JSON 数据
var shortDataMap map[string]interface{}
if err := json.Unmarshal(shortData, &shortDataMap); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 获取当前上海时区日期
loc := time.FixedZone("CST", 8*60*60)
currentDate := time.Now().In(loc).Format("2006-01-02")
// 更新 total_rules 和 today_new_rules
totalRules := getIntValue(shortDataMap, "total_rules", 0)
todayNewRules := getIntValue(shortDataMap, "today_new_rules", 0)
lastRuleUpdate := getStringValue(shortDataMap, "last_rule_update", "")
if lastRuleUpdate != currentDate {
todayNewRules = 0
}
totalRules++
todayNewRules++
// 更新 short_data.json 的数据
shortDataMap["total_rules"] = totalRules
shortDataMap["today_new_rules"] = todayNewRules
shortDataMap["last_rule_update"] = currentDate
// 将更新后的数据写回 short_data.json 文件
updatedShortData, err := json.MarshalIndent(shortDataMap, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := ioutil.WriteFile(shortDataPath, updatedShortData, 0644); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// 构造返回的URL
host := r.Host
shortURL := fmt.Sprintf("http://%s/%s", host, req.ShortCode)
response := ApiResponse{
Type: req.Type,
ShortURL: shortURL,
URLName: req.ShortCode,
}
//发送响应
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
// 默认首页HTML文件
func indexHandler(w http.ResponseWriter, r *http.Request) {
// 读取short_data.json统计数据文件
dataFilePath := filepath.Join(dataDir, "short_data.json")
initializeData(dataFilePath)
file, err := os.Open(dataFilePath)
if err != nil {
http.Error(w, fmt.Sprintf("无法打开统计数据文件: %v", err), http.StatusInternalServerError)
return
}
defer file.Close()
// 解析数据
var data Data
decoder := json.NewDecoder(file)
if err := decoder.Decode(&data); err != nil {
http.Error(w, fmt.Sprintf("无法解析统计数据文件: %v", err), http.StatusInternalServerError)
return
}
// 读取网页文件
htmlContent, err := fs.ReadFile(content, "static/index.html")
if err != nil {
http.Error(w, fmt.Sprintf("无法读取HTML文件: %v", err), http.StatusInternalServerError)
return
}
// 将统计数据的值替换到网页里
htmlString := string(htmlContent)
htmlString = strings.ReplaceAll(htmlString, "{{totalRules}}", strconv.Itoa(data.TotalRules))
htmlString = strings.ReplaceAll(htmlString, "{{todayNewRules}}", strconv.Itoa(data.TodayNewRules))
htmlString = strings.ReplaceAll(htmlString, "{{totalvisits}}", strconv.Itoa(data.TotalVisits))
htmlString = strings.ReplaceAll(htmlString, "{{todayvisits}}", strconv.Itoa(data.TodayVisits))
htmlString = strings.ReplaceAll(htmlString, "修改为你的邮箱", data.Email)
htmlString = strings.ReplaceAll(htmlString, "my-img.jpeg", data.Img)
// 将网页数据响应给客户端
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(htmlString))
}
// 处理其他请求
func shortHandler(w http.ResponseWriter, r *http.Request, dataDir string) {
// 获取请求路径并处理
path := r.URL.Path[1:] // 去掉开头的斜杠
// 将百分号编码转换为中文字符
path, err := url.QueryUnescape(path)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 判断路径中是否包含 "/"
var extra string // 定义用于存储 "/" 后内容的新变量
if idx := strings.Index(path, "/"); idx != -1 {
// 如果包含 "/", 截取 "/" 前后的内容
extra = path[idx+1:] // "/" 后面的内容
path = path[:idx] // "/" 前面的内容
}
// 如果路径为空或者在 dataDir 目录中没有对应的 .json 文件,则重定向到根目录
filePath := filepath.Join(dataDir, path+".json")
_, err = os.Stat(filePath)
if path != "" && err != nil {
// 文件不存在,重定向到根目录
http.Redirect(w, r, "/", http.StatusFound)
return
}
// 如果路径为空,则返回
if path == "" {
errMsg := map[string]string{"error": "空页面!"}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(errMsg)
return
}
// 读取JSON文件内容
jsonData, err := ioutil.ReadFile(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 解析JSON数据
var data map[string]interface{}
if err := json.Unmarshal(jsonData, &data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 检查expiration字段
expirationStr, ok := data["expiration"].(string)
if ok && expirationStr != "" {
// 解析expiration时间
expirationTime, err := time.Parse("2006-01-02 15:04:05", expirationStr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// 获取当前上海时区时间
loc := time.FixedZone("CST", 8*60*60)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
now := time.Now().In(loc)
// 格式化时间为字符串,以便比较
expirationTimeFormatted := expirationTime.Format("2006-01-02 15:04:05")
nowFormatted := now.Format("2006-01-02 15:04:05")
// 比较时间
if expirationTimeFormatted <= nowFormatted {
// 如果过期,返回"链接已过期"并删除文件
err := os.Remove(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "链接已过期")
return
}
}
// 解析JSON内容
var apiRequest ApiRequest
err = json.Unmarshal(jsonData, &apiRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 检查 burn_after_reading 的值,如果为 "true" 则删除文件
if apiRequest.BurnAfterReading == "true" {
err = os.Remove(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// 读取 short_data.json 文件
shortDataPath := filepath.Join(dataDir, "short_data.json")
shortData, err := ioutil.ReadFile(shortDataPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 解析 JSON 数据
var shortDataMap map[string]interface{}
if err := json.Unmarshal(shortData, &shortDataMap); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 获取当前上海时区日期
loc := time.FixedZone("CST", 8*60*60)
currentDate := time.Now().In(loc).Format("2006-01-02")
// 更新 total_rules 和 today_new_rules
totalVisits := getIntValue(shortDataMap, "total_visits", 0)
todayVisits := getIntValue(shortDataMap, "today_visits", 0)
lastVisitsUpdate := getStringValue(shortDataMap, "last_visits_update", "")
if lastVisitsUpdate != currentDate {
todayVisits = 0
}
totalVisits++
todayVisits++
// 更新 short_data.json 的数据
shortDataMap["total_visits"] = totalVisits
shortDataMap["today_visits"] = todayVisits
shortDataMap["last_visits_update"] = currentDate
// 将更新后的数据写回 short_data.json 文件
updatedShortData, err := json.MarshalIndent(shortDataMap, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := ioutil.WriteFile(shortDataPath, updatedShortData, 0644); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 解析JSON内容
var apiReq ApiRequest
err = json.Unmarshal(jsonData, &apiReq)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 根据type值做相应处理
switch apiReq.Type {
case "link":
// 判断 extra 是否为空
if extra != "" {
// 检查 apiReq.LongUrl 是否以 '/' 结尾,或 extra 是否以 '/' 开头
if strings.HasSuffix(apiReq.LongUrl, "/") && strings.HasPrefix(extra, "/") {
// 如果两者都有 '/',移除 extra 的前导 '/'
extra = strings.TrimPrefix(extra, "/")
} else if !strings.HasSuffix(apiReq.LongUrl, "/") && !strings.HasPrefix(extra, "/") {
// 如果两者都没有 '/',在两者之间添加一个 '/'
extra = "/" + extra
}
// 拼接 extra 到 apiReq.LongUrl
apiReq.LongUrl += extra
}
// 如果是 WebSocket 请求,返回特定的头字段或响应体
if r.Header.Get("Upgrade") == "websocket" {
if strings.HasPrefix(apiReq.LongUrl, "http://") {
apiReq.LongUrl = "ws://" + strings.TrimPrefix(apiReq.LongUrl, "http://")
} else if strings.HasPrefix(apiReq.LongUrl, "https://") {
apiReq.LongUrl = "wss://" + strings.TrimPrefix(apiReq.LongUrl, "https://")
} else if !strings.HasPrefix(apiReq.LongUrl, "ws://") && !strings.HasPrefix(apiReq.LongUrl, "wss://") {
// 如果没有前缀,则添加 ws://
apiReq.LongUrl = "ws://" + apiReq.LongUrl
}
}
http.Redirect(w, r, apiReq.LongUrl, http.StatusFound)
case "html":
// 如果是 WebSocket 请求,返回特定的头字段或响应体
if r.Header.Get("Upgrade") == "websocket" {
if strings.HasPrefix(apiReq.LongUrl, "http://") {
apiReq.LongUrl = "ws://" + strings.TrimPrefix(apiReq.LongUrl, "http://")
} else if strings.HasPrefix(apiReq.LongUrl, "https://") {
apiReq.LongUrl = "wss://" + strings.TrimPrefix(apiReq.LongUrl, "https://")
} else if !strings.HasPrefix(apiReq.LongUrl, "ws://") && !strings.HasPrefix(apiReq.LongUrl, "wss://") {
// 如果没有前缀,则添加 ws://
apiReq.LongUrl = "ws://" + apiReq.LongUrl
}
http.Redirect(w, r, apiReq.LongUrl, http.StatusFound)
} else {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(apiReq.LongUrl))
}
case "page":
htmlContent, err := content.ReadFile("static/page.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
responseHtml := strings.Replace(string(htmlContent), "{长内容}", apiReq.LongUrl, -1)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(responseHtml))
case "iframe":
htmlContent, err := content.ReadFile("static/iframe.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if extra != "" {
if strings.HasSuffix(apiReq.LongUrl, "/") && strings.HasPrefix(extra, "/") {
extra = strings.TrimPrefix(extra, "/")
} else if !strings.HasSuffix(apiReq.LongUrl, "/") && !strings.HasPrefix(extra, "/") {
extra = "/" + extra
}
apiReq.LongUrl += extra
}
// 判断是否为 curl 或 wget 请求
userAgent := r.Header.Get("User-Agent")
if strings.Contains(userAgent, "curl") || strings.Contains(userAgent, "wget") {
// 如果是 curl 或 wget 请求,则直接重定向
http.Redirect(w, r, apiReq.LongUrl, http.StatusFound)
return
}
responseHtml := strings.Replace(string(htmlContent), "{套娃地址}", apiReq.LongUrl, -1)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(responseHtml))
case "text":
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(apiReq.LongUrl))
default:
http.Error(w, "Forbidden", http.StatusForbidden)
}
}
// 认证处理函数
func authHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
username := r.FormValue("username")
password := r.FormValue("password")
// 获取当前 IP 地址
ip := getClientIP(r)
if validPassword(username, password) {
log.Printf("用户 IP: %s 登录成功!", ip)
// 认证成功,设置认证 cookie 和 IP 地址 cookie
http.SetCookie(w, &http.Cookie{
Name: authCookieName,
Value: authCookieValue,
Path: "/",
Expires: time.Now().Add(authCookieAge),
HttpOnly: true,
})
http.SetCookie(w, &http.Cookie{
Name: ipCookieName,
Value: ip,
Path: "/",
Expires: time.Now().Add(authCookieAge),
HttpOnly: true,
})
http.Redirect(w, r, "/admin", http.StatusSeeOther)
return
}
// 认证失败,记录错误尝试
log.Printf("用户 IP: %s 使用帐号:%s 密码:%s 尝试登录!", ip, username, password)
lockoutData.Lock()
defer lockoutData.Unlock()
lockoutData.attempts++
if lockoutData.attempts >= maxAttempts {
lockoutData.lockout = time.Now().Add(lockoutDuration)
http.Error(w, "连续输错次数过多,请十分钟后重试", http.StatusForbidden)
return
}
// 显示认证表单并添加错误提示
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #f0f2f5;
font-family: Arial, sans-serif;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.form-container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
text-align: center;
width: 360px;
position: relative;
}
.form-container h1 {
margin-bottom: 20px;
color: #333;
}
.form-container label {
display: block;
margin: 10px 0;
color: #555;
}
.form-container input[type="text"],
.form-container input[type="password"] {
width: calc(100% - 20px);
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
.form-container input[type="submit"] {
background-color: #007bff;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
}
.form-container input[type="submit"]:hover {
background-color: #0056b3;
}
.error-message {
color: red;
margin-bottom: 15px;
display: none;
}
.error-message.show {
display: block;
}
.shake {
animation: shake 0.5s;
}
@keyframes shake {
0% { transform: translateX(0); }
25% { transform: translateX(-5px); }
50% { transform: translateX(5px); }
75% { transform: translateX(-5px); }
100% { transform: translateX(0); }
}
</style>
</head>
<body>
<div class="container">
<div class="form-container">
<h1>登录</h1>
<div id="error-message" class="error-message">账户或密码错误</div>
<form method="post" id="login-form">
<label>用户名: <input type="text" name="username" /></label>
<label>密码: <input type="password" name="password" /></label>
<input type="submit" value="登录" />
</form>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('login-form');
const errorMessage = document.getElementById('error-message');
if (errorMessage.textContent.trim() !== '') {
errorMessage.classList.add('show');
form.classList.add('shake');
setTimeout(() => form.classList.remove('shake'), 500);
}
});
</script>
</body>
</html>
`)
return
}
// 显示认证表单
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #f0f2f5;
font-family: Arial, sans-serif;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.form-container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
text-align: center;
width: 360px;
}
.form-container h1 {
margin-bottom: 20px;
color: #333;
}
.form-container label {
display: block;
margin: 10px 0;
color: #555;
}
.form-container input[type="text"],
.form-container input[type="password"] {
width: calc(100% - 20px);
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
.form-container input[type="submit"] {
background-color: #007bff;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
}
.form-container input[type="submit"]:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<div class="form-container">
<h1>登录</h1>
<form method="post">
<label>用户名: <input type="text" name="username" /></label>
<label>密码: <input type="password" name="password" /></label>
<input type="submit" value="登录" />
</form>
</div>
</div>
</body>
</html>
`)
}
// 校验账户和密码
func validPassword(username, password string) bool {
if pwd, ok := authCredentials[username]; ok && pwd == password {
return true
}
return false
}
// 检查是否已认证
func isAuthenticated(r *http.Request) bool {
authCookie, err := r.Cookie(authCookieName)
if err != nil || authCookie.Value != authCookieValue {
return false
}
ipCookie, err := r.Cookie(ipCookieName)
if err != nil {