Skip to content

Instantly share code, notes, and snippets.

@davidvthecoder
Created October 9, 2013 18:32
Show Gist options
  • Save davidvthecoder/6905911 to your computer and use it in GitHub Desktop.
Save davidvthecoder/6905911 to your computer and use it in GitHub Desktop.
Golang CSV Writer Example for a Web Application - Warning No error handling, just the basic concept.
import (
"../../web"
"bytes"
"encoding/csv"
}
func GenerateCSV(ctx *web.Context, args ...string) {
record := []string{"test1", "test2", "test3"} // just some test data to use for the wr.Writer() method below.
b := &bytes.Buffer{} // creates IO Writer
wr := csv.NewWriter(b) // creates a csv writer that uses the io buffer.
for i := 0; i < 100; i++ { // make a loop for 100 rows just for testing purposes
wr.Write(record) // converts array of string to comma seperated values for 1 row.
}
wr.Flush() // writes the csv writer data to the buffered data io writer(b(bytes.buffer))
ctx.ResponseWriter.Header().Set("Content-Type", "text/csv") // setting the content type header to text/csv
ctx.ResponseWriter.Header().Set("Content-Type", "text/csv")
ctx.ResponseWriter.Header().Set("Content-Disposition", "attachment;filename=TheCSVFileName.csv")
ctx.ResponseWriter.Write(b.Bytes())
}
@rishabh-discovery
Copy link

Very Helpful article. Just to point out, ctx.ResponseWriter.Header().Set("Content-Type", "text/csv") , this has been repeated twice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment