Example #1
0
func (r *Request) setParamValue(args *setParamValueArgs) error {
	// We parse the tag to get the options
	opts := NewParamOptions(args.tags)
	defaultValue := args.tags.Get("default")

	// The tag needs to be ignored
	if opts.Ignore {
		return nil
	}

	if opts.Name == "" {
		opts.Name = args.paramInfo.Name
	}

	// We get the value and apply the transformations
	value := args.source.Get(opts.Name)
	if opts.Trim {
		value = strings.TrimSpace(value)
	}

	if value == "" {
		value = defaultValue
		if opts.Required {
			return apierror.NewBadRequest("parameter [%s] missing", opts.Name)
		}
	}

	// We now set the value in the struct
	if value != "" {
		var errorMsg = fmt.Sprintf("value [%s] for parameter [%s] is invalid", value, opts.Name)

		switch args.param.Kind() {
		case reflect.Bool:
			v, err := strconv.ParseBool(value)
			if err != nil {
				return apierror.NewBadRequest(errorMsg)
			}
			args.param.SetBool(v)
		case reflect.String:
			args.param.SetString(value)
		case reflect.Int:
			v, err := strconv.ParseInt(value, 10, 64)
			if err != nil {
				return apierror.NewBadRequest(errorMsg)
			}
			args.param.SetInt(v)
		}
	}
	return nil
}
Example #2
0
func (a *Article) Create() error {
	if a == nil {
		return apierror.NewServerError("article not instanced")
	}

	if a.Slug == "" {
		a.Slug = slug.Make(a.Title)
	}

	if bson.IsObjectIdHex(a.Slug) {
		return apierror.NewBadRequest("slug cannot be a ObjectId")
	}

	a.CreatedAt = time.Now()

	// To prevent duplicates on the slug, we'll retry the insert() up to 10 times
	originalSlug := a.Slug
	var err error
	for i := 0; i < 10; i++ {
		a.ID = bson.NewObjectId()
		err = Query().Insert(a)

		if err != nil {
			// In case of duplicate we'll add "-X" at the end of the slug, where X is
			// a number
			a.Slug = fmt.Sprintf("%s-%d", originalSlug, i)

			if mgo.IsDup(err) == false {
				return apierror.NewServerError(err.Error())
			}
		} else {
			// everything went well
			return nil
		}
	}

	// after 10 try we just return an error
	return apierror.NewConflict(err.Error())
}