-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (60 loc) · 1.8 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
)
func main() {
port := os.Getenv("PORT")
router := mux.NewRouter().StrictSlash(true)
connection := GetConnection()
router.Path("/solve").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
return
}
puzzle := r.URL.Query().Get("puzzle")
cacheKeySolve := GenerateCacheKey(puzzle, "solve")
cacheKeyCheck := GenerateCacheKey(puzzle, "check")
cachedSolution, ok := GetKey(connection, cacheKeySolve)
if !ok {
solvedPuzzle, valid := Solve(puzzle, false)
if !valid {
http.Error(w, fmt.Errorf("Invalid Sudoku").Error(), http.StatusInternalServerError)
return
}
solved := CheckSolution(solvedPuzzle)
SetKey(connection, cacheKeySolve, solvedPuzzle)
SetKey(connection, cacheKeyCheck, strconv.FormatBool(solved))
SendResponse(w, solvedPuzzle, solved)
return
}
cachedCheck, _ := GetKey(connection, cacheKeyCheck)
solved, _ := strconv.ParseBool(cachedCheck)
SendResponse(w, cachedSolution, solved)
}).Methods(http.MethodGet, http.MethodOptions)
router.HandleFunc("/check", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
return
}
puzzle := r.URL.Query().Get("puzzle")
cacheKeyCheck := GenerateCacheKey(puzzle, "check")
cachedCheck, ok := GetKey(connection, cacheKeyCheck)
if !ok {
solved := CheckSolution(puzzle)
if solved {
SetKey(connection, cacheKeyCheck, "true")
SendResponse(w, puzzle, solved)
return
}
SetKey(connection, cacheKeyCheck, "false")
SendError(w, "Invalid Sudoku")
return
}
solved, _ := strconv.ParseBool(cachedCheck)
SendResponse(w, puzzle, solved)
}).Methods(http.MethodGet, http.MethodOptions)
log.Fatal(http.ListenAndServe(":"+port, router))
}