HTTP Methods
In this chapter, you'll learn about how to add new API routes for each HTTP method.
HTTP Method Handler#
An API route is created for every HTTP method you set a handler function for in the Route of a RouteFile.
The Route struct has a field for each allowed HTTP method: GET, POST, PUT, PATCH, DELETE, OPTIONS, and HEAD. Every field has the type RouteHandler, which is a function that receives a *MedusaRequest and a *MedusaResponse and returns an error: func(req *medusahttp.MedusaRequest, res *medusahttp.MedusaResponse) error.
A method whose field isn't set isn't handled by the route, so requests with that method receive a 404 response.
For example, the following file defines two handlers and a route file that uses both:
package api
import (
medusahttp "github.com/hitkey-io/medusago/packages/core/framework/src/http"
)
// helloGET handles GET /hello-world.
func helloGET(req *medusahttp.MedusaRequest, res *medusahttp.MedusaResponse) error {
return res.JSON(map[string]any{
"message": "[GET] Hello world!",
})
}
// helloPOST handles POST /hello-world.
func helloPOST(req *medusahttp.MedusaRequest, res *medusahttp.MedusaResponse) error {
return res.JSON(map[string]any{
"message": "[POST] Hello world!",
})
}
// HelloWorldRoute adds two API routes: GET /hello-world and POST /hello-world.
var HelloWorldRoute = medusahttp.RouteFile{
Path: "/hello-world",
Route: medusahttp.Route{
GET: helloGET,
POST: helloPOST,
},
}
This file adds two API routes:
- A
GETAPI route athttp://localhost:9000/hello-world. - A
POSTAPI route athttp://localhost:9000/hello-world.
Don't forget to register the route file in the Routes option of the CLI.
GET handler but no HEAD handler, HEAD requests are answered by the GET handler. If it has no OPTIONS handler, an OPTIONS request receives an Allow header with the methods the route supports, unless the CORS middleware answers the preflight request.Handle Errors#
A handler returns an error to report that something went wrong. Return nil after you send the response. Learn more in the Errors chapter.