forked from getfider/fider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv.go
85 lines (75 loc) · 1.63 KB
/
csv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package csv
import (
"bytes"
gocsv "encoding/csv"
"strconv"
"strings"
"time"
"github.com/getfider/fider/app/models"
)
//FromPosts return a byte array of CSV file containing all posts
func FromPosts(posts []*models.Post) ([]byte, error) {
buffer := &bytes.Buffer{}
writer := gocsv.NewWriter(buffer)
header := []string{
"number",
"title",
"description",
"created_at",
"created_by",
"votes_count",
"comments_count",
"status",
"responded_by",
"responded_at",
"response",
"original_number",
"original_title",
"tags",
}
if err := writer.Write(header); err != nil {
return nil, err
}
for _, post := range posts {
var (
originalNumber string
originalTitle string
respondedBy string
respondedAt string
response string
)
if post.Response != nil {
respondedBy = post.Response.User.Name
respondedAt = post.Response.RespondedAt.Format(time.RFC3339)
response = post.Response.Text
if post.Response.Original != nil {
originalNumber = strconv.Itoa(post.Response.Original.Number)
originalTitle = post.Response.Original.Title
}
}
record := []string{
strconv.Itoa(post.Number),
post.Title,
post.Description,
post.CreatedAt.Format(time.RFC3339),
post.User.Name,
strconv.Itoa(post.VotesCount),
strconv.Itoa(post.CommentsCount),
post.Status.Name(),
respondedBy,
respondedAt,
response,
originalNumber,
originalTitle,
strings.Join(post.Tags, ", "),
}
if err := writer.Write(record); err != nil {
return nil, err
}
}
writer.Flush()
if err := writer.Error(); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}