kconfig/kconfig.go

60 lines
1.0 KiB
Go

package kconfig
import (
_ "embed"
"net/http"
"strings"
"kumoly.io/lib/guard/engine"
"kumoly.io/tools/kconfig/public"
)
//go:embed public/index.html
var index string
var servePublic = http.FileServer(http.FS(public.FS))
var tmpl *engine.Engine
func init() {
tmpl = engine.Must(engine.New("").Parse(index))
}
type Kconfig struct {
AppName string
KFJstr string
Mux *http.ServeMux
OnSave func(string) error
Get func() string
}
func New() *Kconfig {
k := &Kconfig{}
mux := http.NewServeMux()
mux.HandleFunc("/", k.App)
k.Mux = mux
return k
}
func (k *Kconfig) ServeHTTP(w http.ResponseWriter, r *http.Request) {
k.Mux.ServeHTTP(w, r)
}
func (k *Kconfig) App(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
tmpl.Execute(w, struct{ AppName string }{k.AppName})
return
}
file, err := public.FS.Open(strings.TrimPrefix(r.URL.String(), "/"))
if err != nil {
http.NotFound(w, r)
return
}
stat, err := file.Stat()
if err != nil || stat.IsDir() {
http.NotFound(w, r)
return
}
servePublic.ServeHTTP(w, r)
}