Skip to content

Commit 08913f5

Browse files
committed
server: improve routing logic
1 parent ff07500 commit 08913f5

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

internal/server/server.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"net/http"
77
"os"
88
"strconv"
9+
"strings"
910
"time"
1011

1112
"github.com/armbian/ansi-hastebin/config"
@@ -67,28 +68,27 @@ func (s *Server) RegisterRoutes() {
6768

6869
// Register static files
6970
static := os.DirFS("static")
70-
s.mux.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
71-
id := chi.URLParam(r, "id")
72-
if file, err := static.Open(id); err == nil {
73-
defer file.Close()
74-
io.Copy(w, file)
71+
fileServer := http.FileServer(http.FS(static))
72+
73+
s.mux.Get("/*", func(w http.ResponseWriter, r *http.Request) {
74+
path := strings.TrimPrefix(r.URL.Path, "/")
75+
if _, err := static.Open(path); err == nil {
76+
fileServer.ServeHTTP(w, r)
7577
return
7678
}
7779

80+
// If file does not exist, serve index.html
7881
index, err := static.Open("index.html")
7982
if err != nil {
8083
http.Error(w, "Not found", http.StatusNotFound)
8184
return
8285
}
83-
8486
defer index.Close()
8587

86-
io.Copy(w, index)
87-
})
88-
89-
fileServer := http.StripPrefix("/", http.FileServer(http.FS(static)))
90-
s.mux.Get("/*", func(w http.ResponseWriter, r *http.Request) {
91-
fileServer.ServeHTTP(w, r)
88+
if _, err := io.Copy(w, index); err != nil {
89+
http.Error(w, "Internal server error", http.StatusInternalServerError)
90+
return
91+
}
9292
})
9393
}
9494

0 commit comments

Comments
 (0)