webserv.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. package webserv
  2. import (
  3. "embed"
  4. _ "embed"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "os"
  10. "path/filepath"
  11. "sync"
  12. "imuslab.com/zoraxy/mod/utils"
  13. )
  14. /*
  15. Static Web Server package
  16. This module host a static web server
  17. */
  18. //go:embed templates/*
  19. var templates embed.FS
  20. type WebServerOptions struct {
  21. Port string //Port for listening
  22. EnableDirectoryListing bool //Enable listing of directory
  23. WebRoot string //Folder for stroing the static web folders
  24. }
  25. type WebServer struct {
  26. mux *http.ServeMux
  27. server *http.Server
  28. option *WebServerOptions
  29. isRunning bool
  30. mu sync.Mutex
  31. }
  32. // NewWebServer creates a new WebServer instance.
  33. func NewWebServer(options *WebServerOptions) *WebServer {
  34. if !utils.FileExists(options.WebRoot) {
  35. //Web root folder not exists. Create one
  36. os.MkdirAll(filepath.Join(options.WebRoot, "html"), 0775)
  37. os.MkdirAll(filepath.Join(options.WebRoot, "templates"), 0775)
  38. indexTemplate, err := templates.ReadFile("templates/index.html")
  39. if err != nil {
  40. log.Println("Failed to read static wev server template file: ", err.Error())
  41. } else {
  42. os.WriteFile(filepath.Join(options.WebRoot, "html", "index.html"), indexTemplate, 0775)
  43. }
  44. }
  45. return &WebServer{
  46. mux: http.NewServeMux(),
  47. option: options,
  48. isRunning: false,
  49. mu: sync.Mutex{},
  50. }
  51. }
  52. // ChangePort changes the server's port.
  53. func (ws *WebServer) ChangePort(port string) error {
  54. ws.mu.Lock()
  55. defer ws.mu.Unlock()
  56. if ws.isRunning {
  57. if err := ws.Stop(); err != nil {
  58. return err
  59. }
  60. }
  61. ws.option.Port = port
  62. ws.server.Addr = ":" + port
  63. return nil
  64. }
  65. // Start starts the web server.
  66. func (ws *WebServer) Start() error {
  67. ws.mu.Lock()
  68. defer ws.mu.Unlock()
  69. //Check if server already running
  70. if ws.isRunning {
  71. return fmt.Errorf("web server is already running")
  72. }
  73. //Check if the port is usable
  74. if IsPortInUse(ws.option.Port) {
  75. return errors.New("Port already in use or access denied by host OS")
  76. }
  77. //Dispose the old mux and create a new one
  78. ws.mux = http.NewServeMux()
  79. //Create a static web server
  80. fs := http.FileServer(http.Dir(filepath.Join(ws.option.WebRoot, "html")))
  81. ws.mux.Handle("/", ws.fsMiddleware(fs))
  82. ws.server = &http.Server{
  83. Addr: ":" + ws.option.Port,
  84. Handler: ws.mux,
  85. }
  86. go func() {
  87. if err := ws.server.ListenAndServe(); err != nil {
  88. if err != http.ErrServerClosed {
  89. fmt.Printf("Web server error: %v\n", err)
  90. }
  91. }
  92. }()
  93. log.Println("Static Web Server started. Listeing on :" + ws.option.Port)
  94. ws.isRunning = true
  95. return nil
  96. }
  97. // Stop stops the web server.
  98. func (ws *WebServer) Stop() error {
  99. ws.mu.Lock()
  100. defer ws.mu.Unlock()
  101. if !ws.isRunning {
  102. return fmt.Errorf("web server is not running")
  103. }
  104. if err := ws.server.Close(); err != nil {
  105. return err
  106. }
  107. ws.isRunning = false
  108. return nil
  109. }
  110. // UpdateDirectoryListing enables or disables directory listing.
  111. func (ws *WebServer) UpdateDirectoryListing(enable bool) {
  112. ws.mu.Lock()
  113. defer ws.mu.Unlock()
  114. ws.option.EnableDirectoryListing = enable
  115. }
  116. // Close stops the web server without returning an error.
  117. func (ws *WebServer) Close() {
  118. ws.Stop()
  119. }