forked from xmdhs/clash2sfa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (70 loc) · 1.62 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
package main
import (
_ "embed"
"fmt"
"net/http"
"os"
"strconv"
"sync/atomic"
"time"
"log/slog"
"github.com/xmdhs/clash2sfa/db"
"github.com/xmdhs/clash2sfa/handle"
"github.com/xmdhs/clash2sfa/utils"
)
//go:embed config.json.template
var configByte []byte
//go:embed frontend.html
var frontendByte []byte
func main() {
port := ":8080"
if p := os.Getenv("port"); p != "" {
port = p
}
db, err := db.NewBBolt("bbolt.db")
if err != nil {
panic(err)
}
levels := os.Getenv("level")
leveln, err := strconv.Atoi(levels)
if err != nil {
leveln = -4
}
level := &slog.LevelVar{}
level.Set(slog.Level(leveln))
c := &http.Client{
Timeout: 10 * time.Second,
}
l := slog.New(&warpSlogHandle{
Handler: slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: level,
}),
})
mux := http.NewServeMux()
mux.HandleFunc("/put", handle.PutArg(db, l))
mux.HandleFunc("/sub", handle.Sub(c, db, configByte, l))
mux.HandleFunc("/config", handle.Frontend(configByte, 604800))
mux.HandleFunc("/", handle.Frontend(frontendByte, 604800))
trackid := atomic.Uint64{}
s := http.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 20 * time.Second,
ReadHeaderTimeout: 5 * time.Second,
Addr: port,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if l.Enabled(ctx, slog.LevelDebug) {
ip, _ := utils.GetIP(r)
trackid.Add(1)
ctx = setCtx(ctx, &reqInfo{
URL: r.URL.String(),
IP: ip,
TrackId: trackid.Load(),
})
r = r.WithContext(ctx)
}
mux.ServeHTTP(w, r)
}),
}
fmt.Println(s.ListenAndServe())
}