webserv.go 3.3 KB

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