-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
104 lines (91 loc) · 1.94 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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
flag "github.com/spf13/pflag"
)
var mocks []Mock
var kv KvStore
var bucketName []byte
var datapath string
var adminPort string
var serverPort string
func init() {
var err error
flag.StringVar(&datapath, "datapath", "", "path to store mockinfo")
flag.StringVar(&serverPort, "serverport", "80", "server port")
flag.StringVar(&adminPort, "adminport", "8089", "admin port")
flag.Parse()
if datapath == "" {
log.Fatal("miss datapath")
return
}
bucketName = []byte("httpmock")
kv, err = NewKvStore(map[string]interface{}{"bucketName": bucketName, "datapath": datapath})
if err != nil {
log.Fatal(err)
return
}
}
func mock(w http.ResponseWriter, r *http.Request) {
var schema string
var url []byte
var mock Mock
if r.TLS != nil {
schema = "https://"
} else {
schema = "http://"
}
url = []byte(schema + r.Host + r.RequestURI)
value, err := kv.Get(url)
if err != nil {
panic(err)
}
if value == nil {
panic("url has not be set")
}
err = json.Unmarshal(value, &mock)
if err != nil {
panic(err)
}
for key, value := range mock.Headers {
w.Header().Set(key, value)
}
w.Write([]byte(mock.Body))
}
func adminMocks(w http.ResponseWriter, r *http.Request) {
var mock Mock
if r.Method == "POST" {
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
err := decoder.Decode(&mock)
if err != nil {
panic(err)
}
//@todo profile
content, err := json.Marshal(mock)
if err != nil {
panic(err)
}
err = kv.Put([]byte(mock.Url), content)
if err != nil {
panic(err)
}
}
}
func main() {
finish := make(chan bool)
mockServer := http.NewServeMux()
mockServer.HandleFunc("/", mock)
adminServer := mux.NewRouter()
adminServer.HandleFunc("/mocks/", adminMocks)
go func() {
log.Fatal(http.ListenAndServe(":"+serverPort, mockServer))
}()
go func() {
log.Fatal(http.ListenAndServe(":"+adminPort, adminServer))
}()
<-finish
}