Print to Log Using Go Simple HTTP Server

I am trying to register the requestor's IP address, which METHOD they are using and which file they are requesting. But for some reason it only outputs to the terminal and does not save it in the logfile.txt file ...

package main import ( "fmt" "net/http" "log" "encoding/json" "io/ioutil" ) type Options struct { Path string Port string } func Log(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL) handler.ServeHTTP(w, r) }) } func main() { op := &Options{Path: "./", Port: "8001"} data, _ := ioutil.ReadFile("./config.json") json.Unmarshal(data, op) http.Handle("/", http.FileServer(http.Dir(op.Path))) err := http.ListenAndServe(":" + op.Port, Log(http.DefaultServeMux)) if err != nil { log.Fatal("ListenAndServe: ", err) } } 
+7
source share
1 answer

In your Log function, you use fmt.Printf not fmt.Fprintf .

For example,

 package main import ( "fmt" "log" "net/http" "os" ) var logFile *os.File func Log(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(logFile, "%s %s %s\n", r.RemoteAddr, r.Method, r.URL) handler.ServeHTTP(w, r) }) } func main() { var err error logFile, err = os.Create("logfile.txt") if err != nil { log.Fatal("Log file create:", err) return } defer logFile.Close() } 
+7
source

All Articles