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

How to Redirect HTTP to HTTPS in a Go Application?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 08:42:111051browse

How to Redirect HTTP to HTTPS in a Go Application?

How to Redirect HTTP Traffic to HTTPS in Go

Problem:

You've enabled TLS, allowing your Go application to accept HTTPS connections. However, you also want to redirect HTTP traffic to HTTPS.

Solution:

Create a custom handler to handle HTTP traffic and redirect it to HTTPS:

import (
    "net/http"
)

func redirectToTls(w http.ResponseWriter, r *http.Request) {
    // If you are serving on Go servers, you can use "r.Host"
    http.Redirect(w, r, "https://your-domain-name.com"+r.RequestURI, http.StatusMovedPermanently)
}

Next, add the following code to redirect HTTP traffic:

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

This will start a separate goroutine for handling HTTP traffic, where it redirects incoming HTTP requests to their HTTPS counterparts.

The above is the detailed content of How to Redirect HTTP to HTTPS in a Go Application?. 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