39 lines
802 B
Go
39 lines
802 B
Go
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)
|
|
}
|
|
}
|