configui/server.go

80 lines
1.9 KiB
Go

package configui
import (
"log"
"net/http"
"strings"
)
func (cui *ConfigUI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cui.middleware(cui.mux()).ServeHTTP(w, r)
}
func (cui *ConfigUI) middleware(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// log.Println(r.URL)
rw := &CuiResponseWriter{w, 0}
defer catch(rw, r)
ip := GetIP(r)
if cui.AllowIP != "" {
if !matchIPGlob(ip, cui.AllowIP) {
rw.WriteHeader(403)
panic("permission denied")
}
}
next.ServeHTTP(rw, r)
//logging
if !strings.HasPrefix(r.URL.Path, "/public") && r.URL.Query().Get("f") != "true" {
log.Printf("%s %s %d %s %s\n", ip, r.Method, rw.StatueCode, r.URL, r.Header.Get("User-Agent"))
}
},
)
}
func (cui *ConfigUI) mux() *http.ServeMux {
cuiR := http.NewServeMux()
cuiR.HandleFunc("/api/conf", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
cui.GetConfig(w, r)
} else if r.Method == "POST" {
cui.PostConfig(w, r)
} else {
w.WriteHeader(404)
}
})
cuiR.HandleFunc("/api/files", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
cui.ListFiles(w, r)
} else {
w.WriteHeader(404)
}
})
cuiR.HandleFunc("/api/file", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
cui.GetFile(w, r)
} else if r.Method == "POST" {
cui.PostFile(w, r)
} else {
w.WriteHeader(404)
}
})
cuiR.HandleFunc("/api/apply", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
cui.Apply(w, r)
} else {
w.WriteHeader(404)
}
})
cuiR.HandleFunc("/api/export", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
cui.Download(w, r)
} else {
w.WriteHeader(404)
}
})
cuiR.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.FS(cui.PublicFS))))
cuiR.HandleFunc("/", cui.App)
return cuiR
}