docs(cooler,diary,festival,fetchguard): compile README Go examples via src= (quick-261118-qsd)
- cooler: ExampleFromApp and the articlesController purge declarations; AllowExport run by TestDocsAllowExport on miniredis - diary: blogLog and ExampleFor; the generated main's run function, run by TestDocsRun in a temp directory with diary.Reset on cleanup - festival: PostPublished/ExampleBus_Fire and PostFormExtended/Collected/ ExampleBus_Collect, with a TestDocsDeclarations for Collected - fetchguard: fetch region run by TestDocsFetchImage (loopback refused as private_ip), client region run by TestDocsSyncItems on a stub transport
This commit is contained in:
@@ -38,49 +38,51 @@ Use cases:
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
Fetching an image URL a user supplied, from the application's image host (images.example.com, say) or its subdomains only:
|
||||
|
||||
```go src=modules/fetchguard/example_test.go#fetch
|
||||
policy := fetchguard.Policy{
|
||||
Mode: fetchguard.AllowHostsMode,
|
||||
AllowHosts: []string{"images.example.com"},
|
||||
AllowHosts: []string{imageHost},
|
||||
MaxBytes: 5 << 20,
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
res, err := fetchguard.Fetch(ctx, imageURL, policy, app.Config)
|
||||
res, err := fetchguard.Fetch(ctx, imageURL, policy, cfg)
|
||||
if err != nil {
|
||||
var fe *fetchguard.Error
|
||||
if errors.As(err, &fe) && fe.Reason == fetchguard.ReasonPrivateIP {
|
||||
return errRejectedURL
|
||||
return nil, errRejectedURL
|
||||
}
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("image fetch: status %d", res.StatusCode)
|
||||
return nil, fmt.Errorf("image fetch: status %d", res.StatusCode)
|
||||
}
|
||||
image := res.Body
|
||||
```
|
||||
|
||||
Calling a service API with a reusable client:
|
||||
|
||||
```go
|
||||
```go src=modules/fetchguard/example_test.go#client
|
||||
vendor, err := fetchguard.NewClient(fetchguard.Policy{
|
||||
Mode: fetchguard.AllowHostsMode,
|
||||
AllowHosts: []string{"api.example.com"},
|
||||
Timeout: 10 * time.Second,
|
||||
}, app.Config)
|
||||
}, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
header := http.Header{}
|
||||
header.Set("Authorization", fetchguard.Bearer(token))
|
||||
res, err := vendor.PostJSON(ctx, "https://api.example.com/v1/items", header, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode == http.StatusTooManyRequests {
|
||||
wait := res.Header.Get("Retry-After")
|
||||
// ...
|
||||
return nil, fmt.Errorf("vendor busy, retry after %s seconds", wait)
|
||||
}
|
||||
|
||||
// Multipart upload: fields first, then files, each in slice order.
|
||||
|
||||
Reference in New Issue
Block a user