Skip to content

rest/httpx.SetValidator might panic #4594

Closed
@xmx

Description

// 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
}

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions