main.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package main
  2. import (
  3. "bytes"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "time"
  13. )
  14. func main() {
  15. port := flag.String("p", "8080", "Listening port")
  16. // postFileDir = flag.String("pfd", "none", "Directory for saving files from POST multi-part requests. If 'none' - files will not be saved.")
  17. stdout := flag.Bool("stdout", true, "Enable print requests to standart output.")
  18. logdir := flag.String("logdir", "", `Directory for saving requests history. If "" - requests will not be saved.`)
  19. flag.Parse()
  20. //Check that all flags are correct
  21. if flag.NArg() > 0 {
  22. fmt.Println("Incorrect argument. Please see help below:")
  23. flag.PrintDefaults()
  24. os.Exit(0)
  25. }
  26. var wr io.Writer
  27. if *logdir != "" {
  28. var logfile *os.File
  29. fi, err := os.Stat(*logdir)
  30. if err != nil {
  31. log.Fatalf("Incorrect log directory: %v", err)
  32. }
  33. if !fi.IsDir() {
  34. log.Fatalf("%q is not directory.", *logdir)
  35. }
  36. logfile, err = os.Create(filepath.Join(*logdir, "stubserver.log")) //todo change hardcorded name to current date
  37. if err != nil {
  38. log.Fatalf("Error creating log file: %v", err)
  39. }
  40. defer logfile.Close()
  41. if *stdout {
  42. wr = io.MultiWriter(os.Stdout, logfile)
  43. } else {
  44. wr = logfile
  45. }
  46. } else {
  47. if *stdout {
  48. wr = os.Stdout
  49. } else {
  50. wr = ioutil.Discard
  51. }
  52. }
  53. log.SetOutput(wr)
  54. http.HandleFunc("/", root)
  55. fmt.Printf("Server started and listen %s port\n", *port)
  56. if err := http.ListenAndServe("localhost:"+*port, nil); err != nil {
  57. log.Fatalf("Error start server: %v", err)
  58. }
  59. }
  60. func root(w http.ResponseWriter, r *http.Request) {
  61. startTime := time.Now()
  62. buf := &bytes.Buffer{}
  63. //Print method, url and protocol
  64. fmt.Fprintf(buf, "%s %s %s\n", r.Method, r.RequestURI, r.Proto)
  65. //Print headers
  66. for k, v := range r.Header {
  67. fmt.Fprintf(buf, "%s: ", k)
  68. for _, value := range v {
  69. buf.WriteString(value)
  70. }
  71. fmt.Fprintln(buf)
  72. }
  73. // Try parse and print data from form if exist
  74. err := r.ParseForm()
  75. if err != nil {
  76. fmt.Fprintf(buf, "Error parse form: %v", err)
  77. }
  78. form := r.Form
  79. if form != nil && len(form) > 0 {
  80. fmt.Fprintf(buf, "\nForm data:\n")
  81. for k, v := range form {
  82. fmt.Fprintf(buf, "%s: ", k)
  83. for _, value := range v {
  84. buf.WriteString(value)
  85. }
  86. fmt.Fprintln(buf)
  87. }
  88. }
  89. multipart := r.MultipartForm
  90. if multipart != nil {
  91. for filek := range multipart.File {
  92. buf.WriteString("multipart: " + filek)
  93. }
  94. } else {
  95. buf.WriteString("multipart is empty\n")
  96. }
  97. //Print body if exists
  98. body := r.Body
  99. defer body.Close()
  100. content, err := ioutil.ReadAll(body)
  101. if err != nil {
  102. buf.WriteString("Error getting body\n")
  103. }
  104. if len(content) != 0 {
  105. fmt.Fprintf(buf, "\nBody:\n")
  106. buf.Write(content)
  107. }
  108. buf.WriteString(fmt.Sprintf("\nRequest processing time: %s", time.Since(startTime)))
  109. //Send response
  110. fmt.Fprint(w, buf)
  111. printOut(buf)
  112. }
  113. // printOut function print output to standart output and/or file depends on command line arguments
  114. func printOut(srcbuf *bytes.Buffer) {
  115. buf := new(bytes.Buffer)
  116. buf.WriteString("---------- Start request ----------\n")
  117. srcbuf.WriteTo(buf)
  118. buf.WriteString("\n---------- End request ----------\n")
  119. log.Println(buf)
  120. }