-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebHooks.go
82 lines (73 loc) · 2.27 KB
/
webHooks.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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
)
// interface for JSON data
type JSONData interface{}
var prettyFlag = flag.Bool("pretty", true, "Enable/disable pretty JSON formatting")
var headersFlag = flag.Bool("headers", true, "Enable/disable technical information of request")
var portFlag = flag.Int("port", 8080, "Set listening port of webhook catcher")
var feedbackFlag = flag.Bool("answer", true, "Enable/disable answer from service (Status: OK, "+
"Data received)")
func main() {
flag.Parse()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
var requestData JSONData
err = json.Unmarshal(body, &requestData)
if err != nil {
http.Error(w, fmt.Sprintf("Error parsing JSON: %v", err), http.StatusBadRequest)
return
}
// parse JSON to empty interface
var formattedJSON []byte
if *prettyFlag {
formattedJSON, err = json.MarshalIndent(requestData, "", " ")
} else {
formattedJSON, err = json.Marshal(requestData)
}
if err != nil {
http.Error(w, fmt.Sprintf("Error formatting JSON: %v", err), http.StatusInternalServerError)
return
}
// Send data to console
if *headersFlag {
fmt.Print("\n\nStart technical info\n")
fmt.Print("====================\n")
fmt.Println("Received request:")
fmt.Printf(" Method: %s\n", r.Method)
fmt.Printf(" URL: %s\n", r.URL)
fmt.Println(" Headers:")
for key, values := range r.Header {
for _, value := range values {
fmt.Printf(" %s: %s\n", key, value)
}
}
fmt.Print("=====================\n")
fmt.Print("End of technical info\n\n\n")
}
fmt.Printf(" Parsed JSON data:\n%s\n\n", formattedJSON)
if *feedbackFlag {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Data received successfully\n"))
}
})
// Run service
address := fmt.Sprintf("localhost:%d", *portFlag)
fmt.Printf("Server is listening on http://%s\n", address)
fmt.Printf("Pretty JSON formatting: %t\n", *prettyFlag)
fmt.Printf("Headers: %t\n", *headersFlag)
fmt.Printf("Answer: %t\n\n", *feedbackFlag)
err := http.ListenAndServe(address, nil)
if err != nil {
fmt.Printf("Error starting the server: %v\n", err)
}
}