Files
old-ibcetvorke/cethttp/cethttp.go
2023-11-27 19:44:23 +01:00

65 lines
1.6 KiB
Go

package cethttp
import (
"embed"
"io/fs"
"log"
"net/http"
"sync"
"github.com/gorilla/mux"
)
//go:embed static/*
var staticFiles embed.FS
// Hardcoded list of usernames and passwords
var users = map[string]string{
"zahf": "Mikrofon savijen dvije case *55",
"teha4": "Subara zvucnik kontroler mobitel *-12",
// Add more users as needed
}
// Middleware for basic authentication
func basicAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || users[username] != password {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized.", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func StartServer(waitgroup *sync.WaitGroup) {
defer waitgroup.Done()
r := mux.NewRouter()
// Serve embedded static files
staticFS, err := fs.Sub(staticFiles, "static")
if err != nil {
log.Fatal("error:", err)
}
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
r.HandleFunc("/p/{postID}/{slug}", postHandler)
r.HandleFunc("/", indexHandler)
r.HandleFunc("/a/", archiveHandler)
r.HandleFunc("/y/{year}/", yearHandler)
r.HandleFunc("/y/{year}/m/{month}/", monthHandler)
// Apply basic authentication middleware to /editor/ routes
editorRouter := r.PathPrefix("/editor/").Subrouter()
editorRouter.Use(basicAuthMiddleware)
editorRouter.HandleFunc("/e/{postID}", editHandler)
editorRouter.HandleFunc("/n/", newHandler)
err = http.ListenAndServe(":8018", r)
if err != nil {
log.Fatal("error:", err)
}
}