-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
227 lines (187 loc) · 5.86 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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"gopkg.in/yaml.v2"
)
// Define the data structure for Batsman and Bowler.
type Batsman struct {
Name string `json:"name"`
Runs string `json:"runs"`
Balls string `json:"balls"`
StrikeRate string `json:"strike_rate"`
}
type Bowler struct {
Name string `json:"name"`
Overs string `json:"overs"`
Runs string `json:"runs"`
Wickets string `json:"wickets"`
}
type LiveScore struct {
Title string `json:"title"`
Update string `json:"update"`
LiveScore string `json:"livescore"`
MatchDate string `json:"match_date"`
RunRate string `json:"runrate"`
CurrentBatsmen []Batsman `json:"current_batsmen"`
CurrentBowler []Bowler `json:"current_bowler"`
}
type Config struct {
APIURL string `yaml:"api_url"`
}
const (
timeout = 10 * time.Second
port = 6053
configFilename = "config.yaml"
escapeTextUsage = "Implement escaping if needed"
maxMatchIDLen = 10
)
var httpClient = &http.Client{
Timeout: timeout,
}
func loadConfig(filename string) (*Config, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
var config Config
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to parse config file: %w", err)
}
if config.APIURL == "" {
return nil, fmt.Errorf("API URL is missing in config")
}
return &config, nil
}
func fetchScore(matchID string, apiURL string) (*LiveScore, error) {
if matchID == "" {
return nil, fmt.Errorf("match ID cannot be empty")
}
url := fmt.Sprintf("%s%s", apiURL, matchID)
resp, err := httpClient.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to fetch score: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var score LiveScore
if err := json.NewDecoder(resp.Body).Decode(&score); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
if err := validateScore(score); err != nil {
return nil, fmt.Errorf("invalid score data: %w", err)
}
return &score, nil
}
func validateScore(score LiveScore) error {
if score.Title == "" || score.LiveScore == "" || score.MatchDate == "" || score.RunRate == "" {
return fmt.Errorf("required fields are missing")
}
if len(score.CurrentBatsmen) == 0 || len(score.CurrentBowler) == 0 {
return fmt.Errorf("batsmen or bowler data is missing")
}
for _, batsman := range score.CurrentBatsmen {
if _, err := strconv.ParseFloat(batsman.StrikeRate, 64); err != nil {
return fmt.Errorf("invalid strike rate for batsman %s: %w", batsman.Name, err)
}
}
for _, bowler := range score.CurrentBowler {
if _, err := strconv.ParseFloat(bowler.Overs, 64); err != nil {
return fmt.Errorf("invalid overs for bowler %s: %w", bowler.Name, err)
}
}
return nil
}
func formatScore(score *LiveScore) string {
result := fmt.Sprintf(
"\n\n Match Details:\n\n Title: %s\n Update: %s\n Live Score: %s\n Match Date: %s\n Run Rate: %s\n\n",
escapeText(score.Title),
escapeText(score.Update),
escapeText(score.LiveScore),
escapeText(score.MatchDate),
escapeText(score.RunRate),
)
result += " Current Batsmen:\n\n"
for _, batsman := range score.CurrentBatsmen {
result += fmt.Sprintf(
" - Name: %s\n Runs: %s\n Balls: %s\n Strike Rate: %s\n\n",
escapeText(batsman.Name),
escapeText(batsman.Runs),
escapeText(batsman.Balls),
escapeText(batsman.StrikeRate),
)
}
result += " Current Bowlers:\n\n"
for _, bowler := range score.CurrentBowler {
result += fmt.Sprintf(
" - Name: %s\n Overs: %s\n Runs: %s\n Wickets: %s\n\n",
escapeText(bowler.Name),
escapeText(bowler.Overs),
escapeText(bowler.Runs),
escapeText(bowler.Wickets),
)
}
return result
}
func escapeText(text string) string {
return text // Implement escaping if needed
}
func liveScoreHandler(w http.ResponseWriter, r *http.Request) {
config, err := loadConfig(configFilename)
if err != nil {
log.Printf("Error loading config: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-XSS-Protection", "1; mode=block")
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
w.Header().Set("X-Robots-Tag", "noindex, nofollow")
matchID := r.URL.Query().Get("id")
if matchID == "" {
http.Error(w, "match ID is required", http.StatusBadRequest)
return
}
if len(matchID) > maxMatchIDLen {
http.Error(w, "match ID is too long", http.StatusBadRequest)
return
}
score, err := fetchScore(matchID, config.APIURL)
if err != nil {
log.Printf("Error fetching score: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, formatScore(score))
}
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 Page Not Found")
}
func internalServerErrorHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 Internal Server Error")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/livescore", liveScoreHandler)
mux.HandleFunc("/404", notFoundHandler)
mux.HandleFunc("/500", internalServerErrorHandler)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.NotFoundHandler().ServeHTTP(w, r)
})
log.Printf("Server starting on port %d\n", port)
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), mux); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}