Generate and download CSV

Hi there ! Someone could help me with some documentation, clarification or examples about how to generate a endpoint to download a csv, please? The main idea is that I don’t want to save the file on the project folder. Thanks everyone!

Save it in the temp folder then delete it once done, something like:

	tmpDir := os.TempDir() + "\\myCSVfile"
	if p, err := os.Stat(tmpDir); os.IsNotExist(err) {
		err = os.Mkdir(tmpDir, 0755)
		defer os.RemoveAll(tmpDir)
		if err != nil {
			fmt.Printf("err 2: %v", err)
		} else {
                      /*********/
                       Save your file, and do whatever you want from it
                     /**********/
		}
	} else {
               os.RemoveAll(tmpDir)
	}

Thanks. But I don’t understand so good the way that the csv will be downloaded. I mean, in other programming languages, I only have tu put the url on the browser and it works, is the same in golang?

Why not use “encoding/csv” to write directly to the http.ResponseWriter? Set the content-type header to text/csv.

You code your endpoint to be executed in response to requests for a URL that you define.

Expanding on what @mje wrote (which I believe is the correct approach based on what you’re describing), here’s an example using encoding/csv to write to an http.ResponseWriter:

package main

import (
	"encoding/csv"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/", serveDummyCSV)
	log.Fatal(http.ListenAndServe(":9090", nil))
}

func serveDummyCSV(w http.ResponseWriter, req *http.Request) {
	items := [][]string{
		{"UserID", "FullName", "Email"},           // Header
		{"1", "Jack Johnson", "jack@hotmail.com"}, // Items
		{"2", "Jill Smith", "jill@hotmail.com"},
		{"3", "James Murphy", "james@hotmail.com"},
	}

	// Set our headers so browser will download the file
	w.Header().Set("Content-Type", "text/csv")
	w.Header().Set("Content-Disposition", "attachment;filename=users.csv")
	// Create a CSV writer using our HTTP response writer as our io.Writer
	wr := csv.NewWriter(w)
	// Write all items and deal with errors
	if err := wr.WriteAll(items); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

Copy/paste that into a main.go file and go run it, then open your browser to localhost:9090, and your browser will download the CSV just fine. Writing/encoding CSV is a trivial matter. Getting your browser to respond by downloading the CSV file as a file is just a matter of setting a few http headers.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.