我想知道为什么保存到 json 文件不能像我预期的那样工作。
-如果我在字段中输入值并单击提交按钮
-表单将提交并且处理函数执行
-process.html 呈现输入值。
-输入值未保存到json 文件。
import (
"net/http"
"html/template"
"os"
"encoding/json"
)
var tpl *template.Template
type Data struct {
First string `json:"First"`
Last string `json:"Last"`
}
func init() {
tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}
func main() {
http.HandleFunc("/", index);
http.HandleFunc("/process", process);
http.ListenAndServe(":80", nil);
}
func index(w http.ResponseWriter, r *http.Request) {
tpl.ExecuteTemplate(w, "index.gohtml", nil)
}
func process(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
f, err := os.Open("name.json");
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer f.Close();
data := new(Data)
data.First = r.FormValue("first");
data.Last = r.FormValue("last");
b, err := json.Marshal(data)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
f.Write(b)
f.Close()
tpl.ExecuteTemplate(w, "process.gohtml", data)
}
最佳答案
我相信 os.Open 默认为只读。我想你想要像 os.OpenFile 这样的东西。
关于html - Golang 保存到 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49827197/