-
Notifications
You must be signed in to change notification settings - Fork 68
/
apiServ.go
82 lines (68 loc) · 1.88 KB
/
apiServ.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
// StartAPI starts the API server.
func StartAPI() {
// Set Gin configuration mode
gin.SetMode(gin.ReleaseMode)
// Configure & Start the HTTP API server
router := gin.Default()
router.GET("/get/config", GetConfig)
router.POST("/set/config", SetConfig)
router.POST("/start", APIStart)
router.Run("127.0.0.1:8000")
}
// API endpoint to set the configuration options
func SetConfig(ctx *gin.Context) {
// Validate input
var config Configuration // temporary variable required for proper validation
if ctx.BindJSON(&config) != nil {
// Invalid JSON sent
ctx.JSON(http.StatusBadRequest, gin.H{
"message": "invalid JSON data",
})
return
}
// Set defaults
SetDefaults(&config)
// Assign to global configuration object
configuration = config
// Send response
ctx.JSON(http.StatusOK, gin.H{
"message": "configuration saved",
})
}
// API endpoint to retrieve the high-level configuration
func GetConfig(ctx *gin.Context) {
// Check if the configuration exists
if len(configuration.Requests) == 0 {
// No configuration currently exists
ctx.JSON(http.StatusBadRequest, gin.H{
"message": "no configuration set",
})
return
}
// Send response
ctx.JSON(http.StatusOK, configuration)
}
// API endpoint to begin the race test using the configuration file already provided.
func APIStart(ctx *gin.Context) {
// Run race test, returning any initial errors
err, responses := StartRace()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"message": fmt.Sprintf("error: %s", err.Error()),
})
}
// Set response values
ctx.Header("Content-Type", "application/json")
ctx.Status(http.StatusOK)
// Manually serialize responses, in order to remove html escaping.
enc := json.NewEncoder(ctx.Writer)
enc.SetEscapeHTML(false) // Disable html escaping
enc.Encode(responses)
}