Created
October 9, 2013 18:32
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very Helpful article. Just to point out, ctx.ResponseWriter.Header().Set("Content-Type", "text/csv") , this has been repeated twice.