handler.go 1002 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "time"
  6. )
  7. type timeHandler struct {
  8. format string
  9. }
  10. func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  11. tm := time.Now().Format(th.format)
  12. w.Write([]byte("The time is: " + tm))
  13. }
  14. func handler(w http.ResponseWriter, r *http.Request) {
  15. w.Write([]byte("OK!"))
  16. }
  17. func main() {
  18. /*
  19. // создаем свой serveMux
  20. serveMux := http.NewServeMux()
  21. serveMux.HandleFunc("/", handler)
  22. // Запускаем веб-сервер на порту 8080 с нашим serveMux
  23. // (в прошлых примерах был nil)
  24. err := http.ListenAndServe(":8080" serverMux)
  25. if err != nil {
  26. fmt.Println("Ошибка запуска сервера:", err)
  27. }
  28. */
  29. mux := http.NewServeMux()
  30. th1123 := &timeHandler{format: time.RFC1123}
  31. mux.Handle("/time/rfc1123", th1123)
  32. th3339 := &timeHandler{format: time.RFC3339}
  33. mux.Handle("/time/rfc3339", th3339)
  34. log.Println("Listening...")
  35. http.ListenAndServe(":3000", mux)
  36. }