From 99bd41229120cbc1a61878544b01c310e7d6d317 Mon Sep 17 00:00:00 2001 From: ston1th Date: Wed, 20 Dec 2023 19:36:28 +0100 Subject: [PATCH] added some client options --- pkg/api/client/client.go | 55 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/pkg/api/client/client.go b/pkg/api/client/client.go index 5f6ea13..6e6878a 100644 --- a/pkg/api/client/client.go +++ b/pkg/api/client/client.go @@ -12,6 +12,7 @@ import ( "net/http" "net/http/httputil" "net/url" + neturl "net/url" "os" "strings" "time" @@ -75,9 +76,11 @@ func WithHTTPClient(httpClient *http.Client) ClientOption { //} var ( - ErrMissingEndpointEnv = errors.New("missing environment variable KEYCTL_ENDPOINT") - - ErrMissingEndpoint = errors.New("missing Endpoint in config") + ErrMissingEndpointEnv = errors.New("missing environment variable KEYCTL_ENDPOINT") + ErrMissingEndpointInURL = errors.New("missing host in URL") + ErrMissingIDInURL = errors.New("missing ID in URL") + ErrUnsupportedScheme = errors.New("unsupported scheme") + ErrMissingEndpoint = errors.New("missing Endpoint in config") ) type Config struct { @@ -112,6 +115,52 @@ func ClientOptionsFromEnv() (options []ClientOption, err error) { return } +func ClientOptionsFromURL(url string) (options []ClientOption, err error) { + u, err := neturl.Parse(url) + if err != nil { + return nil, err + } + if u.Scheme != "keyctl" { + return nil, fmt.Errorf("%w: %s", ErrUnsupportedScheme, u.Scheme) + } + if u.Host == "" { + err = ErrMissingEndpointInURL + return + } + //insecure, _ := strconv.ParseBool(os.Getenv("HAPROXY_LB_INSECURE")) + var endpoint string + if u.Query().Get("tls") == "true" { + endpoint = "https://" + u.Host + } else { + endpoint = "http://" + u.Host + } + + options = []ClientOption{ + WithEndpoint(endpoint), + //WithInsecureClient(insecure), + } + return +} + +func KeyFromURL(url string) (id, share string, err error) { + u, err := neturl.Parse(url) + if err != nil { + return + } + if u.Scheme != "keyctl" { + err = fmt.Errorf("%w: %s", ErrUnsupportedScheme, u.Scheme) + return + } + q := u.Query() + id = q.Get("id") + if id == "" { + err = ErrMissingIDInURL + return + } + share = q.Get("share") + return +} + func NewClient(options ...ClientOption) *Client { client := &Client{}