This似乎可能会回答我的问题,但是我无法将输出写入/保存到" somefile.json" (在我的代码中命名为" deck.json"无论我尝试过什么)。我的猜测是由于文件在错误的时间打开/关闭,表单输入和编写器相互缺失,但老实说我不知道。我试图将这个示例变成一个允许用户输入将保存到JSON文件的术语和定义的表单,该文件将由JavaScript驱动的闪存卡"应用程序安装在另一页上。
这是我现在的代码:
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Flashcards for Learning JS</title>
</head>
<body>
<br>
<form action="/addcard" method="post">
<input type="text" name="term" placeholder="Term">
<br>
<br>
<input type="text" name="definition" placeholder="Definition">
<br>
<br>
<input type="submit" value="Add Card">
</form>
</body>
</html>
GO:
package main
import (
"encoding/json"
"html/template"
"net/http"
"os"
)
type Card struct {
Term string `json:"term"`
Definition string `json:"definition"`
}
func open(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("Form.html")
t.Execute(w, nil)
}
func addcard(w http.ResponseWriter, r *http.Request) {
f, err := os.Open("deck.json")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
card := new(Card)
card.Term = r.FormValue("term")
card.Definition = r.FormValue("definition")
b, err := json.Marshal(card)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
f.Write(b)
f.Close()
}
func main() {
http.HandleFunc("/", open)
http.ListenAndServe(":8080", nil)
http.HandleFunc("/addcard", addcard)
}
答案 0 :(得分:1)
Changed per recommendations made by @JimB. Fixed handler order, and program successfully concatenates each successive submission as valid JSON to the file in question.
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Flashcards for Learning JS</title>
</head>
<body>
<br>
<form action="/addcard" method="post">
<input type="text" name="term" placeholder="Term">
<br>
<br>
<input type="text" name="definition" placeholder="Definition">
<br>
<br>
<input type="submit" value="Add Card">
</form>
</body>
</html>
GO:
package main
import (
"encoding/json"
"html/template"
"net/http"
"os"
)
type Card struct { //defining the data structure for our virtual flashcards
Term string `json:"Term"`
Definition string `json:"Definition"`
}
func open(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("addcard.html")
t.Execute(w, nil)
}
func addcard(w http.ResponseWriter, r *http.Request) {
f, err := os.OpenFile("deck.json", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer f.Close()
card := new(Card)
card.Term = r.FormValue("term")
card.Definition = r.FormValue("definition")
b, err := json.Marshal(card)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
f.Write(b)
f.Close()
}
func main() {
http.HandleFunc("/addcard", addcard)
http.HandleFunc("/", open)
http.ListenAndServe(":8080", nil)
}