Skip to content

Commit

Permalink
Merge pull request #72 from projectdiscovery/issue-68-struct-walk
Browse files Browse the repository at this point in the history
Moving walk to utils package
  • Loading branch information
Mzack9999 authored Feb 3, 2023
2 parents 379a600 + 80b5a41 commit 6b0a0c4
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions structs/structs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package structs

import "reflect"

// CallbackFunc on the struct field
// example:
// structValue := reflect.ValueOf(s)
// ...
// field := structValue.Field(i)
// fieldType := structValue.Type().Field(i)
type CallbackFunc func(reflect.Value, reflect.StructField)

// Walk traverses a struct and executes a callback function on each field in the struct.
// The interface{} passed to the function should be a pointer to a struct
func Walk(s interface{}, callback CallbackFunc) {
structValue := reflect.ValueOf(s)
if structValue.Kind() == reflect.Ptr {
structValue = structValue.Elem()
}
if structValue.Kind() != reflect.Struct {
return
}
for i := 0; i < structValue.NumField(); i++ {
field := structValue.Field(i)
fieldType := structValue.Type().Field(i)
if !fieldType.IsExported() {
continue
}
if field.Kind() == reflect.Struct {
Walk(field.Addr().Interface(), callback)
} else if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct {
Walk(field.Interface(), callback)
} else {
callback(field, fieldType)
}
}
}

0 comments on commit 6b0a0c4

Please sign in to comment.