title: Marshalling HTML form input to JSON and writing to file, golang
body: <p><a href="https://stackoverflow.com/questions/12513963/how-to-read-input-from-a-html-form-and-save-it-in-a-file-golang/39215607#39215607">This</a> 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. </p>
  
  <p>Here is the code I have at this moment:</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
          &lt;meta charset="utf-8"&gt;
          &lt;title&gt;Flashcards for Learning JS&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
     &lt;br&gt;
  &lt;form action="/addcard" method="post"&gt;
     &lt;input type="text" name="term" placeholder="Term"&gt;
     &lt;br&gt;
     &lt;br&gt;
     &lt;input type="text" name="definition" placeholder="Definition"&gt;
     &lt;br&gt;
     &lt;br&gt;
     &lt;input type="submit" value="Add Card"&gt;
  &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>GO:</p>
  
  <pre><code> 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)
  }
  </code></pre>