add https support

This commit is contained in:
2025-12-08 19:52:27 -05:00
parent 8dca9ab5da
commit 120d044648
3 changed files with 20 additions and 4 deletions

View File

@@ -19,7 +19,8 @@ import (
var core embed.FS
func init() {
config.Port = flag.Int("p", 3000, "Set the server port")
config.Port = flag.Int("p", 3000, "Set the server port for http")
config.HTTPSPort = flag.Int("ps", 3000, "Set the server port for https")
config.Color = flag.Bool("no-color", false, "Disable color output")
config.Core = core
}

View File

@@ -4,6 +4,7 @@ import "embed"
var Core embed.FS
var Port *int
var HTTPSPort *int
var Color *bool
type MyConfig struct {

View File

@@ -399,7 +399,7 @@ func Start(dir string) error {
}
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
lp, ok := routes[path]
@@ -457,6 +457,20 @@ func Start(dir string) error {
w.Write(data)
})
fmt.Printf("Server is running on http://localhost:%d\n", *config.Port)
return http.ListenAndServe(fmt.Sprintf(":%d", *config.Port), nil)
addrHTTPS := fmt.Sprintf(":%d", *config.HTTPSPort)
addrHTTP := fmt.Sprintf(":%d", *config.Port)
go func() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
target := "https://" + r.Host + r.RequestURI
http.Redirect(w, r, target, http.StatusMovedPermanently)
})
fmt.Printf("Redirecting HTTP to HTTPS on port %d\n", *config.Port)
if err := http.ListenAndServe(addrHTTP, nil); err != nil {
fmt.Printf("HTTP redirect server error: %v\n", err)
}
}()
fmt.Printf("HTTPS server is running on https://localhost:%d\n", *config.HTTPSPort)
return http.ListenAndServeTLS(addrHTTPS, "cert.pem", "key.pem", handler)
}