-
Notifications
You must be signed in to change notification settings - Fork 0
/
reading_writing_json_8.go
84 lines (63 loc) · 1.71 KB
/
reading_writing_json_8.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"testing"
"time"
)
type validationContextKey string
type helloWorldResponse struct {
Message string `json:"message"`
}
type helloWorldRequest struct {
Name string `json:"name"`
}
func main() {
port := 8080
handler := newValidationHandler(newHelloWorldHandler())
http.Handle("/helloworld", handler)
log.Printf("Server starting on port %v\n", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
type validationHandler struct {
next http.Handler
}
func newValidationHandler(next http.Handler) http.Handler {
return validationHandler{next: next}
}
func (h validationHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
var request helloWorldRequest
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&request)
if err != nil {
http.Error(rw, "Bad request", http.StatusBadRequest)
return
}
c := context.WithValue(r.Context(), validationContextKey("name"), request.Name)
r = r.WithContext(c)
h.next.ServeHTTP(rw, r)
}
type helloWorldHandler struct {
}
func newHelloWorldHandler() http.Handler {
return helloWorldHandler{}
}
func (h helloWorldHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
name := r.Context().Value(validationContextKey("name")).(string)
response := helloWorldResponse{Message: "Hello " + name}
encoder := json.NewEncoder(rw)
encoder.Encode(response)
}
func fetchGoogle(t *testing.T) {
r, _ := http.NewRequest("GET", "https://google.com", nil)
timeoutRequest, cancelFunc := context.WithTimeout(r.Context(), 1*time.Millisecond)
defer cancelFunc()
r = r.WithContext(timeoutRequest)
_, err := http.DefaultClient.Do(r)
if err != nil {
fmt.Println("Error:", err)
}
}