Skip to content

Instantly share code, notes, and snippets.

@artyom
Created June 18, 2018 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artyom/84811a8a3eb4d1801c2ecf1a386816e0 to your computer and use it in GitHub Desktop.
Save artyom/84811a8a3eb4d1801c2ecf1a386816e0 to your computer and use it in GitHub Desktop.
http server replying with random data of requested size
// TODO describe program
package main
import (
"fmt"
"io"
"math/rand"
"net/http"
"os"
"strconv"
"time"
"github.com/artyom/autoflags"
)
func main() {
args := &struct {
Addr string `flag:"addr,address to listen"`
}{Addr: "localhost:8080"}
autoflags.Parse(args)
if err := run(args.Addr); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(addr string) error {
srv := &http.Server{
Addr: addr,
Handler: http.HandlerFunc(handleFunc),
ReadHeaderTimeout: time.Second,
}
return srv.ListenAndServe()
}
func handleFunc(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Accept", "GET")
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
size, err := strconv.Atoi(r.URL.Query().Get("size"))
if err != nil || size <= 0 {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
w.Header().Set("Content-Length", strconv.Itoa(size))
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename=random.bin")
io.Copy(w, io.LimitReader(rand.New(rand.NewSource(time.Now().Unix())), int64(size)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment