• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang govalidator.ValidateStruct函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/asaskevich/govalidator.ValidateStruct函数的典型用法代码示例。如果您正苦于以下问题:Golang ValidateStruct函数的具体用法?Golang ValidateStruct怎么用?Golang ValidateStruct使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ValidateStruct函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Validate

func Validate(v interface{}) *errors.Errors {
	if ok, err := govalidator.ValidateStruct(v); !ok {
		m := FormatErrors(err)
		return m
	}
	return nil
}
开发者ID:GoToolz,项目名称:Validator,代码行数:7,代码来源:validator.go


示例2: Valid

// Valid return true or false depending on whether or not the User is valid. It
// additionally sets the errors field on the User to provide information about
// why the user is not valid
func (u *User) Valid() bool {
	result, err := govalidator.ValidateStruct(u)
	if err != nil {
		u.errors = strings.Split(strings.TrimRight(err.Error(), ";"), ";")
	}
	return result
}
开发者ID:Acidburn0zzz,项目名称:web,代码行数:10,代码来源:users.go


示例3: ReadConfiguration

func ReadConfiguration(configFile string) (*Configuration, error) {
	_, err := os.Stat(configFile)
	if os.IsNotExist(err) {
		return nil, err
	}

	configFile, err = filepath.Abs(configFile)
	if err != nil {
		return nil, err
	}

	var yamlFile []byte
	if yamlFile, err = ioutil.ReadFile(configFile); err != nil {
		return nil, err
	}

	var config Configuration
	if err = yaml.Unmarshal(yamlFile, &config); err != nil {
		return nil, err
	}

	if _, err := valid.ValidateStruct(config); err != nil {
		return nil, err
	}

	return &config, nil
}
开发者ID:latam-airlines,项目名称:crane,代码行数:27,代码来源:config.go


示例4: Create

func (h *Handler) Create(ctx context.Context, rw http.ResponseWriter, req *http.Request) {
	var conn DefaultConnection
	decoder := json.NewDecoder(req.Body)
	if err := decoder.Decode(&conn); err != nil {
		HttpError(rw, err, http.StatusBadRequest)
		return
	}

	if v, err := govalidator.ValidateStruct(conn); !v {
		if err != nil {
			HttpError(rw, err, http.StatusBadRequest)
			return
		}
		HttpError(rw, errors.New("Payload did not validate."), http.StatusBadRequest)
		return
	}

	conn.ID = uuid.New()
	if err := h.s.Create(&conn); err != nil {
		HttpError(rw, err, http.StatusInternalServerError)
		return
	}

	WriteCreatedJSON(rw, "/oauth2/connections/"+conn.ID, &conn)
}
开发者ID:lmineiro,项目名称:hydra,代码行数:25,代码来源:handler.go


示例5: TestUnmarshallDdos

func TestUnmarshallDdos(t *testing.T) {
	buff := ExampleDdos_json()

	var ddos Ddos
	err := json.Unmarshal(buff, &ddos)
	assert.Nil(t, err)

	isValid, err := govalidator.ValidateStruct(ddos)
	assert.Nil(t, err)
	assert.True(t, isValid)

	assert.Equal(t, ddos.Identifier, 12345)
	assert.Equal(t, ddos.Target, "1.2.3.4")

	ddosStart, err := time.Parse(time.RFC3339, "2013-10-24T21:46:39.000Z")
	assert.Nil(t, err)
	assert.Equal(t, ddos.Start, ddosStart)

	ddosEnd, err := time.Parse(time.RFC3339, "2013-10-24T21:55:49.000Z")
	assert.Nil(t, err)
	assert.Equal(t, ddos.End, ddosEnd)

	assert.Equal(t, ddos.Mitigation, "root")
	assert.Equal(t, ddos.MaxPPS, 261758)
	assert.Equal(t, ddos.MaxBPS, 2652170368)
	assert.Equal(t, len(ddos.Timeline), 4)
	assert.Equal(t, ddos.Timeline[0].Timestamp, 1382651259)
	assert.Equal(t, ddos.Timeline[0].PPS, 174463)
	assert.Equal(t, ddos.Timeline[0].BPS, 1780643680)
}
开发者ID:moul,项目名称:onlinenet,代码行数:30,代码来源:resources_test.go


示例6: Validate

// Validate validates configuration
func (c *SlackConf) Validate() (errs []error) {

	if !c.UseThisTime {
		return
	}

	if len(c.HookURL) == 0 {
		errs = append(errs, fmt.Errorf("hookURL must not be empty"))
	}

	if len(c.Channel) == 0 {
		errs = append(errs, fmt.Errorf("channel must not be empty"))
	} else {
		if !(strings.HasPrefix(c.Channel, "#") ||
			c.Channel == "${servername}") {
			errs = append(errs, fmt.Errorf(
				"channel's prefix must be '#', channel: %s", c.Channel))
		}
	}

	if len(c.AuthUser) == 0 {
		errs = append(errs, fmt.Errorf("authUser must not be empty"))
	}

	_, err := valid.ValidateStruct(c)
	if err != nil {
		errs = append(errs, err)
	}

	return
}
开发者ID:Rompei,项目名称:vuls,代码行数:32,代码来源:config.go


示例7: EndCreateHandler

// POST /events/end HTTP Handler
func EndCreateHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	rbody := &endCreateReqBody{}

	// Decode JSON
	err := decoder.Decode(&rbody)
	if err != nil {
		log.Debug(err)
		http.Error(w, http.StatusText(400), 400)
		return
	}

	// Validate
	res, err := v.ValidateStruct(rbody)
	if err != nil {
		log.Debug(res)
		http.Error(w, http.StatusText(422), 422)
		return
	}

	// Publish event
	if err := events.PublishEndEvent(
		c.Env["REDIS"].(*redis.Client),
		rbody.Track,
		rbody.User); err != nil {

		log.Error(err)
		http.Error(w, http.StatusText(500), 500)
		return
	}

	// We got to the end - everything went fine!
	w.WriteHeader(201)
}
开发者ID:thisissoon,项目名称:FM-Perceptor,代码行数:35,代码来源:end.go


示例8: VolumeUpdateHandler

// PUT /volume HTTP Handler
func VolumeUpdateHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	rbody := &volumeUpdateReqBody{}

	// Decode JSON
	err := decoder.Decode(&rbody)
	if err != nil {
		log.Debug(err)
		http.Error(w, http.StatusText(400), 400)
		return
	}

	// Validate
	res, err := v.ValidateStruct(rbody)
	if err != nil {
		log.Debug(res)
		http.Error(w, http.StatusText(422), 422)
		return
	}

	// Set the vol redis keys
	if err := events.PublishVolumeEvent(c.Env["REDIS"].(*redis.Client), rbody.Level); err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(500), 500)
		return
	}

	// We got here! It's alllll good.
	w.WriteHeader(200)
}
开发者ID:thisissoon,项目名称:FM-Perceptor,代码行数:31,代码来源:volume.go


示例9: serviceCreate

