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

rest/httpx.SetValidator might panic #4594

Closed
xmx opened this issue Jan 23, 2025 · 0 comments · Fixed by #4597
Closed

rest/httpx.SetValidator might panic #4594

xmx opened this issue Jan 23, 2025 · 0 comments · Fixed by #4597

Comments

@xmx
Copy link

xmx commented Jan 23, 2025

// SetValidator sets the validator.
// The validator is used to validate the request, only called in Parse,
// not in ParseHeaders, ParseForm, ParseHeader, ParseJsonBody, ParsePath.
func SetValidator(val Validator) {
validator.Store(val)
}

由于 atomic.Value Strore 方法会 校验和首次存储的数据类型是否一致,此处存在 panic 风险。

复现代码:

package main

import (
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func main() {
	httpx.SetValidator(Valid1{})
	httpx.SetValidator(Valid2{}) // panic: sync/atomic: store of inconsistently typed value into Value
}

type Valid1 struct{}

func (v Valid1) Validate(*http.Request, any) error { return nil }

type Valid2 struct{}

func (v Valid2) Validate(*http.Request, any) error { return nil }

SetValidator 方法改进建议:

func SetValidator(val Validator) {
	validator.Store(&validate{val: val})
}

type validate struct {
	val Validator
}

func (v *validate) Validate(r *http.Request, data any) error {
	if v.val != nil {
		return v.val.Validate(r, data)
	}
	
	return nil
}
@kevwan kevwan changed the title rest/httpx.SetValidator 存在 panic 风险 rest/httpx.SetValidator might panic Jan 23, 2025
@kevwan kevwan changed the title rest/httpx.SetValidator might panic rest/httpx.SetValidator might panic Jan 23, 2025
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

Successfully merging a pull request may close this issue.

1 participant