1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package main
- import (
- "flag"
- "io/ioutil"
- "log"
- "math/rand"
- "net/http"
- "strings"
- "time"
- )
- func RandomString(n int) string {
- var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
- s := make([]rune, n)
- for i := range s {
- s[i] = letters[rand.Intn(len(letters))]
- }
- return string(s)
- }
- func createHandler(rw http.ResponseWriter, req *http.Request) {
- log.Println("Clicked!")
- if req.Method == "GET" {
- log.Println("You requested the create-file function.")
- timestamp := time.Now()
- // Filename cannot contain ":", so we need to replace them with "."
- timestampNew := strings.ReplaceAll(timestamp.String(), ":", ".")
- randomBytes := []byte(RandomString(8))
- err := ioutil.WriteFile(timestampNew, randomBytes, 0644)
- if err != nil {
- log.Fatal(err)
- }
- log.Printf("A log file with filename %s is created.\n", timestampNew)
- } else {
- http.Error(rw, "Method "+req.Method+" is not supported", http.StatusNotFound)
- return
- }
- }
- func main() {
- portPointer := flag.String("port", "8000", "An integer")
- flag.Parse()
- log.Println("Port Number: " + *portPointer)
- httpFileServer := http.FileServer(http.Dir("./files"))
- http.Handle("/", httpFileServer)
- http.HandleFunc("/createfunction", createHandler)
- log.Printf("Listening http://localhost:%s\n", *portPointer)
- if error := http.ListenAndServe(":"+*portPointer, nil); error != nil {
- log.Printf("Error: %s\n", error)
- }
- }
|