HTTP-трассировка с точки зрения сервера - PullRequest
1 голос
/ 27 апреля 2019

В Go была добавлена ​​трассировка http 1.7, но она работает только с точки зрения клиента. Можно ли как-то отследить запрос с точки зрения сервера, я имею в виду, я хочу добавить несколько хуков, например, когда было установлено соединение. Должно ли оно быть реализовано как промежуточное ПО или как?

http.HandlerFunc(func(w http.ResponseWriter, r *http.Request)

1 Ответ

2 голосов
/ 27 апреля 2019

Поддержка трассировки на стороне сервера была добавлена ​​намного раньше, в Go 1,3 .Создайте свой собственный http.Server и установите функцию обратного вызова в поле Server.ConnState.

// ConnState specifies an optional callback function that is
// called when a client connection changes state. See the
// ConnState type and associated constants for details.
ConnState func(net.Conn, ConnState) // Go 1.3

http.ConnState подробно, когда / какое соединение устанавливает состояниеобратный вызов уведомляется о.

// StateNew represents a new connection that is expected to
// send a request immediately. Connections begin at this
// state and then transition to either StateActive or
// StateClosed.
StateNew ConnState = iota

// StateActive represents a connection that has read 1 or more
// bytes of a request. The Server.ConnState hook for
// StateActive fires before the request has entered a handler
// and doesn't fire again until the request has been
// handled. After the request is handled, the state
// transitions to StateClosed, StateHijacked, or StateIdle.
// For HTTP/2, StateActive fires on the transition from zero
// to one active request, and only transitions away once all
// active requests are complete. That means that ConnState
// cannot be used to do per-request work; ConnState only notes
// the overall state of the connection.
StateActive

// StateIdle represents a connection that has finished
// handling a request and is in the keep-alive state, waiting
// for a new request. Connections transition from StateIdle
// to either StateActive or StateClosed.
StateIdle

// StateHijacked represents a hijacked connection.
// This is a terminal state. It does not transition to StateClosed.
StateHijacked

// StateClosed represents a closed connection.
// This is a terminal state. Hijacked connections do not
// transition to StateClosed.
StateClosed

Простой пример:

srv := &http.Server{
    Addr: ":8080",
    ConnState: func(conn net.Conn, cs http.ConnState) {
        fmt.Println("Client:", conn.RemoteAddr(), "- new state:", cs)
    },
}
log.Fatal(srv.ListenAndServe())

Выполнение запроса к вышеуказанному серверу:

curl localhost:8080

Выходные данные сервера будут:

Client: 127.0.0.1:39778 - new state: new
Client: 127.0.0.1:39778 - new state: active
Client: 127.0.0.1:39778 - new state: idle
Client: 127.0.0.1:39778 - new state: closed
...