about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-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())
 }