Skip to content

Commit

Permalink
Backend: add a wrapper around the http.Server type.
Browse files Browse the repository at this point in the history
  • Loading branch information
paveloom committed Sep 19, 2024
1 parent 3cfa26c commit 0018097
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 28 deletions.
30 changes: 2 additions & 28 deletions backend/flowey.go
Original file line number Diff line number Diff line change
@@ -1,44 +1,18 @@
package main

import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
)

func run() error {
if len(os.Args) < 2 {
return errors.New("no address specified")
}
address := os.Args[1]
server := &http.Server{Addr: address, Handler: Handler{}}
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
log.Printf("listening at %v", address)

sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)

errs := make(chan error, 1)
go func() {
errs <- server.Serve(listener)
}()

select {
case <-sigint:
fmt.Print("\rinterrupting...\n")
case err := <-errs:
log.Printf("failed to serve: %w", err)
}

return server.Shutdown(context.Background())
server := NewFloweyServer(address)
return server.ListenAndServe()
}

func main() {
Expand Down
48 changes: 48 additions & 0 deletions backend/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package main

import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
)

type FloweyServer struct {
http.Server
}

func NewFloweyServer(address string) *FloweyServer {
var f FloweyServer
f.Addr = address
f.Handler = Handler{}
return &f
}

func (f *FloweyServer) ListenAndServe() error {
listener, err := net.Listen("tcp", f.Addr)
if err != nil {
return err
}
log.Printf("listening at %v", f.Addr)

sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)

errs := make(chan error, 1)
go func() {
errs <- f.Serve(listener)
}()

select {
case <-sigint:
fmt.Print("\rinterrupting...\n")
case err := <-errs:
log.Printf("failed to serve: %w", err)
}

return f.Shutdown(context.Background())

}

0 comments on commit 0018097

Please sign in to comment.