func (as ApiService) serviceCreate(c *gin.Context) {
	var newService types.Service
	if err := c.BindJSON(&newService); err != nil {
		c.Error(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	//Guarantees that no one tries to create a destination together with a service
	newService.Destinations = []types.Destination{}

	if _, errs := govalidator.ValidateStruct(newService); errs != nil {
		c.Error(errs)
		c.JSON(http.StatusBadRequest, gin.H{"errors": govalidator.ErrorsByField(errs)})
		return
	}

	// If everthing is ok send it to Raft
	err := as.balancer.AddService(&newService)
	if err != nil {
		c.Error(err)
		if err == types.ErrServiceAlreadyExists {
			c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("UpsertService() failed: %v", err)})
		}
		return
	}

	c.Header("Location", fmt.Sprintf("/services/%s", newService.Name))
	c.JSON(http.StatusCreated, newService)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:31,代码来源:handlers.go


示例10: Create

func (h *Handler) Create(ctx context.Context, rw http.ResponseWriter, req *http.Request) {
	subject, ok := mux.Vars(req)["subject"]
	if !ok {
		http.Error(rw, "No subject given.", http.StatusBadRequest)
		return
	}

	var conn DefaultConnection
	decoder := json.NewDecoder(req.Body)
	if err := decoder.Decode(&conn); err != nil {
		http.Error(rw, "Could not decode request: "+err.Error(), http.StatusBadRequest)
		return
	}

	if v, err := govalidator.ValidateStruct(conn); !v {
		if err != nil {
			http.Error(rw, err.Error(), http.StatusBadRequest)
			return
		}
		http.Error(rw, "Payload did not validate.", http.StatusBadRequest)
		return
	}

	conn.ID = uuid.New()
	conn.LocalSubject = subject
	if err := h.s.Create(&conn); err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	WriteJSON(rw, &conn)
}
开发者ID:thanzen,项目名称:hydra,代码行数:32,代码来源:handler.go


示例11: Create

func (h *Handler) Create(ctx context.Context, rw http.ResponseWriter, req *http.Request) {
	type Payload struct {
		Email    string `valid:"email,required" json:"email" `
		Password string `valid:"length(6|254),required" json:"password"`
		Data     string `valid:"optional,json", json:"data"`
	}

	var p Payload
	decoder := json.NewDecoder(req.Body)
	if err := decoder.Decode(&p); err != nil {
		http.Error(rw, err.Error(), http.StatusBadRequest)
		return
	}

	if v, err := govalidator.ValidateStruct(p); !v {
		if err != nil {
			http.Error(rw, err.Error(), http.StatusBadRequest)
			return
		}
		http.Error(rw, "Payload did not validate.", http.StatusBadRequest)
		return
	}

	if p.Data == "" {
		p.Data = "{}"
	}

	user, err := h.s.Create(uuid.New(), p.Email, p.Password, p.Data)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	WriteJSON(rw, user)
}
开发者ID:thanzen,项目名称:hydra,代码行数:35,代码来源:handler.go


示例12: ServeHTTP

func (withUser WithUser) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	defer r.Body.Close()

	var body struct {
		FirstName string `json:"firstName" valid:"required"`
		LastName  string `json:"lastName" valid:"required"`
		Password  string `json:"password" valid:"required"`
		Email     string `json:"email" valid:"required,email"`
	}

	if err := decoder.Decode(&body); err != nil {
		respond.With(w, r, http.StatusBadRequest, err)
		return
	}

	if ok, err := govalidator.ValidateStruct(body); ok == false || err != nil {
		errs := govalidator.ErrorsByField(err)
		respond.With(w, r, http.StatusBadRequest, errs)
		return
	}

	user := &User{
		FirstName: body.FirstName,
		LastName:  body.LastName,
		Password:  body.Password,
		Email:     body.Email,
	}

	withUser.next(user).ServeHTTP(w, r)
}
开发者ID:fairlance,项目名称:backend,代码行数:31,代码来源:user.go


示例13: loginHandleFunc

// loginHandleFunc - render template for login page
func loginHandleFunc(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		login := template.Must(getTemlates("login"))
		login.Execute(w, nil)
	} else {
		r.ParseForm()
		// logic part of log in
		user := &m.User{
			Login:    r.FormValue("login"),
			Password: r.FormValue("password"),
		}
		result, err := valid.ValidateStruct(user)
		if err == nil || !result {
			err := user.GetUserByLoginPass(user.Login, user.Password)
			if !err {
				sess := s.Instance(r)
				s.Clear(sess)
				sess.Values["id"] = user.ID
				err := sess.Save(r, w)
				if err != nil {
					log.Println(err)
					return
				}
				url, err := RedirectFunc("home")
				if err != nil {
					http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
					return
				}
				http.Redirect(w, r, url, http.StatusMovedPermanently)
			} else {
				http.Error(w, fmt.Sprintf("User %s not found", user.Login), http.StatusNotFound)
			}
		}
	}
}
开发者ID:Crandel,项目名称:golang_websocket_chat_demo,代码行数:36,代码来源:handlers.go


