Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print to Log using Go Language Simple HTTP Server

Tags:

go

I am trying to log the IP address of the requestor, what METHOD they are using and what file they are requesting. But for some reason it only outputs on the terminal and doesn't save it to logfile.txt...

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)
  }
}
like image 668
B-Ray Avatar asked Oct 11 '12 00:10

B-Ray


People also ask

How do I run a go Lang server?

Start the web server with go run server.go and visit http://localhost:8080/hello . If the server responds with "Hello!" , you can continue to the next step, where you'll learn how to add basic security to your Golang web server routes.

How do I set up a go server?

Once you've set up your handlers, call the http. ListenAndServe function to start the server and listen for requests. In this first chunk of code, you set up the package for your Go program, import the required packages for your program, and create two functions: the getRoot function and the getHello function.

What is HTTP handler Golang?

The Handler interface is an interface with a single method ServeHTTP which takes a http. Response and a http. Request as inputs. type Handler interface { ServeHTTP(ResponseWriter, *Request)


1 Answers

In your Log function, you are using 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()
}
like image 193
peterSO Avatar answered Nov 11 '22 21:11

peterSO