restful-NCSA-logging.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "github.com/emicklei/go-restful"
  4. "io"
  5. "log"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "time"
  10. )
  11. // This example shows how to create a filter that produces log lines
  12. // according to the Common Log Format, also known as the NCSA standard.
  13. //
  14. // kindly contributed by leehambley
  15. //
  16. // GET http://localhost:8080/ping
  17. var logger *log.Logger = log.New(os.Stdout, "", 0)
  18. func NCSACommonLogFormatLogger() restful.FilterFunction {
  19. return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
  20. var username = "-"
  21. if req.Request.URL.User != nil {
  22. if name := req.Request.URL.User.Username(); name != "" {
  23. username = name
  24. }
  25. }
  26. chain.ProcessFilter(req, resp)
  27. logger.Printf("%s - %s [%s] \"%s %s %s\" %d %d",
  28. strings.Split(req.Request.RemoteAddr, ":")[0],
  29. username,
  30. time.Now().Format("02/Jan/2006:15:04:05 -0700"),
  31. req.Request.Method,
  32. req.Request.URL.RequestURI(),
  33. req.Request.Proto,
  34. resp.StatusCode(),
  35. resp.ContentLength(),
  36. )
  37. }
  38. }
  39. func main() {
  40. ws := new(restful.WebService)
  41. ws.Filter(NCSACommonLogFormatLogger())
  42. ws.Route(ws.GET("/ping").To(hello))
  43. restful.Add(ws)
  44. http.ListenAndServe(":8080", nil)
  45. }
  46. func hello(req *restful.Request, resp *restful.Response) {
  47. io.WriteString(resp, "pong")
  48. }