Skip to content

Commit

Permalink
Feat: Refactor server start and graceful shutdown logic
Browse files Browse the repository at this point in the history
  • Loading branch information
mertssmnoglu committed Feb 26, 2024
1 parent 0d28e6d commit 1055e7a
Showing 1 changed file with 33 additions and 9 deletions.
42 changes: 33 additions & 9 deletions internals/server/server.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package server

import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/yazilimcimekani/mdoctor/internals/mdtohtml"
)
Expand All @@ -13,24 +17,44 @@ func Start(port uint16, filePath string) {
if port == 0 {
port = 8080
}
var startMessage string = fmt.Sprintf("Server started on http://localhost:%d", port)

srv := &http.Server{Addr: fmt.Sprintf(":%d", port)}

// Define the routes
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("internals/server/public"))))
http.HandleFunc("/", Markdown(filePath))

// Start the server with logging
log.Println(startMessage)
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
// Start the server in a goroutine
go func() {
startMessage := fmt.Sprintf("Listening on http://localhost:%d", port)
fmt.Println(startMessage)

err := srv.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatalf("Server down: %v", err)
}
}()

stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)

<-stopChan
fmt.Println("Shutting down the server...")

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Shutting down the server gracefully
err := srv.Shutdown(ctx)
if err != nil {
log.Fatal(err)
fmt.Printf("Shutdown request error: %v\n", err)
} else {
fmt.Println("Server gracefully stopped")
}

log.Println("Shutting down gracefully...")
}

func Markdown(filePath string) func(w http.ResponseWriter, r *http.Request) {
const mdTemplatePath = "views/md.html"
const mdTemplatePath = "internals/server/views/md.html"

markdownContent := mdtohtml.MarkdownToHtml(mdtohtml.LoadMdFile(filePath))
html, htmlReadErr := os.ReadFile(mdTemplatePath)
Expand Down

0 comments on commit 1055e7a

Please sign in to comment.