html - Golang 保存到 json 文件

标签 html forms go

我想知道为什么保存到 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/

相关文章:

html - 如何将 CSS 调整大小图标置于子 img 标签上方?

javascript - 如何在 Javascript 中向上或向下移动文本行

php形成多个单选按钮

go - 如何检查对象是否具有特定方法?

amazon-web-services - 使用 AWS 请求签名访问 ES 有问题

html - 基于 colgroup 的表格单元格的宽度不起作用

html - 如何强制 iPad Safari 在纵向模式下不缩小我的网页?

jquery - 向动态 jQuery 表单添加元素

javascript - 如何在提交时隐藏表单?

go - 验证结构变量是否为空