random-redirect/main.go

58 lines
1.2 KiB
Go

package main
import (
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
"golang.org/x/time/rate"
)
func main() {
rand.Seed(time.Now().UnixNano())
var port int
var conf string
var proxy bool
flag.IntVar(&port, "p", 8080, "port to listen on")
flag.StringVar(&conf, "c", "/dev/null", "line delimited file to read urls from")
flag.BoolVar(&proxy, "proxy", false, "proxy content rather than redirect, so refresh works")
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))])
}
if proxy {
resp, err := http.Get(link)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
}
for k, v := range resp.Header {
for _, v2 := range v {
w.Header().Add(k, v2)
}
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
} else {
http.Redirect(w, r, link, http.StatusTemporaryRedirect)
}
})); err != nil {
panic(err)
}
}