-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
145 lines (115 loc) · 2.55 KB
/
server.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"bytes"
"errors"
"fmt"
"git.263.nu/f/srv"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
)
var (
pubkeyfile string
roles arrayFlag
tmpdir string
socket string
)
type formdata map[string][]byte
type H map[string]srv.Handler
func serve() {
check_server_flags()
fmt.Printf("Temporary directory is '%s'\n", tmpdir)
fmt.Printf("Public key is: %s\n", pubkeyfile)
fmt.Printf("Roles claim is: %s\n", roles)
srv.Run(
socket,
[]srv.Route{
{"/check", nil, H{"GET": _check}},
{"/socket", nil, H{"GET": _socket}},
{"/routines", roles, H{"POST": _routines}},
},
pubkeyfile,
)
}
func check_server_flags() {
_, err := os.Stat(tmpdir)
if os.IsNotExist(err) {
log.Println(errors.New("Specified temporary directory does not exist. Creating..."))
os.Mkdir(tmpdir, 0755)
}
t, err := os.Open(tmpdir)
if err != nil {
log.Fatal(errors.New("Specified temporary directory (still) does not exist!"))
}
t.Close()
}
func uri_test(url string) (int, bool) {
if !strings.HasPrefix(url, "http") {
return http.StatusBadRequest, false
}
resp, _ := http.Head(url)
return resp.StatusCode, (resp.StatusCode == http.StatusOK)
}
func snatch(location string) (fname string, err error) {
fname = _filename()
for _, x := range []string{"geojson", "shp", "tiff"} {
if strings.HasSuffix(location, "."+x) {
fname += "." + x
break
}
}
if status, ok := uri_test(location); !ok {
err = errors.New("Couldn not fetch '" + location + "' - Error: " + strconv.Itoa(status))
return
}
resp, e := http.Get(location)
if e != nil {
return "", e
}
defer resp.Body.Close()
file, err := os.Create(fname)
if err != nil {
return "", err
}
defer file.Close()
body, err := ioutil.ReadAll(resp.Body)
if _, err := io.Copy(file, bytes.NewReader(body)); err != nil {
return "", err
}
return fname, nil
}
func form_parse(form *formdata, r *http.Request) (err error) {
t := r.Header.Get("Content-Type")
if strings.HasPrefix(t, "multipart/form-data") {
reader, e := r.MultipartReader()
if e != nil {
err = e
return
}
r.ParseMultipartForm(0) // do not use any memory - it all goes to disk.
for {
part, e := reader.NextPart()
if e == io.EOF {
break
}
for k, _ := range *form {
if part.FormName() == k {
buf := new(bytes.Buffer)
buf.ReadFrom(part)
(*form)[k] = buf.Bytes()
}
}
}
}
if strings.HasPrefix(t, "application/x-www-form-urlencoded") {
r.ParseForm()
for k, _ := range *form {
(*form)[k] = []byte(r.FormValue(k))
}
}
return err
}