-
Notifications
You must be signed in to change notification settings - Fork 1
/
requests.go
89 lines (78 loc) · 2.44 KB
/
requests.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
// Copyright © 2019 tinyzimmer
//
// This file is part of protobuf-registry
//
// protobuf-registry is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// protobuf-registry is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with protobuf-registry. If not, see <https://www.gnu.org/licenses/>.
package common
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/tinyzimmer/protobuf-registry/pkg/config"
)
func GetName(r *http.Request) string {
vars := mux.Vars(r)
return vars["name"]
}
func GetVersion(r *http.Request) string {
vars := mux.Vars(r)
return vars["version"]
}
func UnmarshallInto(body io.Reader, obj interface{}) error {
if body == nil {
return errors.New("Received empty body")
}
raw, err := ioutil.ReadAll(body)
if err != nil {
return err
}
err = json.Unmarshal(raw, obj)
return err
}
func BadRequest(err error, w http.ResponseWriter) {
res := &ServerError{ErrMsg: fmt.Sprintf("Bad request: %s", err.Error())}
http.Error(w, res.JSON(), http.StatusBadRequest)
}
func NotFound(err error, w http.ResponseWriter) {
res := &ServerError{ErrMsg: fmt.Sprintf("Not Found: %s", err.Error())}
http.Error(w, res.JSON(), http.StatusNotFound)
}
func WriteJSONResponse(res interface{}, w http.ResponseWriter) {
out, err := json.MarshalIndent(res, "", " ")
if err != nil {
BadRequest(fmt.Errorf("Failed to write JSON response: %s", err.Error()), w)
return
}
WriteRawResponse(out, w)
}
func WriteRawResponse(out []byte, w http.ResponseWriter) {
if config.GlobalConfig.CORSEnabled {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
if _, err := w.Write(append(out, "\n"...)); err != nil {
BadRequest(err, w)
}
}
func ServeFile(w http.ResponseWriter, r *http.Request, name string, rdr io.ReadSeeker) {
if config.GlobalConfig.CORSEnabled {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", name))
http.ServeContent(w, r, name, time.Now(), rdr)
}