Merge pull request #60 from aykhans/refactor/json-marshal

Refactor json marshal
This commit is contained in:
Aykhan Shahsuvarov 2024-12-20 18:17:11 +04:00 committed by GitHub
commit c83246abe4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 89 additions and 50 deletions

View File

@ -59,9 +59,9 @@ You can find an example config structure in the [config.json](https://github.com
"method": "GET", "method": "GET",
"url": "https://example.com", "url": "https://example.com",
"no_proxy_check": false, "no_proxy_check": false,
"timeout": 10000, "timeout": 2000,
"dodos_count": 1, "dodos_count": 10,
"request_count": 1, "request_count": 1000,
"params": {}, "params": {},
"headers": {}, "headers": {},
"cookies": {}, "cookies": {},

View File

@ -1,9 +1,9 @@
package config package config
import ( import (
"fmt"
"net/url" "net/url"
"os" "os"
"strings"
"time" "time"
. "github.com/aykhans/dodo/types" . "github.com/aykhans/dodo/types"
@ -42,7 +42,18 @@ func (config *RequestConfig) Print() {
t.SetOutputMirror(os.Stdout) t.SetOutputMirror(os.Stdout)
t.SetStyle(table.StyleLight) t.SetStyle(table.StyleLight)
t.SetColumnConfigs([]table.ColumnConfig{ t.SetColumnConfigs([]table.ColumnConfig{
{Number: 2, WidthMax: 50}, {
Number: 2,
WidthMaxEnforcer: func(col string, maxLen int) string {
lines := strings.Split(col, "\n")
for i, line := range lines {
if len(line) > maxLen {
lines[i] = line[:maxLen-3] + "..."
}
}
return strings.Join(lines, "\n")
},
WidthMax: 50},
}) })
newHeaders := make(map[string][]string) newHeaders := make(map[string][]string)
@ -56,23 +67,23 @@ func (config *RequestConfig) Print() {
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"URL", config.URL}) t.AppendRow(table.Row{"URL", config.URL})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Timeout", fmt.Sprintf("%dms", config.Timeout/time.Millisecond)}) t.AppendRow(table.Row{"Timeout", config.Timeout})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Dodos", config.DodosCount}) t.AppendRow(table.Row{"Dodos", config.DodosCount})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Requests", config.RequestCount}) t.AppendRow(table.Row{"Requests", config.RequestCount})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Params", utils.MarshalJSON(config.Params, 3)}) t.AppendRow(table.Row{"Params", string(utils.PrettyJSONMarshal(config.Params, 3, "", " "))})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Headers", utils.MarshalJSON(newHeaders, 3)}) t.AppendRow(table.Row{"Headers", string(utils.PrettyJSONMarshal(newHeaders, 3, "", " "))})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Cookies", utils.MarshalJSON(config.Cookies, 3)}) t.AppendRow(table.Row{"Cookies", string(utils.PrettyJSONMarshal(config.Cookies, 3, "", " "))})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Proxies Count", len(config.Proxies)}) t.AppendRow(table.Row{"Proxies Count", string(utils.PrettyJSONMarshal(config.Proxies, 3, "", " "))})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck}) t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Body", utils.MarshalJSON(config.Body, 3)}) t.AppendRow(table.Row{"Body", string(utils.PrettyJSONMarshal(config.Body, 3, "", " "))})
t.Render() t.Render()
} }

View File

@ -6,49 +6,77 @@ import (
"reflect" "reflect"
) )
func MarshalJSON(v any, maxSliceSize uint) string { type TruncatedMarshaller struct {
rv := reflect.ValueOf(v) Value interface{}
if rv.Kind() == reflect.Slice && rv.Len() == 0 { MaxItems int
return "[]"
}
data, err := json.MarshalIndent(truncateLists(v, int(maxSliceSize)), "", " ")
if err != nil {
return "{}"
}
return string(data)
} }
func truncateLists(v interface{}, maxItems int) interface{} { func (t TruncatedMarshaller) MarshalJSON() ([]byte, error) {
rv := reflect.ValueOf(v) val := reflect.ValueOf(t.Value)
switch rv.Kind() { if val.Kind() != reflect.Slice && val.Kind() != reflect.Array {
case reflect.Slice, reflect.Array: return json.Marshal(t.Value)
if rv.Len() > maxItems { }
newSlice := reflect.MakeSlice(rv.Type(), maxItems, maxItems)
reflect.Copy(newSlice, rv.Slice(0, maxItems)) length := val.Len()
newSlice = reflect.Append(newSlice, reflect.ValueOf(fmt.Sprintf("...(%d more)", rv.Len()-maxItems))) if length <= t.MaxItems {
return newSlice.Interface() return json.Marshal(t.Value)
} }
truncated := make([]interface{}, t.MaxItems+1)
for i := 0; i < t.MaxItems; i++ {
truncated[i] = val.Index(i).Interface()
}
remaining := length - t.MaxItems
truncated[t.MaxItems] = fmt.Sprintf("+%d", remaining)
return json.Marshal(truncated)
}
func PrettyJSONMarshal(v interface{}, maxItems int, prefix, indent string) []byte {
truncated := processValue(v, maxItems)
d, _ := json.MarshalIndent(truncated, prefix, indent)
return d
}
func processValue(v interface{}, maxItems int) interface{} {
val := reflect.ValueOf(v)
switch val.Kind() {
case reflect.Map: case reflect.Map:
newMap := reflect.MakeMap(rv.Type()) newMap := make(map[string]interface{})
for _, key := range rv.MapKeys() { iter := val.MapRange()
newMap.SetMapIndex(key, reflect.ValueOf(truncateLists(rv.MapIndex(key).Interface(), maxItems))) for iter.Next() {
k := iter.Key().String()
newMap[k] = processValue(iter.Value().Interface(), maxItems)
} }
return newMap.Interface() return newMap
case reflect.Struct:
newStruct := reflect.New(rv.Type()).Elem()
for i := 0; i < rv.NumField(); i++ {
newStruct.Field(i).Set(reflect.ValueOf(truncateLists(rv.Field(i).Interface(), maxItems)))
}
return newStruct.Interface()
case reflect.Ptr:
if rv.IsNil() {
return nil
}
return truncateLists(rv.Elem().Interface(), maxItems)
}
return v case reflect.Slice, reflect.Array:
return TruncatedMarshaller{Value: v, MaxItems: maxItems}
case reflect.Struct:
newMap := make(map[string]interface{})
t := val.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.IsExported() {
jsonTag := field.Tag.Get("json")
if jsonTag == "-" {
continue
}
fieldName := field.Name
if jsonTag != "" {
fieldName = jsonTag
}
newMap[fieldName] = processValue(val.Field(i).Interface(), maxItems)
}
}
return newMap
default:
return v
}
} }