-
Notifications
You must be signed in to change notification settings - Fork 0
/
zsond.go
110 lines (102 loc) · 2.24 KB
/
zsond.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
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"bufio"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
func parsePath(path string) (string, error) {
dirpath := filepath.Join(".", path)
if _, err := os.Stat(dirpath); os.IsNotExist(err) {
return "", err
}
return dirpath, nil
}
func findPath(line string) (string, bool) {
if strings.HasPrefix(line, "#path") {
return strings.TrimSpace(line[5:]), true
}
return "", false
}
func openfile(path, name string) (*os.File, string, error) {
for n := 0; n < 100; n++ {
var fname string
if n > 0 {
fname = fmt.Sprintf("%s.%d.log", name, n)
} else {
fname = fmt.Sprintf("%s.log", name)
}
filename := filepath.Join(path, fname)
f, err := os.OpenFile(filename, os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
if os.IsExist(err) {
continue
}
return nil, "", err
}
return f, filename, nil
}
return nil, "", errors.New("too many files")
}
func readPath(reader *bufio.Reader) ([]byte, string, error) {
var buf []byte
for {
line, err := reader.ReadBytes('\n')
if err != nil {
return nil, "", err
}
buf = append(buf, line...)
if path, ok := findPath(string(line)); ok {
return buf, path, nil
}
}
}
func handle(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "bad method", http.StatusForbidden)
return
}
dirPath, err := parsePath(r.URL.RequestURI())
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
reader := bufio.NewReader(r.Body)
header, path, err := readPath(reader)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
file, _, err := openfile(dirPath, path)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if _, err := file.Write(header); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
go func() {
for range time.Tick(5 * time.Second) {
file.Sync()
}
}()
if _, err := io.Copy(file, reader); err != nil {
http.Error(w, err.Error(), http. StatusInternalServerError)
return
}
}
func main() {
port := ":9867"
if len(os.Args) == 2 {
port = os.Args[1]
}
http.HandleFunc("/", handle)
if err := http.ListenAndServe(port, nil); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}