-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
68 lines (59 loc) · 1.64 KB
/
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
package utils
import (
"encoding/json"
"log"
"net/http"
"strings"
"github.com/julienschmidt/httprouter"
"github.com/rs/cors"
)
// Response ...
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Payload interface{} `json:"payload"`
}
// Send ...
func (res *Response) Send(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8;")
w.WriteHeader(200)
if res.Payload == nil && res.Code != http.StatusOK {
res.Payload = struct {
Error bool `json:"error,omitempty"`
Message string `json:"message,omitempty"`
}{
Error: true,
Message: strings.ToUpper(string(res.Message[:2])) + string(res.Message[2:]),
}
}
err := json.NewEncoder(w).Encode(res)
if err != nil {
log.Println("ERROR sending response failed:", err)
}
return
}
// AddCors ...
func AddCors(router *httprouter.Router) http.Handler {
return cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{http.MethodDelete, http.MethodGet, http.MethodPost, http.MethodPut},
AllowedHeaders: []string{"*"},
MaxAge: 10,
AllowCredentials: true,
}).Handler(router)
}
// Unique ...
func Unique(slice []string) []string {
// create a map with all the values as key
uniqMap := make(map[string]struct{})
for _, v := range slice {
uniqMap[v] = struct{}{}
}
// turn the map keys into a slice
uniqSlice := make([]string, 0, len(uniqMap))
for v := range uniqMap {
replace := strings.ReplaceAll(v, "/#", "")
uniqSlice = append(uniqSlice, replace)
}
return uniqSlice
}