---
source_url: https://www.pubnub.com/docs/sdks/go/api-reference/storage-and-playback
title: Message Persistence API for Go SDK
updated_at: 2026-06-19T11:37:25.390Z
sdk_name: PubNub Go SDK
sdk_version: v9.0.1
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Message Persistence API for Go SDK

PubNub Go SDK, use the latest version: v9.0.1

Install:

```bash
go get github.com/pubnub/go/v9@v9.0.1
```

Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see [Message Persistence](https://www.pubnub.com/docs/general/storage).

You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.

You can retrieve the following:

* Messages
* Message reactions
* Files (using the File Sharing API)

## Fetch history

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Fetch historical messages from one or multiple channels. The `includeMessageActions` flag also allows you to fetch message actions along with the messages.

You can control how messages are returned and in what order:

* If you specify only the `start` parameter (without `end`), you receive messages older than the `start` [timetoken](https://www.pubnub.com/docs/sdks/go/api-reference/misc#time).
* If you specify only the `end` parameter (without `start`), you receive messages from that `end` timetoken and newer.
* If you specify both `start` and `end`, you retrieve messages between those timetokens (inclusive of the `end` value).

You can receive up to 100 messages for a single channel, or 25 messages per channel when querying multiple channels (up to 500 channels). If more messages match the time range, make iterative calls and adjust the `start` timetoken to page through the results.

### Method(s)

To run `Fetch History`, you can use the following method(s) in the Go SDK:

```go
pn.Fetch().
    Channels(channels).
    Count(count).
    Start(start).
    End(end).
    IncludeMeta(bool).
    IncludeMessageType(bool).
    IncludeUUID(bool).
    IncludeMessageActions(bool).
    IncludeCustomMessageType(bool).
    QueryParam(queryParam).
    Execute()
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| Channels | string | Yes |  | Specifies `channels`to return history messages. Maximum of 500 channels are allowed. |
| Count | int | Optional | `100 or 25` | Specifies the number of historical messages to return. Default and maximum value is 100 for a single channel, 25 for multiple channels, and 25 when `IncludeMessageActions` is `true`. |
| Start | int64 | Optional |  | Timetoken delimiting the `start` of time slice (exclusive) to pull messages from. |
| End | int64 | Optional |  | Timetoken delimiting the `end` of time slice (inclusive) to pull messages from. |
| IncludeMeta | bool | Optional | `false` | Whether meta (passed when Publishing the message) should be included in response or not. |
| IncludeMessageType | bool | Optional | `true` | Pass `true` to receive the message type with each history message. |
| IncludeUUID | bool | Optional | `true` | Pass `true` to receive the publisher `uuid` with each history message. |
| IncludeMessageActions | bool | Optional | `false` | Whether MessageActions should be included in response or not. If `true`, the method is limited to one channel and 25 messages only. |
| IncludeCustomMessageType | bool | Optional |  | Indicates whether to retrieve messages with the custom message type. For more information, refer to [Retrieving Messages](https://www.pubnub.com/docs/general/storage#retrieving-messages). |
| QueryParam | map[string]string | Optional | `nil` | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |

:::note Truncated response
If you fetch messages with message actions, the response may be truncated when internal limits are reached. If truncated, a `more` property is returned with additional parameters. Make iterative calls to history, adjusting the parameters to fetch more messages.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

Retrieve the last messages on a channel:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchHistoryBasic demonstrates fetching message history from a single channel
func Example_fetchHistoryBasic() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo" // Replace with your subscribe key
	config.PublishKey = "demo"   // Replace with your publish key

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Fetch message history from a channel
	response, status, err := pn.Fetch().
		Channels([]string{"my-go-channel"}).
		Count(10). // Maximum number of messages to retrieve
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Printf("Retrieved messages from history:\n")
		// Print the messages
		// Log the fetched messages
		for channel, messages := range response.Messages {
			fmt.Printf("Channel: %s\n", channel)
			for _, message := range messages {
				fmt.Printf("Message: %v, Timetoken: %v\n", message.Message, message.Timetoken)
			}
		}
	}
}
```

### Returns

The `Fetch()` operation returns a `FetchResponse` object which contains the following field:

| Field | Type | Description |
| --- | --- | --- |
| `Messages` | map[string][]FetchResponseItem | Map where keys are channel names and values are arrays of message items. |

Each `FetchResponseItem` contains:

| Field | Type | Description |
| --- | --- | --- |
| `Message` | interface | Message from history. |
| `Timetoken` | string | Timetoken of the message. |
| `Meta` | interface | The metadata (if sent with the message). |
| `MessageType` | int | Message type. Returns `4` for file messages. |
| `UUID` | string | Publisher UUID of the message. |
| `MessageActions` | map[string]PNHistoryMessageActionsTypeMap | Message actions associated with the message. Details of type `PNHistoryMessageActionsTypeMap` are [described below](#pnhistorymessageactionstypemap). |
| `File` | PNFileDetails | File details if the message contains a file. |
| `Error` | error | Decryption error if message couldn't be decrypted. |

#### PNHistoryMessageActionsTypeMap

| Field | Type | Description |
| --- | --- | --- |
| `ActionsTypeValues` | map[string][]PNHistoryMessageActionTypeVal | Details of type `PNHistoryMessageActionTypeVal` are [described below](#pnhistorymessageactiontypeval). |

#### PNHistoryMessageActionTypeVal

| Field | Type | Description |
| --- | --- | --- |
| `UUID` | string | The UUID of the publisher. |
| `ActionTimetoken` | string | The publish timetoken of the action. |

### Status response

| Field | Type | Description |
| --- | --- | --- |
| `Error` | error | Error information, if any |
| `Category` | StatusCategory | Status category of the operation |
| `Operation` | OperationType | Operation type |
| `StatusCode` | int | HTTP status code |
| `TLSEnabled` | bool | Whether TLS is enabled |
| `UUID` | string | UUID of the client |
| `AuthKey` | string | Auth key used |
| `Origin` | string | Origin server |
| `OriginalResponse` | string | Raw response from server |
| `Request` | string | Request that was sent |
| `AffectedChannels` | []string | Channels affected by this operation |
| `AffectedChannelGroups` | []string | Channel groups affected by this operation |

### Other examples

#### Fetch with metadata

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchWithMetadata demonstrates fetching history with message metadata
func Example_fetchWithMetadata() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Fetch history including metadata
	response, status, err := pn.Fetch().
		Channels([]string{"my-channel"}).
		Count(10).
		IncludeMeta(true). // Include metadata for each message
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		// Get messages for the channel
		if messages, ok := response.Messages["my-channel"]; ok {
			fmt.Printf("Retrieved %d messages\n", len(messages))
			// Access message metadata
			for _, msg := range messages {
				fmt.Printf("Message: %v, Metadata: %v\n", msg.Message, msg.Meta)
			}
		}
	}
}
```

#### Fetch with time range

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"time"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchWithTimeRange demonstrates fetching history within a specific time range
func Example_fetchWithTimeRange() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Get a timetoken before publishing
	timeResp, _, _ := pn.Time().Execute()
	startTime := timeResp.Timetoken

	// Publish test messages
	pn.Publish().Channel("my-channel").Message("Message 1").Execute()
	pn.Publish().Channel("my-channel").Message("Message 2").Execute()
	pn.Publish().Channel("my-channel").Message("Message 3").Execute()

	// Get a timetoken after publishing
	timeResp2, _, _ := pn.Time().Execute()
	endTime := timeResp2.Timetoken
	time.Sleep(2 * time.Second) // Wait for messages to be stored

	// Fetch history within a specific time range
	response, status, err := pn.Fetch().
		Channels([]string{"my-channel"}).
		Start(int64(startTime)). // Start timetoken
		End(int64(endTime)).     // End timetoken
		Count(100).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		// Get messages for the channel
		if messages, ok := response.Messages["my-channel"]; ok {
			fmt.Printf("Retrieved %d messages within time range\n", len(messages))
		}
	}

	// Output:
	// Retrieved 3 messages within time range
}
```

#### Fetch from multiple channels

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchMultipleChannels demonstrates fetching history from multiple channels at once
func Example_fetchMultipleChannels() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Fetch history from multiple channels simultaneously
	response, status, err := pn.Fetch().
		Channels([]string{"channel-1", "channel-2", "channel-3"}). // Multiple channels
		Count(25).                                                 // Max 25 messages per channel when using multiple channels
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Printf("Retrieved messages from history:\n")
		// Print the messages
		// Log the fetched messages
		for channel, messages := range response.Messages {
			fmt.Printf("Channel: %s\n", channel)
			for _, message := range messages {
				fmt.Printf("Message: %v, Timetoken: %v\n", message.Message, message.Timetoken)
			}
		}
	}
}
```

## Delete messages from history

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Remove messages from the history of a specific channel.

:::note Required setting
To accept delete-from-history requests, enable the `Delete-From-History` setting for your key in the Admin Portal and initialize the SDK with a secret key.
:::

### Method(s)

To `Delete Messages from History` you can use the following method(s) in the Go SDK.

```go
pn.DeleteMessages().
    Channel(channel).
    Start(start).
    End(end).
    QueryParam(queryParam).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `Channel` *Type: string | Specifies `channels` to delete messages from. |
