-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
116 lines (92 loc) · 2.37 KB
/
api.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
package main
import (
"errors"
"github.com/gin-gonic/gin"
"log"
"os"
"strconv"
)
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "application/json")
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, API-KEY")
if c.Request.Method == "OPTIONS" {
c.Abort(200)
return
}
c.Next()
}
}
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Header.Get("API-KEY") != os.Getenv("API_KEY") {
c.Abort(401)
return
}
c.Next()
}
}
func presentThermostat(thermostat *Thermostat) gin.H {
return gin.H{
"currentTemp": thermostat.CurrentTemp(),
"targetTemp": thermostat.TargetTemp,
"heaterOn": thermostat.HeaterOn(),
}
}
type ThermostatRequest struct {
TargetTemp int `json:"targetTemp" binding:"required"`
}
type ScheduleResponse struct {
Id int `json:"id"`
Hour int `json:"hour" binding:"required"`
TargetTemp int `json:"target_temp" binding:"required"`
Days string `json:"days" binding:"required"`
}
func Api(thermostat *Thermostat) *gin.Engine {
database := &Database{}
r := gin.New()
r.Use(gin.Recovery())
r.Use(gin.Logger())
r.Use(CORSMiddleware())
if os.Getenv("TERMO_MOCK") != "true" {
r.Use(AuthMiddleware())
}
v1 := r.Group("/v1")
v1.GET("/thermostat", func(c *gin.Context) {
c.JSON(200, presentThermostat(thermostat))
})
v1.POST("/thermostat", func(c *gin.Context) {
var json ThermostatRequest
c.Bind(&json)
var targetTemp int
targetTemp = json.TargetTemp
log.Printf("Setting target temp to: %d", targetTemp)
thermostat.TargetTemp = json.TargetTemp
c.JSON(200, json)
})
v1.GET("/schedules", func(c *gin.Context) {
schedules, _ := FindAllSchedules(database)
c.JSON(200, schedules)
})
v1.POST("/schedules", func(c *gin.Context) {
var schedule Schedule
bound := c.Bind(&schedule)
if !bound {
c.Fail(400, errors.New("Invalid schedule"))
} else {
schedule.Save(database)
c.JSON(200, schedule)
}
})
v1.DELETE("/schedules/:id", func(c *gin.Context) {
id, err := strconv.Atoi(c.Params.ByName("id"))
if err != nil {
c.Fail(400, errors.New("Malformed id"))
} else {
DestroySchedule(database, id)
c.String(200, "")
}
})
return r
}