Add start api command

This commit is contained in:
yo 2024-09-05 09:34:05 +02:00
parent 2afccc5a0e
commit 372e92fc41

96
cmd/api.go Normal file
View File

@ -0,0 +1,96 @@
package cmd
import (
//"io"
"fmt"
"strings"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-contrib/cors"
)
func printJails(jails []string, fields []string) ([]byte, error) {
var res []byte
res = append(res, []byte("[")...)
// Build a filtered jail list
var filteredJails []Jail
if (len(jails) >= 1 && len(jails[0]) > 0) {
for _, j := range gJails {
if isStringInArray(jails, j.Name) {
filteredJails = append(filteredJails, j)
}
}
} else {
filteredJails = gJails
}
for i, j := range filteredJails {
out, err := j.PrintJSON(fields)
if err != nil {
return res, err
}
res = append(res, out...)
if i < len(filteredJails) - 1 {
res = append(res, []byte(",")...)
}
}
res = append(res, []byte("]")...)
return res, nil
}
func startApi(address string, port int) {
// Initialize gJails.
// FIXME: How to update this at running time without doubling the same jails?
// core will do this for us in add and delete functions
ListJails([]string{""}, false)
r := gin.Default()
// Cross Origin Request Support
config := cors.DefaultConfig()
// DANGER !
config.AllowOrigins = []string{"*"}
r.Use(cors.New(config))
r.GET("/jail/list", func(c *gin.Context) {
jailstr := c.Query("jail")
fields := c.Query("fields")
if len(fields) == 0 {
// TODO : Put this default value in (user?) configuration
fields = "Name,Running,Config.Release,Config.Ip4_addr"
}
jsout, err := printJails(strings.Split(jailstr, ","), strings.Split(fields, ","))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": 1, "error": err.Error()})
} else {
c.Data(http.StatusOK, "application/json", jsout)
}
})
r.POST("/jail/start/:jail", func(c *gin.Context) {
jailstr := c.Params.ByName("jail")
// TODO : Capture or redirect output so we can know if jail was started or not
StartJail(strings.Split(jailstr, ","))
c.JSON(http.StatusOK, gin.H{"status": 0, "error": ""})
})
r.POST("/jail/stop/:jail", func(c *gin.Context) {
jailstr := c.Params.ByName("jail")
// TODO : Capture or redirect output so we can know if jail was started or not
StopJail(strings.Split(jailstr, ","))
c.JSON(http.StatusOK, gin.H{"status": 0, "error": ""})
})
r.GET("/jail/properties", func(c *gin.Context) {
props, err := ListJailsProps("json")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": 1, "error": err.Error()})
} else {
c.Data(http.StatusOK, "application/json", []byte(props))
}
})
r.Run(fmt.Sprintf("%s:%d", address, port))
}