Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

78 rader
2.2 KiB

  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file or at
  5. // https://developers.google.com/open-source/licenses/bsd.
  6. package main
  7. import (
  8. "crypto/rand"
  9. "encoding/hex"
  10. "log"
  11. "net/http"
  12. "time"
  13. "cloud.google.com/go/logging"
  14. "github.com/golang/gddo/database"
  15. )
  16. // newGCELogger returns a handler that wraps h but logs each request
  17. // using Google Cloud Logging service.
  18. func newGCELogger(cli *logging.Logger) *GCELogger {
  19. return &GCELogger{cli}
  20. }
  21. type GCELogger struct {
  22. cli *logging.Logger
  23. }
  24. // LogEvent creates an entry in Cloud Logging to record user's behavior. We should only
  25. // use this to log events we are interested in. General request logs are handled by GAE
  26. // automatically in request_log and stderr.
  27. func (g *GCELogger) LogEvent(w http.ResponseWriter, r *http.Request, content interface{}) {
  28. const sessionCookieName = "GODOC_ORG_SESSION_ID"
  29. cookie, err := r.Cookie(sessionCookieName)
  30. if err != nil {
  31. // Generates a random session id and sends it in response.
  32. rs, err := randomString()
  33. if err != nil {
  34. log.Println("error generating a random session id: ", err)
  35. return
  36. }
  37. // This cookie is intentionally short-lived and contains no information
  38. // that might identify the user. Its sole purpose is to tie query
  39. // terms and destination pages together to measure search quality.
  40. cookie = &http.Cookie{
  41. Name: sessionCookieName,
  42. Value: rs,
  43. Expires: time.Now().Add(time.Hour),
  44. }
  45. http.SetCookie(w, cookie)
  46. }
  47. // We must not record the client's IP address, or any other information
  48. // that might compromise the user's privacy.
  49. payload := map[string]interface{}{
  50. sessionCookieName: cookie.Value,
  51. "path": r.URL.RequestURI(),
  52. "method": r.Method,
  53. "referer": r.Referer(),
  54. }
  55. if pkgs, ok := content.([]database.Package); ok {
  56. payload["packages"] = pkgs
  57. }
  58. // Log queues the entry to its internal buffer, or discarding the entry
  59. // if the buffer was full.
  60. g.cli.Log(logging.Entry{
  61. Payload: payload,
  62. })
  63. }
  64. func randomString() (string, error) {
  65. b := make([]byte, 8)
  66. _, err := rand.Read(b)
  67. return hex.EncodeToString(b), err
  68. }