7

我正在尝试记录请求者的 IP 地址、他们使用的 METHOD 以及他们请求的文件。但由于某种原因,它只在终端上输出,并没有将其保存到 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)
  }
}
4

1 回答 1

7

在您的Log功能中,您使用的是fmt.Printfnot fmt.Fprintf

例如,

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()
}
于 2012-10-11T01:12:44.370 回答