-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
181 lines (159 loc) · 4.58 KB
/
main.go
File metadata and controls
181 lines (159 loc) · 4.58 KB
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
package main
import (
"context"
"database/sql"
"embed"
"fmt"
"html/template"
"io/fs"
"log/slog"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/cego/go-lib/v2/logger"
"github.com/cego/go-lib/v2/serve"
"github.com/cego/mysql-admin/internal/config"
"github.com/cego/mysql-admin/internal/db"
"github.com/cego/mysql-admin/internal/handler"
)
//go:embed templates
var templateFS embed.FS
//go:embed static
var staticFS embed.FS
var funcMap = template.FuncMap{
"stringToColor": stringToColor,
"blackOrWhite": blackOrWhite,
"formatNumber": formatNumber,
"join": strings.Join,
"nextDir": nextDir,
"sortIndicator": sortIndicator,
"baseParams": baseParams,
"dict": dict,
}
// dict creates a map from alternating key/value pairs, for use in template calls.
func dict(pairs ...any) map[string]any {
m := make(map[string]any, len(pairs)/2)
for i := 0; i+1 < len(pairs); i += 2 {
m[pairs[i].(string)] = pairs[i+1]
}
return m
}
func main() {
cfg := config.Load()
l := logger.New()
slog.SetDefault(l)
// Open one connection pool per instance at startup and reuse across requests.
dbs := make(map[string]*sql.DB, len(cfg.Instances))
for name, inst := range cfg.Instances {
d, err := db.OpenDB(inst)
if err != nil {
slog.Error("failed to open database", "instance", name, "error", err)
os.Exit(1)
}
defer d.Close()
dbs[name] = d
}
homeTmpl := template.Must(template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/layout.html", "templates/home.html"))
instanceTmpl := template.Must(template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/layout.html", "templates/instance.html", "templates/partials/process_table.html"))
tableTmpl := template.Must(template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/partials/process_table.html"))
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
mux.HandleFunc("GET /{$}", handler.Home(cfg, homeTmpl))
mux.HandleFunc("GET /instance/{name}", handler.Instance(cfg, dbs, instanceTmpl, tableTmpl))
mux.HandleFunc("POST /instance/{name}/kill", handler.Kill(cfg, dbs, tableTmpl))
staticSub, _ := fs.Sub(staticFS, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(staticSub)))
srv := serve.WithDefaults(&http.Server{
Addr: ":" + cfg.Port,
Handler: mux,
})
slog.Info("starting server", "port", cfg.Port, "instances", cfg.InstanceNames())
if err := serve.ListenAndServe(context.Background(), srv, l); err != nil {
slog.Error("server error", "error", err)
os.Exit(1)
}
}
func stringToColor(str string) string {
if str == "" {
return "#000000"
}
var hash int32
for _, c := range str {
hash = c + ((hash << 5) - hash)
}
colour := "#"
for i := 0; i < 3; i++ {
value := (hash >> (i * 8)) & 0xff
colour += fmt.Sprintf("%02x", value)
}
return colour
}
func blackOrWhite(hex string) string {
if len(hex) < 7 {
return "#ffffff"
}
r, _ := strconv.ParseInt(hex[1:3], 16, 64)
g, _ := strconv.ParseInt(hex[3:5], 16, 64)
b, _ := strconv.ParseInt(hex[5:7], 16, 64)
brightness := (r*299 + g*587 + b*114) / 1000
if brightness > 155 {
return "#000000"
}
return "#ffffff"
}
func formatNumber(num int64) string {
s := strconv.FormatInt(num, 10)
if len(s) <= 3 {
return s
}
var result []byte
for i, c := range s {
if i > 0 && (len(s)-i)%3 == 0 {
result = append(result, ' ')
}
result = append(result, byte(c))
}
return string(result)
}
// baseParams returns the persistent query-string tail (starting with &) for all
// params that should survive sort/navigation changes: refresh, hidesleep,
// filteruser, filterdb. Append directly to ?sort=X&dir=Y in hx-get URLs.
//
// Returns template.URL so Go's html/template does not re-encode the & separators
// when the value is interpolated inside an href attribute.
func baseParams(autoRefresh, hideSleep bool, filterUser, filterDB string) template.URL {
var b strings.Builder
if autoRefresh {
b.WriteString("&refresh=on")
}
if !hideSleep {
b.WriteString("&hidesleep=off")
}
if filterUser != "" {
b.WriteString("&filteruser=" + url.QueryEscape(filterUser))
}
if filterDB != "" {
b.WriteString("&filterdb=" + url.QueryEscape(filterDB))
}
return template.URL(b.String())
}
func nextDir(currentCol, currentDir, col string) string {
if currentCol == col {
if currentDir == "asc" {
return "desc"
}
return "asc"
}
return "asc"
}
func sortIndicator(currentCol, currentDir, col string) string {
if currentCol == col {
if currentDir == "asc" {
return " ▲"
}
return " ▼"
}
return ""
}