rewrite server module
This commit is contained in:
@@ -2,17 +2,74 @@ package server
|
||||
|
||||
import (
|
||||
"fes/modules/config"
|
||||
"fes/modules/ui"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var routes map[string]string
|
||||
|
||||
func Start(dir string) {
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("<h1>Sup bitch</h1>"))
|
||||
})
|
||||
if err := os.Chdir(dir); err != nil {
|
||||
ui.Error(fmt.Sprintf("failed to change directory to %s", dir), err)
|
||||
}
|
||||
|
||||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *config.Port), nil))
|
||||
ui.Log("running root=%s, port=%d.", filepath.Clean(dir), *config.Port)
|
||||
|
||||
routes := loadDirs()
|
||||
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
route, ok := routes[r.URL.Path]
|
||||
|
||||
var err error = nil
|
||||
|
||||
/* defer won't update paramaters unless we do this. */
|
||||
defer func() {
|
||||
ui.Path(route, err)
|
||||
}()
|
||||
|
||||
if !ok {
|
||||
err = config.ErrRouteMiss
|
||||
route = r.URL.Path
|
||||
|
||||
if strings.HasPrefix(route, "/archive") {
|
||||
err = readArchive(w, route)
|
||||
} else {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte("not found :("))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
params := make(map[string]string)
|
||||
for k, v := range r.URL.Query() {
|
||||
if len(v) > 0 {
|
||||
params[k] = v[0]
|
||||
}
|
||||
}
|
||||
|
||||
var data []byte
|
||||
if strings.HasSuffix(route, ".lua") {
|
||||
data, err = render(route, reqData{path: r.URL.Path, params: params})
|
||||
} else if strings.HasSuffix(route, ".md") {
|
||||
data, err = os.ReadFile(route)
|
||||
data = []byte(markdownToHTML(string(data)))
|
||||
data = []byte("<style>body {max-width: 80ch;}</style>\n" + string(data))
|
||||
} else {
|
||||
data, err = os.ReadFile(route)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Error loading page: %v", err), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
w.Write(data)
|
||||
})
|
||||
ui.Log("Server initialized")
|
||||
|
||||
log.Fatal(http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", *config.Port), nil))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user