working commit

This commit is contained in:
2026-02-27 19:04:57 +02:00
parent 7de22e3816
commit 9fa5a00421
12 changed files with 210 additions and 213 deletions

View File

@@ -2,13 +2,13 @@ package client
import (
"crypto/tls"
"encoding/base64"
"net/http"
)
type Client struct {
httpClient *http.Client
authenticator Authenticator
userAgent string
httpClient *http.Client
userAgent string
}
func NewClient() *Client {
@@ -22,28 +22,88 @@ func NewClient() *Client {
}
}
func (cli *Client) SetAuthenticator(auth Authenticator) {
cli.authenticator = auth
}
func (cli *Client) SetTransport(transport http.RoundTripper) {
cli.httpClient.Transport = transport
}
type WrapTransport struct {
transport http.RoundTripper
type MiddlewareFunc func(next http.RoundTripper) http.RoundTripper
func (cli *Client) UseMiddleware(mwFunc MiddlewareFunc) {
cli.httpClient.Transport = mwFunc(cli.httpClient.Transport)
}
func NewWrapTransport(transport http.RoundTripper) *WrapTransport {
return &WrapTransport{
transport: transport,
// ExampleMiddleware
func NewExampleMiddleware() MiddlewareFunc {
return func(next http.RoundTripper) http.RoundTripper {
return newExampleTransport(next)
}
}
func (wrap *WrapTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return wrap.transport.RoundTrip(req)
type ExampleTransport struct {
next http.RoundTripper
}
func newExampleTransport(next http.RoundTripper) *ExampleTransport {
return &ExampleTransport{
next: next,
}
}
func (tran ExampleTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return tran.next.RoundTrip(req)
}
// BasicAuthMiddleware
func NewBasicAuthMiddleware(user, pass string) MiddlewareFunc {
return func(next http.RoundTripper) http.RoundTripper {
return newBasicAuthMW(next, user, pass)
}
}
type BasicAuthMW struct {
user, pass string
next http.RoundTripper
}
func newBasicAuthMW(next http.RoundTripper, user, pass string) *BasicAuthMW {
return &BasicAuthMW{
user: user,
pass: pass,
next: next,
}
}
func (tran BasicAuthMW) RoundTrip(req *http.Request) (*http.Response, error) {
pair := base64.StdEncoding.EncodeToString([]byte(tran.user + ":" + tran.pass))
req.Header.Set("Authorization", "Basic "+pair)
return tran.next.RoundTrip(req)
}
// BearerAuthMiddleware
func NewBearerAuthMiddleware(token string) MiddlewareFunc {
return func(next http.RoundTripper) http.RoundTripper {
return newBearerAuthMW(next, token)
}
}
type BearerAuthMW struct {
token string
next http.RoundTripper
}
func newBearerAuthMW(next http.RoundTripper, token string) *BearerAuthMW {
return &BearerAuthMW{
token: token,
next: next,
}
}
func (tran BearerAuthMW) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", "Bearer "+tran.token)
return tran.next.RoundTrip(req)
}
// DefaultTransport
type DefaultTransport struct {
transport http.RoundTripper
}