bootstrap.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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("Content-Type", "text/css")
  26. w.Write(resource_bootstrap_css)
  27. return
  28. } else if r.URL.Path == "/"+this.path+"/bootstrap.js" {
  29. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  30. w.Write(resource_bootstrap_js)
  31. return
  32. } else if r.URL.Path == "/"+this.path+"/jquery.js" {
  33. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  34. w.Write(resource_jquery_js)
  35. return
  36. } else if r.URL.Path == "/"+this.path+"/popper.js" {
  37. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  38. w.Write(resource_popper_js)
  39. return
  40. }
  41. if this.after != nil {
  42. this.after(w, r)
  43. }
  44. }
  45. func Start(h hndl, host string, timeout time.Duration, path string, before callback, after callback) {
  46. mux := http.NewServeMux()
  47. mux.HandleFunc("/", new(path, before, after).handler)
  48. var srv *http.Server
  49. if h == nil {
  50. srv = &http.Server{
  51. Addr: host,
  52. Handler: mux,
  53. }
  54. } else {
  55. srv = &http.Server{
  56. Addr: host,
  57. Handler: h(mux),
  58. }
  59. }
  60. stop := make(chan os.Signal)
  61. signal.Notify(stop, os.Interrupt)
  62. go func() {
  63. fmt.Printf("Starting server at http://%s/\n", host)
  64. if err := srv.ListenAndServe(); err != nil {
  65. if err != http.ErrServerClosed {
  66. fmt.Println(err)
  67. }
  68. }
  69. }()
  70. <-stop
  71. fmt.Println("Shutting down server...")
  72. ctx, cancel := context.WithTimeout(context.Background(), timeout*time.Second)
  73. defer cancel()
  74. if err := srv.Shutdown(ctx); err != nil {
  75. fmt.Println(err)
  76. }
  77. }