github.com/System-Glitch/goyave/v2@v2.10.3-0.20200819142921-51011e75d504/docs_src/src/guide/basics/controllers.md (about) 1 --- 2 meta: 3 - name: "og:title" 4 content: "Controllers - Goyave" 5 - name: "twitter:title" 6 content: "Controllers - Goyave" 7 - name: "title" 8 content: "Controllers - Goyave" 9 --- 10 11 # Controllers 12 13 [[toc]] 14 15 ## Defining controllers 16 17 Controllers are files containing a collection of Handlers related to a specific feature. Each feature should have its own package. For example, if you have a controller handling user registration, user profiles, etc, you should create a `http/controller/user` package. Creating a package for each feature has the advantage of cleaning up route definitions a lot and helps keeping a clean structure for your project. 18 19 Let's take a very simple CRUD as an example for a controller definition: 20 **http/controllers/product/product.go**: 21 ``` go 22 func Index(response *goyave.Response, request *goyave.Request) { 23 products := []model.Product{} 24 result := database.GetConnection().Find(&products) 25 if response.HandleDatabaseError(result) { 26 response.JSON(http.StatusOK, products) 27 } 28 } 29 30 func Show(response *goyave.Response, request *goyave.Request) { 31 product := model.Product{} 32 id, _ := strconv.ParseUint(request.Params["id"], 10, 64) 33 result := database.GetConnection().First(&product, id) 34 if response.HandleDatabaseError(result) { 35 response.JSON(http.StatusOK, product) 36 } 37 } 38 39 func Store(response *goyave.Response, request *goyave.Request) { 40 product := model.Product{ 41 Name: request.String("name"), 42 Price: request.Numeric("price"), 43 } 44 if err := database.GetConnection().Create(&product).Error; err != nil { 45 response.Error(err) 46 } else { 47 response.JSON(http.StatusCreated, map[string]uint{"id": product.ID}) 48 } 49 } 50 51 func Update(response *goyave.Response, request *goyave.Request) { 52 id, _ := strconv.ParseUint(request.Params["id"], 10, 64) 53 product := model.Product{} 54 db := database.GetConnection() 55 result := db.Select("id").First(&product, id) 56 if response.HandleDatabaseError(result) { 57 if err := db.Model(&product).Update("name", request.String("name")).Error; err != nil { 58 response.Error(err) 59 } 60 } 61 } 62 63 func Destroy(response *goyave.Response, request *goyave.Request) { 64 id, _ := strconv.ParseUint(request.Params["id"], 10, 64) 65 product := model.Product{} 66 db := database.GetConnection() 67 result := db.Select("id").First(&product, id) 68 if response.HandleDatabaseError(result) { 69 if err := db.Delete(&product).Error; err != nil { 70 response.Error(err) 71 } 72 } 73 } 74 ``` 75 76 ::: tip 77 - Learn how to handle database errors [here](https://gorm.io/docs/error_handling.html). 78 - It is not necessary to add `response.Status(http.StatusNoContent)` at the end of `Update` and `Destroy` because the framework automatically sets the response status to 204 if its body is empty and no status has been set. 79 ::: 80 81 ## Handlers 82 83 A `Handler` is a `func(*goyave.Response, *goyave.Request)`. The first parameter lets you write a response, and the second contains all the information extracted from the raw incoming request. 84 85 Read about the available request information in the [Requests](./requests.html) section. 86 87 Controller handlers contain the business logic of your application. They should be concise and focused on what matters for this particular feature in your application. For example, if you develop a service manipulating images, the image processing code shouldn't be written in controller handlers. In that case, the controller handler would simply pass the correct parameters to your image processor and write a response. 88 89 ``` go 90 // This handler receives an image, optimizes it and sends the result back. 91 func OptimizeImage(response *goyave.Response, request *goyave.Request) { 92 optimizedImg := processing.OptimizeImage(request.File("image")[0]) 93 response.Write(http.StatusOK, optimizedImg) 94 } 95 ``` 96 ::: tip 97 Setting the `Content-Type` header is not necessary. `response.Write` automatically detects the content type and sets the header accordingly, if the latter has not been defined already. 98 ::: 99 100 ## Naming conventions 101 102 - Controller packages are named after the model they are mostly using, in a singular form. For example a controller for a `Product` model would be called `http/controllers/product`. If a controller isn't related to a model, then give it an expressive name. 103 - Controller handlers are always **exported** so they can be used when registering routes. All functions which aren't handlers **must be unexported**. 104 - CRUD operations naming and routing: 105 106 | Method | URI | Handler name | Description | 107 |------------------|-----------------|--------------|-----------------------| 108 | `GET` | `/product` | `Index()` | Get the products list | 109 | `POST` | `/product` | `Store()` | Create a product | 110 | `GET` | `/product/{id}` | `Show()` | Show a product | 111 | `PUT` or `PATCH` | `/product/{id}` | `Update()` | Update a product | 112 | `DELETE` | `/product/{id}` | `Destroy()` | Delete a product |