member-console/cmd/start.go

73 lines
2.2 KiB
Go

/*
Copyright © 2025 Wiki Cafe <mail@wiki.cafe>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"log"
"net/http"
"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(
middleware.Logging,
)
server := http.Server{
Addr: ":" + port,
Handler: stack(httpRequestRouter),
}
// 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)
}