package main import ( "encoding/json" "net/http" "os" "time" "github.com/rs/zerolog/log" "github.com/urfave/cli/v2" "gopkg.in/yaml.v3" ) type config struct { Routen []routeConfig `yaml:"routen"` } type routeConfig struct { Path string ResponseHTTPStatus int `yaml:"response_http_status"` ResponseBody string `yaml:"response_body"` ResponseFile string `yaml:"response_file"` ResponseHeaders map[string]string `yaml:"response_header"` } type requestData struct { Path string `json:"path"` Time time.Time `json:"time"` } var requestDataList []requestData func (ro routeConfig) httpHandler(w http.ResponseWriter, r *http.Request) { if ro.ResponseHTTPStatus != 0 { w.WriteHeader(ro.ResponseHTTPStatus) } for v := range ro.ResponseHeaders { w.Header().Add(v, ro.ResponseHeaders[v]) } if ro.ResponseBody != "" { _, err := w.Write([]byte(ro.ResponseBody)) if err != nil { log.Error().Err(err).Msg("cant write body to response writer") } } if ro.ResponseFile != "" { content, err := os.ReadFile(ro.ResponseFile) if err != nil { log.Error().Err(err).Msg("cant read response file") } _, err = w.Write(content) if err != nil { log.Error().Err(err).Msg("cant write body to response writer") } } rde := requestData{ Path: r.URL.Path, Time: time.Now(), } requestDataList = append(requestDataList, rde) } func main() { app := &cli.App{ Name: "run", Usage: "Run the minimock http server", Flags: []cli.Flag{ &cli.StringFlag{ Name: "config", Aliases: []string{"c"}, Usage: "Load configuration from `FILE`", Value: "config.yml", }, }, Action: action, } if err := app.Run(os.Args); err != nil { log.Fatal().Err(err).Msg("Finish App") } } func action(c *cli.Context) error { log.Info().Msg("Start") fileContent, err := os.ReadFile(c.String("config")) if err != nil { return err } co := config{} err = yaml.Unmarshal(fileContent, &co) if err != nil { return err } initServer(co) err = http.ListenAndServe(":3333", nil) return err } func initServer(c config) { for _, ro := range c.Routen { log.Debug().Str("path", ro.Path).Msg("Register Route") http.HandleFunc(ro.Path, ro.httpHandler) } http.HandleFunc("/requestlog", func(w http.ResponseWriter, r *http.Request) { data, err := json.Marshal(requestDataList) if err != nil { log.Error().Err(err).Msg("cant marshal request data list") return } _, err = w.Write(data) if err != nil { log.Error().Err(err).Msg("error writing responste data lsit via http") } }) }