コード例 #1
0
ファイル: user.go プロジェクト: fairlance/backend
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)
}
コード例 #2
0
ファイル: handlers.go プロジェクト: tsuru/tsuru
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)
}
コード例 #3
0
ファイル: validator.go プロジェクト: nirandas/ice
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)
	}
}
コード例 #4
0
// 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
}
コード例 #5
0
// 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
}
コード例 #6
0
// 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
}
コード例 #7
0
ファイル: validator.go プロジェクト: GoToolz/Validator
func FormatErrors(errs error) *errors.Errors {

	e := errors.New()

	m := govalidator.ErrorsByField(errs)
	for key, value := range m {

		key = govalidator.CamelCaseToUnderscore(key)
		e.Add(errors.Error{
			Label: fmt.Sprintf("invalid_%s", key),
			Field: key,
			Text:  value,
		})
	}

	return e
}
コード例 #8
0
ファイル: main.go プロジェクト: stellar/bridge-server
// 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,
	}
}
コード例 #9
0
ファイル: freelancer.go プロジェクト: fairlance/backend
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)
}
コード例 #10
0
ファイル: job.go プロジェクト: fairlance/backend
func (withJob WithJob) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	defer r.Body.Close()

	var body struct {
		Name     string     `json:"name" valid:"required"`
		Summary  string     `json:"summary" valid:"required"`
		Details  string     `json:"details" valid:"required"`
		ClientID uint       `json:"clientId" valid:"required"`
		IsActive bool       `json:"isActive"`
		Tags     stringList `json:"tags"`
		Links    stringList `json:"links"`
	}

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

	// https://github.com/asaskevich/govalidator/issues/133
	// https://github.com/asaskevich/govalidator/issues/112
	if len(body.Tags) > 10 {
		respond.With(w, r, http.StatusBadRequest, errors.New("Max of 10 tags are allowed."))
		return
	}

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

	job := &Job{
		Name:     body.Name,
		Summary:  body.Summary,
		Details:  body.Details,
		ClientID: body.ClientID,
		IsActive: body.IsActive,
		Tags:     body.Tags,
		Links:    body.Links,
	}

	withJob.next(job).ServeHTTP(w, r)
}
コード例 #11
0
ファイル: handlers.go プロジェクト: tsuru/tsuru
func (as ApiService) destinationCreate(c *gin.Context) {
	serviceName := c.Param("service_name")
	service, err := as.balancer.GetService(serviceName)
	if err != nil {
		c.Error(err)
		if err == types.ErrServiceNotFound {
			c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("GetService() failed: %v", err)})
		}
		return
	}

	destination := &types.Destination{Weight: 1, Mode: "route", ServiceId: serviceName}
	if err := c.BindJSON(destination); err != nil {
		c.Error(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

	err = as.balancer.AddDestination(service, destination)
	if err != nil {
		c.Error(err)
		if err == types.ErrDestinationAlreadyExists {
			c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("UpsertDestination() failed: %v\n", err)})
		}
		return
	}

	c.Header("Location", fmt.Sprintf("/services/%s/destinations/%s", serviceName, destination.Name))
	c.JSON(http.StatusCreated, destination)
}
コード例 #12
0
ファイル: job.go プロジェクト: fairlance/backend
func (withJobApplication WithJobApplication) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var jobApplication JobApplication
	decoder := json.NewDecoder(r.Body)
	defer r.Body.Close()

	var body struct {
		Message          string     `json:"message" valid:"required"`
		Samples          uintList   `json:"samples" valid:"required"`
		DeliveryEstimate int        `json:"deliveryEstimate" valid:"required"`
		Milestones       stringList `json:"milestones" valid:"required"`
		HourPrice        float64    `json:"hourPrice" valid:"required"`
		Hours            int        `json:"hours" valid:"required"`
		FreelancerID     uint       `json:"freelancerId" valid:"required"`
	}

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

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

	jobApplication = JobApplication{
		Message:          body.Message,
		Milestones:       body.Milestones,
		Samples:          body.Samples,
		DeliveryEstimate: body.DeliveryEstimate,
		Hours:            body.Hours,
		HourPrice:        body.HourPrice,
		FreelancerID:     body.FreelancerID,
	}

	withJobApplication.next(&jobApplication).ServeHTTP(w, r)
}
コード例 #13
0
ファイル: main_test.go プロジェクト: stellar/bridge-server
func TestSeedValidator(t *testing.T) {
	var val struct {
		Empty     string `valid:"stellar_seed"`
		NotSTRKey string `valid:"stellar_seed"`
		NotSeed   string `valid:"stellar_seed"`
		Valid     string `valid:"stellar_seed"`
		WrongType int    `valid:"stellar_seed"`
	}

	val.NotSTRKey = "hello"
	val.NotSeed = "GBXS6WTZNRS7LOGHM3SCMAJD6M6JCXB3GATXECCZ3C5NJ3PVSZ23PEWX"
	val.Valid = "SA5MATAU4RNJDKCTIC6VVSYSGB7MFFBVU3OKWOA5K67S62EYB5ESKLTV"
	val.WrongType = 100

	// run the validation
	ok, err := govalidator.ValidateStruct(val)
	require.False(t, ok)
	require.Error(t, err)

	fields := govalidator.ErrorsByField(err)

	// ensure valid is not in the invalid map
	_, ok = fields["Valid"]
	assert.False(t, ok)

	_, ok = fields["Empty"]
	assert.True(t, ok, "Empty is not an invalid field")

	_, ok = fields["NotSTRKey"]
	assert.True(t, ok, "NotSTRKey is not an invalid field")

	_, ok = fields["NotSeed"]
	assert.True(t, ok, "NotSeed is not an invalid field")

	_, ok = fields["WrongType"]
	assert.True(t, ok, "WrongType is not an invalid field")
}
コード例 #14
0
//validateSiteForm checks the inputs for errors
func validateSiteForm(site *viewmodels.SitesEditViewModel) (valErrors map[string]string) {
	valErrors = make(map[string]string)
	_, err := govalidator.ValidateStruct(site)
	valErrors = govalidator.ErrorsByField(err)
	return valErrors
}