$ go <something...> Example_hello "https://www.google.com/not-exist"
Responded 404
I don’t know how to run Example_hello. It seems to be compile-time only. Is there a way to invoke it without using // Output: since the output might change (fs, http, time, etc.)?
I’m looking for something similar to Rust’s examples/ folder and cargo run --example <example_name>. Is there a go test -run Example_hello -args "https://example.org/" (doesn’t work) -ish trick that I can use?
My current solution is to use an _examples/ or examples/ folder (I don’t really know which is the convention) with package main example programs in it. I wish that these examples would show up on pkg.go.dev, hence my desire to move to testable examples.
I think you might be confused about how examples are supposed to be used. They are unit tests that are also meant to be run on the web/playground in a godoc. Consider this code:
And in the godoc:
Due to them being tests, they are mostly supposed to be deterministic. From the docs:
Examples without output comments are useful for demonstrating code that cannot run as unit tests, such as that which accesses the network, while guaranteeing the example at least compiles.
It’s important to note that the playground is set up in such a way as to make most code deterministic. Thus you can’t access the internet, and time.Now is hard-coded to a specific date. From “about” on the playground:
The playground can use most of the standard library, with some exceptions. The only communication a playground program has to the outside world is by writing to standard output and standard error.
In the playground the time begins at 2009-11-10 23:00:00 UTC (determining the significance of this date is an exercise for the reader). This makes it easier to cache programs by giving them deterministic output.
So - your example wouldn’t work in the playground anyway because it can’t hit the internet. Here’s an adapted example from The Go Programming Language to illustrate that this doesn’t work:
I’m not a Rust dev but reading the docs:
Files located under the examples directory are example uses of the functionality provided by the library.
I would say the thing you are looking for is doing the exact same thing: create an examples folder with a main.go in each subfolder (aka package). So - in your case, change your code to be a main package:
And put it in yourmodule/examples/get. Then from your main folder you can just run it (or any other example) like so:
# Run the "get" example on google.com:
go run ./examples/get/ https://www.google.com
Here’s an example of an examples folder I created recently:
In that case, there is some extra setup that needs to be done (create your astra DB, set .env or env vars with credentials/endpoint). But in the simple case, if somebody clones your repo they can run them with a relative command like I noted above. Another example: