更新 server.go
All checks were successful
K5web Build / linux (1.17, 20) (push) Successful in 2m32s

This commit is contained in:
2025-05-05 17:14:14 +08:00
parent 56023af2a6
commit adc580ecfe

View File

@ -8,7 +8,6 @@ import (
"net/http"
"io/fs"
"os"
"strings"
)
//go:embed dist/*
@ -24,31 +23,31 @@ var serverKey []byte
var httpsPort string
// func redirectToHTTPS(w http.ResponseWriter, r *http.Request) {
// http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
// }
func redirectToHTTPS(w http.ResponseWriter, r *http.Request) {
// 确保在重定向时包含正确的 HTTPS 端口
httpsHost := r.Host
// 检查是否已经有端口号,如果没有再加上端口
if !strings.Contains(r.Host, ":") {
if httpsPort != "443" { // 如果 HTTPS 端口不是默认的 443
httpsHost = fmt.Sprintf("%s:%s", r.Host, httpsPort)
}
}
http.Redirect(w, r, "https://"+httpsHost+r.RequestURI, http.StatusMovedPermanently)
http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
}
// func redirectToHTTPS(w http.ResponseWriter, r *http.Request) {
// // 确保在重定向时包含正确的 HTTPS 端口
// httpsHost := r.Host
// // 检查是否已经有端口号,如果没有再加上端口
// if !strings.Contains(r.Host, ":") {
// if httpsPort != "443" { // 如果 HTTPS 端口不是默认的 443
// httpsHost = fmt.Sprintf("%s:%s", r.Host, httpsPort)
// }
// }
// http.Redirect(w, r, "https://"+httpsHost+r.RequestURI, http.StatusMovedPermanently)
// }
func main() {
// Get ports from environment variables, with default values
httpPort := os.Getenv("HTTP_PORT")
if httpPort == "" {
httpPort = "80"
}
// httpPort := os.Getenv("HTTP_PORT")
// if httpPort == "" {
// httpPort = "80"
// }
httpsPort := os.Getenv("HTTPS_PORT")
if httpsPort == "" {
@ -80,12 +79,12 @@ func main() {
})
// Start HTTP server for redirecting to HTTPS
go func() {
fmt.Printf("Starting HTTP server on http://127.0.0.1:%s\n", httpPort)
if err := http.ListenAndServe(":"+httpPort, http.HandlerFunc(redirectToHTTPS)); err != nil {
log.Fatalf("HTTP server failed to start: %v", err)
}
}()
// go func() {
// fmt.Printf("Starting HTTP server on http://127.0.0.1:%s\n", httpPort)
// if err := http.ListenAndServe(":"+httpPort, http.HandlerFunc(redirectToHTTPS)); err != nil {
// log.Fatalf("HTTP server failed to start: %v", err)
// }
// }()
// Load embedded certificates
cert, err := tls.X509KeyPair(serverCert, serverKey)