1
0
dwelling-radio/internal/http/http.go

52 lines
842 B
Go
Raw Permalink Normal View History

2023-02-07 02:26:10 +04:00
package http
2022-03-08 01:17:24 +04:00
import (
"context"
"log"
"net"
"net/http"
"os"
"time"
)
type HttpServer struct {
2023-05-26 23:55:40 +04:00
s http.Server
2022-03-08 01:17:24 +04:00
}
2023-05-26 23:55:40 +04:00
func NewHttpServer(r http.Handler) *HttpServer {
return &HttpServer{s: http.Server{
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
Handler: r}}
2022-03-08 01:17:24 +04:00
}
func (s *HttpServer) Start(network, address string) error {
listener, err := net.Listen(network, address)
if err != nil {
return err
}
if listener.Addr().Network() == "unix" {
os.Chmod(address, 0777)
}
go func() {
2023-05-26 23:55:40 +04:00
if err = s.s.Serve(listener); err != nil && err != http.ErrServerClosed {
2022-03-08 01:17:24 +04:00
log.Fatalln(err)
}
}()
return nil
}
func (s *HttpServer) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
2023-05-26 23:55:40 +04:00
if err := s.s.Shutdown(ctx); err != nil {
2022-03-08 01:17:24 +04:00
return err
}
return nil
}