-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
148 lines (128 loc) · 3.31 KB
/
main.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/bronze1man/yaml2json/y2jLib"
)
var (
listenAddr string
listenPort int
authKey string
urlSubPath string
Version string
)
func parseConfigs() {
var err error = nil
// parse env vars
if addr := os.Getenv("Y2JS_LISTEN_ADDR"); addr != "" {
listenAddr = addr
} else {
listenAddr = "0.0.0.0"
}
if port := os.Getenv("Y2JS_LISTEN_PORT"); port != "" {
listenPort, err = strconv.Atoi(port)
if err != nil {
log.Fatalf("Bad port number: %s", port)
}
} else {
listenPort = 8080
}
authKey = os.Getenv("Y2JS_AUTH_KEY")
if subPath := os.Getenv("Y2JS_URL_SUB_PATH"); subPath != "" {
urlSubPath = subPath
} else {
urlSubPath = "/"
}
// parse cmd-line args
showVersion := false
flag.StringVar(&listenAddr, "listen", listenAddr, "HTTP listen address")
flag.IntVar(&listenPort, "port", listenPort, "HTTP listen port")
flag.StringVar(&authKey, "key", authKey, "HTTP-API auth key")
flag.StringVar(&urlSubPath, "sub-path", urlSubPath, "HTTP Serve sub-path")
flag.BoolVar(&showVersion, "version", false, "Print the version and exit")
flag.Parse()
// check configs
if showVersion {
if Version == "" {
Version = "development"
}
fmt.Println("yaml2json-server Version:", Version)
os.Exit(0)
}
if listenPort < 0 || listenPort > 65535 {
log.Fatalf("Bad port number: %d", listenPort)
}
}
func checkAuth(r *http.Request, key string) bool {
// check key in URL
if r.URL.Query().Get("key") == key {
return true
}
// check http basic auth
auth := r.Header.Get("Authorization")
if auth != "" && strings.HasPrefix(auth, "Basic ") {
payload, _ := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic "))
if string(payload) == ":"+key {
return true
}
}
return false
}
func httpReturnError(w http.ResponseWriter, statusCode int, reason string) {
w.WriteHeader(statusCode)
errorResponse := map[string]string{"error": reason}
_ = json.NewEncoder(w).Encode(errorResponse)
}
func httpHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// authentication
if authKey != "" {
if !checkAuth(r, authKey) {
httpReturnError(w, http.StatusUnauthorized, "Unauthorized")
return
}
}
// read YAML from given URL
urlParam := r.URL.Query().Get("url")
if urlParam != "" {
resp, err := http.Get(urlParam)
if err != nil {
httpReturnError(w, http.StatusBadRequest, "Failed to fetch YAML from given URL")
return
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
err = y2jLib.TranslateStream(resp.Body, w)
if err != nil {
httpReturnError(w, http.StatusInternalServerError, "Failed to convert YAML to JSON")
return
}
} else {
// or, parse YAML from request body
if r.ContentLength == 0 {
httpReturnError(w, http.StatusBadRequest, "No YAML to convert")
return
}
err := y2jLib.TranslateStream(r.Body, w)
if err != nil {
httpReturnError(w, http.StatusInternalServerError, "Failed to convert YAML to JSON")
return
}
}
}
func main() {
parseConfigs()
http.HandleFunc(urlSubPath, httpHandler)
addr := fmt.Sprintf("%s:%d", listenAddr, listenPort)
log.Printf("yaml2json-server is listening on %s%s", addr, urlSubPath)
log.Fatal(http.ListenAndServe(addr, nil))
}