Documentation ¶
Overview ¶
Package run provides helper functions for building Cloud Run applications.
Index ¶
- Variables
- func AccessSecret(name string) ([]byte, error)
- func AccessSecretVersion(name, version string) ([]byte, error)
- func Configuration() string
- func DeregisterEndpoint(namespace string) error
- func Error(v ...interface{})
- func Fatal(v ...interface{})
- func HTTPProbeHandler(probe Probe) http.Handler
- func Healthy(w http.ResponseWriter, r *http.Request)
- func ID() (string, error)
- func IDToken(serviceURL string) (string, error)
- func IPAddress(interfaces ...net.Interface) (string, error)
- func IPAddresses() ([]string, error)
- func Info(v ...interface{})
- func ListenAndServe(handler http.Handler) error
- func Log(severity, s string)
- func NetworkInterfaceHandler(w http.ResponseWriter, r *http.Request)
- func Notice(v ...interface{})
- func NumericProjectID() (string, error)
- func Port() string
- func ProjectID() (string, error)
- func Ready(w http.ResponseWriter, r *http.Request)
- func Region() (string, error)
- func RegisterEndpoint(namespace string) error
- func Revision() string
- func ServiceName() string
- func SetOutput(w io.Writer)
- func WaitForShutdown()
- type AccessToken
- type Endpoint
- type ErrMetadataUnexpectedResponse
- type ErrNameResolutionUnexpectedResponse
- type ErrSecretUnexpectedResponse
- type Hostname
- type IPAddressNotFoundError
- type ListEndpoints
- type LoadBalancer
- type LogEntry
- type LogEntrySourceLocation
- type Logger
- type NetworkInterface
- type Probe
- type RoundRobinLoadBalancer
- type SecretPayload
- type SecretVersion
- type Service
- type ServiceAddress
- type ServiceStatus
- type Transport
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( DefaultNamespace string DefaultRunDomain = "run.local" )
var Client = &http.Client{ Transport: &Transport{ Base: http.DefaultTransport, InjectAuthHeader: true, balancers: make(map[string]*RoundRobinLoadBalancer), }, }
var ErrInvalidHostname = errors.New("invalid hostname")
var ErrMetadataInvalidRequest = errors.New("run: invalid metadata request")
ErrMetadataInvalidRequest is returned when a metadata request is invalid.
var ErrMetadataNotFound = errors.New("run: metadata key not found")
ErrMetadataNotFound is returned when a metadata key is not found.
var ErrMetadataUnknownError = errors.New("run: unexpected error retrieving metadata key")
ErrMetadataUnknownError is return when calls to the metadata server return an unknown error.
var ErrNameResolutionPermissionDenied = errors.New("run: permission denied to named service")
ErrNameResolutionPermissionDenied is returned when access to the Cloud Run API is denied.
ErrNameResolutionUnauthorized is returned when calls to the Cloud Run API are unauthorized.
var ErrNameResolutionUnknownError = errors.New("run: unexpected error retrieving named service")
ErrNameResolutionUnknownError is return when calls to the Cloud Run API return an unknown error.
var ErrSecretNotFound = errors.New("run: named secret not found")
ErrSecretNotFound is returned when a secret is not found.
var ErrSecretPermissionDenied = errors.New("run: permission denied to named secret")
ErrSecretPermissionDenied is returned when access to a secret is denied.
ErrSecretUnauthorized is returned when calls to the Secret Manager API are unauthorized.
var ErrSecretUnknownError = errors.New("run: unexpected error retrieving named secret")
ErrSecretUnknownError is return when calls to the Secret Manager API return an unknown error.
var ErrServiceNotFound = errors.New("run: named service not found")
ErrServiceNotFound is returned when a service is not found.
Functions ¶
func AccessSecret ¶
AccessSecret returns the latest version of a Google Cloud Secret for the given name.
Example ¶
package main import ( "log" "github.com/kelseyhightower/run" ) func main() { secret, err := run.AccessSecret("apikey") if err != nil { log.Println(err) return } _ = secret }
Output:
func AccessSecretVersion ¶
AccessSecretVersion returns a Google Cloud Secret for the given secret name and version.
Example ¶
package main import ( "log" "github.com/kelseyhightower/run" ) func main() { secret, err := run.AccessSecretVersion("apikey", "1") if err != nil { log.Println(err) return } _ = secret }
Output:
func Configuration ¶
func Configuration() string
Configuration returns the name of the Cloud Run configuration being run.
func DeregisterEndpoint ¶ added in v0.0.20
func Error ¶ added in v0.0.15
func Error(v ...interface{})
Error calls Log on the default logger with severity set to ERROR.
Arguments are handled in the manner of fmt.Print.
func Fatal ¶ added in v0.0.15
func Fatal(v ...interface{})
Fatal calls Log on the default logger with severity set to ERROR followed by a call to os.Exit(1).
Arguments are handled in the manner of fmt.Print.
func HTTPProbeHandler ¶ added in v0.0.18
HTTPProbeHandler returns a request handler that calls the given probe and returns an HTTP 200 response if the probe Ready method returns true, or an HTTP 500 if false.
func Healthy ¶ added in v0.0.18
func Healthy(w http.ResponseWriter, r *http.Request)
Healthy replies to the request with an HTTP 200 response.
func IDToken ¶
IDToken returns an id token based on the service url.
Example ¶
package main import ( "fmt" "log" "net/http" "github.com/kelseyhightower/run" ) func main() { serviceURL := "https://example-6bn2iswfgq-uw.a.run.app" request, err := http.NewRequest(http.MethodGet, serviceURL, nil) if err != nil { log.Println(err) return } idToken, err := run.IDToken(serviceURL) if err != nil { log.Println(err) return } request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", idToken)) }
Output:
func IPAddress ¶ added in v0.0.18
IPAddress returns the RFC 1918 IP address assigned to the Cloud Run instance.
func IPAddresses ¶ added in v0.0.18
func Info ¶ added in v0.0.15
func Info(v ...interface{})
Info calls Log on the default logger with severity set to INFO.
Arguments are handled in the manner of fmt.Print.
func ListenAndServe ¶
ListenAndServe starts an http.Server with the given handler listening on the port defined by the PORT environment variable or "8080" if not set.
ListenAndServe supports requests in HTTP/2 cleartext (h2c) format, because TLS is terminated by Cloud Run for all client requests including HTTP2.
ListenAndServe traps the SIGINT and SIGTERM signals then gracefully shuts down the server without interrupting any active connections by calling the server's Shutdown method.
ListenAndServe always returns a non-nil error; under normal conditions http.ErrServerClosed will be returned indicating a successful graceful shutdown.
Example ¶
package main import ( "net/http" "github.com/kelseyhightower/run" ) func main() { if err := run.ListenAndServe(nil); err != http.ErrServerClosed { run.Fatal(err) } }
Output:
func Log ¶ added in v0.0.15
func Log(severity, s string)
Log writes logging events with the given severity.
The string s contains the text to log.
Source file location data will be included in log entires.
Logs are written to stdout in the Stackdriver structured log format. See https://cloud.google.com/logging/docs/structured-logging for more details.
func NetworkInterfaceHandler ¶ added in v0.0.18
func NetworkInterfaceHandler(w http.ResponseWriter, r *http.Request)
func Notice ¶ added in v0.0.15
func Notice(v ...interface{})
Notice calls Log on the default logger with severity set to NOTICE.
Arguments are handled in the manner of fmt.Print.
func NumericProjectID ¶
NumericProjectID returns the active project ID from the metadata service.
func Ready ¶ added in v0.0.18
func Ready(w http.ResponseWriter, r *http.Request)
Ready replies to the request with an HTTP 200 response.
func RegisterEndpoint ¶ added in v0.0.20
func Revision ¶
func Revision() string
Revision returns the name of the Cloud Run revision being run.
func ServiceName ¶ added in v0.0.8
func ServiceName() string
ServiceName returns the name of the Cloud Run service being run.
func WaitForShutdown ¶ added in v0.0.18
func WaitForShutdown()
WaitForShutdown waits for the SIGKILL, SIGINT, or SIGTERM signals and shutdowns the process.
Types ¶
type AccessToken ¶
type AccessToken struct { AccessToken string `json:"access_token"` ExpiresIn int64 `json:"expires_in"` TokenType string `json:"token_type"` }
AccessToken holds a GCP access token.
func Token ¶
func Token(scopes []string) (*AccessToken, error)
Token returns the default service account token.
Example ¶
package main import ( "fmt" "log" "net/http" "github.com/kelseyhightower/run" ) func main() { scopes := []string{"https://www.googleapis.com/auth/cloud-platform"} project, err := run.ProjectID() if err != nil { log.Println(err) return } endpoint := fmt.Sprintf("https://cloudbuild.googleapis.com/v1/projects/%s/builds", project) request, err := http.NewRequest(http.MethodGet, endpoint, nil) if err != nil { log.Println(err) return } token, err := run.Token(scopes) if err != nil { log.Println(err) return } request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken)) }
Output:
type Endpoint ¶ added in v0.0.20
type ErrMetadataUnexpectedResponse ¶ added in v0.0.12
ErrMetadataUnexpectedResponse is returned when calls to the metadata server return an unexpected response.
func (*ErrMetadataUnexpectedResponse) Error ¶ added in v0.0.12
func (e *ErrMetadataUnexpectedResponse) Error() string
func (*ErrMetadataUnexpectedResponse) Unwrap ¶ added in v0.0.12
func (e *ErrMetadataUnexpectedResponse) Unwrap() error
type ErrNameResolutionUnexpectedResponse ¶ added in v0.0.9
ErrNameResolutionUnexpectedResponse is returned when calls to the Cloud Run API return an unexpected response.
func (*ErrNameResolutionUnexpectedResponse) Error ¶ added in v0.0.9
func (e *ErrNameResolutionUnexpectedResponse) Error() string
func (*ErrNameResolutionUnexpectedResponse) Unwrap ¶ added in v0.0.9
func (e *ErrNameResolutionUnexpectedResponse) Unwrap() error
type ErrSecretUnexpectedResponse ¶ added in v0.0.9
ErrSecretUnexpectedResponse is returned when calls to the Secret Manager API return an unexpected response.
func (*ErrSecretUnexpectedResponse) Error ¶ added in v0.0.9
func (e *ErrSecretUnexpectedResponse) Error() string
func (*ErrSecretUnexpectedResponse) Unwrap ¶ added in v0.0.9
func (e *ErrSecretUnexpectedResponse) Unwrap() error
type IPAddressNotFoundError ¶ added in v0.0.18
type IPAddressNotFoundError struct{}
func (IPAddressNotFoundError) Error ¶ added in v0.0.18
func (e IPAddressNotFoundError) Error() string
type ListEndpoints ¶ added in v0.0.21
type ListEndpoints struct {
Endpoints []Endpoint `json:"endpoints"`
}
type LoadBalancer ¶ added in v0.0.21
type LoadBalancer interface { Next() Endpoint RefreshEndpoints() }
type LogEntry ¶ added in v0.0.3
type LogEntry struct { Message string `json:"message"` Severity string `json:"severity,omitempty"` Component string `json:"component,omitempty"` SourceLocation *LogEntrySourceLocation `json:"logging.googleapis.com/sourceLocation,omitempty"` Trace string `json:"logging.googleapis.com/trace,omitempty"` }
An LogEntry represents a Stackdriver log entry.
type LogEntrySourceLocation ¶
type LogEntrySourceLocation struct { File string `json:"file,omitempty"` Function string `json:"function,omitempty"` Line string `json:"line,omitempty"` }
A LogEntrySourceLocation holds source code location data.
Location data is used to provide additional context when logging to Stackdriver.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
A Logger represents an active logging object that generates JSON formatted log entries to standard out. Logs are formatted as expected by Cloud Run's Stackdriver integration.
Example ¶
package main import ( "github.com/kelseyhightower/run" ) func main() { logger := run.NewLogger() logger.Notice("Starting example service...") }
Output:
Example (DefaultLogger) ¶
package main import ( "github.com/kelseyhightower/run" ) func main() { run.Notice("Starting example service...") }
Output:
Example (LogCorrelation) ¶
package main import ( "net/http" "github.com/kelseyhightower/run" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Pass in the *http.Request as the first argument to correlate // container logs with request logs. run.Info(r, "Handling request...") }) }
Output:
func (*Logger) Error ¶
func (l *Logger) Error(v ...interface{})
Error calls l.Log with severity set to ERROR.
Arguments are handled in the manner of fmt.Print.
func (*Logger) Fatal ¶ added in v0.0.15
func (l *Logger) Fatal(v ...interface{})
Fatal calls l.Log with severity set to ERROR followed by a call to os.Exit(1).
Arguments are handled in the manner of fmt.Print.
func (*Logger) Info ¶
func (l *Logger) Info(v ...interface{})
Info calls l.Log with severity set to INFO.
Arguments are handled in the manner of fmt.Print.
func (*Logger) Log ¶
Log writes logging events with the given severity.
If the first value is an *http.Request, the X-Cloud-Trace-Context HTTP header will be extracted and included in the Stackdriver log entry.
Source file location data will be included in log entires.
Logs are written to stdout in the Stackdriver structured log format. See https://cloud.google.com/logging/docs/structured-logging for more details.
type NetworkInterface ¶ added in v0.0.18
type NetworkInterface struct { Name string `json:"name"` Index int `json:"index"` HardwareAddr string `json:"hardware_address"` IPAddresses []string `json:"ip_addresses"` }
func NetworkInterfaces ¶ added in v0.0.18
func NetworkInterfaces(interfaces ...net.Interface) ([]NetworkInterface, error)
NetworkInterfaces returns a list of network interfaces attached to the Cloud Run instance.
type Probe ¶ added in v0.0.18
type Probe interface {
Ready() bool
}
A Probe responds to health checks.
type RoundRobinLoadBalancer ¶ added in v0.0.21
type RoundRobinLoadBalancer struct {
// contains filtered or unexported fields
}
func NewRoundRobinLoadBalancer ¶ added in v0.0.21
func NewRoundRobinLoadBalancer(name, namespace string) (*RoundRobinLoadBalancer, error)
func (*RoundRobinLoadBalancer) Next ¶ added in v0.0.21
func (lb *RoundRobinLoadBalancer) Next() Endpoint
func (*RoundRobinLoadBalancer) RefreshEndpoints ¶ added in v0.0.21
func (lb *RoundRobinLoadBalancer) RefreshEndpoints()
type SecretPayload ¶
type SecretPayload struct { // A base64-encoded string. Data string `json:"data"` }
SecretPayload holds the secret payload for a Google Cloud Secret.
type SecretVersion ¶
type SecretVersion struct { Name string Payload SecretPayload `json:"payload"` }
SecretVersion represents a Google Cloud Secret.
type Service ¶
type Service struct {
Status ServiceStatus `json:"status"`
}
Service represents a Cloud Run service.
type ServiceAddress ¶ added in v0.0.18
type ServiceAddress struct {
URL string `json:"url"`
}
type ServiceStatus ¶ added in v0.0.3
type ServiceStatus struct { // URL holds the url that will distribute traffic over the // provided traffic targets. It generally has the form // https://{route-hash}-{project-hash}-{cluster-level-suffix}.a.run.app URL string `json:"url"` // Similar to url, information on where the service is available on HTTP. Address ServiceAddress `json:"address"` }
ServiceStatus holds the current state of the Cloud Run service.
type Transport ¶
type Transport struct { // Base optionally provides a http.RoundTripper that handles the // request. If nil, http.DefaultTransport is used. Base http.RoundTripper // InjectAuthHeader optionally adds or replaces the HTTP Authorization // header using the ID token from the metadata service. InjectAuthHeader bool // contains filtered or unexported fields }
Transport is a http.RoundTripper that attaches ID tokens to all outgoing request.
Example ¶
package main import ( "log" "net/http" "github.com/kelseyhightower/run" ) func main() { client := &http.Client{Transport: &run.Transport{}} response, err := client.Get("https://example-6bn2iswfgq-uw.a.run.app") if err != nil { log.Println(err) return } defer response.Body.Close() }
Output:
Example (ServiceNameResolution) ¶
package main import ( "log" "net/http" "github.com/kelseyhightower/run" ) func main() { client := &http.Client{ Transport: &run.Transport{}, } response, err := client.Get("https://service-name") if err != nil { log.Println(err) return } defer response.Body.Close() }
Output: