112 lines
2.1 KiB
Go
112 lines
2.1 KiB
Go
package entity
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"grpccanary/protoapi"
|
|
"math/rand"
|
|
"net"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/reflection"
|
|
)
|
|
|
|
var min = 0
|
|
var max = 100
|
|
var port = ":8080"
|
|
|
|
func random(min, max int, src rand.Source) int {
|
|
return rand.New(src).Intn(max-min) + min
|
|
}
|
|
|
|
// Extra function for creating secure random numbers
|
|
//
|
|
// func randomSecure(min, max int) int {
|
|
// v, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
|
|
// if err != nil {
|
|
// fmt.Println(err)
|
|
// return min
|
|
// }
|
|
// fmt.Println("**", v, min, max)
|
|
|
|
// return min + int(v.Uint64())
|
|
// }
|
|
|
|
func getString(len int64) string {
|
|
temp := ""
|
|
startChar := "!"
|
|
var i int64 = 1
|
|
for {
|
|
// For getting valid ASCII characters
|
|
myRand := random(0, 94, rand.NewSource(time.Now().UnixNano()))
|
|
newChar := string(startChar[0] + byte(myRand))
|
|
temp = temp + newChar
|
|
if i == len {
|
|
break
|
|
}
|
|
i++
|
|
}
|
|
return temp
|
|
}
|
|
|
|
type RandomServer struct {
|
|
protoapi.UnimplementedRandomServer
|
|
}
|
|
|
|
func (RandomServer) GetDate(ctx context.Context, r *protoapi.RequestDateTime) (*protoapi.DateTime, error) {
|
|
currentTime := time.Now()
|
|
response := &protoapi.DateTime{
|
|
Value: currentTime.String(),
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func (RandomServer) GetRandom(ctx context.Context, r *protoapi.RandomParams) (*protoapi.RandomInt, error) {
|
|
src := rand.NewSource(r.GetSeed())
|
|
place := r.GetPlace()
|
|
temp := random(min, max, src)
|
|
for {
|
|
place--
|
|
if place <= 0 {
|
|
break
|
|
}
|
|
temp = random(min, max, src)
|
|
}
|
|
|
|
response := &protoapi.RandomInt{
|
|
Value: int64(temp),
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func (RandomServer) GetRandomPass(ctx context.Context, r *protoapi.RequestPass) (*protoapi.RandomPass, error) {
|
|
rand.Seed(r.GetSeed())
|
|
temp := getString(r.GetLength())
|
|
|
|
response := &protoapi.RandomPass{
|
|
Password: temp,
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func ServerRun(addr string) {
|
|
server := grpc.NewServer()
|
|
var randomServer RandomServer
|
|
protoapi.RegisterRandomServer(server, randomServer)
|
|
|
|
reflection.Register(server)
|
|
|
|
listen, err := net.Listen("tcp", port)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
|
|
fmt.Println("Serving requests...")
|
|
server.Serve(listen)
|
|
}
|