I want to save a file from an incoming POST request and upon request return the file in a GET request as JSON data.

746 views
Skip to first unread message

Hugh Myrie

unread,
Mar 2, 2021, 8:12:22 AM3/2/21
to golang-nuts
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.

Tamás Gulácsi

unread,
Mar 2, 2021, 4:14:10 PM3/2/21
to golang-nuts
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)`.

Hugh Myrie

unread,
Mar 2, 2021, 9:19:06 PM3/2/21
to golang-nuts
Brilliant!! Thanks Tamas, that worked perfectly.
Reply all
Reply to author
Forward
0 new messages