-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (63 loc) · 1.35 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
package main
import (
"bufio"
"fmt"
"net"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
func Start() error {
listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", 8080))
if err != nil {
return err
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
request := scanner.Text()
response := handleRequest(request)
fmt.Fprintf(conn, "%s\n", response)
}
if err := scanner.Err(); err != nil {
fmt.Println("Error reading from connection:", err)
}
}
func handleRequest(request string) string {
parts := strings.Split(request, "|")
if len(parts) != 2 || parts[0] != "PAYMENT" {
return "RESPONSE|REJECTED|Invalid request"
}
amount, err := strconv.Atoi(parts[1])
if err != nil {
return "RESPONSE|REJECTED|Invalid amount"
}
if amount > 100 {
processingTime := amount
if amount > 10000 {
processingTime = 10000
}
time.Sleep(time.Duration(processingTime) * time.Millisecond)
}
return "RESPONSE|ACCEPTED|Transaction processed"
}
func main() {
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
go Start()
<-shutdown
}