-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
52 lines (44 loc) · 1.12 KB
/
main.go
File metadata and controls
52 lines (44 loc) · 1.12 KB
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
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"time"
)
type serverResponse struct {
TimeDelay int32
}
var maxDelay int32
func main() {
fmt.Printf("Please enter the maximum delay to be tested: ")
fmt.Scan(&maxDelay)
fmt.Printf("Listening on localhost:9001, will respond after random delay with JSON.\n")
rand.Seed(time.Now().Unix())
http.HandleFunc("/", returnJSON) // set router
err := http.ListenAndServe(":9001", nil) // set listen port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func returnJSON(w http.ResponseWriter, r *http.Request) {
var timeDelay int32
if maxDelay == 0 {
timeDelay = 0
} else {
timeDelay = rand.Int31n(maxDelay)
}
response := serverResponse{timeDelay}
fmt.Printf("Sleeping %d ....\n", timeDelay)
time.Sleep(time.Second * time.Duration(timeDelay))
js, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Printf("Returning %d ....\n", timeDelay)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(js)
}