Quellcode durchsuchen

Refactor reloading by introducing a struct for it

It can load and update itself, which both encapsulates the logic and the
updating, which improves the usages and clarity of the program.
Lu Stadler vor 7 Jahren
Ursprung
Commit
c434d00c23
1 geänderte Dateien mit 11 neuen und 19 gelöschten Zeilen
  1. 11 19
      go/fake-http/fake-http.go

+ 11 - 19
go/fake-http/fake-http.go

@ -38,7 +38,10 @@ func init() {
38 38
	flag.BoolVar(&flags.proxyMinikube, "proxy-minikube", false, "Shortcut for -proxy-url https://$(minikube ip):8443 -proxy-client-cert ~/.minikube/client.crt -proxy-client-key ~/.minikube/client.key")
39 39
}
40 40
41
var responses = []Response{}
41
var responses Responses
42
43
// Responses is a list of responses that will be stubbed/faked.
44
type Responses []Response
42 45
43 46
func main() {
44 47
	flag.Parse()
@ -58,7 +61,7 @@ func main() {
58 61
	requestLog := make([]LogEntry, 0)
59 62
60 63
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
61
		responses = loadResponses(flag.Arg(0), false, responses)
64
		responses.Load(responsesPath)
62 65
63 66
		var resp *http.Response
64 67
		if flags.proxyURL != "" {
@ -114,15 +117,6 @@ func main() {
114 117
		}
115 118
	})
116 119
117
	http.HandleFunc("/_stubs", func(w http.ResponseWriter, req *http.Request) {
118
		responses = loadResponses(responsesPath, false, responses)
119
120
		err := renderYAML(w, responses)
121
		if err != nil {
122
			log.Printf("Error: Rendering stubs: %s", err)
123
		}
124
	})
125
126 120
	http.HandleFunc("/_help", func(w http.ResponseWriter, req *http.Request) {
127 121
		urls := []struct {
128 122
			URL     string
@ -359,18 +353,16 @@ func readResponse(form url.Values) Response {
359 353
	return r
360 354
}
361 355
362
func loadResponses(path string, abort bool, prevResponses []Response) []Response {
363
	rs, err := loadResponsesRaw(path)
356
// Load loads responses from the YAML file at path.
357
func (rs *Responses) Load(path string) {
358
	responses, err := rs.loadFile(path)
364 359
	if err != nil {
365
		if abort {
366
			log.Fatalf("Error: Parsing %s: %s", flag.Arg(0), err)
367
		}
368
		return prevResponses
360
		log.Printf("Error: Parsing %s: %s", path, err)
369 361
	}
370
	return rs
362
	*rs = responses
371 363
}
372 364
373
func loadResponsesRaw(path string) ([]Response, error) {
365
func (rs *Responses) loadFile(path string) ([]Response, error) {
374 366
	out, err := ioutil.ReadFile(path)
375 367
	if err != nil {
376 368
		return nil, err