Understanding Method Not Allowed
When we use ServerMux, we cannot determine what HTTP Method we will use in the Handler. However, on the router that we are using, we can determine what HTTP method we want to use so that the client will send the appropriate method to the router that we have specified. If it does not comply with the provisions on the Router, a Method Not Allowed error will occur.
By default, if an error like this occurs, the Router will call the http.Error
function and now we will try to change it to our liking by changing
router.MethodNotAllowed = http.Handler
How to Implement
When we set MethodNotAllowed
this is the same as the previous post, namely the NotFound
router. Namely, we need to create a handler function first like this in the handler.go
file.
func MethodNotAllowedHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "method tidak didukung")
}
After that, we call the MethodNotAllowedHandler
function in the main function in the main.go
file.
router.MethodNotAllowed = http.HandlerFunc(MethodNotAllowedHandler)
So, we have implemented the method not allowed page on our router service. Next we will try to test it, so first we rerun our program or service with this command.
go build && ./learn-golang-httprouter
If we compare it with before using the modified not allowed router method, previously a page like this would appear.
➜ santekno-hugo git:(main) ✗ curl --location --request POST 'http://localhost:8080/panic'
Method Not Allowed
then after we use the custom handler not found then we try to access any page using the cURL command below and it will display the page according to what we have created on the router above.
➜ santekno-hugo git:(main) ✗ curl --location --request POST 'http://localhost:8080/panic'
method tidak didukung%
Then we can change whatever we want if the method does not match what we have set on the Router with information that is more relevant and can be read by the user.