webform

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

commit 64077a1b9171d2182764f066e09be97ce694c680
parent 42e5b74e32eb7bafdcc47e058a7665e41a9ac7c6
Author: Matsuda Kenji <info@mtkn.jp>
Date:   Sun, 21 Jul 2024 08:30:54 +0900

write answer to file

Diffstat:
Mmain.go | 45+++++++++++++++++++++++++++++++++++++++------
1 file changed, 39 insertions(+), 6 deletions(-)

diff --git a/main.go b/main.go @@ -1,10 +1,12 @@ package main import ( + "bytes" "encoding/json" "fmt" "log" "net/http" + "os" "strconv" ) @@ -212,14 +214,14 @@ var Q Part = Part{ }, } +var bufc = make(chan []byte) + func main() { - q, err := json.MarshalIndent(Q, "", " ") + f, err := os.Create("a.json") if err != nil { - log.Printf("error: marshal: %v\n", err) - return + log.Fatal("create file: %v\n", err) } - log.Printf("Q: %v\n", string(q)) - + go writer(bufc, f) http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } @@ -238,17 +240,48 @@ func handler(w http.ResponseWriter, r *http.Request) { return } log.Printf("answer json: %v\n", string(answer)) - QQ := Q.copy() if err := QQ.fillAns(r.PostForm); err != nil { log.Printf("fillAns: %v\n", err) return } + q, err := json.Marshal(QQ) + if err != nil { + log.Printf("error: marshall: %v\n", err) + return + } + bufc <- q } else { fmt.Fprint(w, header + Q.HTML() + footer) } } +// 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) { + 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) + continue + } + } + } + if _, err := f.Write(buf.Bytes()); err != nil { + log.Printf("error: write to file: %v\n", err) + } + if err := f.Close(); err != nil { + log.Printf("close file: %v\n", err) + } +} + const header = `<html> <head> </head>