commit aff6390b0e5d3aa3139e8a868d14f0309ba4be5e Author: bel Date: Sun Aug 14 22:34:59 2022 -0600 done diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..81a3b9f --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module gogs.inhome.blapointe.com/random-redirect + +go 1.18 + +require golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..00176fd --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 h1:ftMN5LMiBFjbzleLqtoBZk7KdJwhuybIU+FckUHgoyQ= +golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= diff --git a/main.go b/main.go new file mode 100644 index 0000000..f2fffdf --- /dev/null +++ b/main.go @@ -0,0 +1,38 @@ +package main + +import ( + "bytes" + "flag" + "fmt" + "io/ioutil" + "log" + "math/rand" + "net/http" + + "golang.org/x/time/rate" +) + +func main() { + var port int + var conf string + flag.IntVar(&port, "p", 8080, "port to listen on") + flag.StringVar(&conf, "c", "/dev/null", "line delimited file to read urls from") + flag.Parse() + b, err := ioutil.ReadFile(conf) + if err != nil { + panic(err) + } + links := bytes.Split(b, []byte{'\n'}) + log.Print(port) + limiter := rate.NewLimiter(1, 1) + if err := http.ListenAndServe(fmt.Sprintf(":%d", port), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + limiter.Wait(r.Context()) + link := "" + for len(link) == 0 { + link = string(links[rand.Intn(len(links))]) + } + http.Redirect(w, r, link, http.StatusTemporaryRedirect) + })); err != nil { + panic(err) + } +}