This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.go
114 lines (103 loc) · 2.38 KB
/
utils.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
package middlewares
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"github.com/clbanning/mxj/j2x"
"github.com/prest/middlewares/statements"
)
func getVars(path string) (paths map[string]string) {
pathList := strings.Split(path, "/")
if len(pathList) < 3 || len(pathList) > 4 {
return nil
} else if len(pathList) == 4 {
pathList = pathList[1:]
}
paths = make(map[string]string, 0)
paths["database"] = pathList[0]
paths["schema"] = pathList[1]
paths["table"] = pathList[2]
return
}
func permissionByMethod(method string) (permission string) {
switch method {
case "GET":
permission = statements.READ
case "POST", "PATCH", "PUT":
permission = statements.WRITE
case "DELETE":
permission = statements.DELETE
default:
permission = ""
}
return
}
func renderFormat(w http.ResponseWriter, recorder *httptest.ResponseRecorder, format string) {
for key := range recorder.Header() {
w.Header().Set(key, recorder.Header().Get(key))
}
byt, _ := ioutil.ReadAll(recorder.Body)
if recorder.Code >= 400 {
m := make(map[string]string)
m["error"] = strings.TrimSpace(string(byt))
byt, _ = json.MarshalIndent(m, "", "\t")
}
switch format {
case "xml":
xmldata, err := j2x.JsonToXml(byt)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
xmlStr := fmt.Sprintf("<objects>%s</objects>", string(xmldata))
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(recorder.Code)
w.Write([]byte(xmlStr))
default:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(recorder.Code)
w.Write(byt)
}
}
var defaultAllowMethods = []string{
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS",
}
const (
headerAllowOrigin = "Access-Control-Allow-Origin"
headerAllowCredentials = "Access-Control-Allow-Credentials"
headerAllowHeaders = "Access-Control-Allow-Headers"
headerAllowMethods = "Access-Control-Allow-Methods"
headerOrigin = "Origin"
)
func checkCors(r *http.Request, origin []string) (allowed bool) {
var mAllowed bool
for _, m := range defaultAllowMethods {
if m == r.Method {
mAllowed = true
break
}
}
if !mAllowed {
return
}
org := r.Header.Get(headerOrigin)
var oAllowed bool
for _, o := range origin {
if o == org || o == "*" || org == "*" {
oAllowed = true
break
}
}
if oAllowed && mAllowed {
allowed = true
}
return
}