1
0

middleware.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package webserv
  2. import (
  3. "net/http"
  4. "path/filepath"
  5. "strings"
  6. "imuslab.com/zoraxy/mod/utils"
  7. )
  8. // Convert a request path (e.g. /index.html) into physical path on disk
  9. func (ws *WebServer) resolveFileDiskPath(requestPath string) string {
  10. fileDiskpath := filepath.Join(ws.option.WebRoot, "html", requestPath)
  11. //Force convert it to slash even if the host OS is on Windows
  12. fileDiskpath = filepath.Clean(fileDiskpath)
  13. fileDiskpath = strings.ReplaceAll(fileDiskpath, "\\", "/")
  14. return fileDiskpath
  15. }
  16. // File server middleware to handle directory listing (and future expansion)
  17. func (ws *WebServer) fsMiddleware(h http.Handler) http.Handler {
  18. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  19. if !ws.option.EnableDirectoryListing {
  20. if strings.HasSuffix(r.URL.Path, "/") {
  21. //This is a folder. Let check if index exists
  22. if utils.FileExists(filepath.Join(ws.resolveFileDiskPath(r.URL.Path), "index.html")) {
  23. } else if utils.FileExists(filepath.Join(ws.resolveFileDiskPath(r.URL.Path), "index.htm")) {
  24. } else {
  25. http.NotFound(w, r)
  26. return
  27. }
  28. }
  29. }
  30. h.ServeHTTP(w, r)
  31. })
  32. }