Usage | calendar-links-go | Spatie       

 SPATIE  

calendar-links-go
=================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Calendar-links-go](https://spatie.be/docs/calendar-links-go/v1)  Usage

 Version   v1      

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

  Usage    
- [ Introduction ](https://spatie.be/docs/calendar-links-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/calendar-links-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/calendar-links-go/v1/usage)
- [ Testing ](https://spatie.be/docs/calendar-links-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/calendar-links-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/calendar-links-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/calendar-links-go/v1/support-us)

 Usage
=====

###  On this page 

1. [ All-day events ](#content-all-day-events)
2. [ Separate start and end timezones ](#content-separate-start-and-end-timezones)
3. [ Guests ](#content-guests)
4. [ Yahoo parameters ](#content-yahoo-parameters)
5. [ ICS options ](#content-ics-options)
6. [ Recurring events and timezones ](#content-recurring-events-and-timezones)
7. [ Extending a generator ](#content-extending-a-generator)

```
zone, err := time.LoadLocation("Europe/Brussels")
if err != nil {
	return err
}
from := time.Date(2027, 3, 15, 10, 0, 0, 0, zone)
to := time.Date(2027, 3, 15, 17, 0, 0, 0, zone)
link, err := calendarlinks.New("Birthday party", from, to)
if err != nil {
	return err
}
link.Description = "A full day of hands-on testing. Bring a laptop."
link.Address = "Samberstraat 69D, 2060 Antwerp, Belgium"

// A link that creates the event on Google calendar
fmt.Println(link.Google())

// A link that creates the event on Yahoo calendar
fmt.Println(link.Yahoo())

// A link that creates the event on outlook.live.com
fmt.Println(link.WebOutlook())

// A link that creates the event on outlook.cloud.microsoft
fmt.Println(link.WebOffice())

// A data URI holding an ICS file, for iCal, Apple Calendar and Outlook
uri, err := link.ICS()
if err != nil {
	return err
}
fmt.Println(uri)

// The raw ICS body instead of a data URI, to attach to an email as a file
body, err := link.FormatWith(calendarlinks.ICS{Format: calendarlinks.FormatFile})
if err != nil {
	return err
}
fmt.Println(body)
```

These snippets run inside a function returning `error`. Import `fmt`, `time`, and `calendarlinks "github.com/spatie/calendar-links-go"`. Later examples reuse `link`, `from` and `zone` from above.

`Google()` produces:

```
https://calendar.google.com/calendar/render?action=TEMPLATE&dates=20270315T100000/20270315T170000&ctz=Europe/Brussels&text=Birthday+party&details=A+full+day+of+hands-on+testing.+Bring+a+laptop.&location=Samberstraat+69D%2C+2060+Antwerp%2C+Belgium
```

and `FormatFile` produces:

```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:Spatie calendar-links
BEGIN:VEVENT
UID:520cbd9fe520170f6d0a29e400ac4117
SUMMARY:Birthday party
DTSTAMP:20270315T090000Z
DTSTART:20270315T090000Z
DTEND:20270315T160000Z
DESCRIPTION:A full day of hands-on testing. Bring a laptop.
LOCATION:Samberstraat 69D\, 2060 Antwerp\, Belgium
END:VEVENT
END:VCALENDAR
```

All-day events
--------------------------------------------------------------------------------------------------

Use `NewAllDay()` for a number of days, or `NewAllDayRange()` for inclusive start and end dates. The stored end is exclusive, as calendar services expect.

```
holiday, err := calendarlinks.NewAllDay("Holiday", from, 5)
if err != nil {
	return err
}
fmt.Println(holiday.Google())

holiday, err = calendarlinks.NewAllDayRange("Holiday",
	time.Date(2027, 3, 15, 0, 0, 0, 0, zone),
	time.Date(2027, 3, 19, 0, 0, 0, 0, zone))
if err != nil {
	return err
}
fmt.Println(holiday.Google())
```

An all-day event has calendar dates, not instants. `NewAllDayRange()` reads the date each caller wrote, without gaining or losing a day through timezone conversion. It discards clock times. `NewAllDay()` keeps the start's clock time internally, matching PHP's day-count factory. Both advance calendar days rather than adding 24-hour durations, so daylight saving does not change the requested dates. Zero or negative day counts return `ErrInvalidDayCount`.

Separate start and end timezones
--------------------------------------------------------------------------------------------------------------------------------------------------------

Most events start and end in the same place. Some do not, and a flight is the obvious case. Pass a date in each zone and the difference is kept:

```
tokyo, err := time.LoadLocation("Asia/Tokyo")
if err != nil {
	return err
}
losAngeles, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
	return err
}
flight, err := calendarlinks.New("NH 106 Tokyo to Los Angeles",
	time.Date(2027, 3, 15, 9, 0, 0, 0, tokyo),
	time.Date(2027, 3, 15, 9, 30, 0, 0, losAngeles))
if err != nil {
	return err
}
fmt.Println(flight.Google())
```

Google names each end with `stz` and `etz`, which take priority over `ctz`, so `ctz` is left out:

```
https://calendar.google.com/calendar/render?action=TEMPLATE&dates=20270315T090000/20270315T093000&stz=Asia/Tokyo&etz=America/Los_Angeles&text=NH+106+Tokyo+to+Los+Angeles
```

The ICS file names them with `TZID`, instead of flattening both ends to UTC:

```
DTSTAMP:20270315T000000Z
DTSTART;TZID=Asia/Tokyo:20270315T090000
DTEND;TZID=America/Los_Angeles:20270315T093000
```

`DTStamp` stays in UTC, as RFC 5545 requires. Each zone named this way also gets its own `VTIMEZONE` component, placed before the event and holding the offsets in force around it, so the file stands on its own for a client that does not resolve bare IANA names, such as older Outlook desktop.

The component lists every change the zone makes in the year either side of the event. The last change of each kind carries a yearly recurrence rule whenever the zone repeats it on a fixed weekday of a fixed month. Six later years are checked before writing a rule. A zone that moves its clocks on dates that do not repeat that way, such as Africa/Casablanca's Ramadan changes, is written without a guessed rule. There the listed window is all a client has to go on.

To retain named timezones even when both endpoints share a zone, use `ICSWithTimezones()` or set `WithTimezones` on the generator:

```
uri, err := link.ICSWithTimezones()
if err != nil {
	return err
}
fmt.Println(uri)

rule := "FREQ=WEEKLY"
body, err := link.FormatWith(calendarlinks.ICS{
	Options: calendarlinks.ICSOptions{RRule: &rule},
	Format: calendarlinks.FormatFile,
	WithTimezones: true,
})
if err != nil {
	return err
}
fmt.Println(body)
```

It names resolvable zones including `UTC` and regions without daylight saving such as `Asia/Tokyo`. All-day events remain date-only. Other calendar generators are unaffected.

Both ends must be resolvable. If either one is not, the pair is written in UTC together, since naming only one end would leave the other to be read in whichever zone the viewer sits in.

`ICSWithTimezones()` has one additional fallback. When either endpoint is the second occurrence of a repeated local time after clocks move backward, both endpoints are written in UTC without `VTIMEZONE`. RFC 5545 interprets a local time with `TZID` as the first occurrence, so naming the zone there would change the supplied instant. This applies to half-hour and date-line rollbacks too. A recurrence using this fallback repeats in UTC, not local wall time. The default `ICS()` preserves PHP's legacy policy, including for repeated times.

`link.To()` is normalized into `link.From()`'s zone, so the two are directly comparable. The original zones are available through `FromTimezone()` and `ToTimezone()`. Equal offsets alone do not collapse two places such as London and Lisbon. A plain offset matching a named zone does not need a second timezone name.

Guests
--------------------------------------------------------------------------

Every generator can invite guests, with a required or optional role:

```
if err := link.AddGuest("freek@example.com", false); err != nil {
	return err
}
if err := link.AddGuests([]string{"ruben@example.com", "alex@example.com"}, false); err != nil {
	return err
}
if err := link.AddGuest("willem@example.com", true); err != nil {
	return err
}
```

An address that is already on the list is ignored, compared without regard to case, so the first spelling and role you gave a guest are the ones that are kept. `AddGuests()` validates the entire batch before adding anyone. `Guests()` returns a copy of the guest list.

Each service spells the same thing differently:

GeneratorRequiredOptionalGoogle`add=``add=`, with an `_o` suffix on the addressWebOutlook / WebOffice`to=``cc=`Yahoo`inv_list=``inv_list=`. Yahoo has no optional role, so optional guests are invited as required onesICS`ATTENDEE;ROLE=REQ-PARTICIPANT``ATTENDEE;ROLE=OPT-PARTICIPANT`Only plain ASCII email addresses are accepted. Display names and quoted local parts return `ErrInvalidGuestEmail` because services cannot represent them consistently. Guests are emitted in addition to custom URL parameters. If you also pass `add`, `to`, `cc` or `inv_list` by hand, the parameter appears twice and the service decides which one wins.

Yahoo parameters
--------------------------------------------------------------------------------------------------------

`Yahoo()` takes extra query parameters:

```
fmt.Println(link.Yahoo(calendarlinks.Parameter{Key: "TYPE", Value: "7"}))
```

`TYPE` picks the event charm, as a zero based index into Yahoo's list of 17 charms. `0` is General, `7` is Birthday, and `13` is Phone.

Yahoo has no timezone parameter, so a timed event is sent as floating local time. An event created at 09:00 is composed as 09:00, whatever the reader's timezone. The end is rendered in the start timezone, including for flights.

A multi-day all-day event is composed as a timed event that runs from midnight on the first day to midnight on the exclusive end date. The dates and duration are right, only the all-day banner is missing. `DUR=allday` flips the all-day toggle, but Yahoo ignores `DUR` as soon as `ET` is present. Single-day all-day events need no `ET` and use `ST=<date>&DUR=allday`.

`Google()`, `WebOutlook()` and `WebOffice()` accept extra parameters in the same way. Repeat a key to send multiple values. An empty `Value` writes a bare flag without `=`. `Value: "0"` writes `=0`. Parameters retain insertion order. Go values are strings rather than PHP's mixed scalar arrays.

ICS options
-----------------------------------------------------------------------------------------

`ICSOptions` holds properties that are written into the file as RFC 5545 values:

```
uid := "workshop-2027-03-15"
eventURL := "https://example.com/events/birthday-party"
rule := "FREQ=WEEKLY;BYDAY=MO,WE,FR"
reminderDescription := "The workshop starts in 15 minutes"
body, err := link.FormatWith(calendarlinks.ICS{
	Options: calendarlinks.ICSOptions{
		UID: &uid,
		URL: &eventURL,
		RRule: &rule,
		Transparency: "TRANSPARENT",
		Class: "PRIVATE",
		Reminder: &calendarlinks.Reminder{Description: &reminderDescription},
	},
	Format: calendarlinks.FormatFile,
})
if err != nil {
	return err
}
fmt.Println(body)
```

OptionWhat it doesSpecification`UID`Identifies the event, so a later file carrying the same value updates it instead of creating a second one[section 3.8.4.7](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.4.7)`URL`Points at a page about the event[section 3.8.4.6](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.4.6)`ProdID`Names the product that wrote the file. Defaults to `Spatie calendar-links`[section 3.7.3](https://datatracker.ietf.org/doc/html/rfc5545#section-3.7.3)`DTStamp`When the event information was last revised. Takes a `*time.Time` and is written in UTC. Defaults to the event start[section 3.8.7.2](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.7.2)`Reminder`Adds an alarm. Use `&calendarlinks.Reminder{}` for 15 minutes before, or set `Description` and `Time`[section 3.6.6](https://datatracker.ietf.org/doc/html/rfc5545#section-3.6.6)`RRule`Repeats the event[section 3.8.5.3](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.5.3)`Transparency``OPAQUE` shows the time as busy, `TRANSPARENT` shows it as free[section 3.8.2.7](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.2.7)`Class`Visibility, either `PUBLIC`, `PRIVATE` or `CONFIDENTIAL`[section 3.8.1.3](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.1.3)`MicrosoftBusyStatus``FREE`, `TENTATIVE`, `BUSY` or `OOF`. Outlook needs this extension to show tentative or out of officeMS-OXCICAL`DTStamp` defaults to the event start rather than the moment the file is written, so the same `Link` always produces the same bytes and output stays cacheable. Pass your own value for revision semantics when importing the same `UID` twice:

```
uid := "workshop-2027-03-15"
stamp := time.Now()
body, err := link.FormatWith(calendarlinks.ICS{
	Options: calendarlinks.ICSOptions{UID: &uid, DTStamp: &stamp},
	Format: calendarlinks.FormatFile,
})
if err != nil {
	return err
}
fmt.Println(body)
```

`URL` and `RRule` are written verbatim, so they must be valid UTF-8 without control characters. `Transparency`, `Class` and `MicrosoftBusyStatus` take one of the ASCII tokens listed above in any case, and are written upper-cased. Empty token strings omit the property. `Class` deliberately accepts only those three, not the extension tokens RFC 5545 also permits. Invalid values return an error wrapping `ErrInvalidOption` when generating.

Route user-supplied text through the title argument, `Description` and `Address`, which are escaped for you. HTML tags are stripped from the ICS description, leaving their text and entities intact. Web calendar descriptions retain HTML. ICS TEXT values escape backslashes, commas, semicolons and newlines. Content lines fold at 75 octets without splitting a UTF-8 character, and end in CRLF.

Pointer options distinguish an absent property from an explicitly empty value. `Reminder.Time` is an absolute instant. Its absence uses a relative trigger fifteen minutes before the event. Dates and reminders are typed, so a misspelled type fails to compile rather than silently producing the default alarm.

The `Format` field controls presentation rather than content. `FormatHTML`, the default, returns a base64 data URI. `FormatFile` returns the raw ICS body. Other values return `ErrInvalidOption`.

Recurring events and timezones
--------------------------------------------------------------------------------------------------------------------------------------------------

A recurrence repeats the local time of its start, so the zone that time is read in decides where every later occurrence lands. `ICS()` names zones for events with distinct resolvable endpoint zones and recurrences in zones with clock changes. `ICSWithTimezones()` also names shared and fixed-offset regions, with or without an `RRule`. A named zone keeps a weekly 09:00 at 09:00 across daylight saving changes:

```
DTSTART;TZID=Europe/Warsaw:20260323T090000
DTEND;TZID=Europe/Warsaw:20260323T093000
RRULE:FREQ=WEEKLY
```

Recurring events with `WithTimezones: true` in `UTC` and fixed-offset regions such as `Asia/Tokyo` use the same named-zone representation. Bare offsets, unsupported abbreviations and second occurrences of repeated local times keep UTC endpoints on this opt-in path. `UNTIL` remains a UTC date-time for a timed recurrence. `BYHOUR`, `BYMINUTE` and `BYDAY` are interpreted in the timezone of `DTSTART`. The package validates safe serialization of an `RRule`, not its complete recurrence grammar.

Extending a generator
-----------------------------------------------------------------------------------------------------------------------

The generators cover the options that at least two services share. Everything else is deliberately left to custom generators. The ICS generator has two hooks for exactly that:

```
generator := calendarlinks.ICS{
	Format: calendarlinks.FormatFile,
	CalendarProperties: func(event *calendarlinks.Link) []string {
		return []string{"X-WR-CALNAME:" + calendarlinks.EscapeText(event.Title())}
	},
	EventProperties: func(event *calendarlinks.Link) []string {
		return []string{
			"CATEGORIES:" + calendarlinks.EscapeText("Workshops"),
			"STATUS:CONFIRMED",
		}
	},
}
body, err := link.FormatWith(generator)
if err != nil {
	return err
}
fmt.Println(body)
```

`CalendarProperties` adds properties at the `VCALENDAR` level, before timezone components. `EventProperties` adds them inside the event, before the alarm. Supply complete, already escaped property lines, not nested components. Use `EscapeText()` for TEXT values. These hooks return trusted generator output and are not a place for unchecked user input.

`WebGenerator` can target another endpoint with `BaseURL`, append ordered `Parameters`, and override value escaping with `EncodeValue`. `Encode(value, true)` matches Google's form encoding, while `Encode(value, false)` matches Yahoo and Outlook's percent encoding. For example:

```
url, err := link.FormatWith(calendarlinks.WebGenerator{
	Service: calendarlinks.Yahoo,
	BaseURL: "https://calendar.example/?v=60",
	Parameters: []calendarlinks.Parameter{{Key: "TYPE", Value: "7"}},
})
if err != nil {
	return err
}
fmt.Println(url)
```

A completely custom generator only needs to implement `Generate(*Link) (string, error)`. Functions can use `GeneratorFunc`:

```
result, err := link.FormatWith(calendarlinks.GeneratorFunc(func(event *calendarlinks.Link) (string, error) {
	return "event:" + event.Title(), nil
}))
if err != nil {
	return err
}
fmt.Println(result)
```

Generators receive the whole event through exported accessors. Compose a built-in generator and post-process its output, or replace it entirely. Go interfaces and hooks replace PHP subclassing. Errors from custom generators are returned unchanged.

Configure links and generators before sharing them. Concurrent rendering is safe when no caller mutates the link, its generator options or state captured by custom hooks.

 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)
