bootstrap.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. }
  72. }
  73. }()
  74. <-stop
  75. fmt.Println("Shutting down server...")
  76. ctx, cancel := context.WithTimeout(context.Background(), timeout*time.Second)
  77. defer cancel()
  78. if err := srv.Shutdown(ctx); err != nil {
  79. fmt.Println(err)
  80. }
  81. }