Skip to content

Instantly share code, notes, and snippets.

@dmitshur
Last active September 6, 2017 08:32
Show Gist options
  • Save dmitshur/bf19e90ca5cf502c7de2 to your computer and use it in GitHub Desktop.
Save dmitshur/bf19e90ca5cf502c7de2 to your computer and use it in GitHub Desktop.
Server for HTTP protocol. Redirects all requests to HTTPS.
// Server for HTTP protocol. Redirects all requests to HTTPS.
package main
import (
"flag"
"log"
"net/http"
)
var (
httpFlag = flag.String("http", ":http", "Listen for HTTP connections on this address.")
)
func main() {
flag.Parse()
err := http.ListenAndServe(*httpFlag, httpToHTTPSRedirector{})
if err != nil {
log.Fatalln(err)
}
}
// httpToHTTPSRedirector redirects all requests from http to https.
type httpToHTTPSRedirector struct{}
func (httpToHTTPSRedirector) ServeHTTP(w http.ResponseWriter, req *http.Request) {
u := *req.URL
u.Scheme = "https"
u.Host = req.Host
/* TODO: Figure out if I should do this, and if this is the best way.
req.Header.Set("Connection", "close")
req.Close = true*/
// TODO: Should this be changed to http.StatusMovedPermanently?
http.Redirect(w, req, u.String(), http.StatusTemporaryRedirect)
}
@mholt
Copy link

mholt commented Feb 28, 2016

L27 is clever; for some reason, dereferencing the URL never occurred to me, but it seems useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment