webform

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit 73e870f522af0be4749e711c698941a7bafccad5
parent 31ef635290cad3679b29e49b114d47660c054388
Author: Matsuda Kenji <info@mtkn.jp>
Date:   Mon, 22 Jul 2024 08:30:58 +0900

catch SIGINT

Diffstat:
Mmain.go | 41++++++++++++++++++++++++++++-------------
1 file changed, 28 insertions(+), 13 deletions(-)

diff --git a/main.go b/main.go @@ -7,6 +7,7 @@ import ( "log" "net/http" "os" + "os/signal" "strconv" ) @@ -216,9 +217,17 @@ func main() { if err != nil { log.Fatal("create file: %v\n", err) } - go writer(bufc, f) + intc := make(chan os.Signal) + done := make(chan struct{}) + signal.Notify(intc, os.Interrupt) + go writer(intc, done, bufc, f) http.HandleFunc("/", handler) - log.Fatal(http.ListenAndServe("localhost:8000", nil)) + go func() { + log.Printf("listenAndServe: %v\n", + http.ListenAndServe("localhost:8000", nil)) + }() + <-done + os.Exit(0) } func handler(w http.ResponseWriter, r *http.Request) { @@ -241,7 +250,6 @@ func handler(w http.ResponseWriter, r *http.Request) { return } log.Printf("A: %v\n", string(A)) - bufc <- A } else { fmt.Fprint(w, header+Q.HTML()+footer) @@ -250,20 +258,27 @@ func handler(w http.ResponseWriter, r *http.Request) { // Writer reads json data from c and writes them to f. // This function closes f after c is closed. -func writer(c <-chan []byte, f *os.File) { +func writer(intc <-chan os.Signal, done chan<- struct{}, c <-chan []byte, f *os.File) { + defer close(done) const bufSize = 4096 var buf bytes.Buffer - for q := range c { - if err := json.Compact(&buf, q); err != nil { - log.Printf("error: compact: %v\n", err) - continue - } - log.Printf("buf: %v\n", buf.String()) - if buf.Len() >= bufSize { - if _, err := f.Write(buf.Next(bufSize)); err != nil { - log.Printf("error: write to file: %v\n", err) +L: + for { + select { + case q := <- c: + if err := json.Compact(&buf, q); err != nil { + log.Printf("error: compact: %v\n", err) continue } + log.Printf("buf: %v\n", buf.String()) + if buf.Len() >= bufSize { + if _, err := f.Write(buf.Next(bufSize)); err != nil { + log.Printf("error: write to file: %v\n", err) + continue + } + } + case <-intc: + break L } } if _, err := f.Write(buf.Bytes()); err != nil {