1

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)
}

1 Answer 1

1

I believe that os.Open defaults to read-only. I think you want something like os.OpenFile.

Sign up to request clarification or add additional context in comments.

1 Comment

os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.