91 lines
2.6 KiB
Go
91 lines
2.6 KiB
Go
package cmd
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.coopcloud.tech/wiki-cafe/member-console/internal/middleware"
|
|
"github.com/spf13/cobra"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
var startCmd = &cobra.Command{
|
|
Use: "start",
|
|
Short: "Start serving the member-console web application",
|
|
Long: `The start command starts an HTTP server that serves the member-console web
|
|
application from the components directory in the current directory.
|
|
|
|
The server listens on port 8080 by default, unless a different port is specified using the --port flag.`,
|
|
Args: cobra.NoArgs,
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
// Retrieve the port value from Viper
|
|
port := viper.GetString("port")
|
|
|
|
// Create a new HTTP request router
|
|
httpRequestRouter := http.NewServeMux()
|
|
|
|
// Create a middleware stack
|
|
stack := middleware.CreateStack(
|
|
loggingMiddleware,
|
|
authMiddleware,
|
|
)
|
|
|
|
server := http.Server{
|
|
Addr: ":" + port,
|
|
Handler: stack(httpRequestRouter),
|
|
}
|
|
|
|
// Register the login page handler
|
|
httpRequestRouter.HandleFunc("/login", serveLoginPage)
|
|
|
|
// Serve the components directory
|
|
httpRequestRouter.Handle("/", http.FileServer(http.Dir("./components")))
|
|
log.Println("Starting server on port", port)
|
|
log.Fatal(server.ListenAndServe())
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
// Register the port flag with Cobra
|
|
startCmd.Flags().StringP("port", "p", "", "Port to listen on")
|
|
|
|
// Bind the flag to Viper
|
|
viper.BindPFlag("port", startCmd.Flags().Lookup("port"))
|
|
|
|
// Set a default value for the port if no flag or env variable is provided
|
|
viper.SetDefault("port", "8080")
|
|
|
|
// Add the command to the root command
|
|
rootCmd.AddCommand(startCmd)
|
|
}
|
|
|
|
// authMiddleware is a simple middleware function that checks for a valid session cookie
|
|
func authMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Check for the session cookie
|
|
cookie, err := r.Cookie("session")
|
|
if err != nil || cookie.Value != "authenticated" {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
// Call the next handler
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// loggerMiddleware is a simple middleware function that logs the request method and URL
|
|
func loggingMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
next.ServeHTTP(w, r)
|
|
log.Println(r.Method, r.URL.Path, time.Since(start))
|
|
})
|
|
}
|
|
|
|
// serveLoginPage is a simple handler function that serves the login page
|
|
func serveLoginPage(w http.ResponseWriter, r *http.Request) {
|
|
http.ServeFile(w, r, "./components/login.html")
|
|
}
|