github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/docs/apis/Marshal.md (about)

     1  # `Marshal()` (type)
     2  
     3  > Converts structured memory into a structured file format (eg for stdio)
     4  
     5  ## Description
     6  
     7  This is a function you would write when programming a Murex data-type.
     8  The marshal function takes in a Go (golang) `type` or `struct` and returns
     9  a byte slice of a "string" representation of that format (eg in JSON) or an
    10  error.
    11  
    12  This marshaller is then registered to Murex inside an `init()` function
    13  and Murex builtins can use that marshaller via the `MarshalData()` API.
    14  
    15  ## Usage
    16  
    17  Registering `Marshal()` (for writing builtin data-types)
    18  
    19  ```go
    20  // To avoid data races, this should only happen inside func init()
    21  lang.Marshallers[ /* your type name */ ] = /* your readIndex func */
    22  ```
    23  
    24  Using an existing marshaller (eg inside a builtin command)
    25  
    26  ```go
    27  // See documentation on lang.MarshalData for more details
    28  b, err := lang.MarshalData(p, dataType, data)
    29  ```
    30  
    31  ## Examples
    32  
    33  Defining a marshaller for a murex data-type
    34  
    35  ```go
    36  package example
    37  
    38  import (
    39  	"encoding/json"
    40  
    41  	"github.com/lmorg/murex/lang"
    42  )
    43  
    44  func init() {
    45  	// Register data-type
    46  	lang.Marshallers["json"] = marshal
    47  }
    48  
    49  // Describe marshaller
    50  func marshal(p *lang.Process, v interface{}) ([]byte, error) {
    51  	if p.Stdout.IsTTY() {
    52  		// If STDOUT is a TTY (ie not pipe, text file or other destination other
    53  		// than a terminal) then output JSON in an indented, human readable,
    54  		// format....
    55  		return json.MarshalIndent(v, "", "    ")
    56  	}
    57  
    58  	// ....otherwise we might as well output it in a minified format
    59  	return json.Marshal(v)
    60  }
    61  ```
    62  
    63  ## Parameters
    64  
    65  1. `*lang.Process`: Process's runtime state. Typically expressed as the variable `p` 
    66  2. `interface{}`: data you wish to marshal
    67  
    68  ## See Also
    69  
    70  * [apis/`Unmarshal()` (type)](../apis/Unmarshal.md):
    71    Converts a structured file format into structured memory
    72  * [apis/`lang.MarshalData()` (system API)](../apis/lang.MarshalData.md):
    73    Converts structured memory into a Murex data-type (eg for stdio)
    74  * [apis/`lang.UnmarshalData()` (system API)](../apis/lang.UnmarshalData.md):
    75    Converts a Murex data-type into structured memory
    76  
    77  <hr/>
    78  
    79  This document was generated from [lang/define_marshal_doc.yaml](https://github.com/lmorg/murex/blob/master/lang/define_marshal_doc.yaml).