forked from decred/dcrwebapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
68 lines (60 loc) · 2.23 KB
/
helper.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
// Copyright (c) 2017-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"math"
"net/http"
"strings"
)
const (
// semanticBuildAlphabet defines the allowed characters for the build
// portion of a semantic version string.
semanticBuildAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.+"
)
// normalizeSemString returns the passed string stripped of all characters
// which are not valid according to the provided semantic versioning alphabet.
func normalizeSemString(str, alphabet string) string {
var result bytes.Buffer
for _, r := range str {
if strings.ContainsRune(alphabet, r) {
result.WriteRune(r)
}
}
return result.String()
}
// NormalizeBuildString returns the passed string stripped of all characters
// which are not valid according to the semantic versioning guidelines for build
// metadata strings. In particular they MUST only contain characters in
// semanticBuildAlphabet.
func NormalizeBuildString(str string) string {
return normalizeSemString(str, semanticBuildAlphabet)
}
// writeJSONResponse convenience func for writing json responses
func writeJSONResponse(writer *http.ResponseWriter, code int,
respJSON *[]byte) {
(*writer).Header().Set("Content-Type", "application/json")
(*writer).Header().Set("Strict-Transport-Security", "max-age=15552001")
(*writer).Header().Set("Vary", "Accept-Encoding")
(*writer).Header().Set("X-Content-Type-Options", "nosniff")
(*writer).WriteHeader(code)
(*writer).Write(*respJSON)
}
// writeJSONErrorResponse convenience func for writing json error responses
func writeJSONErrorResponse(writer *http.ResponseWriter, code int, err error) {
errorBody := map[string]interface{}{}
errorBody["error"] = err.Error()
errorJSON, _ := json.Marshal(errorBody)
(*writer).Header().Set("Content-Type", "application/json")
(*writer).Header().Set("Strict-Transport-Security", "max-age=15552001")
(*writer).Header().Set("Vary", "Accept-Encoding")
(*writer).WriteHeader(code)
(*writer).Write(errorJSON)
}
// round rounding func
func round(f float64, places uint) float64 {
shift := math.Pow(10, float64(places))
return math.Floor(f*shift+.5) / shift
}