| `Start`Type: int64 | Timetoken delimiting the `start` of time slice (inclusive) to delete messages from. |
| `End`Type: int64 | Timetoken delimiting the `end` of time slice (exclusive) to delete messages from. |
| `QueryParam`Type: map[string]string | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |

### Sample code

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"time"

	pubnub "github.com/pubnub/go/v9"
)

// Example_deleteMessagesTimeRange demonstrates deleting messages within a specific time range
func Example_deleteMessagesTimeRange() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExamplePAMConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Publish test messages

	timeBeforeFirstMessage := time.Now().UnixMilli()

	pn.Publish().Channel("my-channel").Message("Message 1").Execute()
	pn.Publish().Channel("my-channel").Message("Message 2").Execute()
	pn.Publish().Channel("my-channel").Message("Message 3").Execute()

	timeAftereLastMessage := time.Now().UnixMilli()

	// Delete messages within a specific time range
	_, status, err := pn.DeleteMessages().
		Channel("my-channel").
		Start(int64(timeAftereLastMessage)). // Start timetoken is the most recent time from where to delete messages
		End(int64(timeBeforeFirstMessage)).  // End timetoken is the oldest time from where to delete messages
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Println("Messages in time range deleted successfully")
	}

	// Output:
	// Messages in time range deleted successfully
}
```

### Returns

The `DeleteMessages()` operation returns an empty `HistoryDeleteResponse` struct. Check the status response to verify success.

### Status response

| Field | Type | Description |
| --- | --- | --- |
| `Error` | error | Error information, if any |
| `Category` | StatusCategory | Status category of the operation |
| `Operation` | OperationType | Operation type |
| `StatusCode` | int | HTTP status code |
| `TLSEnabled` | bool | Whether TLS is enabled |
| `UUID` | string | UUID of the client |
| `AuthKey` | string | Auth key used |
| `Origin` | string | Origin server |
| `OriginalResponse` | string | Raw response from server |
| `Request` | string | Request that was sent |
| `AffectedChannels` | []string | Channels affected by this operation |
| `AffectedChannelGroups` | []string | Channel groups affected by this operation |

### Other examples

#### Delete specific message from history

To delete a specific message, pass the `publish timetoken` (received from a successful publish) in the `End` parameter and `timetoken +/- 1` in the `Start` parameter. For example, if `15526611838554310` is the `publish timetoken`, pass `15526611838554309` in `Start` and `15526611838554310` in `End` parameters respectively as shown in the following code snippet.

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_deleteMessages demonstrates deleting messages from channel history
func Example_deleteMessages() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExamplePAMConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Delete all messages from a channel's history
	_, status, err := pn.DeleteMessages().
		Channel("my-channel").
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Println("Messages deleted successfully")
	}

	// Output:
	// Messages deleted successfully
}
```

