/
context.go
63 lines (52 loc) · 1.48 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package context
import (
"context"
"errors"
"net/http"
"net/url"
"github.com/TosinShada/stellar-core/services/horizon/internal/db2/history"
"github.com/TosinShada/stellar-core/support/db"
)
type CtxKey string
var RequestContextKey = CtxKey("request")
var SessionContextKey = CtxKey("session")
func RequestFromContext(ctx context.Context) *http.Request {
found, _ := ctx.Value(&RequestContextKey).(*http.Request)
return found
}
// requestContext returns a context representing the provided http action.
func RequestContext(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
if r == nil {
panic("Cannot bind nil *http.Request to context tree")
}
return context.WithValue(ctx, &RequestContextKey, r)
}
// BaseURL returns the "base" url for this request, defined as a url containing
// the Host and Scheme portions of the request uri.
func BaseURL(ctx context.Context) *url.URL {
r := RequestFromContext(ctx)
if r == nil {
return nil
}
var scheme string
switch {
case r.Header.Get("X-Forwarded-Proto") != "":
scheme = r.Header.Get("X-Forwarded-Proto")
case r.TLS != nil:
scheme = "https"
default:
scheme = "http"
}
return &url.URL{
Scheme: scheme,
Host: r.Host,
}
}
func HistoryQFromRequest(request *http.Request) (*history.Q, error) {
ctx := request.Context()
session, ok := ctx.Value(&SessionContextKey).(db.SessionInterface)
if !ok {
return nil, errors.New("missing session in request context")
}
return &history.Q{session}, nil
}