Validate uuid in http url

Hello,

I’m developing a Rest API with Go and I need a way to validate that the url parameter has a uuid format.

router := httprouter.New()
router.GET("/", Index)
router.GET("/books/{uuid}", BookIndex)

For integer ID I’m using the regular expression [0-9]+ to validate it as shown below:

router.GET("/books/{uuid:[0-9]+}", BookIndex).

Unfortunately I couldn’t find a regular expression for uuid so I’m wondering if you have an idea about how to validate the uuid format in http url.

Thank you

Hello @geosoft1

Thank you for your answer.

I have already seen this thread but it’s not what I’m looking for. The server should not take the request if the url parameter does not match the UUID format. If I use the solution proposed in this thread I will have to handle the request and respond with an error status which is not the behavior I would like to implement.

Thank you again

package main

import (
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

func YourHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Gorilla!\n"))
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/{id:[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$}", YourHandler)

	log.Fatal(http.ListenAndServe(":8000", r))
}
1 Like

@luk4z7

Thank you so much. Your solution worked for me.

Well, the server always take the request even if you match the route with regexp or not but the idea in that thread is to avoid regexp in routes because is expensive. However you can check the uuid on middleware if you don’t want to do it in the handler.

Is there a specific reason for the server not to take the request? (and then validate the URI in the handler)

Because there is a confusion between some routes when the uuid is passed only as a string without validation.

@luk4z7 Hi
i have a question please. Your solution worked for but only when the uuid is in the end of the url. It does not work for the url below for example :

r.HandleFunc("/{id:[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/import}", YourHandler)

do you have an idea why or how to bypass that ?

Thank you

r.HandleFunc("/{id:[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}}/import", YourHandler)

@Younes fixed, try make a middleware, you return the same way a response with status code