如何在golang中获取HTTP请求的初始时间戳?

时间:2018-10-01 11:31:52

标签: http go httprequest httpcontext revel

我正在使用revel框架编写golang程序,在该程序中,我需要检查http请求的初始时间戳。

我知道如何在C#中做到这一点:

 HttpContextWrapper context = Request.Properties["MS_HttpContext"] as HttpContextWrapper;

DateTime t2 = context.Timestamp.ToUniversalTime();

在Go中没有太多的操作方法。

2 个答案:

答案 0 :(得分:1)

.p框架sets the timestamp when a request arrives at the server中的

HttpContext类。您最好将时间戳记存储在请求处理程序函数的第一行中。

答案 1 :(得分:0)

最简单的方法是在处理程序中获取当前时间。

type Handler struct {
}

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  rs := time.Now().UTC()

  //TODO: Use the time.
}

如果要测量处理程序之前所有中间件所花费的时间,则可以更新Go上下文并将中间件放置在中间件链的开始。

以下是该中间件的外观示例:

package timemiddleware

import (
    "context"
    "net/http"
    "time"
)

// New returns new middleware which tracks the time that a request started.
func New(next http.Handler) http.Handler {
    return handler{
        next: next,
    }
}

type key int

const id = key(1)

type handler struct {
    next http.Handler
}

func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    ctx := context.WithValue(r.Context(), id, time.Now().UTC())
    h.next.ServeHTTP(w, r.WithContext(ctx))
}

// GetTime returns time from the current request, where it has previously been added by the middleware.
func GetTime(r *http.Request) (t time.Time, ok bool) {
    v := r.Context().Value(id)
    t, ok = v.(time.Time)
    return
}

您将按照以下示例使用它:

软件包主要

import (
    "fmt"
    "net/http"
    "time"

    "github.com/xxxxx/timemiddleware"
)

func main() {
    next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(time.Second * 5)
        w.Write([]byte("Hello"))
        if t, ok := timemiddleware.GetTime(r); ok {
            fmt.Println(t)
            fmt.Println(time.Now().UTC())
        }
    })

    h := timemiddleware.New(next)
    fmt.Println(http.ListenAndServe("0.0.0.0:8080", h))
}