## Message counts

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Return the number of messages published on one or more channels since a given time. The `count` is the number of messages in history with a timetoken greater than or equal to the value passed in `ChannelsTimetoken`.

:::note Unlimited message retention
For keys with unlimited message retention enabled, this method considers only messages published in the last 30 days.
:::

### Method(s)

You can use the following method(s) in the Go SDK:

```go
pn.MessageCounts().
    Channels(channels).
    ChannelsTimetoken(channelsTimetoken).
    QueryParam(queryParam).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `Channels` *Type: []stringDefault: n/a | The `channels` to fetch the message count |
| `ChannelsTimetoken` *Type: []int64Default: `nil` | Array of `timetokens`, in order of the channels list. Specify a single `timetoken` to apply it to all channels. Otherwise, the list of `timetokens` must be the same length as the list of channels, or the function returns a `PNStatus` with an error flag. |
| `QueryParam`Type: map[string]stringDefault: `nil` | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |

### Sample code

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_messageCounts demonstrates getting message counts for channels
func Example_messageCounts() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Get count of messages published since a specific timetoken
	response, status, err := pn.MessageCounts().
		Channels([]string{"my-channel"}).
		ChannelsTimetoken([]int64{17300000000000000}). // Count messages since this timetoken
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Println("Message counts retrieved successfully")
		for channel, count := range response.Channels {
			fmt.Printf("Channel: %s, Count: %d\n", channel, count)
		}
	}
}
```

