Skip to content

Commit

Permalink
ignore unexported fields in struct to avoid panic
Browse files Browse the repository at this point in the history
  • Loading branch information
violin0622 authored and david-littlefarmer committed Jan 31, 2024
1 parent 8a3ed0d commit 6820774
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
6 changes: 6 additions & 0 deletions devslog.go
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,9 @@ func (h *developHandler) formatStruct(st reflect.Type, sv reflect.Value, l int)
pr := h.structKeyPadding(sv, nil)

for i := 0; i < sv.NumField(); i++ {
if !sv.Type().Field(i).IsExported() {
continue
}
v := sv.Field(i)
t := v.Type()

Expand Down Expand Up @@ -624,6 +627,9 @@ func (h *developHandler) mapKeyPadding(rv reflect.Value, fgColor *foregroundColo
func (h *developHandler) structKeyPadding(sv reflect.Value, fgColor *foregroundColor) (p int) {
st := sv.Type()
for i := 0; i < sv.NumField(); i++ {
if !st.Field(i).IsExported() {
continue
}
c := len(st.Field(i).Name)
if fgColor != nil {
c = len(cs([]byte(st.Field(i).Name), *fgColor))
Expand Down
26 changes: 14 additions & 12 deletions devslog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -679,21 +679,23 @@ func test_Struct(t *testing.T, o *Options) {
logger := slog.New(NewHandler(w, o))

type StructTest struct {
Slice []int
Map map[int]int
Struct struct{ B bool }
SliceP *[]int
MapP *map[int]int
StructP *struct{ B bool }
Slice []int
Map map[int]int
Struct struct{ B bool }
SliceP *[]int
MapP *map[int]int
StructP *struct{ B bool }
unexported int
}

s := &StructTest{
Slice: []int{},
Map: map[int]int{},
Struct: struct{ B bool }{},
SliceP: &[]int{},
MapP: &map[int]int{},
StructP: &struct{ B bool }{},
Slice: []int{},
Map: map[int]int{},
Struct: struct{ B bool }{},
SliceP: &[]int{},
MapP: &map[int]int{},
StructP: &struct{ B bool }{},
unexported: 5,
}

logger.Info("msg",
Expand Down

0 comments on commit 6820774

Please sign in to comment.