1
0

Updated HttpServer to the latest implementation.

This commit is contained in:
Alexander Andreev 2023-08-13 02:25:04 +04:00
parent 6cf74599cc
commit 54bc8d744d
Signed by: Arav
GPG Key ID: D22A817D95815393
2 changed files with 28 additions and 22 deletions

View File

@ -7,10 +7,8 @@ import (
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"net/netip"
"os" "os"
"os/signal" "os/signal"
"strings"
"syscall" "syscall"
"git.arav.su/Arav/httpr" "git.arav.su/Arav/httpr"
@ -32,23 +30,6 @@ func main() {
return return
} }
var network string
if !strings.ContainsRune(*listenAddress, ':') {
network = "unix"
defer os.Remove(*listenAddress)
} else {
ap, err := netip.ParseAddrPort(*listenAddress)
if err != nil {
log.Fatalln(err)
}
if ap.Addr().Is4() {
network = "tcp4"
} else if ap.Addr().Is6() {
network = "tcp6"
}
}
hand := dwhttp.New(directoryPath, !*enableFileHandler) hand := dwhttp.New(directoryPath, !*enableFileHandler)
r := httpr.New() r := httpr.New()
@ -58,7 +39,7 @@ func main() {
r.Handler(http.MethodGet, "/", hand.Index) r.Handler(http.MethodGet, "/", hand.Index)
srv := dwhttp.NewHttpServer(r) srv := dwhttp.NewHttpServer(r)
if err := srv.Start(network, *listenAddress); err != nil { if err := srv.Start(*listenAddress); err != nil {
log.Fatalln(err) log.Fatalln(err)
} }

View File

@ -5,12 +5,15 @@ import (
"log" "log"
"net" "net"
"net/http" "net/http"
"net/netip"
"os" "os"
"strings"
"time" "time"
) )
type HttpServer struct { type HttpServer struct {
s http.Server s http.Server
addr net.Addr
} }
func NewHttpServer(r http.Handler) *HttpServer { func NewHttpServer(r http.Handler) *HttpServer {
@ -20,7 +23,23 @@ func NewHttpServer(r http.Handler) *HttpServer {
Handler: r}} Handler: r}}
} }
func (s *HttpServer) Start(network, address string) error { 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"
}
}
listener, err := net.Listen(network, address) listener, err := net.Listen(network, address)
if err != nil { if err != nil {
return err return err
@ -30,6 +49,8 @@ func (s *HttpServer) Start(network, address string) error {
os.Chmod(address, 0777) os.Chmod(address, 0777)
} }
s.addr = listener.Addr()
go func() { go func() {
if err = s.s.Serve(listener); err != nil && err != http.ErrServerClosed { if err = s.s.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalln(err) log.Fatalln(err)
@ -43,6 +64,10 @@ func (s *HttpServer) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
if s.addr.Network() == "unix" {
defer os.Remove(s.addr.String())
}
if err := s.s.Shutdown(ctx); err != nil { if err := s.s.Shutdown(ctx); err != nil {
return err return err
} }