### Returns

The `MessageCounts()` operation returns a `MessageCountsResponse` object which contains the following field:

| Field | Type | Description |
| --- | --- | --- |
| `Channels` | map[string]int | Channel names with message counts. Channels without messages have a count of 0. Channels with 10,000 messages or more have a count of 10000. |

### Status response

| Field | Type | Description |
| --- | --- | --- |
| `Error` | error | Error information, if any |
| `Category` | StatusCategory | Status category of the operation |
| `Operation` | OperationType | Operation type |
| `StatusCode` | int | HTTP status code |
| `TLSEnabled` | bool | Whether TLS is enabled |
| `UUID` | string | UUID of the client |
| `AuthKey` | string | Auth key used |
| `Origin` | string | Origin server |
| `OriginalResponse` | string | Raw response from server |
| `Request` | string | Request that was sent |
| `AffectedChannels` | []string | Channels affected by this operation |
| `AffectedChannelGroups` | []string | Channel groups affected by this operation |

### Other examples

#### Retrieve count of messages using different timetokens for each channel

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_messageCountsMultiple demonstrates getting message counts for multiple channels
func Example_messageCountsMultiple() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Get count of messages published since a specific timetoken
	response, status, err := pn.MessageCounts().
		Channels([]string{"my-channel", "my-channel-1"}).
		ChannelsTimetoken([]int64{17300000000000000}). // Count messages since this timetoken
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Println("Message counts retrieved successfully")
		for channel, count := range response.Channels {
			fmt.Printf("Channel: %s, Count: %d\n", channel, count)
		}
	}
}
```

## History (deprecated)

:::warning Requires Message Persistence
Enable Message Persistence for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

:::note Alternative method
This method is deprecated. Use [fetch history](#fetch-history) instead.
:::

This function fetches historical messages of a channel.

It is possible to control how messages are returned and in what order, for example you can:

* Search for messages starting on the newest end of the timeline (default behavior - `Reverse` = `false`)
* Search for messages from the oldest end of the timeline by setting `Reverse` to `true`.
* Page through results by providing a `Start` OR `End` timetoken.
* Retrieve a *slice* of the time line by providing both a `Start` AND `End` timetoken.
* Limit the number of messages to a specific quantity using the `Count` parameter.

:::tip Start & End parameter usage clarity
If only the `Start` parameter is specified (without `End`), you will receive messages that are **older** than and up to that `Start` timetoken value. If only the `End` parameter is specified (without `Start`) you will receive messages that match that `End` timetoken value and **newer**. Specifying values for both `Start` *and* `End` parameters will return messages between those timetoken values (inclusive on the `End` value). Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the `Start` timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
:::

### Method(s)

To run `History` you can use the following method(s) in the Go SDK:

```go
pn.History().
    Channel(string).
    Reverse(bool).
    IncludeTimetoken(bool).
    IncludeMeta(bool).
    Start(int64).
    End(int64).
    Count(int).
    QueryParam(queryParam).
    Execute()
