-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
129 lines (114 loc) · 2.45 KB
/
main.go
File metadata and controls
129 lines (114 loc) · 2.45 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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"strconv"
)
const RandomURL = "https://api.random.org/json-rpc/2/invoke"
const APIKey = ""
type random struct {
Jsonrpc string `json:"jsonrpc"`
Method string `json:"method"`
Params Params `json:"params"`
ID int `json:"id"`
}
type Params struct {
APIKey string `json:"apiKey"`
N int `json:"n"`
Min int `json:"min"`
Max int `json:"max"`
Replacement bool `json:"replacement"`
}
type result struct {
Jsonrpc string `json:"jsonrpc"`
Result struct {
Random struct {
Data []int `json:"data"`
CompletionTime string `json:"completionTime"`
} `json:"random"`
BitsUsed int `json:"bitsUsed"`
BitsLeft int `json:"bitsLeft"`
RequestsLeft int `json:"requestsLeft"`
AdvisoryDelay int `json:"advisoryDelay"`
} `json:"result"`
ID int `json:"id"`
}
func getRandomNumber(min, max int) (int, error) {
myrand := random{
Jsonrpc: "2.0",
Method: "generateIntegers",
Params: Params{
APIKey: APIKey,
N: 1,
Min: min,
Max: max,
Replacement: false,
},
ID: 16,
}
tmp, err := json.Marshal(myrand)
if err != nil {
log.Println(err)
return 0, err
}
r := bytes.NewBuffer(tmp)
fmt.Println(string(tmp))
resp, err := http.Post(RandomURL, "application/json", r)
if err != nil {
log.Println(err)
return 0, err
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
fmt.Println(string(bodyBytes))
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return 0, fmt.Errorf("Response error: %s", resp.Status)
}
var result result
err = json.Unmarshal(bodyBytes, &result)
if err != nil {
resp.Body.Close()
return 0, err
}
resp.Body.Close()
return result.Result.Random.Data[0], nil
}
func mainPage(w http.ResponseWriter, r *http.Request) {
res := 0
tmpl, _ := template.ParseFiles("mainPage.html")
switch r.Method {
case "GET":
tmpl.Execute(w, res)
case "POST":
min := r.FormValue("Min number")
max := r.FormValue("Max number")
m1, err := strconv.Atoi(min)
if err != nil {
log.Println(err)
}
m2, err := strconv.Atoi(max)
if err != nil {
log.Println(err)
}
if m1 >= m2 {
m2 += m1
}
res, err := getRandomNumber(m1, m2)
if err != nil {
log.Println(err)
}
tmpl.Execute(w, res)
}
}
func main() {
http.HandleFunc("/", mainPage)
http.ListenAndServe(":8080", nil)
}