-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
118 lines (101 loc) · 2.44 KB
/
main.go
File metadata and controls
118 lines (101 loc) · 2.44 KB
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
package main
import (
"bufio"
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"log"
"net/http"
"os"
"strings"
)
// Add your allowed keys here
var allowedKeys = map[string]bool{
"unkwn|9032748983": true,
}
func loadAllowedKeys() {
file, err := os.Open("allowed_keys.txt")
if err != nil {
log.Printf("Warning: Could not load allowed_keys.txt: %v", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
key := strings.TrimSpace(scanner.Text())
if key != "" {
allowedKeys[key] = true
}
}
}
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("x-api-key")
if !allowedKeys[key] {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next(w, r)
}
}
type SolveResponse struct {
X int `json:"x"`
Y int `json:"y"`
Confidence float64 `json:"confidence"`
}
func solveHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse multipart form
err := r.ParseMultipartForm(10 << 20) // 10 MB limit
if err != nil {
http.Error(w, "Failed to parse form", http.StatusBadRequest)
return
}
bgFile, _, err := r.FormFile("background")
if err != nil {
http.Error(w, "Missing background image", http.StatusBadRequest)
return
}
defer bgFile.Close()
sliceFile, _, err := r.FormFile("piece")
if err != nil {
http.Error(w, "Missing piece image", http.StatusBadRequest)
return
}
defer sliceFile.Close()
bgImg, _, err := image.Decode(bgFile)
if err != nil {
http.Error(w, "Invalid background image", http.StatusBadRequest)
return
}
sliceImg, _, err := image.Decode(sliceFile)
if err != nil {
http.Error(w, "Invalid piece image", http.StatusBadRequest)
return
}
// Call Solve from solve.go
pos, score, err := Solve(bgImg, sliceImg)
if err != nil {
http.Error(w, fmt.Sprintf("Solver error: %v", err), http.StatusInternalServerError)
return
}
resp := SolveResponse{
X: pos.X,
Y: pos.Y,
Confidence: score,
}
fmt.Println(resp)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func main() {
http.HandleFunc("/solve", authMiddleware(solveHandler))
port := "8085"
fmt.Printf("Server starting on port %s...\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}