-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.go
119 lines (108 loc) · 2.43 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
package main
import (
"encoding/json"
"github.com/bertoort/sugoku/puzzle"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
)
func parse(j string) puzzle.Puzzle {
board := []byte(j)
var b [9][9]int
json.Unmarshal(board, &b)
return puzzle.New(b)
}
// CORSMiddleware allows others to access the api
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set(
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With",
)
c.Writer.Header().Set(
"Access-Control-Allow-Methods",
"POST, OPTIONS, GET, PUT",
)
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
g := gin.Default()
g.LoadHTMLGlob("templates/*.html")
g.Static("/public", "public")
g.Use(CORSMiddleware())
g.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl.html", gin.H{
"title": "suGOku",
})
})
g.GET("/board", func(c *gin.Context) {
dif := c.Query("difficulty")
var b [9][9]int
if dif == "random" {
b = puzzle.GenRandom()
} else if dif == "hard" {
b = puzzle.Generate(dif)
} else if dif == "medium" {
b = puzzle.Generate(dif)
} else if dif == "easy" {
b = puzzle.Generate(dif)
}
c.JSON(http.StatusOK, gin.H{"board": b})
})
g.POST("/solve", func(c *gin.Context) {
j := c.PostForm("board")
s := parse(j)
s.Grade()
err := s.SlowSolve()
v := s.Validate()
sol, stat, dif := s.Display()
if err && v {
stat = "solved"
} else if err {
stat = "broken"
}
c.JSON(http.StatusOK, gin.H{
"solution": sol,
"status": stat,
"difficulty": dif,
})
})
g.POST("/grade", func(c *gin.Context) {
j := c.PostForm("board")
s := parse(j)
s.Grade()
_, _, dif := s.Display()
c.JSON(http.StatusOK, gin.H{
"difficulty": dif,
})
})
g.POST("/validate", func(c *gin.Context) {
j := c.PostForm("board")
s := parse(j)
v := s.Validate()
_, stat, _ := s.Display()
err := s.SlowSolve()
_, newStat, _ := s.Display()
if err && v {
stat = "solved"
} else if err || newStat == "unsolvable" {
stat = "broken"
}
c.JSON(http.StatusOK, gin.H{
"status": stat,
})
})
g.Run(":" + port)
}