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

How to Redirect HTTP to HTTPS in a Go Web Application?

DDD
Release: 2024-11-28 17:59:12
Original
327 people have browsed it

How to Redirect HTTP to HTTPS in a Go Web Application?

Handling HTTP to HTTPS Redirection in Go

When deploying a TLS-enabled Go web application, redirecting HTTP traffic to HTTPS is crucial for security and maintaining a secure connection. Here's how to achieve this effectively:

Implement a custom HTTP handler responsible for handling the redirection. Define a function like the following:

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

In this handler, we create an HTTPS redirect to the same URI using the HTTP status code "Moved Permanently" (301).

Next, we need to handle HTTP traffic and redirect it to the HTTPS URL. Add the following code to your main Go file:

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

This code creates a separate Go routine that listens on port 80 for HTTP traffic. When a request arrives, it redirects to the HTTPS URL using the redirectToTls handler.

This approach allows you to seamlessly redirect HTTP traffic to HTTPS and maintain a secure connection for your Go web application.

The above is the detailed content of How to Redirect HTTP to HTTPS in a Go Web Application?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template