2016-05-31 17 views
8

Ho installato TLS e funziona. So come riscrivere da http a https in nginx, ma non uso più nginx. Non so come farlo in Go correttamente.Come posso riscrivere/reindirizzare da http a https in 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!")) 
} 

Come farei questo in un buon modo?

risposta

5

Creare un gestore che gestisce il reindirizzamento a https come:

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

quindi reindirizzare il traffico http:

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

grazie mille! – Alex

+1

per l'indirizzo a cui reindirizzare, starai meglio usando "" https: // "+ r.Host + r.RequestURI', che eviterà che il tuo nome host o indirizzo IP sia codificato. –

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

Grazie per l'aiuto! Ho dato la risposta all'altro post che era qualche ora prima. Buona giornata! – Alex

+0

C'è un problema qui con l'indirizzo 127.0.0.1 esplicito? Potrebbe essere necessario il nome di dominio contatenato, ad esempio "https: //" + dominio + r.RequestURI. –

+0

Inoltre, 443 è la porta predefinita per https e può essere omessa. –

Problemi correlati