-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (84 loc) · 1.96 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "5000"
}
hostname, _ := os.Hostname()
fmt.Fprintf(os.Stdout, "Server has started on %s.\n", port)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Add("Content-Type", "application/json")
result := struct {
hostname string
}{
hostname: hostname,
}
json := convertToJSON(result)
writeResponse(w, string(json))
})
http.HandleFunc("/date", func(w http.ResponseWriter, r *http.Request) {
date, _ := time.Now().MarshalJSON()
w.WriteHeader(200)
w.Header().Add("Content-Type", "application/json")
result := struct {
hostname string
date string
}{
hostname: hostname,
date: string(date),
}
json := convertToJSON(result)
writeResponse(w, string(json))
})
http.HandleFunc("/joke", func(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://icanhazdadjoke.com/", nil)
req.Header.Add("Accept", "text/plain")
response, err := client.Do(req)
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
return
}
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
return
}
w.WriteHeader(200)
w.Header().Add("Content-Type", "application/json")
result := struct {
hostname string
joke string
}{
hostname: hostname,
joke: string(responseData),
}
json := convertToJSON(result)
writeResponse(w, string(json))
})
listenError := http.ListenAndServe(":"+port, nil)
log.Fatal(listenError)
}
func writeResponse(w io.Writer, response string) {
fmt.Fprintln(w, response)
fmt.Fprintln(os.Stdout, response)
}
func convertToJSON(data any) string {
json, err := json.Marshal(data)
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
return ""
}
return string(json)
}