github.com/aaabigfish/gopkg@v1.1.0/ginx/csv.go (about) 1 package ginx 2 3 import ( 4 "encoding/csv" 5 "fmt" 6 "net/http" 7 ) 8 9 // CSV struct. 10 type CSV struct { 11 Data [][]string 12 Title string 13 } 14 15 var csvContentType = []string{"text/csv; charset=utf-8"} 16 17 // Render (CSV) writes data with CSV ContentType. 18 func (c CSV) Render(w http.ResponseWriter) (err error) { 19 c.WriteContentType(w) 20 21 writer := csv.NewWriter(w) 22 23 // add utf bom 24 w.Write([]byte{0xEF, 0xBB, 0xBF}) 25 26 if err = writer.WriteAll(c.Data); err != nil { 27 return 28 } 29 return 30 } 31 32 // WriteContentType write CSV ContentType. 33 func (c CSV) WriteContentType(w http.ResponseWriter) { 34 header := w.Header() 35 if val := header["Content-Type"]; len(val) == 0 { 36 header["Content-Type"] = csvContentType 37 } 38 39 header["Content-Disposition"] = append(header["Content-Disposition"], 40 fmt.Sprintf("attachment; filename=%s.csv", c.Title)) 41 }