```

| Parameter | Description |
| --- | --- |
| `Channel`Type: stringDefault: n/a | Specifies `channel` to return history messages from. |
| `Reverse`Type: boolDefault: `false` | Setting to true will traverse the time line in reverse starting with the oldest message first. |
| `IncludeTimetoken`Type: boolDefault: `false` | Whether event dates timetokens should be included in response or not. |
| `IncludeMeta`Type: boolDefault: `false` | Whether meta (passed when Publishing the message) should be included in response or not. |
| `Start`Type: int64Default: n/a | Timetoken delimiting the start of time slice (exclusive) to pull messages from. |
| `End`Type: int64Default: n/a | Timetoken delimiting the end of time slice (inclusive) to pull messages from. |
| `Count`Type: intDefault: 100 | Specifies the number of historical messages to return. |
| `QueryParam`Type: map[string]stringDefault: `nil` | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |

:::tip
Using the
reverse
parameter
Messages are always returned sorted in ascending time direction from history regardless of `Reverse`. The `Reverse` direction matters when you have more than 100 (or `Count`, if it's set) messages in the time interval, in which case `Reverse` determines the end of the time interval from which it should start retrieving the messages.
:::

### Sample code

Retrieve the last 100 messages on a channel:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_historyDeprecated demonstrates using the deprecated History API
// Note: For new code, use Fetch() instead as it provides more features
func Example_historyDeprecated() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Use the deprecated History API (single channel only)
	response, status, err := pn.History().
		Channel("history-channel").
		Count(10).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		fmt.Printf("Retrieved %d messages using History API\n", len(response.Messages))
		for _, msg := range response.Messages {
			fmt.Printf("Message: %v\n", msg.Message)
		}
	}
}
```

### Returns

The `History()` operation returns a `HistoryResponse` object which contains the following fields:

| Field | Type | Description |
| --- | --- | --- |
| `Messages` | []HistoryResponseItem | Array of messages. See [HistoryResponseItem](#historyresponseitem) for more details. |
| `StartTimetoken` | int64 | Start timetoken of the returned messages. |
| `EndTimetoken` | int64 | End timetoken of the returned messages. |

#### HistoryResponseItem

| Field | Type | Description |
| --- | --- | --- |
| `Timetoken` | int64 | Timetoken of the message. |
| `Message` | interface | The message content. |
| `Meta` | interface | The metadata (if sent when publishing the message). |
| `Error` | error | Decryption error if message couldn't be decrypted. |

### Status response

| Field | Type | Description |
| --- | --- | --- |
| `Error` | error | Error information, if any |
| `Category` | StatusCategory | Status category of the operation |
| `Operation` | OperationType | Operation type |
| `StatusCode` | int | HTTP status code |
| `TLSEnabled` | bool | Whether TLS is enabled |
| `UUID` | string | UUID of the client |
| `AuthKey` | string | Auth key used |
| `Origin` | string | Origin server |
| `OriginalResponse` | string | Raw response from server |
| `Request` | string | Request that was sent |
| `AffectedChannels` | []string | Channels affected by this operation |
| `AffectedChannelGroups` | []string | Channel groups affected by this operation |

### Other examples

#### Use history() to retrieve the three oldest messages

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchOldestMessages demonstrates retrieving the three oldest messages
func Example_fetchOldestMessages() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Fetch the three oldest messages
	response, status, err := pn.Fetch().
		Channels([]string{"history-channel"}).
		Count(3).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		if messages, ok := response.Messages["history-channel"]; ok {
			fmt.Printf("Retrieved %d oldest messages\n", len(messages))
		}
	}
}
```

#### Use history() to retrieve messages newer than a given timetoken

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchNewerThanTimetoken demonstrates retrieving messages newer than a given timetoken
func Example_fetchNewerThanTimetoken() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Fetch messages newer than the specified timetoken
	response, status, err := pn.Fetch().
		Channels([]string{"history-channel"}).
		Count(100).
		End(int64(15343325004275466)). // Get messages from this timetoken and newer
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		if messages, ok := response.Messages["history-channel"]; ok {
			fmt.Printf("Retrieved %d messages newer than timetoken\n", len(messages))
		}
	}
}
```

