Using Ray with Go | ray-go | Spatie       

 SPATIE  

ray-go
======

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Ray-go](https://spatie.be/docs/ray-go/v1)  Using Ray with Go

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/ray-go/v1) 

  Using Ray with Go    
- [ Introduction ](https://spatie.be/docs/ray-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/ray-go/v1/installation-and-setup)
- [ Using Ray with Go ](https://spatie.be/docs/ray-go/v1/usage)
- [ Configuration ](https://spatie.be/docs/ray-go/v1/configuration)
- [ Methods ](https://spatie.be/docs/ray-go/v1/reference)
- [ Detecting and removing Ray calls ](https://spatie.be/docs/ray-go/v1/detecting-removing-ray-calls)
- [ Testing ](https://spatie.be/docs/ray-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/ray-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/ray-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/ray-go/v1/support-us)

 Using Ray with Go
=================

###  On this page 

1. [ Basic output ](#content-basic-output)
2. [ Customizing output ](#content-customizing-output)
3. [ Output formats ](#content-output-formats)
4. [ Inspecting values ](#content-inspecting-values)
5. [ Caller and stack trace ](#content-caller-and-stack-trace)
6. [ Measuring and counting ](#content-measuring-and-counting)
7. [ Limiting output ](#content-limiting-output)
8. [ Conditional output ](#content-conditional-output)
9. [ Handling exceptions ](#content-handling-exceptions)
10. [ Updating and removing items ](#content-updating-and-removing-items)
11. [ Execution control ](#content-execution-control)
12. [ Flow helpers ](#content-flow-helpers)
13. [ Custom functions ](#content-custom-functions)
14. [ Managing the Ray app ](#content-managing-the-ray-app)
15. [ Fun stuff ](#content-fun-stuff)

This page covers sending values to Ray, formatting output and controlling a debugging session. See the [method reference](reference) for an overview of methods.

Examples below use an explicit `client` and `ctx`. Set them up once:

```
ctx := context.Background()
client, err := ray.New(ray.DefaultConfig())
if err != nil {
    log.Fatal(err)
}
```

Import `context`, `log` and `ray "github.com/spatie/ray-go"`. The date example also imports `time`. Check `.Err()` at the end of each chain. The first error is retained and later methods on that entry do not send anything. New entries have independent error state.

Basic output
--------------------------------------------------------------------------------------------

To display something in Ray, use `Send`. It accepts many different data types: strings, arrays, structs, maps, and more.

```
client.Send(ctx, "Hello world").Green()
client.Send(ctx, map[string]int{"a": 1, "b": 2}).Color("red")
client.Send(ctx, "as", "many", "arguments", "as", "you", "like")
```

Multiple arguments are displayed as separate messages in the same entry. `ray.Send(ctx, values...)` uses a shared process-wide default client. Explicit clients keep configuration and state isolated.

Go values use `encoding/json`. Structs, maps, arrays and slices use Ray's JSON renderer rather than Symfony VarDumper HTML. Only exported struct fields are serialized. JSON tags and `json.Marshaler` work as usual. Use `Debug` for channels, functions and other values that JSON cannot serialize. Functions passed to `Send` are not executed.

Customizing output
--------------------------------------------------------------------------------------------------------------

Ray has some useful methods that you can use to add more context or differentiate messages from one another.

### Expanding arrays and objects

Use `Expand` to open a depth, a named key, or dot-separated nested keys. `ExpandAll` requests all levels.

```
entry := client.Send(ctx, map[string]any{"myKey": map[string]int{"nestedKey": 1}})
entry.Expand()
entry.Expand(3)
entry.Expand("myKey", "anotherKey")
entry.Expand("myKey.nestedKey")
entry.ExpandAll()
```

These commands target compatible expandable renderers, including custom HTML payloads. The desktop app controls native JSON expansion.

### Using colors

You can colorize things you sent to Ray by using one of the color functions.

```
client.Send(ctx, "this is green").Green()
client.Send(ctx, "this is yellow").Yellow()
client.Send(ctx, "this is red").Red()
client.Send(ctx, "this is blue").Blue()
client.Send(ctx, "this is purple").Purple()
client.Send(ctx, "this is gray").Gray()
```

`Yellow` sends Ray's orange color. `Grey` is an alias for `Gray`.

### Using sizes

Ray can display things in different sizes.

```
client.Send(ctx, "small").Small()
client.Send(ctx, "regular")
client.Send(ctx, "large").Large()
```

### Adding a label

You can customize the label displayed next to an item with `Label`.

```
client.Send(ctx, []string{"John", "Paul", "George", "Ringo"}).Label("Beatles")
```

### Displaying a table

You can send a map, struct, array or slice to Ray with `Table`. Pass an empty label to use "Table".

```
client.Entry(ctx).Table(map[string]any{"First": "First value", "Second": 2}, "")
client.Entry(ctx).Table([]string{"John", "Paul", "George", "Ringo"}, "Beatles")
```

Nested cells use escaped, preformatted JSON. Scalar table input returns an error.

Output formats
--------------------------------------------------------------------------------------------------

### Working with JSON

Want to display the JSON representation of anything you'd like in Ray? Use `ToJSON`. You can provide any value that `encoding/json` can marshal. Both `ToJSON` and `JSON` accept multiple values.

```
client.Entry(ctx).ToJSON(map[string]any{"a": 1, "b": map[string]int{"c": 3}}, []int{4, 5})
client.Entry(ctx).JSON(`{"a":1,"b":{"c":3}}`, `[4,5]`)
```

`JSON` accepts valid JSON strings. Invalid input returns an error rather than displaying null as PHP does. Go's map ordering and Unicode and slash escaping differ from PHP's `json_encode`, but the values are preserved.

### Working with XML

You can send a valid XML string to Ray with `XML`. It will be displayed as formatted XML.

```
client.Entry(ctx).XML("<one><two><three>3</three></two></one>")
```

Formatting uses `encoding/xml`, so namespace prefixes, declarations and empty-element formatting can differ from PHP DOM. Invalid documents return an error. External entities are not resolved.

### Working with dates

Go uses `time.Time` instead of Carbon. `Send` recognizes `time.Time` and `*time.Time` and uses Ray's date renderer. `Date` accepts a pointer, including nil.

```
now := time.Now()
client.Send(ctx, now)
client.Entry(ctx).Date(&now)
client.Entry(ctx).Date(nil)
```

### Working with files

You can display the contents of any UTF-8 text file in Ray with `File`.

```
client.Entry(ctx).File("somefile.txt")
```

A missing file produces a message in Ray. Other read errors and invalid UTF-8 are returned. Text is HTML-escaped.

### Displaying images

To display an image, call `Image` and pass a filename, URL, or a valid base64-encoded image as its only argument.

```
client.Entry(ctx).Image("https://placekitten.com/200/300")
client.Entry(ctx).Image("/home/user/kitten.jpg")
client.Entry(ctx).Image("data:image/png;base64,aGVsbG8=")
client.Entry(ctx).Image("aGVsbG8=")
```

The short base64 examples show transport syntax, not valid image bytes. Supply PNG image data when displaying one. Base64 input uses an `image/png` prefix. Existing filenames become escaped absolute file URLs. Quotes and ampersands in image locations are HTML-escaped rather than discarded.

### Displaying a link

You can render a clickable link in Ray by using `Link`. Pass an empty label to use the URL.

```
client.Entry(ctx).Link("spatie.be", "")
client.Entry(ctx).Link("spatie.be", "Spatie homepage")
```

We assume that `spatie.be` means `https://spatie.be`. URLs and labels are escaped, so markup is not interpreted. The PHP `url` spelling is omitted in favor of `Link`.

### Rendering HTML

To render a piece of trusted HTML directly in Ray, you can use `HTML`.

```
client.Entry(ctx).HTML("<b>Bold string</b>")
```

### Displaying text content

To display raw text while preserving whitespace formatting, use `Text`. If the text contains HTML, it will be displayed as-is and is not rendered.

```
client.Entry(ctx).Text("<em>this string is html encoded</em>")
client.Entry(ctx).Text("  whitespace formatting\n   is preserved as well.")
```

Inspecting values
-----------------------------------------------------------------------------------------------------------

### Display the type name of an object

To quickly send the Go type name of a value to Ray, use `TypeName`.

```
client.Entry(ctx).TypeName(struct{ Company string }{"Spatie"})
```

### Displaying private properties and methods

Go does not support PHP's `invade` behavior without unsafe access. This package does not bypass Go visibility. Use a method on your own type to return the information you want to debug.

### Showing raw values

Use `Raw` to bypass specialized boolean, null and date rendering and your payload finder. Structured values use escaped, preformatted JSON. `Debug` uses Go's `%#v` formatting instead of JSON.

```
client.Entry(ctx).Raw(true, nil, map[string]int{"value": 3})
client.Entry(ctx).Debug(make(chan int))
```

### Showing runtime info

PHP INI inspection is not applicable to Go. Request metadata includes the Go runtime version. Send selected `runtime` values explicitly if you need more detail.

Caller and stack trace
--------------------------------------------------------------------------------------------------------------------------

### See the caller of a function

Sometimes you want to know where your code is being called. You can determine that by using `Caller`. To see the entire backtrace, use `Trace(0, 0)`. Its arguments are the offset and limit. A nonpositive limit includes all remaining frames.

```
client.Entry(ctx).Caller()
client.Entry(ctx).Trace(0, 0)
client.Entry(ctx).Trace(1, 5)
```

Origins use the Go callsite, not the library's internal methods. Stack frames use Go function names. Remote paths are mapped in both origins and traces.

Measuring and counting
--------------------------------------------------------------------------------------------------------------------------

### Counting execution times

You can display a count of how many times a piece of code was called using `Count`. Pass a name to share a counter, or an empty name to use the callsite.

```
for i := 0; i < 4; i++ {
    client.Entry(ctx).Count("first")
}
count := client.CounterValue("first")
log.Print(count)
client.ClearCounters()
```

Each counter updates the same entry in Ray until counters are cleared.

### Measuring performance

You can use `Measure` to display runtime. When `Measure` is called again, the time between this and the previous call is also displayed. An empty name selects the default timer.

```
client.Entry(ctx).Measure("")
client.Entry(ctx).Measure("")
client.Entry(ctx).MeasureFunc(func() {
    // Do some work.
})
client.StopTime("default")
client.StopTime("")
```

Durations use a monotonic clock and are sent in milliseconds. Symfony's peak heap measurements have no direct Go equivalent, so their required protocol fields are zero. `StopTime("")` resets all timers. Callback panics are not intercepted.

Limiting output
-----------------------------------------------------------------------------------------------------

### Limiting the number of sent payloads

To limit the number of requests sent by a particular callsite, use `Limit`. It works well for debugging loops.

```
for i := 0; i < 10; i++ {
    client.Entry(ctx).Limit(3).Send(i)
    client.Entry(ctx).Limit(6).Send(i)
}
```

If the limit is negative or zero, limiting is disabled. Every chained request, including colors and labels, consumes one allowance. The first limit configured at a source location is retained for that client's lifetime.

### Using a rate limiter

A rate limiter reduces the number of sent requests. Configure it on the client:

```
client.Max(10)
client.PerSecond(10)
client.Send(ctx, "limited output")
client.ClearRateLimits()
```

Zero permits no requests. A negative value disables the selected rate limit. Per-second limits use a sliding one-second window. Ray receives one notification when a limit is reached. A successful window recovery allows another notification later. Failed network attempts also consume allowances.

### Sending a payload once

To only send a payload once from a source location, use `Once`. It accepts optional values, or limits the next chained request.

```
for i := 0; i < 10; i++ {
    client.Entry(ctx).Once(i)
    client.Entry(ctx).Once().HTML("<strong>Once</strong>")
}
```

Conditional output
--------------------------------------------------------------------------------------------------------------

### Conditionally showing items

`ShowIf` removes the entry when its condition is false. `RemoveWhen` removes it when its condition is true. Use normal Go expressions and functions to evaluate conditions.

```
client.Send(ctx, "will be shown").ShowIf(true)
client.Send(ctx, "will be removed").RemoveWhen(true)
```

### Conditionally sending items to Ray

Use `When` to gate all following sends. A later call replaces the gate. A callback does not change the gate for following methods.

```
client.Entry(ctx).When(false).Text("not sent").When(true).Text("sent")
client.Send(ctx, "value").When(true, func(entry *ray.Entry) {
    entry.Large()
}).Green()
```

Handling exceptions
-----------------------------------------------------------------------------------------------------------------

### Displaying errors

You can display information about a Go error in Ray with `Exception`. It sends the error type, message, metadata and an observation-site stack, then colors the entry red. Nil errors are ignored.

```
client.Entry(ctx).Exception(errors.New("test"), map[string]any{"job": "import"})
```

This example also imports `errors`. Go errors do not contain PHP throw-site snippets. Handle errors and panics with normal Go control flow. This library does not defer errors until shutdown or silently catch panics.

Updating and removing items
-----------------------------------------------------------------------------------------------------------------------------------------

### Updating displayed items

You can update values that are already displayed in Ray. Hold on to the returned entry and call `Send` on it.

```
entry := client.Send(ctx, "counting down!")
for number := 10; number > 0; number-- {
    entry.Send(number)
}
entry.Red().Large()
```

All updates use the same UUID. Calling `client.Entry` or `client.Send` starts a new entry. Clients are safe to share between goroutines, but individual mutable entries are not. Share the client and create an entry per goroutine.

### Removing items

To remove an item that is already displayed in Ray, call `Remove` on the returned entry. Use `Hide` to collapse it instead.

```
entry := client.Send(ctx, "will be removed")
entry.Remove()
```

Execution control
-----------------------------------------------------------------------------------------------------------

### Pausing execution

You can pause the current goroutine by using `Pause`. Press Continue in Ray to resume. Stop execution returns `ray.ErrStopExecutionRequested`. Propagate it to stop your operation. The library never kills your process.

```
err := client.Entry(ctx).Pause().Err()
if errors.Is(err, ray.ErrStopExecutionRequested) {
    log.Print("Stopped from Ray")
}
```

`Pause` polls once per second. Pass a cancellable context to avoid waiting indefinitely. Disabled, gated or limited entries do not poll locks. Network failure resumes execution in best-effort mode. Set `ReportErrors` to report it. The client never calls `os.Exit`, and there is no `die` or `rd` equivalent.

Flow helpers
--------------------------------------------------------------------------------------------

### Returning items

To send something to Ray and return that same typed value, use the generic `Pass` function. This is handy when debugging return values.

```
value, err := ray.Pass(ctx, client, "return value")
log.Print(value, err)
```

Custom functions
--------------------------------------------------------------------------------------------------------

Use ordinary Go functions instead of dynamically registered PHP macros. `SendCustom` displays custom content and a label. `SendRequest` accepts protocol payloads and metadata. See [configuration](configuration) for custom transport, payload selection, origin factories and request hooks.

```
client.Entry(ctx).SendCustom("my custom content", "hey")
client.Entry(ctx).SendRequest([]ray.Payload{
    {Type: "custom", Content: map[string]any{"content": "extension", "label": "Custom"}},
}, map[string]any{"source": "my package"})
```

Managing the Ray app
--------------------------------------------------------------------------------------------------------------------

### Creating a new screen

You can use `NewScreen` or `ClearScreen` to programmatically create a new screen. Your previous messages are automatically saved and moved to the message archive. Pass an empty name for an unnamed screen.

```
client.Entry(ctx).NewScreen("")
client.Entry(ctx).NewScreen("My debug screen")
client.Entry(ctx).ClearScreen()
client.Entry(ctx).ClearAll()
client.Entry(ctx).ScreenGreen()
```

`ClearAll` also clears previous screens. Other screen color helpers are `ScreenOrange`, `ScreenRed`, `ScreenPurple`, `ScreenBlue` and `ScreenGray`.

### Showing and hiding the app

You can show and hide the Ray app via code. `Windows` and `Theme` query the app and return its raw JSON response. Query errors are always reported.

```
client.Entry(ctx).ShowApp()
client.Entry(ctx).HideApp()
windows, err := client.Windows(ctx)
log.Print(string(windows), err)
theme, err := client.Theme(ctx)
log.Print(string(theme), err)
```

### Enabling and disabling Ray

You can enable and disable sending stuff to Ray with `Enable` and `Disable`. This affects all entries sharing the same client, not separately constructed clients.

```
client.Send(ctx, "one")
client.Disable()
client.Send(ctx, "two")
client.Enable()
client.Send(ctx, "three")
log.Print(client.Enabled())
```

Fun stuff
-----------------------------------------------------------------------------------

### Displaying a notification

You can use Ray to display a system notification.

```
client.Entry(ctx).Notify("This is my notification")
```

### Shooting confetti

For those times when success is to be celebrated.

```
client.Entry(ctx).Confetti()
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
