From 94e84cce4186a15d331074ff5f2b3e895379d008 Mon Sep 17 00:00:00 2001 From: raul Date: Fri, 17 May 2024 13:45:29 +0200 Subject: [PATCH] Add logging capabilities --- cmd/serverFunc.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/cmd/serverFunc.go b/cmd/serverFunc.go index 1de23ad..c48d0e9 100644 --- a/cmd/serverFunc.go +++ b/cmd/serverFunc.go @@ -3,7 +3,10 @@ package cmd import ( "fmt" "github.com/gin-gonic/gin" + "log" "net/http" + "os" + "time" ) var ( @@ -12,11 +15,34 @@ var ( func server() { fmt.Printf("Listening on port %v...\n", listenPort) + + gin.SetMode(gin.ReleaseMode) + gin.DisableConsoleColor() + router := gin.New() router.GET("/", serveIP) router.Run(":" + listenPort) } func serveIP(c *gin.Context) { + c.Writer.Header().Set("Federal-Agents", "Outside my home") c.String(http.StatusOK, c.ClientIP()+"\n") + writeToLog(c.ClientIP(), c.Request.UserAgent(), c.Request.URL.Path, c.Request.Method) +} + +func writeToLog(ip string, useragent string, request string, requestmethod string) { + f, err := os.OpenFile("./reply-ip.log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0660) + if err != nil { + log.Printf("Error happened opening file: %v\n", err) + } + defer f.Close() + + log := fmt.Sprintf("[%v] | [%v] | [%v] | [%v \"%v\"]\n", getTime(), useragent, ip, requestmethod, request) + f.WriteString(log) +} + +func getTime() string { + t := time.Now() + currentTime := fmt.Sprintf("%d-%02d-%02d | %02d:%02d:%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) + return currentTime }