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

How to Redirect HTTP to HTTPS in Go?

Patricia Arquette
Release: 2024-11-29 03:27:13
Original
371 people have browsed it

How to Redirect HTTP to HTTPS in Go?

Redirecting from HTTP to HTTPS in Go

In order to enforce HTTPS-only connections, you can redirect HTTP requests to HTTPS counterparts. Here's how to do it effectively in Go:

1. Create a Redirect Handler:

Define a custom HTTP handler that handles the redirection:

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

This handler will redirect all HTTP requests to the corresponding HTTPS URL (replace "IPAddr" with your server's IP address or domain name).

2. Redirect HTTP Traffic:

Start an HTTP server that listens on port 80 and uses the redirect handler:

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

With this setup, all HTTP requests received on port 80 will be automatically redirected to their HTTPS counterparts, ensuring a secure connection to your website.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template