This appeared as if it might answer my question, however I am not able to make the output write/save properly to "somefile.json" ( named "deck.json" in my code) no matter what I have tried. My guess is that the form input and the writer are missing each other due to the file being opened/closed at the wrong times, but I honestly do not know. I am attempting to shoehorn this example into a form that allows for a user to input terms and definitions that will save to a JSON file which will be referenced by a JavaScript-powered "flash card" app housed on another page.
Here is the code I have at this moment:
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)
}