-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
52 lines (45 loc) · 1.13 KB
/
server.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
package main
import (
"encoding/json"
"fmt"
"html"
"log"
"net/http"
"net/url"
)
// Response is strucure that is return for every request
type Response struct {
OK bool `json:"ok"`
Path string `json:"path"`
Method string `json:"method"`
Query url.Values `json:"query"`
Header http.Header `json:"header"`
}
// BuildResponse builds the response for a specific request
func BuildResponse(r *http.Request) ([]byte, error) {
res := Response{
OK: true,
Path: html.EscapeString(r.URL.Path),
Method: r.Method,
Query: r.URL.Query(),
Header: r.Header,
}
// ignore error
return json.Marshal(res)
}
func main() {
port := 8080
fmt.Printf("Starting to listen on port: %v\n", port)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Request received: %q\n", html.EscapeString(r.URL.Path))
res, err := BuildResponse(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Error: %q", err)
} else {
w.Header().Set("Content-Type", "application/json")
w.Write(res)
}
})
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}