func TestValidateInt(t *testing.T) { testVal, err := util.ValidateInt("15", 10) if err != nil { t.Error("'15' should pass validation") } if 15 != testVal { t.Error("validation should return 15") } testVal, err = util.ValidateInt("1a5", 10) if err == nil { t.Error("'1a5' should fail validation") } if 10 != testVal { t.Error("validation should return 10 (default value)") } testVal, err = util.ValidateInt("", 10) if err != nil { t.Error("'' should pass validation (empty string)") } if 10 != testVal { t.Error("validation should return 10 (default value)") } }
func ExampleValidateInt() { value, err := util.ValidateInt("1a5", 10) // fails to validate, returns default if err != nil { // if you care that validation failed, otherwise value == default (10) } value, err = util.ValidateInt("15", 10) // validates, returns parsed val fmt.Printf("%v | %v", value, err) // Output: 15 | <nil> }
func (c *streamController) coalesceStreams(w http.ResponseWriter, r *http.Request, ps httprouter.Params) error { body, err := ioutil.ReadAll(r.Body) log.WithFields(fieldsFor(r, body, err)).Debug("/coalesce") queryParams := r.URL.Query() limit, err := util.ValidateInt(queryParams.Get("limit"), 10) if err != nil { return StatusError{Code: 422, Err: errors.New("Limit should be a number")} } fromSlug := queryParams.Get("from") var query model.StreamQuery err = json.Unmarshal(body, &query) if err != nil { return StatusError{Code: 422, Err: err} } response, err := c.streamService.Load(query, limit, fromSlug) if err != nil { return StatusError{Code: 400, Err: errors.New("An error occurred loading streams")} } addLink(w, nextPage(r, response, limit)) c.JSON(w, http.StatusOK, response.Items) return nil }
func (c *streamController) getStream(w http.ResponseWriter, r *http.Request, ps httprouter.Params) error { startTime := time.Now() log.WithFields(fieldsFor(r, nil, nil)).Debug("/getStream") //get ID and validate that it is a uuid. streamID := ps.ByName("id") queryParams := r.URL.Query() limit, err := util.ValidateInt(queryParams.Get("limit"), 10) if err != nil { return StatusError{Code: 422, Err: errors.New("Limit should be a number")} } fromSlug := queryParams.Get("from") response, err := c.streamService.Load(model.StreamQuery{Streams: []string{streamID}}, limit, fromSlug) if err != nil { return StatusError{Code: 400, Err: errors.New("An error occurred loading streams")} } addLink(w, nextPage(r, response, limit)) c.JSON(w, http.StatusOK, response.Items) getStreamTimer.UpdateSince(startTime) return nil }