Last active
November 8, 2024 20:28
-
-
Save blakelead/0b3477f11e2c304ef75fb02c4f83d412 to your computer and use it in GitHub Desktop.
Go server that serves CSV files with random data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/csv" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"math/rand" | |
"net/http" | |
"os" | |
) | |
func main() { | |
err := os.MkdirAll("content", 0755) | |
if err != nil { | |
log.Fatal(err) | |
} | |
filesCount := 10 | |
for i := 1; i <= filesCount; i++ { | |
records := generateCSV() | |
if err := writeToFile(fmt.Sprintf("content/file%03d.csv", i), records); err != nil { | |
log.Fatal(err) | |
} | |
} | |
log.Fatal(serve("7000")) | |
} | |
func generateCSV() [][]string { | |
cols := 5 | |
rows := 5 | |
wordSize := 8 | |
var records [][]string | |
for i := 0; i < cols; i++ { | |
records = append(records, randomStringArray(wordSize, rows)) | |
} | |
return records | |
} | |
func randomStringArray(strLength, arrayLength int) []string { | |
var letters = []rune("abcdefghijklmnopqrstuvwxyz") | |
a := make([]string, arrayLength) | |
for i := range a { | |
b := make([]rune, strLength) | |
for j := range b { | |
b[j] = letters[rand.Intn(len(letters))] | |
} | |
a[i] = string(b) | |
} | |
return a | |
} | |
func writeToFile(name string, records [][]string) error { | |
file, err := os.Create(name) | |
if err != nil { | |
return err | |
} | |
w := csv.NewWriter(file) | |
w.WriteAll(records) | |
if err := w.Error(); err != nil { | |
return err | |
} | |
return nil | |
} | |
func serve(port string) error { | |
http.HandleFunc("/random", func(res http.ResponseWriter, req *http.Request) { | |
fileList, err := ioutil.ReadDir("content") | |
if err != nil { | |
return | |
} | |
file := fileList[rand.Intn(len(fileList))] | |
if file.IsDir() { | |
return | |
} | |
res.Header().Set("Random-Csv-Filename", file.Name()) | |
http.ServeFile(res, req, "content/"+file.Name()) | |
}) | |
http.Handle("/", http.FileServer(http.Dir("content"))) | |
log.Printf("Serving directory %s at :%s", "content", port) | |
return http.ListenAndServe(":"+port, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment