I am wondering why saving to json file does'nt work as I expected.
-If I input values in the fields and click submit button
-The form will submit and the process function executes
-The process.html renders the input values.
-The input values not saving to the json file.
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)
}