2023-01-16 05:24:07 +04:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
2023-08-12 23:53:26 +04:00
|
|
|
"net/netip"
|
2023-01-16 05:24:07 +04:00
|
|
|
"os"
|
2023-08-12 23:53:26 +04:00
|
|
|
"strings"
|
2023-01-16 05:24:07 +04:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HttpServer struct {
|
2023-08-12 23:53:26 +04:00
|
|
|
s http.Server
|
|
|
|
addr net.Addr
|
2023-01-16 05:24:07 +04:00
|
|
|
}
|
|
|
|
|
2023-05-27 20:57:00 +04:00
|
|
|
func NewHttpServer(r http.Handler) *HttpServer {
|
|
|
|
return &HttpServer{s: http.Server{
|
|
|
|
ReadTimeout: 3 * time.Second,
|
|
|
|
WriteTimeout: 3 * time.Second,
|
|
|
|
Handler: r}}
|
2023-01-16 05:24:07 +04:00
|
|
|
}
|
|
|
|
|
2023-08-12 23:53:26 +04:00
|
|
|
func (s *HttpServer) Start(address string) error {
|
|
|
|
var network string
|
|
|
|
if !strings.ContainsRune(address, ':') {
|
|
|
|
network = "unix"
|
|
|
|
} else {
|
|
|
|
ap, err := netip.ParseAddrPort(address)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if ap.Addr().Is4() {
|
|
|
|
network = "tcp4"
|
|
|
|
} else if ap.Addr().Is6() {
|
|
|
|
network = "tcp6"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-16 05:24:07 +04:00
|
|
|
listener, err := net.Listen(network, address)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if listener.Addr().Network() == "unix" {
|
|
|
|
os.Chmod(address, 0777)
|
|
|
|
}
|
|
|
|
|
2023-08-12 23:53:26 +04:00
|
|
|
s.addr = listener.Addr()
|
|
|
|
|
2023-01-16 05:24:07 +04:00
|
|
|
go func() {
|
2023-05-27 20:57:00 +04:00
|
|
|
if err = s.s.Serve(listener); err != nil && err != http.ErrServerClosed {
|
2023-01-16 05:24:07 +04:00
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *HttpServer) Stop() error {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2023-08-12 23:53:26 +04:00
|
|
|
if s.addr.Network() == "unix" {
|
|
|
|
defer os.Remove(s.addr.String())
|
|
|
|
}
|
|
|
|
|
2023-05-27 20:57:00 +04:00
|
|
|
if err := s.s.Shutdown(ctx); err != nil {
|
2023-01-16 05:24:07 +04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|