spiegel_podman/pkg/bindings/generate/generate.go
Moritz "WanzenBug" Wanzenböck 5df883e87d bindings: reuse context for API requests
One of the main uses of context.Context is to provide cancellation for
go-routines, including API requests. While all user-facing bindings
already used a context parameter, it was only used to pass the client
information around.

This commit changes the internal DoRequest wrapper to take an additional
context argument, and pass that to the http request. Previously, the context
was derived from context.Background(), which made it impossible to cancel
once started.

All the convenience wrappers already supported the context parameter, so the
only user facing change is that cancelling those context now works as one
would expect.

Signed-off-by: Moritz "WanzenBug" Wanzenböck <moritz@wanzenbug.xyz>
2021-11-15 15:42:39 +01:00

68 lines
1.6 KiB
Go

package generate
import (
"context"
"errors"
"net/http"
"github.com/containers/podman/v3/pkg/bindings"
"github.com/containers/podman/v3/pkg/domain/entities"
)
func Systemd(ctx context.Context, nameOrID string, options *SystemdOptions) (*entities.GenerateSystemdReport, error) {
if options == nil {
options = new(SystemdOptions)
}
conn, err := bindings.GetClient(ctx)
if err != nil {
return nil, err
}
params, err := options.ToParams()
if err != nil {
return nil, err
}
response, err := conn.DoRequest(ctx, nil, http.MethodGet, "/generate/%s/systemd", params, nil, nameOrID)
if err != nil {
return nil, err
}
defer response.Body.Close()
report := &entities.GenerateSystemdReport{}
return report, response.Process(&report.Units)
}
// Kube generate Kubernetes YAML (v1 specification)
//
// Note: Caller is responsible for closing returned reader
func Kube(ctx context.Context, nameOrIDs []string, options *KubeOptions) (*entities.GenerateKubeReport, error) {
if options == nil {
options = new(KubeOptions)
}
conn, err := bindings.GetClient(ctx)
if err != nil {
return nil, err
}
if len(nameOrIDs) < 1 {
return nil, errors.New("must provide the name or ID of one container or pod")
}
params, err := options.ToParams()
if err != nil {
return nil, err
}
for _, name := range nameOrIDs {
params.Add("names", name)
}
response, err := conn.DoRequest(ctx, nil, http.MethodGet, "/generate/kube", params, nil)
if err != nil {
return nil, err
}
if response.StatusCode == http.StatusOK {
return &entities.GenerateKubeReport{Reader: response.Body}, nil
}
// Unpack the error.
return nil, response.Process(nil)
}