-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput.go
74 lines (63 loc) · 1.59 KB
/
output.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
package simple_collector
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/vidmed/logger"
)
type ResponseData struct {
Url string
ResponseCode int `json:"response_code"`
Latency string `json:"latency"`
Error string `json:"error"`
}
type Output struct {
ResponseData []*ResponseData
writer func(resp []*ResponseData, outputFile string) error
}
func NewOutput(writer func(resp []*ResponseData, outputFile string) error) (*Output, error) {
if writer == nil {
return nil, fmt.Errorf("writer not set")
}
return &Output{writer: writer}, nil
}
func (s Output) writeResult(outputFile string) error {
if len(s.ResponseData) == 0 {
return fmt.Errorf("there nothing to save")
}
return s.writer(s.ResponseData, outputFile)
}
func saveJson(resp []*ResponseData, outputFile string) error {
data, err := json.Marshal(resp)
if err != nil {
return err
}
return writeFile(outputFile, data)
}
func saveText(resp []*ResponseData, outputFile string) error {
var str string
for _, r := range resp {
str = str + fmt.Sprintf(
"url:%s code:%d, latency:%s, error:%s \n",
r.Url, r.ResponseCode, r.Latency, r.Error)
}
return writeFile(outputFile, []byte(str))
}
func writeFile(filename string, data []byte) (err error) {
err = ioutil.WriteFile(filename, data, 0644)
if err != nil {
logger.Get().Errorln(err)
}
return
}
func getWriter(t string) (func(resp []*ResponseData, outputFile string) error) {
switch t {
case "txt":
return saveText
case "json":
return saveJson
default:
logger.Get().Errorf("output type %s is not supported \n", t)
return nil
}
}