Files
Admin/main.go
metacryst 5ba9bae02c init
2025-04-08 11:53:18 -05:00

114 lines
2.6 KiB
Go

// main.go
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"time"
"Admin/src"
)
type RequestInfo struct {
Timestamp string `json:"timestamp"`
Host string `json:"host"`
IP string `json:"ip"`
Path string `json:"path"`
Method string `json:"method"`
}
// Global store for request logs
var (
requests []RequestInfo
mu sync.Mutex
)
func isLocalIP(ipStr string) bool {
if ipStr == "[::1]" {
return true
}
return false
}
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
cleanIP, _, _ := strings.Cut(ip, ":") // Split at first colon, ignore port
cleanIP = strings.Trim(cleanIP, "[]") // Remove IPv6 brackets
cleanIP = strings.TrimPrefix(cleanIP, "::ffff:")
path := r.URL.Path[1:]
if path == "" {
path = "/"
}
now := time.Now()
formattedTime := fmt.Sprintf("%d.%d %d:%02d:%02d%s",
now.Month(), now.Day(), now.Hour()%12, now.Minute(), now.Second(),
map[bool]string{true: "am", false: "pm"}[now.Hour() < 12])
ipWithPort := r.RemoteAddr
ipWithPort = ipWithPort[:strings.LastIndex(ipWithPort, ":")] // Trim port for isLocalIP
if isLocalIP(ipWithPort) {
log.Printf("%s %s %s", r.Host, cleanIP, path)
} else {
log.Printf("%s %s \033[33m%s%s\033[0m", formattedTime, cleanIP, r.Host, path)
}
// Add request info to global store
mu.Lock()
requests = append(requests, RequestInfo{
Timestamp: time.Now().Format(time.RFC3339), // e.g., "2025-03-26T12:34:56Z"
Host: r.Host,
IP: cleanIP,
Path: path,
Method: r.Method,
})
mu.Unlock()
next(w, r)
}
}
func outsideHandler(w http.ResponseWriter, r *http.Request) {
if r.Host == "america.sun.museum" {
target, _ := url.Parse("http://localhost:8000")
proxy := httputil.NewSingleHostReverseProxy(target)
r.Host = target.Host
proxy.ServeHTTP(w, r)
return
} else
if r.Host == "admin.sun.museum" {
src.BetaSignupHandler(w, r)
return
}
fmt.Fprintf(w, "Hello, World! You're from outside.")
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
ip = ip[:strings.LastIndex(ip, ":")] // Trim port
if isLocalIP(ip) {
src.UIServer(w, r)
} else {
outsideHandler(w, r)
}
}
func main() {
log.SetFlags(0)
http.HandleFunc("/", loggingMiddleware(rootHandler))
certFile := "/etc/letsencrypt/live/parchment.page/fullchain.pem"
keyFile := "/etc/letsencrypt/live/parchment.page/privkey.pem"
log.Println("Server running on port 3000")
err := http.ListenAndServeTLS(":3000", certFile, keyFile, nil)
if err != nil {
log.Fatalf("Server failed: %v", err)
}
}