Documentation
¶
Index ¶
- func Initialize(spec interface{}) error
- func ParseClaimsFromRequest(r *http.Request, claims interface{}) error
- func ParsePubSubEnvelope(r *http.Request) ([]byte, string, time.Time, error)
- func UnmarshalJSONBody(r *http.Request, target interface{}) error
- type Config
- type EndpointHandler
- type HTTPResponse
- type PubSubHandler
- type PubSubMessage
- type Service
- func (s *Service) AddAuthenticatedEndpoint(method, relativePath, permission string, handler EndpointHandler)
- func (s *Service) AddCloudSchedulerEndpoint(relativePath string, handler EndpointHandler)
- func (s *Service) AddCloudTaskEndpoint(relativePath string, handler EndpointHandler)
- func (s *Service) AddPubSubEndpoint(relativePath string, handler EndpointHandler)
- func (s *Service) AddPublicEndpoint(method, relativePath string, handler EndpointHandler)
- func (s *Service) AddServiceEndpoint(method, relativePath, permission string, handler EndpointHandler)
- func (s *Service) AddWebsocketEndpoint(relativePath string, handler WebsocketHandler)
- func (s *Service) AuthClient() (*http.Client, error)
- func (s *Service) AuthenticateRequest(r *http.Request, permission string) (bool, error)
- func (s *Service) Config() *Config
- func (s *Service) CreateCloudTask(queue, callbackURL string, body []byte, delay, timeout time.Duration) error
- func (s *Service) GenerateGoogleIDToken(audience string) (string, error)
- func (s *Service) IsRequestFromService(r *http.Request) bool
- func (s *Service) PublishToPubSub(topic string, message interface{}) (string, error)
- func (s *Service) Run(state State)
- func (s *Service) SetAuthProvider(authProvider auth.AuthProvider) error
- func (s *Service) Shutdown()
- type State
- type WebsocketHandler
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Initialize ¶
func Initialize(spec interface{}) error
Initialize loads the environment variables specified in the provided spec struct. In a local development environment, if any variables are missing, the user is prompted to enter the missing values. In a production environment, if required variables are not set, the function returns an error, indicating that the configuration is incomplete and the service should not start until the issue is resolved.
func ParseClaimsFromRequest ¶
ParseClaimsFromRequest extracts the JWT from the Authorization header of the request, decodes the payload, and unmarshals it into the provided claims struct WITHOUT VERIFYING THE SIGNATURE.
func ParsePubSubEnvelope ¶ added in v0.1.10
ParsePubSubEnvelope extracts and decodes the Pub/Sub message from an incoming HTTP request.
This function expects a JSON payload containing a Pub/Sub message envelope. It performs the following steps: 1. Decodes the JSON request body into a structured envelope. 2. Extracts the base64-encoded message data, message ID, and publish timestamp. 3. Returns the decoded data, message ID, and publish timestamp. If an error occurs at any step, it is returned.
Parameters:
- r *http.Request: The incoming HTTP request containing the Pub/Sub message.
Returns:
- []byte: The decoded message data.
- string: The unique Pub/Sub message ID.
- time.Time: The timestamp when the message was published.
- error: An error if JSON decoding or base64 decoding fails, otherwise nil.
func UnmarshalJSONBody ¶
UnmarshalJSONBody reads the JSON-encoded body of an HTTP request and unmarshals it into the provided target. It returns an error if the request body is empty or if the JSON decoding fails.
Types ¶
type Config ¶
type Config struct { CloudSQLConnection string // Cloud SQL instance connection string in the format "project:region:instance" CloudSQLDatabase string // Name of the specific database within the Cloud SQL instance CloudSQLUser string // Username for accessing the Cloud SQL database GCPProjectID string // Google Cloud Platform Project ID where the service is deployed Host string // The host address where the service listens for incoming requests (e.g., ":8080") ServiceAccount string // Service account email used for authentication with GCP resources }
type EndpointHandler ¶
type EndpointHandler func(*Service, *http.Request) *HTTPResponse
type HTTPResponse ¶
type HTTPResponse struct { StatusCode int // The HTTP status code of the response (e.g., 200, 404) Headers http.Header // The headers of the HTTP response (e.g., Content-Type, Set-Cookie) Body io.ReadCloser // The response body, allowing streaming of the content and efficient memory usage }
func InternalServerError ¶
func InternalServerError() *HTTPResponse
InternalServerError returns an HTTP 500 response with a standard "internal server error" message.
func JSON ¶
func JSON(statusCode int, obj interface{}) *HTTPResponse
JSON sets the HTTP response with the provided status code and a JSON-encoded body generated from the provided object. If an error occurs during the JSON encoding process (e.g., unsupported types or invalid data), the function gracefully handles it by setting the response body to `null`. The response is streamed using a pipe to avoid loading the entire JSON payload into memory at once, making it suitable for handling large objects.
func Text ¶
func Text(statusCode int, text string) *HTTPResponse
Text sets the HTTP response with the provided status code and plain text body.
func Textf ¶
func Textf(statusCode int, text string, args ...any) *HTTPResponse
Textf formats a string with the provided arguments and sets the HTTP response with the given status code and the formatted plain text body. It is a variant of the Text function that supports formatted text using fmt.Sprintf.
type PubSubHandler ¶
type PubSubHandler func(*Service, PubSubMessage) error
type PubSubMessage ¶
type Service ¶
type Service struct { Context context.Context CloudStorageClient *storage.Client CloudTasksClient *cloudtasks.Client GoogleCredentials *google.Credentials IAMClient *credentials.IamCredentialsClient DB *sql.DB Log *slog.Logger Name string // contains filtered or unexported fields }
func New ¶
New initializes a new service instance with a service name, and configuration. It validates the configuration, sets up Google Cloud credentials, and prepares the service for use. Returns a configured Service or an error on failure.
func (*Service) AddAuthenticatedEndpoint ¶
func (s *Service) AddAuthenticatedEndpoint(method, relativePath, permission string, handler EndpointHandler)
AddAuthenticatedEndpoint registers an HTTP endpoint that requires authentication.
Optionally, a permission can be specified and is checked after authentication. If the permission requirements is not met, a 403 Forbidden response is returned.
If the service was initialized without an AuthProvider, it logs a fatal error and exits. If authentication fails, a 401 Unauthorized response is returned. If authorization requirements are provided and the request fails authorization, a 403 Forbidden response is returned. In case of an internal error during processing, a 500 Internal Server Error is returned.
func (*Service) AddCloudSchedulerEndpoint ¶
func (s *Service) AddCloudSchedulerEndpoint(relativePath string, handler EndpointHandler)
AddCloudSchedulerEndpoint registers a new POST endpoint at the specified relativePath to handle incoming Google Cloud Scheduler requests. In production, it verifies the authenticity of the request, while in local or non-production environments, request verification is skipped.
func (*Service) AddCloudTaskEndpoint ¶
func (s *Service) AddCloudTaskEndpoint(relativePath string, handler EndpointHandler)
AddCloudTaskEndpoint registers a new POST endpoint at the specified relativePath to handle incoming Google Cloud Tasks. In production, it verifies the authenticity of the request, while in local or non-production environments, request verification is skipped.
func (*Service) AddPubSubEndpoint ¶
func (s *Service) AddPubSubEndpoint(relativePath string, handler EndpointHandler)
AddPubSubEndpoint registers a new POST endpoint at the specified relativePath to handle incoming Pub/Sub messages. In production, it verifies the authenticity of the request, while in local or non-production environments, request verification is skipped.
func (*Service) AddPublicEndpoint ¶
func (s *Service) AddPublicEndpoint(method, relativePath string, handler EndpointHandler)
AddPublicEndpoint registers a new HTTP endpoint with the specified method (e.g., "GET", "POST") and relative path. It wraps the provided handler function so that the current Service instance is passed into the handler when the endpoint is invoked. This endpoint does not require authentication. If an error occurs while registering the endpoint, the function will log the error and terminate the program.
func (*Service) AddServiceEndpoint ¶
func (s *Service) AddServiceEndpoint(method, relativePath, permission string, handler EndpointHandler)
AddServiceEndpoint registers an HTTP endpoint that requires authentication and is restricted to service requests only. It first authenticates the request, ensuring that only valid credentials are allowed, and then verifies that the request comes specifically from a trusted service.
If the service was initialized without an AuthProvider, it logs a fatal error and exits. If authentication fails, a 401 Unauthorized response is returned. If the request is not verified as coming from a service, a 403 Forbidden response is returned indicating that access is restricted to services.
Optionally, a permission can be specified and is checked after authentication. If the permission requirements is not met, a 403 Forbidden response is returned.
The handler function receives the Service instance and the HTTP request, and returns an HTTPResponse. In case of an internal error during processing, a 500 Internal Server Error is returned. This endpoint is intended for use by other services and ensures only authenticated and verified service requests are permitted.
func (*Service) AddWebsocketEndpoint ¶
func (s *Service) AddWebsocketEndpoint(relativePath string, handler WebsocketHandler)
AddWebsocketEndpoint registers a WebSocket handler at the specified relative path, handling the WebSocket upgrade process and connection lifecycle. It wraps the provided WebsocketHandler function with middleware to upgrade HTTP requests to WebSocket connections, and automatically closes the connection when the handler completes.
func (*Service) AuthClient ¶
AuthClient returns an *http.Client that automatically attaches JWT tokens to requests and refreshes them as needed. It requires the service to have been initialized with an AuthProvider.
func (*Service) AuthenticateRequest ¶ added in v0.1.1
AuthenticateRequest validates an HTTP request by performing both authentication and authorization checks using the AuthProvider configured for the service. It ensures the request is authenticated and then verifies that it meets the specified authorization requirement.
Parameters: - r: The HTTP request to be authenticated and authorized. - permission: Name of a permission the client is required to have.
Returns: - A boolean indicating whether the request is successfully authenticated and authorized. - An error if something goes wrong.
Notes: - Uses the service's configured AuthProvider to perform all checks.
func (*Service) Config ¶
Config returns the current configuration of the service. It provides access to the internal configuration stored in the service.
func (*Service) CreateCloudTask ¶ added in v0.1.9
func (s *Service) CreateCloudTask(queue, callbackURL string, body []byte, delay, timeout time.Duration) error
CreateCloudTask creates and schedules a new task in the specified Cloud Tasks queue.
The task is configured as an HTTP request with a POST method, sending the provided request body to the given callback URL. It also includes an OIDC token for authentication.
Parameters:
- queue: The fully qualified name of the Cloud Tasks queue where the task will be created.
- callbackURL: The URL that will receive the HTTP request when the task is executed.
- body: The request payload to be sent in the task's HTTP request body.
- delay: The duration to wait before the task is executed (schedules the task in the future).
- timeout: The maximum duration allowed for the task to execute before it times out.
Returns:
- error: An error if the task creation fails, otherwise nil.
The function uses the CloudTasksClient to create a new task with the specified parameters. The task is authenticated using an OIDC token associated with the configured service account.
func (*Service) GenerateGoogleIDToken ¶
GenerateGoogleIDToken generates a Google ID token for a given audience. It uses a service account to create the token, either by impersonating the account in non-production environments or by querying the metadata server in production.
func (*Service) IsRequestFromService ¶ added in v0.1.2
IsRequestFromService checks whether the given HTTP request originates from a service. It delegates the request to the underlying AuthProvider to perform the service request check.
func (*Service) PublishToPubSub ¶
PublishToPubSub sends a message to the specified Pub/Sub topic. It returns the message ID or an error if the operation fails.
func (*Service) Run ¶
Run starts the service and blocks, waiting for an OS signal, context cancellation, or an error. Lifecycle callbacks from the State struct are invoked at each stage: - `Starting`: Called when the service starts. - `Running`: Called when the service is running. - `Terminating`: Called during shutdown, with an error if one triggered the termination.
The function returns only after the service has gracefully shut down.
func (*Service) SetAuthProvider ¶ added in v0.1.1
func (s *Service) SetAuthProvider(authProvider auth.AuthProvider) error
SetAuthProvider initializes the authentication provider for the service.
type State ¶
type State struct { Starting func() // Called when the service is starting Running func() // Called when the service is running Terminating func(err error) // Called when the service is terminating, with an optional error if it was due to a failure }