Golang github.com-asaskevich-govalidator.ValidateStruct类(方法)实例源码

下面列出了Golang github.com-asaskevich-govalidator.ValidateStruct 类(方法)源码代码实例,从而了解它的用法。

作者:GoTool    项目:Validato   
func Validate(v interface{}) *errors.Errors {
	if ok, err := govalidator.ValidateStruct(v); !ok {
		m := FormatErrors(err)
		return m
	}
	return nil
}

作者:Acidburn0zz    项目:we   
// 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
}

作者:latam-airline    项目:cran   
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
}

作者:lmineir    项目:hydr   
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)
}

作者:mou    项目:onlinene   
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)
}

作者:Rompe    项目:vul   
// 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
}

作者:thisissoo    项目:FM-Percepto   
// 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)
}

作者:thisissoo    项目:FM-Percepto   
// 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)
}

作者:tsur    项目:tsur   
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)
}

作者:thanze    项目:hydr   
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)
}

作者:thanze    项目:hydr   
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)
}

作者:fairlanc    项目:backen   
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)
}

作者:Crande    项目:golang_websocket_chat_dem   
// 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)
			}
		}
	}
}

作者:michaeljs199    项目:resallo   
// 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
}

作者:quid-cit    项目:ap   
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
}

作者:lmineir    项目:hydr   
func validate(r interface{}) error {
	if v, err := govalidator.ValidateStruct(r); !v {
		return pkg.ErrInvalidPayload
	} else if err != nil {
		return pkg.ErrInvalidPayload
	}
	return nil
}

作者:niranda    项目:ic   
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)
	}
}

作者:turnkey-commerc    项目:go-ping-site   
// 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
}

作者:turnkey-commerc    项目:go-ping-site   
// 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
}

作者:turnkey-commerc    项目:go-ping-site   
// 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
}


问题


面经


文章

微信
公众号

扫码关注公众号