2016-05-31 20 views
8

Podniosłem TLS i to działa. Wiem, jak przepisać z http na https w nginx, ale już nie używam nginx. Nie wiem jak to zrobić w Idź poprawnie.Jak przepisać/przekierować z http na https w Go?

func main() { 

    certificate := "/srv/ssl/ssl-bundle.crt" 
    privateKey := "/srv/ssl/mykey.key" 

    http.HandleFunc("/", rootHander) 
    // log.Fatal(http.ListenAndServe(":80", nil)) 
    log.Fatal(http.ListenAndServeTLS(":443", certificate, privateKey, nil)) 
} 

func rootHander(w http.ResponseWriter, r *http.Request) { 
    w.Write([]byte("To the moon!")) 
} 

Jak mogę to zrobić w dobry sposób?

Odpowiedz

5

utworzyć uchwyt, który obsługuje przekierowanie do https jak:

func redirectTLS(w http.ResponseWriter, r *http.Request) { 
    http.Redirect(w, r, "https://IPAddr:443"+r.RequestURI, http.StatusMovedPermanently) 
} 

Następnie przekierować ruch http:

go func() { 
    if err := http.ListenAndServe(":80", http.HandlerFunc(redirectTLS)); err != nil { 
     log.Fatalf("ListenAndServe error: %v", err) 
    } 
}() 
+0

Dziękuję bardzo! – Alex

+1

dla adresu, do którego ma nastąpić przekierowanie, lepiej byłoby użyć '" https: // "+ r.Host + r.RequestURI', co pozwoli uniknąć zakodowania na stałe nazwy hosta lub adresu IP. –

1
Package main 
import (
    "fmt" 
    "net/http" 
) 
func redirectToHttps(w http.ResponseWriter, r *http.Request) { 
    // Redirect the incoming HTTP request. Note that "127.0.0.1:443" will only work if you are accessing the server from your local machine. 
    http.Redirect(w, r, "https://127.0.0.1:443"+r.RequestURI, http.StatusMovedPermanently) 
} 
func handler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "Hi there!") 
    fmt.Println(r.RequestURI) 
} 
func main() { 
    http.HandleFunc("/", handler) 
    // Start the HTTPS server in a goroutine 
    go http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil) 
    // Start the HTTP server and redirect all incoming connections to HTTPS 
    http.ListenAndServe(":8080", http.HandlerFunc(redirectToHttps)) 
} 
+0

Dziękujemy za pomoc! Dałem odpowiedź na inny post, który był kilka godzin wcześniej. Miłego dnia! – Alex

+0

Czy jest tu jakiś problem z wyraźnym adresem 127.0.0.1? Może wymagać połączenia nazwy domeny, np. "Https: //" + domena + r.RequestURI. –

+0

Ponadto 443 to domyślny port dla protokołu HTTPS i można go pominąć. –

Powiązane problemy