1c/Ox
1
0
mirror of https://github.com/LazarenkoA/Ox.git synced 2025-11-23 21:33:13 +02:00
Files
Ox/observer/internal/http/srv.go

95 lines
2.0 KiB
Go
Raw Normal View History

2025-10-30 15:51:56 +03:00
package http
import (
"context"
"fmt"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"io/fs"
"load_testing/observer"
2025-11-04 18:58:12 +03:00
"load_testing/observer/internal/app"
2025-10-30 15:51:56 +03:00
"log"
"log/slog"
"net/http"
2025-11-04 18:58:12 +03:00
"sync"
2025-10-30 15:51:56 +03:00
"time"
)
2025-11-04 18:58:12 +03:00
type IObserver interface {
Workers() []*app.Worker
WorkerByID(id int) *app.Worker
}
2025-10-30 15:51:56 +03:00
type HttpSrv struct {
2025-11-04 18:58:12 +03:00
port int
logger *slog.Logger
httpServ *http.Server
ws *WSServer
mx sync.Mutex
router *mux.Router
2025-10-30 15:51:56 +03:00
}
2025-11-04 18:58:12 +03:00
func NewHTTP(port int) *HttpSrv {
router := mux.NewRouter()
2025-10-30 15:51:56 +03:00
resp := &HttpSrv{
2025-11-04 18:58:12 +03:00
port: port,
router: router,
logger: slog.Default(),
2025-10-30 15:51:56 +03:00
httpServ: &http.Server{
Addr: fmt.Sprintf(":%d", port),
2025-11-04 18:58:12 +03:00
Handler: router,
2025-10-30 15:51:56 +03:00
ReadHeaderTimeout: 2 * time.Second,
},
}
2025-11-04 18:58:12 +03:00
return resp
2025-10-30 15:51:56 +03:00
}
2025-11-04 18:58:12 +03:00
func (h *HttpSrv) InitRouts(workers IObserver) error {
2025-10-30 15:51:56 +03:00
staticFS, err := fs.Sub(observer.StaticFS, "static")
if err != nil {
return err
}
2025-11-04 18:58:12 +03:00
h.router.Use(loggingMiddleware(h.logger))
h.router.Use(enableCORS)
2025-10-30 15:51:56 +03:00
// Отдаём статику (CSS/JS)
2025-11-04 18:58:12 +03:00
h.router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
h.router.HandleFunc("/", h.index(workers))
2025-10-30 15:51:56 +03:00
2025-11-04 18:58:12 +03:00
v1 := h.router.PathPrefix("/api/v1").Subrouter()
v1.HandleFunc("/workers", h.workers(workers))
v1.HandleFunc("/workers/{id}/start", h.workerStart(workers))
v1.HandleFunc("/workers/{id}/stop", h.workerStop(workers))
v1.HandleFunc("/workers/{id}/set_script", h.setScript(workers))
v1.Handle("/ws", sendWorkersStatus(workers)(http.HandlerFunc(h.openWS)))
2025-10-30 15:51:56 +03:00
return nil
}
func (h *HttpSrv) Run(ctx context.Context) error {
go func() {
<-ctx.Done()
sdCtx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
h.httpServ.Shutdown(sdCtx)
}()
2025-11-04 18:58:12 +03:00
log.Printf("http starting on port %d", h.port)
2025-10-30 15:51:56 +03:00
if err := h.httpServ.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
2025-11-04 18:58:12 +03:00
func (h *HttpSrv) WriteWSMessage(msg string) error {
if h.ws != nil && !h.ws.closed.Load() {
return h.ws.WriteMsg(msg)
}
return nil
}