Brilliant!! Thanks Tamas, that worked perfectly. On Tuesday, March 2, 2021 at 4:14:10 PM UTC-5 Tamás Gulácsi wrote:
> If I understand correctly, you receive "bodyBytes", store it in a file, > and later want to serve it. > Then a `w.Write(b)` would suffice. > Or without reading the whole file into memory: `io.Copy(w, file)`. > > [email protected] a következőt írta (2021. március 2., kedd, 14:12:22 > UTC+1): > >> Here is what I have tried. >> >> type product struct { >> ID int `json:"id"` >> Description string `json:"description"` >> Price float64 `json:"price"` >> Bin string `json:"bin"` >> Qoh int `json:"qoh"` >> } >> // ********* function to save data to a file *********// >> func saveBackup(w http.ResponseWriter, r *http.Request) { >> >> type Resp struct { >> Message string `json:"message"` >> Affected string `json:"affected"` >> } >> resp:= Resp{} >> >> >> for k, v := range r.URL.Query() { >> kee = k >> val = v[0] >> } >> fileName := val // r.FormValue("filename") >> >> bodyBytes, err := ioutil.ReadAll(r.Body) >> >> var items product >> json.Unmarshal(bodyBytes, &items) >> fmt.Printf("%+v\n",items) >> f, err := os.Create(fileName) >> if err != nil { >> fmt.Println(err) >> return >> } >> l, err := f.Write(bodyBytes) >> if err != nil { >> fmt.Println(err) >> f.Close() >> return >> } >> fmt.Println(l, "bytes written successfully") >> err = f.Close() >> if err != nil { >> fmt.Println(err) >> return >> } >> resp.Message = "Save successful" >> resp.Affected = "Saved" >> respondWithJSON(w, http.StatusOK, resp) >> >> } >> >> //******** Retrieving the file ********** // >> >> func getBackup(w http.ResponseWriter, r *http.Request) { >> >> kee := "" >> fileName := "" >> for k, v := range r.URL.Query() { >> kee = k >> fileName = v[0] >> } >> var lines []product <=== []string - had this prior to scan Text >> >> file, err := os.Open(fileName) >> if err != nil { >> log.Fatal(err) >> } >> defer func() { >> if err = file.Close(); err != nil { >> log.Fatal(err) >> } >> }() >> >> // scanner := bufio.NewScanner(file) >> // for scanner.Scan() { >> // lines = append(lines, scanner.Text()) >> // } >> b, err := ioutil.ReadFile(file) >> append(lines, b) <== I know this is wrong >> >> response, _ := json.Marshal(lines) >> >> w.Header().Set("Content-Type", "application/json") >> w.WriteHeader(http.StatusOK) >> w.Write(response) >> >> } >> >> How can I return the result as a JSON file to the requesting application? >> The client application parses the result to load into an array. >> > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ae159a92-26ae-4b49-90af-bc1511364ef6n%40googlegroups.com.
