github.com/System-Glitch/goyave/v2@v2.10.3-0.20200819142921-51011e75d504/docs_src/src/guide/advanced/helpers.md (about)

     1  ---
     2  meta:
     3    - name: "og:title"
     4      content: "Helpers - Goyave"
     5    - name: "twitter:title"
     6      content: "Helpers - Goyave"
     7    - name: "title"
     8      content: "Helpers - Goyave"
     9  ---
    10  
    11  # Helpers
    12  
    13  [[toc]]
    14  
    15  The Goyave framework offers a collection of helpers to ease development.
    16  
    17  ## General
    18  
    19  The helpers require the `helper` package to be imported.
    20  
    21  ``` go
    22  import "github.com/System-Glitch/goyave/v2/helper"
    23  ```
    24  
    25  **List of general helpers**:
    26  ::: table
    27  [IndexOf](#helper-indexof)
    28  [Contains](#helper-contains)
    29  [IndexOfStr](#helper-indexofstr)
    30  [ContainsStr](#helper-containsstr)
    31  [SliceEqual](#helper-sliceequal)
    32  [ToFloat64](#helper-tofloat64)
    33  [ToString](#helper-tostring)
    34  [ParseMultiValuesHeader](#helper-parsemultivaluesheader)
    35  [RemoveHiddenFields](#helper-removehiddenfields)
    36  :::
    37  
    38  #### helper.IndexOf
    39  
    40  Get the index of the given value in the given slice, or `-1` if not found.
    41  
    42  | Parameters          | Return |
    43  |---------------------|--------|
    44  | `slice interface{}` | `int`  |
    45  | `value interface{}` |        |
    46  
    47  **Example:**
    48  ``` go
    49  slice := []interface{}{'r', "Goyave", 3, 2.42}
    50  fmt.Println(helper.IndexOf(slice, "Goyave")) // 1
    51  ```
    52  
    53  #### helper.Contains
    54  
    55  Check if a generic slice contains the given value.
    56  
    57  | Parameters          | Return |
    58  |---------------------|--------|
    59  | `slice interface{}` | `bool` |
    60  | `value interface{}` |        |
    61  
    62  **Example:**
    63  ``` go
    64  slice := []interface{}{'r', "Goyave", 3, 2.42}
    65  fmt.Println(helper.Contains(slice, "Goyave")) // true
    66  ```
    67  
    68  #### helper.IndexOfStr
    69  
    70  Get the index of the given value in the given string slice, or `-1` if not found.
    71  
    72  Prefer using this helper instead of `IndexOf` for better performance.
    73  
    74  | Parameters       | Return |
    75  |------------------|--------|
    76  | `slice []string` | `int`  |
    77  | `value []string` |        |
    78  
    79  **Example:**
    80  ``` go
    81  slice := []string{"Avogado", "Goyave", "Pear", "Apple"}
    82  fmt.Println(helper.IndexOfStr(slice, "Goyave")) // 1
    83  ```
    84  
    85  #### helper.ContainsStr
    86  
    87  Check if a string slice contains the given value.
    88  
    89  Prefer using this helper instead of `Contains` for better performance.
    90  
    91  | Parameters       | Return |
    92  |------------------|--------|
    93  | `slice []string` | `bool` |
    94  | `value []string` |        |
    95  
    96  **Example:**
    97  ``` go
    98  slice := []string{"Avogado", "Goyave", "Pear", "Apple"}
    99  fmt.Println(helper.ContainsStr(slice, "Goyave")) // true
   100  ```
   101  
   102  #### helper.SliceEqual
   103  
   104  Check if two generic slices are the same.
   105  
   106  | Parameters           | Return |
   107  |----------------------|--------|
   108  | `first interface{}`  | `bool` |
   109  | `second interface{}` |        |
   110  
   111  **Example:**
   112  ``` go
   113  first := []string{"Avogado", "Goyave", "Pear", "Apple"}
   114  second := []string{"Goyave", "Avogado", "Pear", "Apple"}
   115  fmt.Println(helper.SliceEqual(first, second)) // false
   116  ```
   117  
   118  #### helper.ToFloat64
   119  
   120  Check if two generic slices are the same.
   121  
   122  | Parameters          | Return    |
   123  |---------------------|-----------|
   124  | `value interface{}` | `float64` |
   125  |                     | `error`   |
   126  
   127  **Examples:**
   128  ``` go
   129  fmt.Println(helper.ToFloat64(1.42)) // 1.42 nil
   130  fmt.Println(helper.ToFloat64(1)) // 1.0 nil
   131  fmt.Println(helper.ToFloat64("1.42")) // 1.42 nil
   132  fmt.Println(helper.ToFloat64("NaN")) // 0 nil
   133  fmt.Println(helper.ToFloat64([]string{})) // 0 nil
   134  ```
   135  
   136  #### helper.ToString
   137  
   138  Convert a generic value to string.
   139  
   140  | Parameters          | Return   |
   141  |---------------------|----------|
   142  | `value interface{}` | `string` |
   143  
   144  **Examples:**
   145  ``` go
   146  fmt.Println(helper.ToString(1.42)) // "1.42"
   147  fmt.Println(helper.ToString(nil)) // "nil"
   148  fmt.Println(helper.ToString("hello")) // "hello"
   149  fmt.Println(helper.ToString([]string{})) // "[]"
   150  ```
   151  
   152  #### helper.ParseMultiValuesHeader
   153  
   154  Parses multi-values HTTP headers, taking the quality values into account. The result is a slice of values sorted according to the order of priority.
   155  
   156  See: [https://developer.mozilla.org/en-US/docs/Glossary/Quality_values](https://developer.mozilla.org/en-US/docs/Glossary/Quality_values)
   157  
   158  | Parameters      | Return                     |
   159  |-----------------|----------------------------|
   160  | `header string` | `[]filesystem.HeaderValue` |
   161  
   162  **HeaderValue struct:**
   163  
   164  | Attribute  | Type      |
   165  |------------|-----------|
   166  | `Value`    | `string`  |
   167  | `Priority` | `float64` |
   168  
   169  **Examples:**
   170  ``` go
   171  fmt.Println(helper.ParseMultiValuesHeader("text/html,text/*;q=0.5,*/*;q=0.7"))
   172  // [{text/html 1} {*/* 0.7} {text/* 0.5}]
   173  
   174  fmt.Println(helper.ParseMultiValuesHeader("text/html;q=0.8,text/*;q=0.8,*/*;q=0.8"))
   175  // [{text/html 0.8} {text/* 0.8} {*/* 0.8}]
   176  ```
   177  
   178  #### helper.RemoveHiddenFields
   179  
   180  Remove hidden fields if the given model is a struct pointer. All fields marked with the tag `model:"hide"` will be set to their zero value.
   181  
   182  For example, this allows to send user models to the client without their password field.
   183  
   184  | Parameters          | Return |
   185  |---------------------|--------|
   186  | `model interface{}` | `void` |
   187  
   188  **Example:**
   189  ``` go
   190  type Model struct {
   191      Username string
   192      Password string `model:"hide" json:",omitempty"`
   193  }
   194  
   195  model := &Model{
   196      Username: "Jeff",
   197      Password: "bcrypted password",
   198  }
   199  
   200  helper.RemoveHiddenFields(model)
   201  fmt.Println(model) // &{ Jeff}
   202  ```
   203  
   204  ## Filesystem
   205  
   206  The filesystem helpers require the `filesystem`  package to be imported.
   207  
   208  ``` go
   209  import "github.com/System-Glitch/goyave/v2/helper/filesystem"
   210  ```
   211  
   212  All files received in a requests are stored in the `filesystem.File` structure. This structres gives all the information you need on a file and its content, as well as a helper function to save it easily.
   213  
   214  | Attribute  | Type                    |
   215  |------------|-------------------------|
   216  | `Header`   | `*multipart.FileHeader` |
   217  | `MIMEType` | `string`                |
   218  | `Data`     | `multipart.File`        |
   219  
   220  ::: warning
   221  The data in `file.Header` come from the client and **shouldn't be trusted**. The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. You cannot rely on the size given in the header neither.
   222  :::
   223  
   224  **List of filesystem helpers**:
   225  ::: table
   226  [File.Save](#filesystem-file-save)
   227  [GetFileExtension](#filesystem-getfileextension)
   228  [GetMIMEType](#filesystem-getmimetype)
   229  [FileExists](#filesystem-fileexists)
   230  [IsDirectory](#filesystem-isdirectory)
   231  [Delete](#filesystem-delete)
   232  :::
   233  
   234  #### filesystem.File.Save
   235  
   236  Writes the given file on the disk.
   237  Appends a timestamp to the given file name to avoid duplicate file names.
   238  The file is not readable anymore once saved as its FileReader has already been closed.
   239  
   240  Returns the actual file name.
   241  
   242  | Parameters    | Return   |
   243  |---------------|----------|
   244  | `path string` | `string` |
   245  | `name string` |          |
   246  
   247  **Example:**
   248  ``` go
   249  image := request.Data["image"].([]filesystem.File)[0]
   250  // As file fields can be multi-files uploads, a file field
   251  // is always a slice.
   252  
   253  name := request.Data["name"].(string)
   254  product := model.Product{
   255      Name: name,
   256      Price: request.Data["price"].(float64),
   257      Image: image.Save("storage/img", name)
   258  }
   259  database.GetConnection().Create(&product)
   260  ```
   261  
   262  #### filesystem.GetFileExtension
   263  
   264  Returns the last part of a file name. If the file doesn't have an extension, returns an empty string.
   265  
   266  | Parameters    | Return   |
   267  |---------------|----------|
   268  | `file string` | `string` |
   269  
   270  **Examples:**
   271  ``` go
   272  fmt.Println(filesystem.GetFileExtension("README.md")) // "md"
   273  fmt.Println(filesystem.GetFileExtension("LICENSE")) // empty string
   274  fmt.Println(filesystem.GetFileExtension("archive.tar.gz")) // "gz"
   275  ```
   276  
   277  #### filesystem.GetMIMEType
   278  
   279  Get the MIME type and size of the given file. If the file cannot be opened, panics. You should check if the file exists, using `filesystem.FileExists()`, before calling this function.
   280  
   281  | Parameters    | Return   |
   282  |---------------|----------|
   283  | `file string` | `string` |
   284  
   285  **Examples:**
   286  ``` go
   287  fmt.Println(filesystem.GetMIMEType("logo.png")) // "image/png"
   288  fmt.Println(filesystem.GetFileExtension("config.json")) // "application/json; charset=utf-8"
   289  fmt.Println(filesystem.GetFileExtension("index.html")) // "text/html; charset=utf-8"
   290  ```
   291  
   292  #### filesystem.FileExists
   293  
   294  Returns true if the file at the given path exists and is readable. Returns false if the given file is a directory
   295  
   296  | Parameters    | Return |
   297  |---------------|--------|
   298  | `file string` | `bool` |
   299  
   300  **Example:**
   301  ``` go
   302  fmt.Println(filesystem.FileExists("README.md")) // true
   303  ```
   304  
   305  #### filesystem.IsDirectory
   306  
   307  Returns true if the file at the given path exists, is a directory and is readable.
   308  
   309  | Parameters    | Return |
   310  |---------------|--------|
   311  | `path string` | `bool` |
   312  
   313  **Example:**
   314  ``` go
   315  fmt.Println(filesystem.IsDirectory("README.md")) // false
   316  fmt.Println(filesystem.IsDirectory("resources")) // true
   317  ```
   318  
   319  #### filesystem.Delete
   320  
   321  Delete the file at the given path. Panics if the file cannot be deleted.
   322  
   323  You should check if the file exists, using `filesystem.FileExists()`, before calling this function.
   324  
   325  | Parameters    | Return |
   326  |---------------|--------|
   327  | `file string` | `void` |
   328  
   329  **Example:**
   330  ``` go
   331  filesystem.Delete("README.md")
   332  ```