/
server_costs.go
49 lines (41 loc) · 1.18 KB
/
server_costs.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
package handler
import (
"net/http"
"github.com/fatih/structs"
"github.com/gin-gonic/gin"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/lmaraite/hcloud-cost-service/controller"
)
const (
apiTokenHeader = "API_TOKEN"
errorMessageKey = "error_message"
)
type ServerCostsController interface {
CalculateServerCosts() (*controller.ServerCostsResponse, error)
}
type ServerCostsHandler struct {
Controller ServerCostsController
}
func NewServerCostsHandler(controller ServerCostsController) *ServerCostsHandler {
return &ServerCostsHandler{
Controller: controller,
}
}
func DefaultServerCostsHandler(c *gin.Context) *ServerCostsHandler {
apiToken := c.GetHeader(apiTokenHeader)
client := &hcloud.NewClient(hcloud.WithToken(apiToken)).Server
controller := controller.NewServerCostsController(client)
return &ServerCostsHandler{
Controller: controller,
}
}
func (handler *ServerCostsHandler) ServerCosts(c *gin.Context) {
response, err := handler.Controller.CalculateServerCosts()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
errorMessageKey: err.Error(),
})
return
}
c.JSON(http.StatusOK, structs.Map(&response))
}