commit 2d5e7d73bcc3dff66520eb406634d5d05f691162 Author: Jim Myhrberg Date: Mon May 23 23:24:09 2022 +0100 feat: initial commit diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..99f69c9 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/jimeh/dotkatapult + +go 1.18 diff --git a/main.go b/main.go new file mode 100644 index 0000000..8ca409e --- /dev/null +++ b/main.go @@ -0,0 +1,53 @@ +package main + +import ( + "fmt" + "log" + "net" + "net/http" + "os" + "strings" + "time" +) + +func main() { + srv := &http.Server{ + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + IdleTimeout: 30 * time.Second, + Handler: http.HandlerFunc(handler), + } + + port := "8080" + if v := os.Getenv("PORT"); v != "" { + port = v + } + + ln, err := net.Listen("tcp", ":"+port) + if err != nil { + log.Fatal(err) + } + + log.Fatal(srv.Serve(ln)) +} + +func handler(w http.ResponseWriter, req *http.Request) { + target := "katapult.io" + hostname := strings.SplitN(req.Host, ":", 2)[0] + + if strings.HasSuffix(hostname, ".katapult") { + sub := strings.TrimSuffix(hostname, ".katapult") + switch sub { + case "my": + target = "my.katapult.io" + case "io": + target = "katapult.io" + default: + target = "my.katapult.io/o/" + sub + } + } + + w.Header().Set("Connection", "close") + url := fmt.Sprintf("https://%s", target) + http.Redirect(w, req, url, http.StatusTemporaryRedirect) +}