bootstrap.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package bootstrap
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "time"
  9. )
  10. type hndl func(h http.Handler) http.Handler
  11. type callback func(w http.ResponseWriter, r *http.Request)
  12. type bootstrap struct {
  13. path string
  14. before callback
  15. after callback
  16. }
  17. func new(path string, before callback, after callback) *bootstrap {
  18. return &bootstrap{path, before, after}
  19. }
  20. func (this *bootstrap) handler(w http.ResponseWriter, r *http.Request) {
  21. if this.before != nil {
  22. this.before(w, r)
  23. }
  24. if r.URL.Path == "/"+this.path+"/bootstrap.css" {
  25. w.Header().Set("Cache-Control", "public, max-age=31536000")
  26. w.Header().Set("Content-Type", "text/css")
  27. w.Write(resource_bootstrap_css)
  28. return
  29. } else if r.URL.Path == "/"+this.path+"/bootstrap.js" {
  30. w.Header().Set("Cache-Control", "public, max-age=31536000")
  31. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  32. w.Write(resource_bootstrap_js)
  33. return
  34. } else if r.URL.Path == "/"+this.path+"/jquery.js" {
  35. w.Header().Set("Cache-Control", "public, max-age=31536000")
  36. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  37. w.Write(resource_jquery_js)
  38. return
  39. } else if r.URL.Path == "/"+this.path+"/popper.js" {
  40. w.Header().Set("Cache-Control", "public, max-age=31536000")
  41. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  42. w.Write(resource_popper_js)
  43. return
  44. }
  45. if this.after != nil {
  46. this.after(w, r)
  47. }
  48. }
  49. func Start(h hndl, host string, timeout time.Duration, path string, before callback, after callback) {
  50. mux := http.NewServeMux()
  51. mux.HandleFunc("/", new(path, before, after).handler)
  52. var srv *http.Server
  53. if h == nil {
  54. srv = &http.Server{
  55. Addr: host,
  56. Handler: mux,
  57. }
  58. } else {
  59. srv = &http.Server{
  60. Addr: host,
  61. Handler: h(mux),
  62. }
  63. }
  64. stop := make(chan os.Signal)
  65. signal.Notify(stop, os.Interrupt)
  66. go func() {
  67. fmt.Printf("Starting server at http://%s/\n", host)
  68. if err := srv.ListenAndServe(); err != nil {
  69. if err != http.ErrServerClosed {
  70. fmt.Println(err)
  71. stop <- os.Interrupt
  72. }
  73. }
  74. }()
  75. <-stop
  76. fmt.Println("Shutting down server...")
  77. ctx, cancel := context.WithTimeout(context.Background(), timeout*time.Second)
  78. defer cancel()
  79. if err := srv.Shutdown(ctx); err != nil {
  80. fmt.Println(err)
  81. }
  82. }