feat: add *Server.Stop method (#1863)

* feat: add `*Server.Stop` method

Signed-off-by: Dwi Siswanto <git@dw1.io>

* feat: implement `*Server.Stop`

Signed-off-by: Dwi Siswanto <git@dw1.io>

---------

Signed-off-by: Dwi Siswanto <git@dw1.io>
This commit is contained in:
Dwi Siswanto
2024-08-14 23:20:14 +07:00
committed by GitHub
parent 2fd380afbc
commit d2742ae00c
2 changed files with 28 additions and 4 deletions
+24 -4
View File
@@ -2,6 +2,9 @@
package runner
import (
"context"
"time"
"encoding/json"
"net/http"
)
@@ -12,8 +15,9 @@ type Concurrency struct {
// Server represents the HTTP server that handles the concurrency settings endpoints.
type Server struct {
addr string
config *Options
addr string
config *Options
httpServer *http.Server
}
// New creates a new instance of Server.
@@ -26,10 +30,18 @@ func NewServer(addr string, config *Options) *Server {
// Start initializes the server and its routes, then starts listening on the specified address.
func (s *Server) Start() error {
http.HandleFunc("/api/concurrency", s.handleConcurrency)
if err := http.ListenAndServe(s.addr, nil); err != nil {
mux := http.NewServeMux()
mux.HandleFunc("/api/concurrency", s.handleConcurrency)
s.httpServer = &http.Server{
Addr: s.addr,
Handler: mux,
}
if err := s.httpServer.ListenAndServe(); err != nil {
return err
}
return nil
}
@@ -71,3 +83,11 @@ func (s *Server) updateSettings(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
// Stop gracefully shuts down the server.
func (s *Server) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return s.httpServer.Shutdown(ctx)
}
+4
View File
@@ -671,6 +671,7 @@ func (r *Runner) Close() {
r.hm.Close()
r.hp.Dialer.Close()
r.ratelimiter.Stop()
if r.options.HostMaxErrors >= 0 {
r.HostErrorsCache.Purge()
}
@@ -680,6 +681,9 @@ func (r *Runner) Close() {
if r.options.ShowStatistics {
_ = r.stats.Stop()
}
if r.options.HttpApiEndpoint != "" {
_ = r.httpApiEndpoint.Stop()
}
if r.options.OnClose != nil {
r.options.OnClose()
}