1
0
mirror of https://github.com/alice-lg/alice-lg.git synced 2024-05-11 05:55:03 +00:00
alice-lg-alice-lg/backend/api_validators.go
2017-06-28 12:42:28 +02:00

72 lines
1.5 KiB
Go

package main
import (
"fmt"
"strconv"
"net/http"
)
// Helper: Validate source Id
func validateSourceId(id string) (int, error) {
rsId, err := strconv.Atoi(id)
if err != nil {
return 0, err
}
if rsId < 0 {
return 0, fmt.Errorf("Source id may not be negative")
}
if rsId >= len(AliceConfig.Sources) {
return 0, fmt.Errorf("Source id not within [0, %d]", len(AliceConfig.Sources)-1)
}
return rsId, nil
}
// Helper: Validate query string
func validateQueryString(req *http.Request, key string) (string, error) {
query := req.URL.Query()
values, ok := query[key]
if !ok {
return "", fmt.Errorf("Query param %s is missing.", key)
}
if len(values) != 1 {
return "", fmt.Errorf("Query param %s is ambigous.", key)
}
value := values[0]
if value == "" {
return "", fmt.Errorf("Query param %s may not be empty.", key)
}
return value, nil
}
// Helper: Validate prefix query
func validatePrefixQuery(value string) (string, error) {
// We should at least provide 2 chars
if len(value) < 2 {
return "", fmt.Errorf("Query too short")
}
// Query constraints: Should at least include a dot or colon
/* let's try without this :)
if strings.Index(value, ".") == -1 &&
strings.Index(value, ":") == -1 {
return "", fmt.Errorf("Query needs at least a ':' or '.'")
}
*/
return value, nil
}
// Get pagination parameters: limit and offset
// Refer to defaults if none are given.
func validatePaginationParams(req *http.Request, limit, offset int) (int, int, error) {
return limit, offset, nil
}