Move handler out of cmd and into separate pacakge
This commit is contained in:
@@ -1,156 +0,0 @@
|
||||
package main
|
||||
|
||||
import "log"
|
||||
import "fmt"
|
||||
import "path"
|
||||
import "io/fs"
|
||||
import "strings"
|
||||
import "strconv"
|
||||
import "net/http"
|
||||
import "path/filepath"
|
||||
import "git.tebibyte.media/sashakoshka/step"
|
||||
import "git.tebibyte.media/sashakoshka/goutil/container"
|
||||
|
||||
type handler struct {
|
||||
environment *step.Environment
|
||||
directories bool
|
||||
stepExt ucontainer.Set[string]
|
||||
index []string
|
||||
}
|
||||
|
||||
func (this *handler) ServeHTTP (res http.ResponseWriter, req *http.Request) {
|
||||
remoteAddr := req.RemoteAddr
|
||||
if addr := req.Header.Get("CF-Connecting-IP"); addr != "" {
|
||||
remoteAddr = fmt.Sprintf("%s --CF-> %s", addr, req.RemoteAddr)
|
||||
} else if addr := req.Header.Get("X-Forwarded-For"); addr != "" {
|
||||
remoteAddr = fmt.Sprintf("%s --??-> %s", addr, req.RemoteAddr)
|
||||
}
|
||||
log.Println("(i)", req.Method, req.URL, "from", remoteAddr)
|
||||
filesystem := this.environment.GetFS()
|
||||
|
||||
// normalize path
|
||||
pat := req.URL.Path
|
||||
if !strings.HasPrefix(pat, "/") {
|
||||
pat = "/" + pat
|
||||
req.URL.Path = pat
|
||||
}
|
||||
pat = path.Clean(req.URL.Path)
|
||||
|
||||
info, err := statFile(filesystem, pathToName(pat))
|
||||
if err != nil {
|
||||
// TODO need more detailed error, should allow specifying error
|
||||
// documents
|
||||
this.serveError(res, req, http.StatusNotFound, req.URL)
|
||||
return
|
||||
}
|
||||
if info.IsDir() {
|
||||
// try to find an index
|
||||
for _, base := range this.index {
|
||||
currentPath := path.Join(pat, base)
|
||||
info, err := statFile(filesystem, pathToName(currentPath))
|
||||
if err != nil { continue }
|
||||
if info.IsDir() { continue }
|
||||
this.serveFile(res, req, filesystem, currentPath)
|
||||
return
|
||||
}
|
||||
|
||||
if !this.directories {
|
||||
this.serveError(res, req, http.StatusForbidden, req.URL)
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: serve a directory and return
|
||||
// have a custom directory listing document that takes in a list
|
||||
// of the files in the directory and the path to the directory
|
||||
// as data
|
||||
}
|
||||
|
||||
this.serveFile(res, req, filesystem, pat)
|
||||
}
|
||||
|
||||
func (this *handler) serveFile (res http.ResponseWriter, req *http.Request, filesystem fs.FS, pat string) {
|
||||
name := pathToName(pat)
|
||||
if !this.stepExt.Has(filepath.Ext(name)) {
|
||||
// just a normal file
|
||||
http.ServeFileFS(res, req, this.environment.GetFS(), name)
|
||||
return
|
||||
}
|
||||
|
||||
// parse
|
||||
document, err := this.environment.Parse(name)
|
||||
if err != nil {
|
||||
this.serveError(res, req, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
// set up HTTP response recorder
|
||||
recorder := step.HTTPResponseRecorder { }
|
||||
resetRecorder := func () {
|
||||
recorder.Reset()
|
||||
recorder.Head = res.Header().Clone()
|
||||
}
|
||||
if contentType, ok := document.FrontMatter["content-type"]; ok {
|
||||
recorder.Header().Set("Content-Type", contentType)
|
||||
}
|
||||
if status, ok := document.FrontMatter["status"]; ok {
|
||||
if status, err := strconv.Atoi(status); err == nil {
|
||||
recorder.Status = status
|
||||
}
|
||||
}
|
||||
|
||||
// execute document
|
||||
data := step.HTTPData { }
|
||||
data.Res.Header = recorder.Header()
|
||||
data.Res.WriteHeader = recorder.WriteHeader
|
||||
data.Res.Reset = resetRecorder
|
||||
data.Req = req
|
||||
err = document.Execute(&recorder, step.ExecutionData {
|
||||
Data: data,
|
||||
})
|
||||
if err != nil {
|
||||
this.serveError(res, req, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
// play back recorded response
|
||||
err = recorder.Play(res)
|
||||
if err != nil {
|
||||
this.logErr(name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (this *handler) serveError (res http.ResponseWriter, req *http.Request, status int, message any) {
|
||||
res.Header().Add("Content-Type", "text/plain")
|
||||
res.WriteHeader(status)
|
||||
// TODO: allow customization with templates
|
||||
if message == nil {
|
||||
fmt.Fprintf(res, "%d %s\n", status, http.StatusText(status))
|
||||
} else {
|
||||
fmt.Fprintf(res, "%d %s: %v\n", status, http.StatusText(status), message)
|
||||
}
|
||||
log.Printf("ERR %d %s: %v\n", status, http.StatusText(status), message)
|
||||
}
|
||||
|
||||
func (this *handler) logErr (name string, err error) {
|
||||
log.Printf("ERR %s: %v\n", name, err)
|
||||
}
|
||||
|
||||
func statFile (filesystem fs.FS, name string) (fs.FileInfo, error) {
|
||||
if filesystem, ok := filesystem.(fs.StatFS); ok {
|
||||
return filesystem.Stat(name)
|
||||
}
|
||||
file, err := filesystem.Open(name)
|
||||
if err != nil { return nil, err }
|
||||
defer file.Close()
|
||||
return file.Stat()
|
||||
}
|
||||
|
||||
func pathToName (pat string) string {
|
||||
if strings.HasPrefix(pat, "/") {
|
||||
pat = strings.TrimPrefix(pat, "/")
|
||||
}
|
||||
if pat == "" {
|
||||
return "."
|
||||
}
|
||||
return pat
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import "git.tebibyte.media/sashakoshka/go-cli"
|
||||
import "git.tebibyte.media/sashakoshka/step/providers"
|
||||
import "git.tebibyte.media/sashakoshka/goutil/container"
|
||||
import "git.tebibyte.media/sashakoshka/go-service/daemon"
|
||||
import stephttp"git.tebibyte.media/sashakoshka/step/http"
|
||||
import "git.tebibyte.media/sashakoshka/go-service/routines"
|
||||
|
||||
func main () {
|
||||
@@ -45,11 +46,11 @@ func main () {
|
||||
if err != nil { log.Fatal(err) }
|
||||
|
||||
// set up the HTTP handler
|
||||
handler := handler {
|
||||
environment: &environment,
|
||||
directories: flagDirectories.Value == "true",
|
||||
stepExt: ucontainer.NewSet(".step"),
|
||||
index: []string { "index.step", "index.html", "index" },
|
||||
handler := stephttp.Handler {
|
||||
Environment: &environment,
|
||||
Directories: flagDirectories.Value == "true",
|
||||
StepExt: ucontainer.NewSet(".step"),
|
||||
Index: []string { "index.step", "index.html", "index" },
|
||||
}
|
||||
|
||||
// set up the HTTP server
|
||||
|
||||
Reference in New Issue
Block a user