-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (75 loc) · 1.76 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
package main
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"strconv"
"github.com/go-chi/chi"
)
type Param struct {
Type string
Length int
}
type ambar struct {
mas map[int]interface{}
}
func (ambar *ambar) handler(w http.ResponseWriter, r *http.Request) {
var body Param
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
fmt.Println("err")
}
r.Body.Close()
an := map[string]interface{}{}
an["id"] = len(ambar.mas)
b, e := json.Marshal(an)
if e != nil {
fmt.Println("ошибка json")
}
defer r.Body.Close()
w.Write([]byte(string(b)))
if body.Type == "int" {
i, _ := strconv.ParseInt(RandIntRunes(body.Length), 10, 64)
ambar.mas[len(ambar.mas)] = i
} else {
ambar.mas[len(ambar.mas)] = RandStringRunes(body.Length)
}
}
func (ambar *ambar) handler2(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
i, _ := strconv.ParseInt(id, 10, 64)
am := map[string]interface{}{}
am["value"] = ambar.mas[int(i)]
b, e := json.Marshal(am)
if e != nil {
fmt.Println("ошибка json")
}
w.Write([]byte(string(b)))
}
func main() {
ambar := ambar{map[int]interface{}{}}
r := chi.NewRouter()
srv := http.Server{Addr: ":3000", Handler: r}
defer srv.Shutdown(context.TODO())
r.Post("/api/generate/", ambar.handler)
r.Get("/api/retrieve/", ambar.handler2)
srv.ListenAndServe()
}
func RandStringRunes(n int) string {
letterRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func RandIntRunes(n int) string {
letterRunes := []rune("0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}