Skip to content

Instantly share code, notes, and snippets.

@joshua
Created January 9, 2020 15:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshua/9ec2aa907b8173f6d4f0a58b3e393891 to your computer and use it in GitHub Desktop.
Save joshua/9ec2aa907b8173f6d4f0a58b3e393891 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"text/tabwriter"
"time"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/netlify/open-api/go/porcelain"
openapiClient "github.com/go-openapi/runtime/client"
netlifyContext "github.com/netlify/open-api/go/porcelain/context"
)
const (
apiHostname = "api.netlify.com"
apiPath = "/api/v1"
apiToken = "ACCESS_TOKEN_GOES_HERE"
apiDebug = true
)
type ctxKey int
const (
apiClientKey ctxKey = 1 + iota
)
func main() {
ctx := newContext()
client := getClient(ctx)
sites, err := client.ListSites(ctx, nil)
if err != nil {
log.Fatal(err)
}
t := tabwriter.NewWriter(os.Stdout, 0, 10, 5, ' ', 0)
buffer := new(bytes.Buffer)
fmt.Fprintf(buffer, "Site\tCustom Domain\n")
for _, s := range sites {
fmt.Fprintf(buffer, "%s\t%s\n", s.Name, s.URL)
}
buffer.WriteTo(t)
t.Flush()
}
func newContext() context.Context {
ctx := context.Background()
// add OpenAPI Runtime credentials to context
creds := runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
r.SetHeaderParam("User-Agent", "test")
r.SetHeaderParam("Authorization", "Bearer "+apiToken)
return nil
})
ctx = netlifyContext.WithAuthInfo(ctx, creds)
// create an OpenAPI transport
transport := openapiClient.NewWithClient(apiHostname, apiPath, []string{"https"}, httpClient())
transport.SetDebug(apiDebug)
// create a Netlify api client and add to context
//
// client can be porcelain.New or porcelain.NewRetryable
// client := porcelain.New(transport, strfmt.Default)
client := porcelain.NewRetryable(transport, strfmt.Default, porcelain.DefaultRetryAttempts)
ctx = context.WithValue(ctx, apiClientKey, client)
return ctx
}
func getClient(ctx context.Context) *porcelain.Netlify {
return ctx.Value(apiClientKey).(*porcelain.Netlify)
}
func httpClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: -1,
DisableKeepAlives: true,
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment