Просмотр исходного кода

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 лет назад: 7
Родитель
Сommit
c434d00c23
1 измененных файлов с 11 добавлено и 19 удалено
  1. 11 19
      go/fake-http/fake-http.go

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

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")
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
func main() {
46
func main() {
44
	flag.Parse()
47
	flag.Parse()
58
	requestLog := make([]LogEntry, 0)
61
	requestLog := make([]LogEntry, 0)
59
62
60
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
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
		var resp *http.Response
66
		var resp *http.Response
64
		if flags.proxyURL != "" {
67
		if flags.proxyURL != "" {
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
	http.HandleFunc("/_help", func(w http.ResponseWriter, req *http.Request) {
120
	http.HandleFunc("/_help", func(w http.ResponseWriter, req *http.Request) {
127
		urls := []struct {
121
		urls := []struct {
128
			URL     string
122
			URL     string
359
	return r
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
	if err != nil {
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
	out, err := ioutil.ReadFile(path)
366
	out, err := ioutil.ReadFile(path)
375
	if err != nil {
367
	if err != nil {
376
		return nil, err
368
		return nil, err