Skip to content
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

Support passing httptest URLs in api.ClientOptions #167

Open
mntlty opened this issue Jun 4, 2024 · 1 comment
Open

Support passing httptest URLs in api.ClientOptions #167

mntlty opened this issue Jun 4, 2024 · 1 comment

Comments

@mntlty
Copy link
Contributor

mntlty commented Jun 4, 2024

The standard library's httptest package makes stubbing APIs easy, if the client calls the test server's URL:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	tls := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	defer tls.Close()
	fmt.Println("tls hostname - ", tls.URL)
	// prints: tls hostname - https://127.0.0.1:42002

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	defer ts.Close()
	fmt.Println("ts hostname - ", ts.URL)
	// prints: ts hostname -  http://127.0.0.1:35061
}

In api.ClientOptions, one of the configuration fields is Host

Host string

for certain values the argument is returned unmodified

func restURL(hostname string, pathOrURL string) string {
if strings.HasPrefix(pathOrURL, "https://") || strings.HasPrefix(pathOrURL, "http://") {
return pathOrURL
}

I would like to propose adding another condition to the restURL function which would return the unmodified httptest server URL

if strings.HasPrefix(hostname, "https://127.0.0.1:") || strings.HasPrefix(hostname, "http://127.0.0.1:") {
	return hostname
}

This aligns with the conditional check on the prefix for the pathOrURL argument.

For reference, setting the ts.URL value to Host results in a URL similar to:

https://http//127.0.0.1:56261/api/v3/

as it satisfies this condition

if isEnterprise(hostname) {

I don't know if this means my proposed solution would break with Enterprises.

In writing this all out, I also realized that passing the hostname + path to client.Get, rather than just the api path, solves this issue.

@andyfeller
Copy link
Contributor

andyfeller commented Jun 4, 2024

Appreciate ideas for making it easier for extension authors to build better tests, a sentiment I believe @williammartin and I both support! ❤

I'm hesitant putting localhost/127.0.0.1 specific logic into restUrl as such URLs should be URLs and return back unmodified from the existing logic.

That said, I can see the challenge behind convincing the api logic to treat a given URL as a GHES or GitHub tenancy host 🤔 Possibly a host type override option?

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