about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorBen Morrison <ben@gbmor.dev>2020-05-06 01:06:11 -0400
committerBen Morrison <ben@gbmor.dev>2020-05-06 01:06:11 -0400
commit860d648785e96ec8a23c16ad5c1ccbe16850cb1e (patch)
treedc6faf353fba399cc5c515fb3484ef2ade864d8b
parent9274eef9ed55685e091ce379b3690bf8eb8fbef4 (diff)
downloadapi-860d648785e96ec8a23c16ad5c1ccbe16850cb1e.tar.gz
using file logging and catching SIGINT to cleanly shut down
-rw-r--r--logging.go24
-rw-r--r--main.go20
2 files changed, 42 insertions, 2 deletions
diff --git a/logging.go b/logging.go
index 26eb416..311aa8b 100644
--- a/logging.go
+++ b/logging.go
@@ -4,8 +4,32 @@ import (
 	"fmt"
 	"log"
 	"net/http"
+	"os"
 )
 
+var logChan = make(chan struct{})
+
+func initLogging() {
+	logfile, err := os.OpenFile("api.log", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
+	if err != nil {
+		log.SetOutput(os.Stderr)
+		log.Printf("Log init error: %s", err.Error())
+		return
+	}
+
+	go func(*os.File) {
+		<-logChan
+		log.Printf("Closing log file ...")
+		err := logfile.Close()
+		if err != nil {
+			log.SetOutput(os.Stderr)
+			log.Printf("Error closing log file: %s", err.Error())
+		}
+	}(logfile)
+
+	log.SetOutput(logfile)
+}
+
 // Appends a 200 OK to the request log
 func log200(r *http.Request) {
 	useragent := r.Header["User-Agent"]
diff --git a/main.go b/main.go
index 079fd98..5662388 100644
--- a/main.go
+++ b/main.go
@@ -3,12 +3,25 @@ package main
 import (
 	"log"
 	"net/http"
+	"os"
+	"os/signal"
 	"time"
 )
 
 func main() {
-	mux := http.NewServeMux()
+	initLogging()
+
+	sigC := make(chan os.Signal, 1)
+	signal.Notify(sigC, os.Interrupt)
+	go func() {
+		for range sigC {
+			log.Printf("^C Caught. Shutting down ...")
+			logChan <- struct{}{}
+			os.Exit(1)
+		}
+	}()
 
+	mux := http.NewServeMux()
 	mux.HandleFunc("/", validateRequest)
 
 	server := &http.Server{
@@ -18,5 +31,8 @@ func main() {
 		WriteTimeout: 10 * time.Second,
 	}
 
-	log.Fatalf("%s", server.ListenAndServe())
+	log.Println("Starting up")
+	log.Printf("Listening on %s\n", server.Addr)
+
+	log.Fatalf("%s", server.ListenAndServe().Error())
 }