-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
65 lines (57 loc) · 1.32 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
package main
import (
"encoding/json"
"log"
"net/http"
"net/url"
"os"
"strconv"
)
type JsonableRequest struct {
Method string
URL url.URL
Proto string
Header http.Header
ContentLength int64
Host string
RemoteAddr string
RequestURI string
}
func main() {
log.Println("Starting Simple HTTP echo")
port := 3000
portEnv := os.Getenv("PORT")
if portEnv != "" {
portInt, err := strconv.Atoi(portEnv)
if err == nil {
port = portInt
}
}
listenStr := ":" + strconv.Itoa(port)
log.Printf("Listening on %s", listenStr)
server := http.NewServeMux()
server.HandleFunc("/", handleRequest)
err := http.ListenAndServe(listenStr, server)
if err != nil {
log.Panic(err)
}
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
// http.Request contains methods which the JSON marshaller doesn't like.
jsonRequest := JsonableRequest{
Method: r.Method,
URL: *r.URL,
Proto: r.Proto,
Header: r.Header,
ContentLength: r.ContentLength,
Host: r.Host,
RemoteAddr: r.RemoteAddr,
RequestURI: r.RequestURI,
}
log.Printf("Received HTTP request: %+v\n", jsonRequest)
requestJson, err := json.MarshalIndent(jsonRequest, "", "\t")
if err != nil {
log.Printf("Error encoding JSON: %v", err)
}
w.Write(requestJson)
}