Skip to content
Open
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
44 changes: 44 additions & 0 deletions bind.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package strip

import (
"errors"
"reflect"
)

func Bind(input interface{}) error {

// Get the value of the input
v := reflect.ValueOf(input)

// Ensure the input is a pointer
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return errors.New("input is a nil pointer")
}
v = v.Elem()
}

// Get the type of the value
t := v.Type()

// Ensure the dereferenced value is a struct
if t.Kind() != reflect.Struct {
return errors.New("input is not a struct or pointer to a struct")
}

// Iterate through the fields
for i := 0; i < v.NumField(); i++ {
field := t.Field(i) // Get the field
value := v.Field(i) // Get the field's value
tag := field.Tag.Get("strip_tag") // Get the 'validate' tag

// Check if the tag is set to "true" and the field is a string
if tag == "true" && value.Kind() == reflect.String {
// Strip the HTML tags
clean := StripTags(value.String())
value.SetString(clean)
}
}

return nil
}
26 changes: 26 additions & 0 deletions bind_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package strip

import "testing"

func TestBindStruct(t *testing.T) {
// Sample struct
type user struct {
Name string `strip_tag:"true"`
Age int
Email string `strip_tag:"true"`
Photo string
}

users := user{
Name: "<b>John Doe</b>",
Age: 30,
Email: "<script>alert('Hello')</script>",
Photo: "<h1>aa</h1>profile.jpg",
}

if err := Bind(&users); err != nil {
t.Error(err)
}

t.Log(users)
}