-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.go
99 lines (80 loc) · 2.31 KB
/
webserver.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
// Created by Ibn Aleem (github.com/ibnaleem)
// Updated Friday 08 November, 2024 @ 12:22 GMT
// Repository: https://github.com/ibnaleem/cc-validation-webserver
// Issues: https://github.com/ibnaleem/cc-validation-webserver/issues
package main
import (
"fmt"
"net/http"
"encoding/json"
"errors"
"os"
"io"
"strconv"
)
var PORT string = "3333"
func getRoot(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") == "" {
fmt.Printf("[%s] on root (/) with cURL\n", r.Method)
} else {
fmt.Printf("[%s] on root (/) with header %s\n", r.Method, r.Header.Get("Content-Type"))
}
if r.Header.Get("Content-Type") == "application/json" {
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
value, exists := data["credit-card"] // replace "credit-card" with the actual card-card field on your front-end
if exists {
valueInt, err := strconv.Atoi(value.(string))
if err != nil {
http.Error(w, "Invalid credit card number", http.StatusBadRequest)
return
}
if validator(valueInt) {
io.WriteString(w, strconv.FormatBool(true))
} else {
io.WriteString(w, strconv.FormatBool(false))
}
} else {
http.Error(w, "Missing expected field in JSON", http.StatusBadRequest)
}
} else {
http.Error(w, "Expected JSON", http.StatusBadRequest)
}
}
func validator(cc int) bool {
count := 0
sum := 0
// Iterate over the digits of cc
for cc > 0 {
digit := cc % 10 // Extract the last digit
cc /= 10 // Remove the last digit
count++
// Double the digit if count is even
if count % 2 == 0 {
digit *= 2
// If the doubled digit is greater than 9, subtract 9
if digit > 9 {
digit -= 9
}
}
// Add the digit to the sum
sum += digit
}
return sum % 10 == 0
}
func main() {
fmt.Println(":: Please open issues @ https://github.com/ibnaleem/cc-validation-webserver/issues")
fmt.Printf(":: Webserver started on port %s ::\n", PORT)
http.HandleFunc("/", getRoot)
err := http.ListenAndServe(":" + PORT, nil)
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf(":: Server closed ::\n")
} else if err != nil {
fmt.Printf(":: Error starting server: %s\n ::", err)
os.Exit(1)
}
fmt.Println(":: Webserver started on port 3333 ::")
}