From 5ebc35ad11989328c0c417230805b4ff9ed7a045 Mon Sep 17 00:00:00 2001 From: Přemysl Eric Janouch Date: Thu, 6 Oct 2022 00:44:09 +0200 Subject: Add a basic tool for collecting web comments --- hswc/main.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 hswc/main.go (limited to 'hswc') diff --git a/hswc/main.go b/hswc/main.go new file mode 100644 index 0000000..99aa3c6 --- /dev/null +++ b/hswc/main.go @@ -0,0 +1,68 @@ +package main + +import ( + "fmt" + "log" + "net/http" + "os" + "regexp" + "strings" + "sync" + "time" +) + +var ( + long = regexp.MustCompile(`(.{72}\S*)\s+`) + file *os.File + m sync.Mutex +) + +func wrap(s string) string { + return strings.ReplaceAll(long.ReplaceAllString( + strings.ReplaceAll(s, "\r", ""), "$1\n"), "\n", "\n ") +} + +func handler(w http.ResponseWriter, r *http.Request) { + defer r.Body.Close() + if err := r.ParseForm(); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + text := r.FormValue("text") + if len(text) > 64<<10 { + w.WriteHeader(http.StatusBadRequest) + return + } + + m.Lock() + defer m.Unlock() + + if s, err := file.Stat(); err != nil { + log.Fatalln(err) + } else if s.Size()+int64(len(text)) > 64<<20 { + w.WriteHeader(http.StatusInternalServerError) + } else { + fmt.Fprintf(file, "%s %s\n %s\n", + time.Now().Local().Format(time.RFC1123), r.RequestURI, wrap(text)) + if err := file.Sync(); err != nil { + log.Fatalln(err) + } + + fmt.Fprintln(w, "Saved.") + } +} + +func main() { + if len(os.Args) != 3 { + log.Fatalf("Usage: %s BIND DB\n", os.Args[0]) + } + + var err error + if file, err = os.OpenFile( + os.Args[2], os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); err != nil { + log.Fatalln(err) + } + + http.HandleFunc("/", handler) + log.Fatalln(http.ListenAndServe(os.Args[1], nil)) +} -- cgit v1.2.3-70-g09d2