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()) | |
} |
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
How do i use this with a Query pull?
func query(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
rows, err := db.Query("SELECT rma_id, order_id, customer_id, bin_id, owner, asin, lpn, warehouse_id FROM crt.returns_in_inv WHERE warehouse_id = 'PHX7' limit 100;")
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
defer rows.Close()
}