Skip to content

Instantly share code, notes, and snippets.

@tnhu
Forked from ericchiang/https_server.go
Created September 29, 2015 01:01
Show Gist options
  • Save tnhu/a366b1bb20542573bab8 to your computer and use it in GitHub Desktop.
Save tnhu/a366b1bb20542573bab8 to your computer and use it in GitHub Desktop.
Golang HTTPS server
package main
import (
"net/http"
"strings"
)
/*
Generate cert.pem and key.pem with:
openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem
Taken from https://docs.nodejitsu.com/articles/HTTP/servers/how-to-create-a-HTTPS-server
*/
var (
httpPort string = ":3031"
httpsPort string = ":3030"
)
// HTTPSRedirectFunc redirects from http to https
func HTTPSRedirectFunc(w http.ResponseWriter, r *http.Request) {
url := r.URL
url.Scheme = "https"
urlParts := strings.Split(url.Host, ":")
url.Host = urlParts[0] + ":" + httpsPort
http.Redirect(w, r, url.String(), http.StatusMovedPermanently)
}
func HelloHandlerFunc(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello\n"))
}
var (
HelloHandler http.Handler = http.HandlerFunc(HelloHandlerFunc)
HTTPSRedirecter http.Handler = http.HandlerFunc(HTTPSRedirectFunc)
)
func main() {
go http.ListenAndServeTLS(httpsPort, "cert.pem", "key.pem", HelloHandler)
http.ListenAndServe(httpPort, HTTPSRedirecter)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment