-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (84 loc) · 2.18 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
package main
import (
"fmt"
"io"
"log"
"net/http"
jsoniter "github.com/json-iterator/go"
"gopkg.in/yaml.v3"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.HandleFunc("/json2yaml", json2yamlHandler)
http.HandleFunc("/yaml2json", yaml2jsonHandler)
fmt.Println("starting server on :21111")
if err := http.ListenAndServe(":21111", nil); err != nil {
log.Fatal(err)
}
}
func json2yamlHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "invalid request method", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("failed to read request body, error:%v", err)
http.Error(w, "failed to read request body", http.StatusBadRequest)
return
}
bytes, err := json2yaml(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/x-yaml")
_, _ = w.Write(bytes)
}
func yaml2jsonHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "invalid request method", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("failed to read request body, error:%v", err)
http.Error(w, "failed to read request body", http.StatusBadRequest)
return
}
bytes, err := yaml2json(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(bytes)
}
func json2yaml(data []byte) ([]byte, error) {
var tmp map[string]any
err := jsoniter.Unmarshal(data, &tmp)
if err != nil {
log.Println("json unmarshal error:", err)
return nil, err
}
out, err := yaml.Marshal(&tmp)
if err != nil {
log.Println("yaml marshal error:", err)
return nil, err
}
return out, nil
}
func yaml2json(data []byte) ([]byte, error) {
var tmp map[string]any
err := yaml.Unmarshal(data, &tmp)
if err != nil {
log.Println("yaml unmarshal error:", err)
return nil, err
}
out, err := jsoniter.MarshalIndent(&tmp, "", " ")
if err != nil {
log.Println("json marshal error:", err)
return nil, err
}
return out, nil
}