#### Use history() to retrieve messages until a given timetoken

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchUntilTimetoken demonstrates retrieving messages until a given timetoken
func Example_fetchUntilTimetoken() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Fetch messages until (older than) the specified timetoken
	response, status, err := pn.Fetch().
		Channels([]string{"history-channel"}).
		Count(100).
		Start(int64(15343325004275466)). // Get messages older than this timetoken
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		if messages, ok := response.Messages["history-channel"]; ok {
			fmt.Printf("Retrieved %d messages until timetoken\n", len(messages))
		}
	}
}
```

#### History paging example

```go
// Example_fetchPaging demonstrates paging through message history
func Example_fetchPaging() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	// Publish some test messages for paging demonstration
	pn := pubnub.NewPubNub(config)
	for i := 1; i <= 5; i++ {
		pn.Publish().
			Channel("history-channel").
			Message(fmt.Sprintf("Test message %d", i)).
			Execute()
	}
	time.Sleep(2 * time.Second)

	// Get the first batch of messages
	response, status, err := pn.Fetch().
		Channels([]string{"history-channel"}).
		Count(2).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	var totalMessages int
	if status.StatusCode == 200 {
		if messages, ok := response.Messages["history-channel"]; ok {
			totalMessages += len(messages)
			fmt.Printf("First page: %d messages\n", len(messages))

			// Get the next page using the first message's timetoken
			if len(messages) > 0 {
				firstTimetokenStr := messages[0].Timetoken
				firstTimetoken, _ := strconv.ParseInt(firstTimetokenStr, 10, 64)

				// Fetch next batch ending before the first timetoken
				response2, status2, err2 := pn.Fetch().
					Channels([]string{"history-channel"}).
					Count(2).
					Start(firstTimetoken). // Get messages older than first message
					Execute()

				if err2 != nil {
					fmt.Printf("Error: %v\n", err2)
					return
				}

				if status2.StatusCode == 200 {
					if messages2, ok2 := response2.Messages["history-channel"]; ok2 {
						totalMessages += len(messages2)
						fmt.Printf("Second page: %d messages\n", len(messages2))
					}
				}
			}
		}
		fmt.Printf("Total messages retrieved: %d\n", totalMessages)
	}

	// Output:
	// First page: 2 messages
	// Second page: 2 messages
	// Total messages retrieved: 4
}
```

#### Include timetoken in history response

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_fetchWithTimetoken demonstrates that Fetch includes timetokens by default
func Example_fetchWithTimetoken() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)

	// Fetch() includes timetoken in response by default
	response, status, err := pn.Fetch().
		Channels([]string{"history-channel"}).
		Count(10).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 {
		if messages, ok := response.Messages["history-channel"]; ok {
			fmt.Printf("Retrieved %d messages with timetokens\n", len(messages))
			// Each message includes a Timetoken field
			for _, msg := range messages {
				// Access msg.Timetoken for each message
				_ = msg.Timetoken
			}
		}
	}
}
```

## Terms in this document

* **Message** - A unit of data transmitted between clients or between a client and a server in PubNub, containing information such as text, binary data, or structured data formats like JSON. Messages are sent over channels and can be tracked for delivery and read status.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.