Update 'main.go'

This commit is contained in:
Gyula Kerezsi
2018-10-03 12:30:53 +00:00
parent bd6c056660
commit 79d466d13d

70
main.go Normal file
View File

@@ -0,0 +1,70 @@
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"strings"
"time"
)
func makeServer(addr string) *http.Server {
srv := &http.Server{Addr: addr}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
proto := r.Header.Get("X-Forwarded-Proto")
if !strings.HasSuffix(proto, "://") {
if !strings.HasSuffix(proto, ":") {
proto = proto + ":"
}
proto = proto + "//"
}
newURL := strings.ToLower(proto + r.Host + r.RequestURI)
if os.Getenv("DEBUG") != "true" {
log.Print(newURL)
}
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
})
return srv
}
func main() {
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
addr := os.Getenv("ADDR")
if addr == "" {
addr = "127.0.0.1"
}
srv := makeServer(addr + ":" + port)
go func() {
log.Print("listening on http://" + addr + ":" + port)
if err := srv.ListenAndServe(); err != nil {
log.Fatal(err)
}
}()
<-stop
log.Print("Shutting down...")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
srv.Shutdown(ctx)
log.Print("Shut Down")
}