Documentation
¶
Overview ¶
Package cdn purges CDN cache entries by URL. Callers use only the Purger interface; New picks the provider: "cloudflare" or "none" (no purge, the cache expires by its TTL). It purges by URL only, not by tag or host name: those are plan features of some CDNs and have no common equivalent.
It depends on the standard library only.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Purger ¶
Purger removes cached copies of URLs from the CDN.
Example ¶
ExamplePurger uses a Purger behind an interface and treats a purge as best effort.
package main
import (
"context"
"errors"
"fmt"
"github.com/phcp-tech/common-library-golang/cdn"
)
// recorder is a test Purger: callers depend on the interface only, so a unit
// test needs no CDN.
type recorder struct {
urls []string
err error
}
func (r *recorder) PurgeURLs(_ context.Context, urls []string) error {
r.urls = append(r.urls, urls...)
return r.err
}
// publish changes data, then purges its URLs. A purge failure is only
// reported: the cache expires by its TTL, so the change itself succeeded.
func publish(ctx context.Context, p cdn.Purger, slug string) error {
if err := p.PurgeURLs(ctx, []string{"https://example.com/articles/" + slug}); err != nil {
fmt.Println("purge failed, the cache expires by its TTL:", err)
}
return nil
}
func main() {
ctx := context.Background()
ok := &recorder{}
fmt.Println(publish(ctx, ok, "hello"), ok.urls)
failing := &recorder{err: errors.New("HTTP 403")}
fmt.Println(publish(ctx, failing, "hello"))
}
Output: <nil> [https://example.com/articles/hello] purge failed, the cache expires by its TTL: HTTP 403 <nil>
func New ¶
New returns the Purger of provider: "cloudflare" or "none".
Example ¶
ExampleNew picks the purger from configuration. "none" purges nothing, for local runs without a token; "cloudflare" needs a zone id and a purge token.
package main
import (
"context"
"fmt"
"github.com/phcp-tech/common-library-golang/cdn"
)
func main() {
p, err := cdn.New("none", "", "")
fmt.Println(err, p.PurgeURLs(context.Background(), []string{"https://example.com/a"}))
_, err = cdn.New("cloudflare", "zone-id", "")
fmt.Println(err)
_, err = cdn.New("cloudfront", "zone-id", "token")
fmt.Println(err)
}
Output: <nil> <nil> cdn: cloudflare needs a zone id and a purge token cdn: unknown provider "cloudfront" (cloudflare|none)