This repository has been archived by the owner on Oct 8, 2020. It is now read-only.
/
handlers.go
152 lines (127 loc) · 5.06 KB
/
handlers.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
tid "github.com/Financial-Times/transactionid-utils-go"
"github.com/gorilla/mux"
"golang.org/x/net/context"
)
const uuidKey = "uuid"
type ContentHandler struct {
serviceConfig *ServiceConfig
log *AppLogger
metrics *Metrics
}
func (h ContentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
uuid := vars["uuid"]
h.log.TransactionStartedEvent(r.RequestURI, tid.GetTransactionIDFromRequest(r), uuid)
ctx := tid.TransactionAwareContext(context.Background(), r.Header.Get(tid.TransactionIDHeader))
ctx = context.WithValue(ctx, uuidKey, uuid)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
nativeContentSourceAppResponse, err := h.getNativeContent(ctx, w)
if err != nil {
return
}
defer nativeContentSourceAppResponse.Body.Close()
transformAppResponse, err := h.getTransformedContent(ctx, *nativeContentSourceAppResponse, w)
if err != nil {
return
}
defer transformAppResponse.Body.Close()
io.Copy(w, transformAppResponse.Body)
h.metrics.recordResponseEvent()
}
func (h ContentHandler) getNativeContent(ctx context.Context, w http.ResponseWriter) (*http.Response, error) {
uuid := ctx.Value(uuidKey).(string)
requestUrl := fmt.Sprintf("%s%s", h.serviceConfig.sourceAppUri, uuid)
transactionId, _ := tid.GetTransactionIDFromContext(ctx)
h.log.RequestEvent(h.serviceConfig.sourceAppName, requestUrl, transactionId, uuid)
req, err := http.NewRequest("GET", requestUrl, nil)
req.Header.Set(tid.TransactionIDHeader, transactionId)
req.Header.Set("Authorization", "Basic "+h.serviceConfig.sourceAppAuth)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "UPP Content Preview")
resp, err := client.Do(req)
err = h.handleResponse(req, resp, err, w, uuid, h.serviceConfig.sourceAppName)
if err != nil {
if resp != nil {
// close now and don't return the resp
resp.Body.Close()
resp = nil
}
}
return resp, err
}
func (h ContentHandler) getTransformedContent(ctx context.Context, nativeContentSourceAppResponse http.Response, w http.ResponseWriter) (*http.Response, error) {
uuid := ctx.Value(uuidKey).(string)
requestUrl := fmt.Sprintf("%s?preview=true", h.serviceConfig.transformAppUri)
transactionId, _ := tid.GetTransactionIDFromContext(ctx)
//TODO we need to assert that resp.Header.Get(tid.TransactionIDHeader) == transactionId
//to ensure that we are logging exactly what is actually passed around in the headers
h.log.RequestEvent(h.serviceConfig.transformAppName, requestUrl, transactionId, uuid)
req, err := http.NewRequest("POST", requestUrl, nativeContentSourceAppResponse.Body)
req.Header.Set(tid.TransactionIDHeader, transactionId)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "UPP Content Preview")
resp, err := client.Do(req)
err = h.handleResponse(req, resp, err, w, uuid, h.serviceConfig.transformAppName)
if err != nil {
if resp != nil {
// close now and don't return the resp
resp.Body.Close()
resp = nil
}
}
return resp, err
}
func (h ContentHandler) handleResponse(req *http.Request, extResp *http.Response, err error, w http.ResponseWriter, uuid, calledServiceName string) error {
//this happens when hostname cannot be resolved or host is not accessible
if err != nil {
h.handleError(w, err, calledServiceName, req.URL.String(), req.Header.Get(tid.TransactionIDHeader), uuid)
return err
}
switch extResp.StatusCode {
case http.StatusOK:
h.log.ResponseEvent(calledServiceName, req.URL.String(), extResp, uuid)
return nil
case http.StatusUnprocessableEntity:
fallthrough
case http.StatusNotFound:
h.handleClientError(w, calledServiceName, req.URL.String(), extResp, uuid)
return errors.New("not found")
default:
h.handleFailedRequest(w, calledServiceName, req.URL.String(), extResp, uuid)
return errors.New("request failed")
}
}
func (h ContentHandler) handleError(w http.ResponseWriter, err error, serviceName string, url string, transactionId string, uuid string) {
w.WriteHeader(http.StatusServiceUnavailable)
h.log.ErrorEvent(serviceName, url, transactionId, err, uuid)
h.metrics.recordErrorEvent()
}
func (h ContentHandler) handleFailedRequest(w http.ResponseWriter, serviceName string, url string, resp *http.Response, uuid string) {
w.WriteHeader(http.StatusServiceUnavailable)
h.log.RequestFailedEvent(serviceName, url, resp, uuid)
h.metrics.recordRequestFailedEvent()
}
func (h ContentHandler) handleClientError(w http.ResponseWriter, serviceName string, url string, resp *http.Response, uuid string) {
status := resp.StatusCode
w.WriteHeader(status)
msg := make(map[string]string)
switch status {
case http.StatusUnprocessableEntity:
msg["message"] = "Unable to map content for preview."
case http.StatusNotFound:
msg["message"] = "Content not found."
default:
msg["message"] = fmt.Sprintf("Unexpected error, call to %s returned HTTP status %v.", serviceName, status)
}
by, _ := json.Marshal(msg)
w.Write(by)
h.log.RequestFailedEvent(serviceName, url, resp, uuid)
h.metrics.recordRequestFailedEvent()
}