Skip to content

feat: add initial support for custom entry unmarshaler #557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 35 additions & 23 deletions v3/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,38 +246,19 @@ func readTag(f reflect.StructField) (string, bool) {
// // ...
// }
func (e *Entry) Unmarshal(i interface{}) (err error) {
// Make sure it's a ptr
if vo := reflect.ValueOf(i).Kind(); vo != reflect.Ptr {
return fmt.Errorf("ldap: cannot use %s, expected pointer to a struct", vo)
}

sv, st := reflect.ValueOf(i).Elem(), reflect.TypeOf(i).Elem()
// Make sure it's pointing to a struct
if sv.Kind() != reflect.Struct {
return fmt.Errorf("ldap: expected pointer to a struct, got %s", sv.Kind())
}

for n := 0; n < st.NumField(); n++ {
// Holds struct field value and type
fv, ft := sv.Field(n), st.Field(n)

// skip unexported fields
if ft.PkgPath != "" {
continue
}

return e.UnmarshalFunc(i, func(entry *Entry, ft reflect.StructField, fv reflect.Value) error {
// omitempty can be safely discarded, as it's not needed when unmarshalling
fieldTag, _ := readTag(ft)

// Fill the field with the distinguishedName if the tag key is `dn`
if fieldTag == "dn" {
fv.SetString(e.DN)
continue
return nil
}

values := e.GetAttributeValues(fieldTag)
if len(values) == 0 {
continue
return nil
}

switch fv.Interface().(type) {
Expand Down Expand Up @@ -320,8 +301,39 @@ func (e *Entry) Unmarshal(i interface{}) (err error) {
default:
return fmt.Errorf("ldap: expected field to be of type string, *string, []string, int, int64, []byte, *DN, []*DN or time.Time, got %v", ft.Type)
}
return nil
})
}

// UnmarshalFunc allows you to define a custom unmarshaler to parse an Entry values.
// A custom unmarshaler can be found in the Unmarshal function or in the test files.
func (e *Entry) UnmarshalFunc(i interface{},
fn func(entry *Entry, fieldType reflect.StructField, fieldValue reflect.Value) error) error {
// Make sure it's a ptr
if vo := reflect.ValueOf(i).Kind(); vo != reflect.Ptr {
return fmt.Errorf("ldap: cannot use %s, expected pointer to a struct", vo)
}

sv, st := reflect.ValueOf(i).Elem(), reflect.TypeOf(i).Elem()
// Make sure it's pointing to a struct
if sv.Kind() != reflect.Struct {
return fmt.Errorf("ldap: expected pointer to a struct, got %s", sv.Kind())
}

for n := 0; n < st.NumField(); n++ {
fv, ft := sv.Field(n), st.Field(n)

// skip unexported fields
if ft.PkgPath != "" {
continue
}

if err := fn(e, ft, fv); err != nil {
return err
}
}
return

return nil
}

// NewEntryAttribute returns a new EntryAttribute with the desired key-value pair
Expand Down
59 changes: 59 additions & 0 deletions v3/search_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ldap

import (
"fmt"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -219,3 +220,61 @@ func TestEntry_Unmarshal(t *testing.T) {
assert.Equal(t, expect, result)
})
}

func TestEntry_UnmarshalFunc(t *testing.T) {
conn, err := DialURL(ldapServer)
if err != nil {
t.Fatalf("Failed to connect: %s\n", err)
}
defer conn.Close()

searchResult, err := conn.Search(&SearchRequest{
BaseDN: baseDN,
Scope: ScopeWholeSubtree,
Filter: "(cn=cis-fac)",
Attributes: []string{"cn", "objectClass"},
})
if err != nil {
t.Fatalf("Failed to search: %s\n", err)
}

type user struct {
ObjectClass string `custom_tag:"objectClass"`
CN string `custom_tag:"cn"`
}

t.Run("expect custom unmarshal function to be successfull", func(t *testing.T) {
for _, entry := range searchResult.Entries {
var u user
if err := entry.UnmarshalFunc(&u, func(entry *Entry, fieldType reflect.StructField, fieldValue reflect.Value) error {
tagData, ok := fieldType.Tag.Lookup("custom_tag")
if !ok {
return nil
}

value := entry.GetAttributeValue(tagData)
// log.Printf("Marshaling field %s with tag %s and value '%s'", fieldType.Name, tagData, value)
fieldValue.SetString(value)
return nil
}); err != nil {
t.Errorf("Failed to unmarshal entry: %s\n", err)
}

if u.CN != entry.GetAttributeValue("cn") {
t.Errorf("UnmarshalFunc did not set the field correctly. Expected: %s, got: %s", entry.GetAttributeValue("cn"), u.CN)
}
}
})

t.Run("expect an error within the custom unmarshal function", func(t *testing.T) {
for _, entry := range searchResult.Entries {
var u user
err := entry.UnmarshalFunc(&u, func(entry *Entry, fieldType reflect.StructField, fieldValue reflect.Value) error {
return fmt.Errorf("error from custom unmarshal func on field: %s", fieldType.Name)
})
if err == nil {
t.Errorf("UnmarshalFunc should have returned an error")
}
}
})
}
Loading