Преглед на файлове

Make it possible to export the stubs

Originally I wanted to export the responses from the log, so that will
come next.
Lu Stadler преди 7 години
родител
ревизия
3b406163aa
променени са 1 файла, в които са добавени 27 реда и са изтрити 5 реда
  1. 27 5
      go/fake-http/fake-http.go

+ 27 - 5
go/fake-http/fake-http.go

@ -114,12 +114,15 @@ func main() {
114 114
	})
115 115
116 116
	http.HandleFunc("/_stubs", func(w http.ResponseWriter, req *http.Request) {
117
		w.Header().Set("Content-Type", "text/html")
118
		fmt.Fprintf(w, "<!doctype html><html><head><style>pre{max-width:100vw;padding:0.5em;background-color:#eee;white-space:pre-wrap;}</style></head><body><ul>\n")
119
		for _, resp := range responses {
120
			fmt.Fprintf(w, "<li><pre>%s</pre></li>\n", resp.String())
117
		var err error
118
		if strings.Contains(req.Header.Get("Accept"), "application/yaml") {
119
			err = renderYAML(w, responses)
120
		} else {
121
			err = renderHTML(w, responses)
122
		}
123
		if err != nil {
124
			log.Printf("Error: Rendering stubs: %s", err)
121 125
		}
122
		fmt.Fprintf(w, "\n</ul></body></html>")
123 126
	})
124 127
125 128
	http.HandleFunc("/_help", func(w http.ResponseWriter, req *http.Request) {
@ -250,6 +253,25 @@ func prettyfyJSON(r io.Reader) ([]byte, error) {
250 253
	return json.MarshalIndent(val, "", "    ")
251 254
}
252 255
256
func renderYAML(w http.ResponseWriter, responses []Response) error {
257
	out, err := yaml.Marshal(responses)
258
	if err != nil {
259
		return err
260
	}
261
	w.Write(out)
262
	return nil
263
}
264
265
func renderHTML(w http.ResponseWriter, responses []Response) error {
266
	w.Header().Set("Content-Type", "text/html")
267
	fmt.Fprintf(w, "<!doctype html><html><head><style>pre{max-width:100vw;padding:0.5em;background-color:#eee;white-space:pre-wrap;}</style></head><body><ul>\n")
268
	for _, resp := range responses {
269
		fmt.Fprintf(w, "<li><pre>%s</pre></li>\n", resp.String())
270
	}
271
	fmt.Fprintf(w, "\n</ul></body></html>")
272
	return nil
273
}
274
253 275
// Request is a stored serialized HTTP request.
254 276
type Request []byte
255 277