Usage | url-signer-go | Spatie       

 SPATIE  

url-signer-go
=============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Url-signer-go](https://spatie.be/docs/url-signer-go/v1)  Usage

 Version   v1      

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

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

 Usage
=====

###  On this page 

1. [ Generating URLs ](#content-generating-urls)
2. [ Validating URLs ](#content-validating-urls)
3. [ Custom keys and parameter names ](#content-custom-keys-and-parameter-names)
4. [ Writing custom signers ](#content-writing-custom-signers)
5. [ URL normalization and shared links ](#content-url-normalization-and-shared-links)
6. [ Testing the expiry boundary ](#content-testing-the-expiry-boundary)

```
import "github.com/spatie/url-signer-go"

signer, err := urlsigner.New("mysecretkey")
if err != nil {
    return err
}
```

A signer can sign URLs and validate signed URLs. A secret key is used to generate signatures. The snippets below belong inside a function returning an error, with `urlsigner` and standard-library `time` imported.

Generating URLs
-----------------------------------------------------------------------------------------------------

Signed URLs can be generated by providing a regular URL and an expiration date to the `SignUntil` method.

```
expirationDate := time.Now().Add(10 * 24 * time.Hour)

signedURL, err := signer.SignUntil("https://myapp.com", expirationDate)
if err != nil {
    return err
}

// The generated URL will be valid for 10 days.
```

Use `Sign` with a `time.Duration` for a relative lifetime. Unlike PHP's integer argument, a Go duration makes the unit explicit.

```
signedURL, err := signer.Sign("https://myapp.com", 30*time.Second)
if err != nil {
    return err
}

// The generated URL will be valid for 30 seconds.
```

Expirations have whole-second precision. Subsecond durations are truncated. Negative durations, past absolute expirations and timestamp overflow return `ErrInvalidExpiration`. Zero seconds is allowed. An empty default key returns `ErrInvalidSignatureKey`. Errors can be checked with `errors.Is`.

Validating URLs
-----------------------------------------------------------------------------------------------------

To validate a signed URL, simply call the `Validate` method. This will return a boolean.

```
valid := signer.Validate(signedURL)
```

The expiration check is inclusive. A URL expiring at Unix second 100 is valid at second 100 and invalid at second 101. Malformed or missing expiration and signature values return `false`, including array-valued signing parameters. Signatures use constant-time comparison for equal-length values.

Use a cryptographically random secret and keep it out of URLs, logs and source control. Signing does not encrypt the URL or prevent replay before expiration. Your application must enforce authorization and use HTTPS.

Custom keys and parameter names
-----------------------------------------------------------------------------------------------------------------------------------------------------

You can override the default key for an individual URL. Both sides must use the same key and parameter names.

```
signer, err := urlsigner.New("mysecretkey", func(config *urlsigner.Config) {
    config.ExpiresParameter = "until"
    config.SignatureParameter = "hash"
})
if err != nil {
    return err
}

signedURL, err := signer.SignWithKey("https://myapp.com", 30*time.Second, "custom-key")
if err != nil {
    return err
}
valid := signer.ValidateWithKey(signedURL, "custom-key")
```

`SignUntilWithKey` accepts an absolute `time.Time` and a per-call key. As in PHP, the per-call key may be empty for compatibility. Use nonempty random keys for new links.

Names must be distinct and nonempty, without whitespace, control characters, dots or brackets. Integer names are rejected because query merging renumbers them. Invalid names return `ErrInvalidParameterNames` from `New`. A nil clock or signature function returns `ErrInvalidConfig`.

Writing custom signers
--------------------------------------------------------------------------------------------------------------------------

This package provides a signer that uses SHA256 to generate signatures. You can create your own signer by supplying a `SignatureFunc`. The signer handles query normalization, expiration and signature validation, like PHP's `AbstractUrlSigner`.

```
signer, err := urlsigner.New("mysecretkey", func(config *urlsigner.Config) {
    config.Signature = func(url, expiration, key string) string {
        return "custom:" + urlsigner.SHA256(url, expiration, key)
    }
})
if err != nil {
    return err
}
```

The function receives the normalized URL, the original expiration text and the selected key. It returns the exact signature text to store. Set `config.Signature = urlsigner.MD5` to validate existing links using the legacy MD5 algorithm. It is not HMAC-MD5. Use the default SHA256 signer for new links.

To replace the whole signer, accept a Go interface containing the methods your application needs. No PHP class names or inheritance are required.

URL normalization and shared links
--------------------------------------------------------------------------------------------------------------------------------------------------------------

SHA256 signatures use hex HMAC-SHA256 over `url::expiration`. The legacy MD5 signer hashes `url::expiration::key`.

The URL text before the first `?` stays unchanged. The signer does not add a slash, lowercase hostnames, remove default ports or clean paths. Query order is retained, duplicate scalar keys keep the last value, nested PHP arrays are rebuilt, spaces become `+`, and query names containing dots or spaces become underscores. Existing signature and expiration parameters are removed before signing.

Avoid fragments in signed links used by browsers. The signer treats the input as text. For example, `https://myapp.com?x=value#section` becomes a query containing `x=value%23section`. With no `?`, `#section` stays in the base and the signing parameters follow it. A browser will not send its fragment to your server.

Use named top-level query keys. Integer keys are renumbered when the signing parameters are appended and can produce an unverifiable URL. PHP's default parser limits also apply. Queries near 1,000 parameters can push the signing fields beyond the limit, making the generated link unverifiable. Keep shared links below that limit and below 64 nested array levels.

For links shared with [spatie/url-signer](https://github.com/spatie/url-signer), use 64-bit PHP 8.3+ with `arg_separator.input=&`, `arg_separator.output=&`, `max_input_vars=1000`, and `max_input_nesting_level=64`. PHP 8.2 assigns different appended array indices after negative keys. Use explicit nonnegative indices for links shared with that runtime. Changing PHP's INI settings can change signatures.

The PHP source has no `docs/` tree. These pages preserve its README's introduction, installation, generating URLs, validating URLs and writing custom signers sections, following the Rust port's documentation layout. Interoperability tests use PHP source commit `3cddceff31fcbffc19ee21e5abf7cbf6c196292e` and fixtures from the Rust port. See [testing](testing).

Testing the expiry boundary
-----------------------------------------------------------------------------------------------------------------------------------------

Supply a clock through `Config.Now` for deterministic validation. Production signers use the system clock.

```
now := int64(100)
signer, err := urlsigner.New("mysecretkey", func(config *urlsigner.Config) {
    config.Now = func() time.Time { return time.Unix(now, 0) }
})
if err != nil {
    return err
}
signedURL, err := signer.Sign("https://myapp.com", 0)
if err != nil {
    return err
}
validAtExpiry := signer.Validate(signedURL) // true
now = 101
validAfterExpiry := signer.Validate(signedURL) // false
```

Signer configuration is copied when `New` returns. A signer can be shared by goroutines if its custom signature function and clock are concurrency-safe. Synchronize a mutable test clock before using it in concurrent tests.

 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)
