add main.go
This commit is contained in:
70
mian.go
Normal file
70
mian.go
Normal 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")
|
||||
}
|
||||
Reference in New Issue
Block a user