示例14: RegisterController

// RegisterController handles account creation
func RegisterController(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	var s Register
	var sr = RegisterSuccess{false, ""}

	json.NewDecoder(r.Body).Decode(&s)
	r.Body.Close()
	// Result ignored since a nil err value tells us
	// the same thing that a result of true does.
	if _, err := govalidator.ValidateStruct(s); err != nil {
		sr.Message = err.Error()
		w.WriteHeader(400)
		w.Write(Marshal(sr))
		return
	}

	if err := (User{
		Username: s.Name,
		Password: s.Password,
	}.Create()); err != nil {
		sr.Message = err.Error()
		w.WriteHeader(400)
		w.Write(Marshal(sr))
		return
	}

	sr.Message = "Users has been created"
	sr.Success = true
	w.Write(Marshal(sr))
	return
}
开发者ID:michaeljs1990,项目名称:resalloc,代码行数:31,代码来源:controllers.go


示例15: Validate

func (r *Report) Validate(col *bongo.Collection) []error {
	_, err := valid.ValidateStruct(r)
	errs := util.ConvertGovalidatorErrors(err)
	if r.Type != REQUEST && r.Type != COMPLAIN {
		errs = append(errs, errors.New("Type: invalid type of report"))
	}
	return errs
}
开发者ID:quid-city,项目名称:api,代码行数:8,代码来源:report.go


示例16: validate

func validate(r interface{}) error {
	if v, err := govalidator.ValidateStruct(r); !v {
		return pkg.ErrInvalidPayload
	} else if err != nil {
		return pkg.ErrInvalidPayload
	}
	return nil
}
开发者ID:lmineiro,项目名称:hydra,代码行数:8,代码来源:store.go


示例17: Validate

func (v *Validator) Validate(req interface{}) {
	_, err := validator.ValidateStruct(req)
	if err == nil {
		v.IsValid = true
		v.Errors = make(map[string]string)
	} else {
		v.Errors = validator.ErrorsByField(err)
	}
}
开发者ID:nirandas,项目名称:ice,代码行数:9,代码来源:validator.go


示例18: validateContactForm

// validateUserForm checks the inputs for errors
func validateContactForm(contact *viewmodels.ContactsEditViewModel) (valErrors map[string]string) {
	valErrors = make(map[string]string)

	_, err := govalidator.ValidateStruct(contact)
	valErrors = govalidator.ErrorsByField(err)

	validateContact(contact, valErrors)

	return valErrors
}
开发者ID:turnkey-commerce,项目名称:go-ping-sites,代码行数:11,代码来源:contacts.go


示例19: validateUserForm

// validateUserForm checks the inputs for errors
func validateUserForm(user *viewmodels.UsersEditViewModel, allowMissingPassword bool) (valErrors map[string]string) {
	valErrors = make(map[string]string)

	_, err := govalidator.ValidateStruct(user)
	valErrors = govalidator.ErrorsByField(err)

	validatePassword(allowMissingPassword, user.Password, user.Password2, valErrors)

	return valErrors
}
开发者ID:turnkey-commerce,项目名称:go-ping-sites,代码行数:11,代码来源:users.go


示例20: validateDeleteUserForm

// validateUserForm checks the inputs for errors
func validateDeleteUserForm(user *viewmodels.UsersEditViewModel, currentUser string) (valErrors map[string]string) {
	valErrors = make(map[string]string)

	_, err := govalidator.ValidateStruct(user)
	valErrors = govalidator.ErrorsByField(err)

	if currentUser == user.Username {
		valErrors["Username"] = "Can't delete currently logged-in user."
	}

	return valErrors
}
开发者ID:turnkey-commerce,项目名称:go-ping-sites,代码行数:13,代码来源:users.go



注:本文中的github.com/asaskevich/govalidator.ValidateStruct函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang util.Config类代码示例发布时间:2022-05-24
下一篇:
Golang govalidator.IsURL函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap