diff --git a/http/handler.go b/http/handler.go new file mode 100644 index 0000000..fc08239 --- /dev/null +++ b/http/handler.go @@ -0,0 +1,10 @@ +package http + +import "net/http" + +func NewServer() http.Handler { + mux := http.NewServeMux() + addRoutes(mux) + var handler http.Handler = mux + return handler +} diff --git a/http/helloworld.go b/http/helloworld.go new file mode 100644 index 0000000..f497ac2 --- /dev/null +++ b/http/helloworld.go @@ -0,0 +1,9 @@ +package http + +import "net/http" + +func HelloWorld(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("hello world")) + }) +} diff --git a/http/routes.go b/http/routes.go new file mode 100644 index 0000000..f53888f --- /dev/null +++ b/http/routes.go @@ -0,0 +1,10 @@ +package http + +import "net/http" + +func addRoutes( + mux *http.ServeMux, +) { + mux.Handle("/", http.NotFoundHandler()) + mux.Handle("/helloworld", HelloWorld(nil)) +} diff --git a/http/server.go b/http/server.go new file mode 100644 index 0000000..158f8c8 --- /dev/null +++ b/http/server.go @@ -0,0 +1,40 @@ +package http + +import ( + "context" + "fmt" + "log" + "net" + "net/http" + "os" + "sync" + "time" +) + +func StartServer(ctx context.Context, config struct{ Host, Port string }) error { + srv := NewServer() + httpServer := &http.Server{ + Addr: net.JoinHostPort(config.Host, config.Port), + Handler: srv, + } + go func() { + log.Printf("orphan listening on %s\n", httpServer.Addr) + if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + fmt.Fprintf(os.Stderr, "error listening and serving: %s\n", err) + } + }() + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + <-ctx.Done() + shutdownCtx := context.Background() + shutdownCtx, cancel := context.WithTimeout(shutdownCtx, 10*time.Second) + defer cancel() + if err := httpServer.Shutdown(shutdownCtx); err != nil { + fmt.Fprintf(os.Stderr, "error shutting down http server: %s\n", err) + } + }() + wg.Wait() + return nil +} diff --git a/main.go b/main.go index a3dd973..82b22dd 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,34 @@ package main -import "fmt" +import ( + "context" + "fmt" + "io" + "os" + "os/signal" + + "git.dubyatp.xyz/orphanage/http" +) + +func run(ctx context.Context, w io.Writer, args []string) error { + ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) + defer cancel() + + config := struct { + Host string + Port string + }{ + Host: "0.0.0.0", + Port: "8080", + } + + return http.StartServer(ctx, config) +} func main() { - fmt.Println("Hello, World!") + ctx := context.Background() + if err := run(ctx, os.Stdout, os.Args); err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + os.Exit(1) + } }