This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver_util.go
112 lines (95 loc) · 2.41 KB
/
server_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
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"crypto/md5"
"database/sql"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/dimfeld/httptreemux"
)
var jsonHeaders = map[string]string{
"Cache-Control": "max-age=0, must-revalidate",
"Expires": "Fri, 01 Jan 1990 00:00:00 GMT",
"Content-Type": "application/json",
}
var htmlHeaders = map[string]string{
"Cache-Control": "max-age=0, must-revalidate",
"Expires": "Fri, 01 Jan 1990 00:00:00 GMT",
"Content-Type": "text/html",
}
// Error with an attached HTTP status code
type StatusError interface {
error
Status() int
}
// Chunk of data returned to client to track upload progress
type Chunk struct {
SHA1 string
Current int
Total int
}
// Handle error and devulge code from error type or value
func httpError(w http.ResponseWriter, r *http.Request, err error) {
code := 500
switch err.(type) {
case StatusError:
code = err.(StatusError).Status()
case *strconv.NumError:
code = 400
default:
if err == sql.ErrNoRows {
code = 404
}
}
http.Error(w, fmt.Sprintf("%d %s", code, err), code)
if code >= 500 && code < 600 {
stderr.Printf("server: %s: %s", r.RemoteAddr, err)
}
}
func sendError(w http.ResponseWriter, code int, err error) {
http.Error(w, fmt.Sprintf("%d %s", code, err), code)
}
func send404(w http.ResponseWriter) {
http.Error(w, "404 not found", 404)
}
func send400(w http.ResponseWriter, err error) {
sendError(w, 400, err)
}
func send500(w http.ResponseWriter, r *http.Request, err error) {
sendError(w, 500, err)
stderr.Printf("server: %s: %s", r.RemoteAddr, err)
}
// Extract URL paramater from request context
func extractParam(r *http.Request, id string) string {
return httptreemux.ContextParams(r.Context())[id]
}
func setHeaders(w http.ResponseWriter, headers map[string]string) {
head := w.Header()
for key, val := range headers {
head.Set(key, val)
}
}
func serveJSON(w http.ResponseWriter, r *http.Request, data interface{}) {
buf, err := json.Marshal(data)
if err != nil {
send500(w, r, err)
return
}
serveData(w, r, jsonHeaders, buf)
}
func serveData(w http.ResponseWriter, r *http.Request,
headers map[string]string, buf []byte,
) {
h := md5.Sum(buf)
etag := base64.RawStdEncoding.EncodeToString(h[:])
if r.Header.Get("If-None-Match") == etag {
w.WriteHeader(304)
return
}
setHeaders(w, headers)
w.Header().Set("ETag", etag)
w.Header().Set("Content-Length", strconv.Itoa(len(buf)))
w.Write(buf)
}