Skip to content
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

bug about type alias #174

Open
ghost opened this issue Sep 1, 2022 · 2 comments
Open

bug about type alias #174

ghost opened this issue Sep 1, 2022 · 2 comments

Comments

@ghost
Copy link

ghost commented Sep 1, 2022

if I set a type alias of basic type,like []string ,then, I neet to add two function,such as ( value and scan ,mysql json need this), the bug is appened.
the entire code under:

package main

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"

	validation "github.com/go-ozzo/ozzo-validation"
)

type Tags []string

// mysql 8.0 json need value and scan function, so I need type alias
type Courses struct {
	Tag Tags `gorm:"type:json;comment:体系名是json格式" json:"tag"`
}

// !!!!!! IF YOU REMOVE THIS FUNCTION, IT IS VALIDETED !!!!!
// !!!!!! IF YOU ADD PONITER IN P, IT IS VALIDETED  !!!!
func (p Tags) Value() (driver.Value, error) {
	b, err := json.Marshal(p)
	return b, err
}


func (p *Tags) Scan(input any) error {
	return json.Unmarshal(input.([]byte), p)
}

func main() {

	var courseDto Courses
	courseDto.Tag = Tags{"student", "engineer"}
	err := validation.ValidateStruct(&courseDto,
		validation.Field(&courseDto.Tag, validation.Required, validation.Length(1, 3)),
	)
	fmt.Println(err)
}

Something strange is coming in function value !!!
If p without pointer can't pass validate!

func (p Tags) Value() (driver.Value, error) {
	//b, err := json.Marshal(p)
	return nil, nil
}

But, if add pointer, it pass!

@bokunodev
Copy link

bokunodev commented Oct 28, 2022

its because of how Value method is implemented.
it return []byte from json.Unmarshal. which is obviously would be longger than 3 or shorter than 1

the solution would be to have separate type for request validation and dto.

@bokunodev
Copy link

bokunodev commented Nov 6, 2022

solution: use is package as mentioned in the credit. asaskevich/govalidator does not check for sql valuer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant