Home >Backend Development >Golang >How to Efficiently Redirect HTTP to HTTPS in Go?

How to Efficiently Redirect HTTP to HTTPS in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 17:38:11749browse

How to Efficiently Redirect HTTP to HTTPS in Go?

Redirecting HTTP to HTTPS in Go

This article addresses the issue of redirecting HTTP traffic to HTTPS in Go applications. Despite setting up TLS successfully, understanding how to implement this redirection efficiently is crucial.

Establishing the Redirection Handler

To initiate the redirection, create a handler that handles the redirection to HTTPS. Here's an example:

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

This handler will redirect HTTP requests to their corresponding HTTPS counterparts, using the IP address and port 443.

Redirecting HTTP Traffic

Once the redirection handler is established, it's necessary to redirect incoming HTTP traffic to it. This can be achieved by launching a goroutine that listens on port 80 and serves the redirection handler:

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

This goroutine will continuously listen on port 80 and redirect any incoming HTTP requests to HTTPS, effectively ensuring that all traffic is encrypted.

The above is the detailed content of How to Efficiently Redirect HTTP to HTTPS in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn