0

I am building a Go DELETE REST endpoint. This request requires a set of query parameters which filters what objects to delete.

for eg.

https://endpoint.blah.com/users?userId=7&age=24

As of now, if somebody sends a request like

https://endpoint.blah.com/users?userId123=7&age=24

my implementation deletes all users with age=24 and ignores the invalid userId123.

I want to implement a way to check if the query parameter in the request is invalid. Having userId123 in the request in this case should return Bad Request.

The only way that I can think of is, doing a string match for each parameter against the User struct fields. I would like to know of a better way to do this.

All help appreciated. Using go version go version go1.13.4 darwin/amd64 and net/http for http framework.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
jazz
  • 27
  • 1
  • 10

2 Answers2

1

Record valid parameters in a map:

var allowedDeleteParams = map[string]bool{"userid": true, "age": true}

Write a function to validate parameters with that map:

func checkParams(w http.ResponseWriter, r *http.Request, allowedParams map[string]bool) bool {
    r.ParseForm()
    for k := range r.Form {
        if _, ok := allowedParams[k]; !ok {
            http.Error(w, "Bad request", http.StatusBadRequest)
            return false
        }
    }
    return true
}

Use it in a handler like this:

func handleDelete(w http.ResponseWriter, r *http.Request) {
  if !checkParams(w, r, allowedDeleteParams) {
     return
  }
  ...
0

+1 to @iLoveReflection.

Additionally, what you really need might not be "checking userId123 is invalid". Rather, you might want to make sure userId != "" at the beginning of the function. So sth like this:

func YourAPI(...) error {
    // 1. Parsing inputs to variables, usually into a struct
    // 2. Validate all required inputs are not nil, or invalid (eg. should not exceed maximum value or sth like that), for example:
    if p.UserID == "" {
        return error.New("Missing userId")
    }
    // 3. Start doing other works
}
idk
  • 53
  • 7