Add PrintJSON() for API use

This commit is contained in:
yo 2024-09-05 09:32:13 +02:00
parent 0e0ab8c653
commit 5ce62bc7de

View File

@ -1,7 +1,10 @@
package cmd package cmd
import ( import (
"fmt"
"sort"
"time" "time"
"strings"
) )
const ( const (
@ -561,3 +564,90 @@ type DatastoreSort struct {
AvailableDec datastoreLessFunc AvailableDec datastoreLessFunc
} }
type Field struct {
Name string
MaxLen int
Value string
}
func (j *Jail) PrintJSON(fields []string) ([]byte, error) {
return j.PrintJSONWithUpper("", fields)
}
func (j *Jail) PrintJSONWithUpper(upper string, fields []string) ([]byte, error) {
var res []byte
if len(fields) < 1 {
return res, nil
}
if len(upper) > 0 {
res = append(res, []byte(fmt.Sprintf("\"%s\": {", upper))...)
} else {
res = append(res, []byte("{")...)
}
// Reorder fields so we got fields of a sub-structure adjacents
sort.Strings(fields)
var ffname string
offset := 0
for i, _ := range fields {
if i + offset >= len(fields) {
break
}
// Is this struct in struct?
if strings.Contains(fields[i+offset], ".") {
// Count items in this struct
var subfields []string
var newUpper string
for _, sf := range fields[i+offset:] {
if strings.Split(sf, ".")[0] == strings.Split(fields[i+offset], ".")[0] {
newUpper = strings.Split(sf, ".")[0]
sub := strings.Join(strings.Split(string(sf), ".")[1:], ".")
subfields = append(subfields, sub)
}
}
out, err := j.PrintJSONWithUpper(newUpper, subfields)
if err != nil {
return []byte{}, err
}
res = append(res, out...)
offset += len(subfields)-1
if i + offset < len(fields) - 1 {
res = append(res, []byte(",")...)
}
continue
}
if len(upper) > 0 {
ffname = fmt.Sprintf("%s.%s", upper, fields[i+offset])
} else {
ffname = fields[i+offset]
}
val, _, err := getStructFieldValue(j, ffname)
if err != nil {
return []byte{}, fmt.Errorf("Error accessing field \"%s\" : %v\n", fields[i+offset], err)
}
res = append(res, []byte(fmt.Sprintf("\"%s\": ", fields[i+offset]))...)
switch val.Interface().(type) {
case string:
res = append(res, []byte(fmt.Sprintf("\"%s\"", val.Interface().(string)))...)
case int:
res = append(res, []byte(fmt.Sprintf("%d", val.Interface().(int)))...)
case bool:
res = append(res, []byte(fmt.Sprintf("%t", val.Interface().(bool)))...)
default:
fmt.Printf("ERREUR dans Jail.PrintJSONWithUpper() : Type inconnu : %T\n", val.Interface())
}
if i + offset < len(fields) - 1 {
res = append(res, []byte(",")...)
}
}
res = append(res, []byte("}")...)
return res, nil
}