103 lines
2.4 KiB
Go
103 lines
2.4 KiB
Go
package web
|
|
|
|
import (
|
|
"html/template"
|
|
"net/http"
|
|
"path/filepath"
|
|
"pool-stats/helpers"
|
|
|
|
"fmt"
|
|
|
|
"github.com/gofrs/uuid/v5"
|
|
"github.com/ostafen/clover/v2"
|
|
)
|
|
|
|
type WebServer struct {
|
|
db *clover.DB
|
|
port int
|
|
templates *template.Template
|
|
sessions map[string]string
|
|
adminPassword string
|
|
}
|
|
|
|
func NewWebServer(db *clover.DB, port int, adminPassword string) *WebServer {
|
|
templates := template.New("base").Funcs(template.FuncMap{
|
|
"add": func(a, b int) int { return a + b },
|
|
"sub": func(a, b int) int { return a - b },
|
|
"humanDiff": helpers.HumanDiff,
|
|
"formatHashrate": helpers.FormatHashrate,
|
|
"formatCreateDate": helpers.FormatCreateDate,
|
|
})
|
|
|
|
templates = template.Must(templates.ParseFiles(
|
|
"templates/layout.html",
|
|
))
|
|
|
|
return &WebServer{
|
|
db: db,
|
|
port: port,
|
|
templates: templates,
|
|
sessions: make(map[string]string),
|
|
adminPassword: adminPassword,
|
|
}
|
|
}
|
|
|
|
func (ws *WebServer) Start() error {
|
|
http.HandleFunc("/", ws.IndexHandler)
|
|
http.HandleFunc("/cp", ws.ControlPanelHandler)
|
|
http.HandleFunc("/login", ws.LoginHandler)
|
|
http.HandleFunc("/logout", ws.LogoutHandler)
|
|
http.HandleFunc("/shares", ws.SharesHandler)
|
|
http.HandleFunc("/top-shares", ws.TopSharesHandler)
|
|
http.HandleFunc("/daily-stats", ws.DailyStatsHandler)
|
|
|
|
address := ":" + fmt.Sprint(ws.port)
|
|
println("Listening on", address)
|
|
return http.ListenAndServe(address, nil)
|
|
}
|
|
|
|
func generateSessionID() string {
|
|
uuid, err := uuid.NewV4()
|
|
if err != nil {
|
|
fmt.Println("Error generating session ID:", err)
|
|
return ""
|
|
}
|
|
|
|
return uuid.String()
|
|
}
|
|
|
|
func (ws *WebServer) getUser(r *http.Request) string {
|
|
cookie, err := r.Cookie("session_id")
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
if user, ok := ws.sessions[cookie.Value]; ok {
|
|
return user
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (ws *WebServer) renderTemplate(
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
templateFile string,
|
|
data IPageDataBase) {
|
|
|
|
data.SetUserName(ws.getUser(r))
|
|
|
|
tmpl, err := template.Must(ws.templates.Clone()).ParseFiles(templateFile)
|
|
if err != nil {
|
|
http.Error(w, "Failed to parse template", 500)
|
|
println("Error parsing template:", err.Error())
|
|
return
|
|
}
|
|
|
|
templateName := filepath.Base(templateFile)
|
|
|
|
if err := tmpl.ExecuteTemplate(w, templateName, data); err != nil {
|
|
http.Error(w, "Failed to render template", 500)
|
|
println("Error rendering template:", err.Error())
|
|
return
|
|
}
|
|
}
|