8000 no way to legally construct a source.Client · Issue #256 · google/go-licenses · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

no way to legally construct a source.Client #256

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Adjective-Object opened this issue Feb 14, 2024 · 1 comment
Open

no way to legally construct a source.Client #256

Adjective-Object opened this issue Feb 14, 2024 · 1 comment

Comments

@Adjective-Object
Copy link

The public method license.FileURL requires a source.Client.

There is currently no way to construct a source.Client when consuming go-licenses as a library consumer.

@tkw1536
Copy link
tkw1536 commented Mar 30, 2025

I encountered the same issue.

The following is a terrible workaround that I'm posting in case someone else needs it.
This implements source.NewClient via reflect, and then passes it to the FileURL method via reflect also.
It's particularly terrible because it's using reflect.Value.Set on an unexported field which should really not be done.

The better approach would be for the package maintainers to provide a legal way to construct a source.Client.

package pleasedontusethis

import (
	"context"
	"net/http"
	"reflect"
	"time"

	"github.com/google/go-licenses/v2/licenses"
	"go.opencensus.io/plugin/ochttp"
)

var libraryFunc = reflect.ValueOf((*licenses.Library).FileURL)
var sourceClientTyp = libraryFunc.Type().In(2).Elem() // reflect.TypeFor[source.Client]

// like (*licenses.Library).FileURL, but not taking an internal parameter
func goLicensesLibraryFileURL(lib *licenses.Library, context context.Context, timeout time.Duration, file string) (string, error) {
	result := libraryFunc.Call([]reflect.Value{
		reflect.ValueOf(lib),
		reflect.ValueOf(context),
		newSourceClient(timeout),
		reflect.ValueOf(file),
	})

	str := result[0].String()
	err, _ := result[1].Interface().(error)
	return str, err
}

// like source.NewClient, but not internal
func newSourceClient(timeout time.Duration) reflect.Value {
	client := &http.Client{
		Transport: &ochttp.Transport{},
		Timeout:   timeout,
	}

	sourceClient := reflect.New(sourceClientTyp)

	// get the httpClient field
	// and forget that it was retrieved by means of an unexported field
	httpClientField := sourceClient.Elem().FieldByName("httpClient")
	httpClientField = reflect.NewAt(httpClientField.Type(), httpClientField.Addr().UnsafePointer()).Elem()
	httpClientField.Set(reflect.ValueOf(client))

	return sourceClient
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
0