main.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "flag"
  4. "io/ioutil"
  5. "log"
  6. "math/rand"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. func RandomString(n int) string {
  12. var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  13. s := make([]rune, n)
  14. for i := range s {
  15. s[i] = letters[rand.Intn(len(letters))]
  16. }
  17. return string(s)
  18. }
  19. func createHandler(rw http.ResponseWriter, req *http.Request) {
  20. log.Println("Clicked!")
  21. if req.Method == "GET" {
  22. log.Println("You requested the create-file function.")
  23. timestamp := time.Now()
  24. // Filename cannot contain ":", so we need to replace them with "."
  25. timestampNew := strings.ReplaceAll(timestamp.String(), ":", ".")
  26. randomBytes := []byte(RandomString(8))
  27. err := ioutil.WriteFile(timestampNew, randomBytes, 0644)
  28. if err != nil {
  29. log.Fatal(err)
  30. }
  31. log.Printf("A log file with filename %s is created.\n", timestampNew)
  32. } else {
  33. http.Error(rw, "Method "+req.Method+" is not supported", http.StatusNotFound)
  34. return
  35. }
  36. }
  37. func main() {
  38. portPointer := flag.String("port", "8000", "An integer")
  39. flag.Parse()
  40. log.Println("Port Number: " + *portPointer)
  41. httpFileServer := http.FileServer(http.Dir("./files"))
  42. http.Handle("/", httpFileServer)
  43. http.HandleFunc("/createfunction", createHandler)
  44. log.Printf("Listening http://localhost:%s\n", *portPointer)
  45. if error := http.ListenAndServe(":"+*portPointer, nil); error != nil {
  46. log.Printf("Error: %s\n", error)
  47. }
  48. }