Skip to content

HTTP Controller

EinarCLI allows you to generate custom controllers with the necessary files and imports to handle your http requests.

πŸ‘¨β€πŸ’» Generate a New Controller

Inside your project directory, run the following command to create a new controller:

Terminal window
einar generate post-controller post-customer

Here’s an example of how the generated code will look:

Terminal window
func init() {
ioc.Registry(postCustomer, httpserver.New)
}
func postCustomer(s httpserver.Server) {
fuego.Post(s.Manager, "/insert-your-custom-pattern-here",
func(c *fuego.ContextNoBody) (any, error) {
return "unimplemented", nil
}, option.Summary("postCustomer"))
}

s httpserver.Server is a wrapper for the official fuego package. After generating the controller, you must manually replace the placeholder /insert-your-custom-pattern-here with the actual path you intend to use in your application. The file post_customer.go will be created in the following directory structure:

/app
/adapter
/in
/api
- post_customer.go

🌐 Check The Controller Response

Execute the following request to retrieve the default response of your generated controller:

Terminal window
curl -X POST http://localhost:8080/insert-your-custom-pattern-here

ResponseBody:

Terminal window
{
"message": "Unimplemented"
}

Bind & Validate Data

By default, Fuego includes go-playground/validator framework for validation, as shown in the example below.

Terminal window
type Customer struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
}
func init() {
ioc.Registry(postCustomer, httpserver.New)
}
func postCustomer(s httpserver.Server) {
fuego.Post(s.Manager, "/api/customer",
func(c *fuego.ContextWithBody[Customer]) (any, error) {
_, err := c.Body()
if err != nil {
return nil, err
}
return "unimplemented", nil
}, option.Summary("postCustomer"))
}

CURL

Terminal window
curl --location 'http://localhost:8080/api/customer' \
--header 'Content-Type: application/json' \
--data '{
"name":"",
"email":""
}'

ResponseBody

Terminal window
{
"title": "Validation Error",
"status": 400,
"detail": "Name is required, Email is required",
"errors": [
{
"name": "Customer.Name",
"reason": "Key: 'Customer.Name' Error:Field validation for 'Name' failed on the 'required' tag",
"more": {
"field": "Name",
"nsField": "Customer.Name",
"param": "",
"tag": "required",
"value": ""
}
},
{
"name": "Customer.Email",
"reason": "Key: 'Customer.Email' Error:Field validation for 'Email' failed on the 'required' tag",
"more": {
"field": "Email",
"nsField": "Customer.Email",
"param": "",
"tag": "required",
"value": ""
}
}
]
}