This repository has been archived by the owner on Sep 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
pingback.go
54 lines (49 loc) · 1.49 KB
/
pingback.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
package httpwares_testing
import (
"encoding/json"
"net/http"
"strconv"
)
const (
DefaultPingBackStatusCode = http.StatusCreated
)
// PingBackResponse is a JSON struct that encodes the inbound request.
type PingBackResponse struct {
ProtoMajor int `json:"protoMajor"`
Method string `json:"method"`
UrlHost string `json:"urlHost"`
UrlPath string `json:"urlPath"`
HdHost string `json:"hdHost"`
Headers map[string]string `json:"headers"`
}
// PingBackHandler is an http.Handler that pings back the request info as JSON.
func PingBackHandler(retCode int) http.HandlerFunc {
return func(resp http.ResponseWriter, req *http.Request) {
respJs := &PingBackResponse{
ProtoMajor: req.ProtoMajor,
Method: req.Method,
UrlHost: req.URL.Host,
UrlPath: req.URL.Path,
HdHost: req.Host,
Headers: make(map[string]string),
}
for k, _ := range req.Header {
respJs.Headers[k] = req.Header.Get(k)
}
req.ParseForm()
if code := req.Form.Get("code"); code != "" {
retCode, _ = strconv.Atoi(code)
}
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(retCode)
json.NewEncoder(resp).Encode(respJs)
}
}
// DecodePingBack returns a parsed PingBackResponse for assertion purposes.
func DecodePingBack(resp *http.Response) (*PingBackResponse, error) {
val := &PingBackResponse{}
if err := json.NewDecoder(resp.Body).Decode(val); err != nil {
return nil, err
}
return val, nil
}