forked from fwhezfwhez/tcpx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (95 loc) · 2.22 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
// export http api to validate stream from all language clients
package main
import (
"encoding/json"
"encoding/xml"
"io/ioutil"
"net/http"
"time"
"github.com/CocoKelam/tcpx"
"github.com/CocoKelam/tcpx/all-language-clients/model"
"github.com/rs/cors"
)
type H map[string]interface{}
type C struct {
w http.ResponseWriter
r *http.Request
}
func (c *C) Bind(dest interface{}) error {
buf, e := ioutil.ReadAll(c.r.Body)
if e != nil {
return e
}
return json.Unmarshal(buf, dest)
}
func (c *C) JSON(statusCode int, data interface{}) {
c.w.WriteHeader(statusCode)
buf, _ := json.Marshal(data)
c.w.Write(buf)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/tcpx/clients/stream/", func(w http.ResponseWriter, r *http.Request) {
var c = C{
w: w,
r: r,
}
type Param struct {
Stream []byte `json:"stream"`
MarshalName string `json:"marshal_name"`
}
var param Param
e := c.Bind(¶m)
if e != nil {
c.JSON(400, H{"message": e.Error()})
return
}
var user interface{}
type JSONUser struct {
Username string `json:"username"`
}
type XMLUser struct {
XMLName xml.Name `xml:"xml"`
Username string `xml:"username"`
}
type TOMLUser struct {
Username string `toml:"username"`
}
type YAMLUser struct {
Username string `yaml:"username"`
}
switch param.MarshalName {
case "json":
user = &JSONUser{}
case "xml":
user = &XMLUser{}
case "toml", "tml":
user = &TOMLUser{}
case "yaml", "yml":
user = &YAMLUser{}
case "protobuf", "proto":
user = &model.User{}
default:
c.JSON(400, H{"message": "marshal_name only accept ['json', 'xml', 'toml','yaml','protobuf']"})
return
}
message, e := tcpx.UnpackWithMarshallerName(param.Stream, user, param.MarshalName)
if e != nil {
c.JSON(400, H{"message": e.Error(), "result": "not ok"})
return
}
c.JSON(200, H{"message": "success", "result": "ok", "ms": message})
})
s := &http.Server{
Addr: ":7001",
Handler: cors.AllowAll().Handler(mux),
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 21,
}
s.ListenAndServe()
}
func Debug(src interface{}) string {
buf, _ := json.MarshalIndent(src, " ", " ")
return string(buf)
}