-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (83 loc) · 2.24 KB
/
main.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
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
)
func printHeaders(h http.Header) {
maxLen := 0
for k := range h {
if len(k) > maxLen {
maxLen = len(k)
}
}
fmt.Println("http request headers ...................")
for k, v := range h {
dots := strings.Repeat(".", maxLen-len(k)+1)
fmt.Printf("%s %s %v\n", k, dots, v)
}
fmt.Println(strings.Repeat(".", 40))
fmt.Println()
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Println(strings.Repeat("-", 80))
fmt.Println("method ...... ", r.Method)
fmt.Println()
printHeaders(r.Header)
body, err := io.ReadAll(r.Body)
fmt.Println("error ..................................")
fmt.Println(err)
fmt.Println(strings.Repeat(".", 40))
fmt.Println()
if err == nil {
bodyStr := string(body)
if len(bodyStr) > 0 {
fmt.Println("body ...................................")
fmt.Println(bodyStr)
fmt.Println(strings.Repeat(".", 40))
}
if *optHMACSecret != "" && *optHMACHeader != "" {
fmt.Println()
fmt.Println("hmac validation ........................")
signature := r.Header.Get(*optHMACHeader)
h := hmac.New(sha256.New, []byte(*optHMACSecret))
h.Write(body)
expectedSignature := hex.EncodeToString(h.Sum(nil))
fmt.Println("expected signature...", expectedSignature)
fmt.Println("incoming signature...", signature)
fmt.Println("is valid?............", hmac.Equal([]byte(expectedSignature), []byte(signature)))
fmt.Println(strings.Repeat(".", 40))
}
}
fmt.Println(strings.Repeat("-", 80))
fmt.Println()
_, _ = fmt.Fprintf(w, "OK")
}
var (
optHMACSecret *string
optHMACHeader *string
optListenADDR *string
)
type server struct{}
func main() {
optHMACSecret = flag.String("hmac-secret", "", "HMAC secret")
optHMACHeader = flag.String("hmac-header-name", "", "Signature response header name")
optListenADDR = flag.String("listen", ":9002", "Listen address, default: ':9002'")
flag.Parse()
srv := &http.Server{
Addr: *optListenADDR,
Handler: new(server),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
fmt.Println("running server at", *optListenADDR)
log.Fatal(srv.ListenAndServe())
}