Skip to content

Instantly share code, notes, and snippets.

@leetrout
Forked from d-schmidt/redirectExample.go
Last active April 29, 2019 21:04
Show Gist options
  • Save leetrout/9f667ace185b95dcc79baece4e8b421c to your computer and use it in GitHub Desktop.
Save leetrout/9f667ace185b95dcc79baece4e8b421c to your computer and use it in GitHub Desktop.
How to redirect HTTP to HTTPS with a golang webserver.
// From https://gist.github.com/d-schmidt/587ceec34ce1334a5e60
package main
import (
"log"
"net/http"
"net/url"
"os"
"strings"
)
var host = os.Getenv("HOST")
var keepPort = os.Getenv("KEEP_PORT")
func redirect(w http.ResponseWriter, r *http.Request) {
toHost := host
if toHost == "" {
toHost = r.Host
}
if keepPort == "" {
toHost = strings.Split(toHost, ":")[0]
}
targetUrl := url.URL{
Scheme: "https",
Host: toHost,
Path: r.URL.Path,
RawQuery: r.URL.RawQuery,
}
log.Printf("redirect to: %s", targetUrl)
http.Redirect(w, r, targetUrl.String(), http.StatusTemporaryRedirect)
}
func main() {
// redirect every http request to https
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
log.Println("listening on", port)
http.ListenAndServe(":"+port, http.HandlerFunc(redirect))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment