github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/http/http.go (about)

     1  package http
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"net"
     8  	"net/http"
     9  	"time"
    10  
    11  	"github.com/rs/zerolog"
    12  )
    13  
    14  type server struct {
    15  	srv *http.Server
    16  }
    17  
    18  func NewServer(ctx context.Context, handler http.Handler, cfg Config) *server {
    19  	stdlog := log.New(cfg.Logger, "", 0)
    20  
    21  	return &server{
    22  		srv: &http.Server{
    23  			Addr:         cfg.ListenAddr,
    24  			Handler:      handler,
    25  			ErrorLog:     stdlog,
    26  			ReadTimeout:  cfg.ReadTimeout,
    27  			WriteTimeout: cfg.WriteTimeout,
    28  			IdleTimeout:  cfg.IdleTimeout,
    29  			BaseContext:  func(net.Listener) context.Context { return ctx },
    30  		},
    31  	}
    32  }
    33  
    34  func (s *server) ListenAddr() string {
    35  	return s.srv.Addr
    36  }
    37  
    38  func (s *server) Run(l net.Listener) error {
    39  	s.srv.ErrorLog.Printf("Starting HTTP server on %s...", s.srv.Addr)
    40  
    41  	err := s.srv.Serve(l)
    42  	if err != nil && err != http.ErrServerClosed {
    43  		return fmt.Errorf("could not serve HTTP on %s: %w", s.srv.Addr, err)
    44  	}
    45  
    46  	return nil
    47  }
    48  
    49  func (s *server) Shutdown(ctx context.Context) error {
    50  	return s.srv.Shutdown(ctx)
    51  }
    52  
    53  type Config struct {
    54  	ListenAddr   string
    55  	Logger       zerolog.Logger
    56  	ReadTimeout  time.Duration
    57  	WriteTimeout time.Duration
    58  	IdleTimeout  time.Duration
    59  }