bootstrap.go 1.8 KB

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