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
Release: 2024-12-04 08:42:11
Original
1027 people have browsed it

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)
}
Copy after login

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)
        }
    }()
Copy after login

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!

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