-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
82 lines (60 loc) · 1.66 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"time"
"gopkg.in/yaml.v3"
)
func generateHandleFunc(e Endpoint) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Duration(e.Delay) * time.Millisecond)
for i := 0; i <= len(e.Headers)-1; i++ {
current := e.Headers[i]
w.Header().Add(current.Name, current.Value)
}
w.WriteHeader(e.Status)
strBody, ok := e.Body.(string)
if ok {
fmt.Fprintf(w, "%s", strBody)
} else {
jsonEncoded, _ := json.Marshal(e.Body)
fmt.Fprintf(w, "%s", string(jsonEncoded))
}
}
}
func serveMockAPI(data []byte) {
mux := http.NewServeMux()
t := Config{}
err := yaml.Unmarshal([]byte(data), &t)
if err != nil {
log.Fatalf("err %v", err)
}
for i := 0; i <= len(t.Endpoints)-1; i++ {
currentEndpoint := t.Endpoints[i]
var muxPath string = fmt.Sprintf("%s %s", currentEndpoint.Method, currentEndpoint.Path)
log.Println("Route Added: ", muxPath)
mux.HandleFunc(muxPath, generateHandleFunc(t.Endpoints[i]))
}
log.Printf("Running Server... http://localhost:%d\n", t.Port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", "", t.Port), mux))
}
func main() {
if len(os.Args) < 2 {
log.Fatalln("Missing configuration (*.yml) file.")
}
configFile := os.Args[1]
fullConfigPath, err := filepath.Abs(configFile)
if err != nil {
log.Fatalf("Could not get absolute path of configuration: %v", err)
}
log.Println("Configuration File Loaded:", fullConfigPath)
config, err := os.ReadFile(fullConfigPath)
if err != nil {
log.Fatalf("Could not read configuration: %v", err)
}
serveMockAPI([]byte(config))
}