func Validate(v interface{}) *errors.Errors { if ok, err := govalidator.ValidateStruct(v); !ok { m := FormatErrors(err) return m } return nil }
// 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 }
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 }
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) }
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) }
// 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 }
// 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) }
// 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) }
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) }
// Validate SMTP configuration func (c *smtpConf) Validate() (errs []error) { if !c.UseThisTime { return } // Check Emails fromat emails := []string{} emails = append(emails, c.From) emails = append(emails, c.To...) emails = append(emails, c.Cc...) if emailErrs := checkEmails(emails); 0 < len(emailErrs) { errs = append(errs, emailErrs...) } if len(c.SMTPAddr) == 0 { errs = append(errs, fmt.Errorf("smtpAddr must not be empty")) } if len(c.SMTPPort) == 0 { errs = append(errs, fmt.Errorf("smtpPort must not be empty")) } if len(c.To) == 0 { errs = append(errs, fmt.Errorf("To required at least one address")) } if len(c.From) == 0 { errs = append(errs, fmt.Errorf("From required at least one address")) } _, err := valid.ValidateStruct(c) if err != nil { errs = append(errs, err) } return }
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) }
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) }
func (h *Handler) Create(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { var conn Connection var ctx = context.Background() if _, err := h.W.HTTPActionAllowed(ctx, r, &ladon.Request{ Resource: connectionsResource, Action: "create", }, scope); err != nil { h.H.WriteError(ctx, w, r, err) return } if err := json.NewDecoder(r.Body).Decode(&conn); err != nil { h.H.WriteErrorCode(ctx, w, r, http.StatusBadRequest, err) return } if v, err := govalidator.ValidateStruct(conn); err != nil { h.H.WriteErrorCode(ctx, w, r, http.StatusBadRequest, err) return } else if !v { h.H.WriteErrorCode(ctx, w, r, http.StatusBadRequest, errors.New("Payload did not validate.")) return } conn.ID = uuid.New() if err := h.Manager.Create(&conn); err != nil { h.H.WriteError(ctx, w, r, err) return } h.H.WriteCreated(ctx, w, r, "/oauth2/connections/"+conn.ID, &conn) }
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) }
// 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) } } } }
// 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 }
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 }
func validate(r interface{}) error { if v, err := govalidator.ValidateStruct(r); !v { return pkg.ErrInvalidPayload } else if err != nil { return pkg.ErrInvalidPayload } return nil }
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) } }
// 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 }
// 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 }
// 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"] = "******" } return valErrors }
func (h *DBHandler) cardCreateHandler(rw http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) createCard := CreateCardRequest{} err := decoder.Decode(&createCard) if err != nil { h.r.JSON(rw, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } var cardCount int h.db.Model(Card{}).Where("code = ? AND is_active = ?", createCard.Code, true).Count(&cardCount) if cardCount > 0 { h.r.JSON(rw, http.StatusConflict, map[string]string{"error": "More than one active card with that code"}) return } card := Card{} card.Name = createCard.Name card.Code = createCard.Code card.Pin = createCard.Pin card.IsActive = createCard.IsActive _, err = govalidator.ValidateStruct(&card) if err != nil { h.r.JSON(rw, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } scheduleIds := []int64{} for _, val := range createCard.Schedules { scheduleIds = append(scheduleIds, val.ID) } schedules := []Schedule{} h.db.Where("id in (?)", scheduleIds).Find(&schedules) card.Schedules = schedules h.db.Save(&card) h.r.JSON(rw, http.StatusOK, &card) }
// DeleteLeaseController removes a lease from the remote machine func DeleteLeaseController(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { var s DeleteLease sr := DeleteLeaseSuccess{} if err := VerifyToken(r.Header.Get("token")); err != nil { sr.Message = err.Error() w.WriteHeader(401) w.Write(Marshal(sr)) return } json.NewDecoder(r.Body).Decode(&s) r.Body.Close() _, err := govalidator.ValidateStruct(s) if err != nil { sr.Message = err.Error() w.WriteHeader(400) w.Write(Marshal(sr)) return } // Get information about lease so we know what machine it is located on l := Lease{} if err := l.Fetch(s.Name); err != nil { sr.Message = err.Error() w.WriteHeader(400) w.Write(Marshal(sr)) return } // Connect to machine that the lease is on docker, err := dockerclient.NewDockerClient("http://"+l.MachineName+":5555", nil) if err != nil { sr.Message = err.Error() w.WriteHeader(400) w.Write(Marshal(sr)) return } // Remove the container if err := docker.RemoveContainer(s.Name, true, true); err != nil { sr.Message = err.Error() w.WriteHeader(400) w.Write(Marshal(sr)) return } // Remove container from the database l.Delete() sr.Success = true sr.Message = "Your lease has been removed" w.Write(Marshal(sr)) return }
func ExampleParseOptions() { ////////////////////////////////////////////////////////////////////////////// // Add the custom command to run the sync loop syncCommand := &cobra.Command{ Use: "sync", Short: "Periodically perform a task", RunE: func(cmd *cobra.Command, args []string) error { fmt.Printf("Sync command!\n") return nil }, } // Include the basic auth flags for the sync command registerSpartaCommandLineFlags(syncCommand) CommandLineOptions.Root.AddCommand(syncCommand) ////////////////////////////////////////////////////////////////////////////// // Register custom flags for pre-existing Sparta commands registerSpartaCommandLineFlags(CommandLineOptions.Provision) CommandLineOptions.Provision.Flags().StringVarP(&options.SSHKeyName, "key", "k", "", "SSH Key Name to use for EC2 instances") ////////////////////////////////////////////////////////////////////////////// // Define a validation hook s.t. we can validate the CLI user input validationHook := func(command *cobra.Command) error { if command.Name() == "provision" && len(options.SSHKeyName) <= 0 { return fmt.Errorf("SSHKeyName option is required") } fmt.Printf("Command: %s\n", command.Name()) switch command.Name() { case "provision", "sync": _, validationErr := govalidator.ValidateStruct(options) return validationErr default: return nil } } // If the validation hooks failed, exit the application parseErr := ParseOptions(validationHook) if nil != parseErr { os.Exit(3) } ////////////////////////////////////////////////////////////////////////////// // // Standard Sparta application // ... }
func (h *DBHandler) cardUpdateHandler(rw http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) updateCard := UpdateCardRequest{} err := decoder.Decode(&updateCard) if err != nil { h.r.JSON(rw, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } id := getId(req) card := Card{} h.db.First(&card, id) card.Name = updateCard.Name card.IsActive = updateCard.IsActive if len(updateCard.Pin) > 0 { card.Pin = updateCard.Pin } _, err = govalidator.ValidateStruct(&card) if err != nil { h.r.JSON(rw, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } h.db.Save(&card) scheduleIds := []int64{} for _, val := range updateCard.Schedules { scheduleIds = append(scheduleIds, val.ID) } schedules := []Schedule{} h.db.Where("id in (?)", scheduleIds).Find(&schedules) h.db.Model(&card).Association("Schedules").Replace(schedules) h.r.JSON(rw, http.StatusOK, &card) }
func (e ApiEnv) createPost(request *restful.Request, response *restful.Response) { post := model.Post{} err := request.ReadEntity(&post) if err != nil { response.WriteErrorString(400, err.Error()) return } if post.Url == "" && post.Body == "" { response.WriteErrorString(400, "Neither url or body specified") return } result, err := valid.ValidateStruct(post) e.Log.Debug(result) if err != nil { switch err := err.(type) { case valid.Errors: for _, err := range err { switch err := err.(type) { case valid.Error: if err.Name == "Url" { e.WriteErrorJsonString(response, 400, "The url specified is invalid") } } } } return } tok := request.HeaderParameter(e.AuthHeader) if tok == "" { response.WriteErrorString(400, "No valid user session") return } post.UserHandle, err = e.Model().GetActiveUser(tok) if err != nil { response.WriteErrorString(400, "No valid user session") return } err = e.Model().CreatePost(&post) if err != nil { response.WriteErrorString(500, err.Error()) return } response.WriteEntity(post) }
// Validate the struct fields. func (u *User) Validate() error { // Validate the struct result, err := govalidator.ValidateStruct(u) if err != nil { return fmt.Errorf("invalid required user fields: %v", err) } else if !result { return fmt.Errorf("invalid required user fields") } // Check if the user groups are valid. valid := validGroups(u.Groups...) if !valid { return fmt.Errorf("invalid user group(s): %v", u.Groups) } return nil }
// Read takes the TOML configuration file at `path`, parses it into `dest` and // then uses github.com/asaskevich/govalidator to validate the struct. func Read(path string, dest interface{}) error { _, err := toml.DecodeFile(path, dest) if err != nil { return errors.Wrap(err, "decode-file failed") } valid, err := govalidator.ValidateStruct(dest) if valid { return nil } fields := govalidator.ErrorsByField(err) return &InvalidConfigError{ InvalidFields: fields, } }
func (wr withReference) ServeHTTP(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) defer r.Body.Close() var reference Reference if err := decoder.Decode(&reference); err != nil { respond.With(w, r, http.StatusBadRequest, err) return } if ok, err := govalidator.ValidateStruct(reference); ok == false || err != nil { errs := govalidator.ErrorsByField(err) respond.With(w, r, http.StatusBadRequest, errs) return } wr.next(&reference).ServeHTTP(w, r) }