github.com/System-Glitch/goyave/v2@v2.10.3-0.20200819142921-51011e75d504/docs_src/src/guide/basics/requests.md (about) 1 --- 2 meta: 3 - name: "og:title" 4 content: "Requests - Goyave" 5 - name: "twitter:title" 6 content: "Requests - Goyave" 7 - name: "title" 8 content: "Requests - Goyave" 9 --- 10 11 # Requests 12 13 [[toc]] 14 15 ## Introduction 16 17 Handlers receive a `goyave.Response` and a `goyave.Request` as parameters. This section is a technical reference of the `Request` object. This object can give you a lot of information about the incoming request, such as its headers, cookies, or body. 18 19 All functions below require the `goyave` package to be imported. 20 21 ``` go 22 import "github.com/System-Glitch/goyave/v2" 23 ``` 24 25 ## Methods 26 27 ::: table 28 [Request](#request-request) 29 [Method](#request-method) 30 [Protocol](#request-protocol) 31 [URI](#request-uri) 32 [Header](#request-header) 33 [ContentLength](#request-contentlength) 34 [RemoteAddress](#request-remoteaddress) 35 [Cookies](#request-cookies) 36 [Referrer](#request-referrer) 37 [UserAgent](#request-useragent) 38 [BasicAuth](#request-basicauth) 39 [BearerToken](#request-bearertoken) 40 [CORSOptions](#request-corsoptions) 41 ::: 42 43 #### Request.Request 44 45 Return the raw http request. Prefer using the "goyave.Request" accessors. 46 47 | Parameters | Return | 48 |------------|-----------------| 49 | | `*http.Request` | 50 51 #### Request.Method 52 53 The HTTP method (GET, POST, PUT, etc.). 54 55 | Parameters | Return | 56 |------------|----------| 57 | | `string` | 58 59 **Example:** 60 ``` go 61 fmt.Println(request.Method()) // GET 62 ``` 63 64 #### Request.Protocol 65 66 The protocol used by this request, "HTTP/1.1" for example. 67 68 | Parameters | Return | 69 |------------|----------| 70 | | `string` | 71 72 **Example:** 73 ``` go 74 fmt.Println(request.Protocol()) // "HTTP/1.1" 75 ``` 76 77 #### Request.URI 78 79 URI specifies the URI being requested. Use this if you absolutely need the raw query params, url, etc. Otherwise use the provided methods and fields of the `goyave.Request`. 80 81 | Parameters | Return | 82 |------------|------------| 83 | | `*url.URL` | 84 85 **Example:** 86 ``` go 87 fmt.Println(request.URI().Path) // "/foo/bar" 88 ``` 89 90 #### Request.Header 91 92 Header contains the request header fields either received by the server or to be sent by the client. Header names are case-insensitive. 93 94 If the raw request has the following header lines, 95 ``` 96 Host: example.com 97 accept-encoding: gzip, deflate 98 Accept-Language: en-us 99 fOO: Bar 100 foo: two 101 ``` 102 then the header map will look like this: 103 ```go 104 Header = map[string][]string{ 105 "Accept-Encoding": {"gzip, deflate"}, 106 "Accept-Language": {"en-us"}, 107 "Foo": {"Bar", "two"}, 108 } 109 ``` 110 111 | Parameters | Return | 112 |------------|---------------| 113 | | `http.Header` | 114 115 **Example:** 116 ``` go 117 fmt.Println(request.Header().Get("Content-Type")) // "application/json" 118 ``` 119 120 #### Request.ContentLength 121 122 ContentLength records the length (in bytes) of the associated content. The value -1 indicates that the length is unknown. 123 124 | Parameters | Return | 125 |------------|---------| 126 | | `int64` | 127 128 **Example:** 129 ``` go 130 fmt.Println(request.ContentLength()) // 758 131 ``` 132 133 #### Request.RemoteAddress 134 135 RemoteAddress allows to record the network address that sent the request, usually for logging. 136 137 | Parameters | Return | 138 |------------|----------| 139 | | `string` | 140 141 **Example:** 142 ``` go 143 fmt.Println(request.RemoteAddress()) // 192.168.0.10:1234 144 ``` 145 146 #### Request.Cookies 147 148 Cookies returns the HTTP cookies sent with the request. 149 150 | Parameters | Return | 151 |---------------|------------------| 152 | `name string` | `[]*http.Cookie` | 153 154 **Example:** 155 ``` go 156 cookie := request.Cookies("cookie-name") 157 fmt.Println(cookie[0].value) 158 ``` 159 160 ::: warning 161 Protect yourself from [CSRF attacks](https://en.wikipedia.org/wiki/Cross-site_request_forgery) when using cookies! 162 ::: 163 164 #### Request.Referrer 165 166 Referrer returns the referring URL, if sent in the request. 167 168 | Parameters | Return | 169 |------------|----------| 170 | | `string` | 171 172 **Example:** 173 ``` go 174 fmt.Println(request.Referrer()) // "https://github.com/System-Glitch/goyave/" 175 ``` 176 177 #### Request.UserAgent 178 179 UserAgent returns the client's User-Agent, if sent in the request. 180 181 | Parameters | Return | 182 |------------|----------| 183 | | `string` | 184 185 **Example:** 186 ``` go 187 fmt.Println(request.UserAgent()) // "Mozilla/5.0 ..." 188 ``` 189 190 #### Request.CORSOptions 191 192 <p><Badge text="Since v2.3.0"/></p> 193 194 Returns the CORS options applied to this request, or `nil`. Learn more about CORS [here](../advanced/cors.html). 195 196 The returned object is a copy of the options applied to the router. Therefore, altering the returned object will not alter the router's options. 197 198 | Parameters | Return | 199 |------------|----------| 200 | | `string` | 201 202 **Example:** 203 ``` go 204 fmt.Println(request.CORSOptions().AllowedMethods) // "[HEAD GET POST PUT PATCH DELETE]" 205 ``` 206 207 #### Request.BasicAuth 208 209 Returns the username and password provided in the request's `Authorization` header, if the request uses HTTP Basic Authentication. 210 211 | Parameters | Return | 212 |------------|-------------------| 213 | | `username string` | 214 | | `password string` | 215 | | `ok bool` | 216 217 **Example:** 218 ``` go 219 username, password, ok := request.BasicAuth() 220 fmt.Println(username) // "admin" 221 fmt.Println(password) // "secret" 222 fmt.Println(ok) // true 223 ``` 224 225 #### Request.BearerToken 226 227 <p><Badge text="Since v2.5.0"/></p> 228 229 Extract the auth token from the "Authorization" header. Only takes tokens of type "Bearer". 230 231 Returns empty string if no token found or the header is invalid. 232 233 | Parameters | Return | 234 |------------|----------------| 235 | | `token string` | 236 | | `ok bool` | 237 238 **Example:** 239 ``` go 240 token, ok := request.BearerToken() 241 fmt.Println(token) // "ey..." 242 fmt.Println(ok) // true 243 ``` 244 245 ### Accessors 246 247 <p><Badge text="Since v2.0.0"/></p> 248 249 Accessors are helper functions to retrieve request data without having to write the type assertion. This is helpful to make your controllers cleaner. You shouldn't use these accessors in middleware because they assume the data has been converted by the validation already. Data can still be accessed through the `Data` attribute. There is currently no accessor for slices. 250 251 ::: table 252 [Has](#request-has) 253 [String](#request-string) 254 [Numeric](#request-numeric) 255 [Integer](#request-integer) 256 [Bool](#request-bool) 257 [File](#request-file) 258 [Timezone](#request-timezone) 259 [IP](#request-ip) 260 [URL](#request-url) 261 [UUID](#request-uuid) 262 [Date](#request-date) 263 ::: 264 265 #### Request.Has 266 267 Check if the given field exists in the request data. 268 269 | Parameters | Return | 270 |----------------|--------| 271 | `field string` | `bool` | 272 273 **Example:** 274 ``` go 275 fmt.Println(request.Has("name")) // true 276 ``` 277 278 #### Request.String 279 280 Get a string field from the request data. Panics if the field is not a string or doesn't exist. 281 282 | Parameters | Return | 283 |----------------|----------| 284 | `field string` | `string` | 285 286 **Example:** 287 ``` go 288 fmt.Println(request.String("name")) // "JohnDoe" 289 ``` 290 291 #### Request.Numeric 292 293 Get a numeric field from the request data. Panics if the field is not numeric or doesn't exist. 294 295 | Parameters | Return | 296 |----------------|-----------| 297 | `field string` | `float64` | 298 299 **Example:** 300 ``` go 301 fmt.Println(request.Numeric("price")) // 42.3 302 ``` 303 304 #### Request.Integer 305 306 Get an integer field from the request data. Panics if the field is not an integer or doesn't exist. 307 308 | Parameters | Return | 309 |----------------|--------| 310 | `field string` | `int` | 311 312 **Example:** 313 ``` go 314 fmt.Println(request.Integer("age")) // 32 315 ``` 316 317 #### Request.Bool 318 319 Get a bool field from the request data. Panics if the field is not a bool or doesn't exist. 320 321 | Parameters | Return | 322 |----------------|--------| 323 | `field string` | `bool` | 324 325 **Example:** 326 ``` go 327 fmt.Println(request.Bool("EULA")) // true 328 ``` 329 330 #### Request.File 331 332 Get a file field from the request data. Panics if the field is not a file or doesn't exist. 333 334 | Parameters | Return | 335 |----------------|---------------------| 336 | `field string` | `[]filesystem.File` | 337 338 **Example:** 339 ``` go 340 for _, f := range request.File("images") { 341 fmt.Println(f.Header.Filename) 342 } 343 ``` 344 345 #### Request.Timezone 346 347 Get a timezone field from the request data. Panics if the field is not a timezone or doesn't exist. 348 349 | Parameters | Return | 350 |----------------|------------------| 351 | `field string` | `*time.Location` | 352 353 **Example:** 354 ``` go 355 fmt.Println(request.Timezone("tz").String()) // "America/New_York" 356 ``` 357 358 #### Request.IP 359 360 Get an IP field from the request data. Panics if the field is not an IP or doesn't exist. 361 362 | Parameters | Return | 363 |----------------|----------| 364 | `field string` | `net.IP` | 365 366 **Example:** 367 ``` go 368 fmt.Println(request.IP("host").String()) // "127.0.0.1" 369 ``` 370 371 #### Request.URL 372 373 Get a URL field from the request data. Panics if the field is not a URL or doesn't exist. 374 375 | Parameters | Return | 376 |----------------|------------| 377 | `field string` | `*url.URL` | 378 379 **Example:** 380 ``` go 381 fmt.Println(request.URL("link").String()) // "https://google.com" 382 ``` 383 384 #### Request.UUID 385 386 Get a UUID field from the request data. Panics if the field is not a UUID or doesn't exist. 387 388 | Parameters | Return | 389 |----------------|-------------| 390 | `field string` | `uuid.UUID` | 391 392 **Example:** 393 ``` go 394 fmt.Println(request.UUID("id").String()) // "3bbcee75-cecc-5b56-8031-b6641c1ed1f1" 395 ``` 396 397 #### Request.Date 398 399 Get a date field from the request data. Panics if the field is not a date or doesn't exist. 400 401 | Parameters | Return | 402 |----------------|-------------| 403 | `field string` | `time.Time` | 404 405 **Example:** 406 ``` go 407 fmt.Println(request.Date("birthdate").String()) // "2019-11-21 00:00:00 +0000 UTC" 408 ``` 409 410 ## Attributes 411 412 ::: table 413 [Rules](#request-rules) 414 [Data](#request-data) 415 [Params](#request-params) 416 [Lang](#request-lang) 417 ::: 418 419 #### Request.Rules 420 421 The validation rule set associated with this request. See the [validation](./validation.html) section for more information. 422 423 #### Request.Data 424 425 A `map[string]interface{}` containing the request's data. The key is the name of the field. This map contains the data from the request's body **and** the URL query string values. The request's body parameters takes precedence over the URL query string values. 426 427 For the given JSON request: 428 ```json 429 { 430 "name": "John Doe", 431 "tags": ["tag1", "tag2"] 432 } 433 ``` 434 ``` go 435 fmt.Println(request.Data["name"]) // "John Doe" 436 fmt.Println(request.Data["tags"]) // "[tag1 tag2]" ([]string) 437 ``` 438 439 You would obtain the same result for the following url-encoded request: 440 ``` 441 name=John%20Doe&tags=tag1&tags=tag2 442 ``` 443 444 Because the `Data` attribute can hold any type of data, you will likely need type assertion. If you validated your request, checking for type assertion errors is not necessary. 445 ``` go 446 tags, _ := request.Data["tags"].([]string) 447 ``` 448 449 #### Request.Params 450 451 `Params` is a `map[string]string` of the route parameters. 452 453 For the given route definition and request: 454 ``` 455 /categories/{category}/{product_id} 456 ``` 457 ``` 458 /categories/3/5 459 ``` 460 ``` go 461 fmt.Println(request.Params["category"]) // "3" 462 fmt.Println(request.Params["product_id"]) // "5" 463 ``` 464 465 #### Request.Lang 466 467 `Lang` indicates the language desired by the user. This attribute is automatically set by a core middleware, based on the `Accept-Language` header, if present. If the desired language is not available, the default language is used. 468 469 Learn more in the [localization](../advanced/localization.html) section. 470 471 ``` go 472 fmt.Println(request.Lang) // "en-US" 473 fmt.Println(lang.Get(request.Lang, "validation.rules.required")) // "The :field is required." 474 ``` 475 476 #### Request.User 477 478 <p><Badge text="Since v2.5.0"/></p> 479 480 `User` is an `interface{}` containing the authenticated user if the route is protected, `nil` otherwise. 481 482 Learn more in the [authentication](../advanced/authentication.html) section. 483 484 **Example:** 485 ``` go 486 fmt.Println(request.User.(*model.User).Name) // "John Doe" 487 ```