This commit is contained in:
51
server.go
51
server.go
@ -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)
|
||||
|
Reference in New Issue
Block a user