-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.go
99 lines (87 loc) · 1.92 KB
/
util.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package activityserve
import (
"bufio"
"bytes"
"encoding/json"
"github.com/gologme/log"
"io"
"net/http"
"os"
)
func isSuccess(code int) bool {
return code == http.StatusOK ||
code == http.StatusCreated ||
code == http.StatusAccepted ||
code == http.StatusNoContent
}
// PrettyPrint maps
func PrettyPrint(themap map[string]interface{}) {
b, err := json.MarshalIndent(themap, "", " ")
if err != nil {
log.Info("error:", err)
}
log.Print(string(b))
}
// PrettyPrintJSON does what it's name says
func PrettyPrintJSON(theJSON []byte) {
dst := new(bytes.Buffer)
json.Indent(dst, theJSON, "", "\t")
log.Info(dst)
}
// FormatJSON formats json with tabs and
// returns the new string
func FormatJSON(theJSON []byte) string {
dst := new(bytes.Buffer)
json.Indent(dst, theJSON, "", "\t")
return dst.String()
}
// FormatHeaders to string for printing
func FormatHeaders(header http.Header) string {
buf := new(bytes.Buffer)
header.Write(buf)
return buf.String()
}
func context() [1]string {
return [1]string{"https://www.w3.org/ns/activitystreams"}
}
// ReadLines reads specific lines from a file and returns them as
// an array of strings
func ReadLines(filename string, from, to int) (lines []string, err error) {
lines = make([]string, 0, to-from)
reader, err := os.Open(filename)
if err != nil {
log.Info("could not read file")
log.Info(err)
return
}
sc := bufio.NewScanner(reader)
line := 0
for sc.Scan() {
line++
if line >= from && line <= to {
lines = append(lines, sc.Text())
}
}
return lines, nil
}
func lineCounter(filename string) (int, error) {
r, err := os.Open(filename)
if err != nil {
log.Info("could not read file")
log.Info(err)
return 0, nil
}
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}