From c0e58d89c46877d2b87a6f252ab9cac3454053f1 Mon Sep 17 00:00:00 2001 From: Gyula Kerezsi Date: Wed, 3 Oct 2018 12:29:54 +0000 Subject: [PATCH] add main.go --- mian.go | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 mian.go diff --git a/mian.go b/mian.go new file mode 100644 index 0000000..2bd52c4 --- /dev/null +++ b/mian.go @@ -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") +}