logoalt Hacker News

Redefining Go Functions

75 pointsby todsacerdotitoday at 2:27 PM24 commentsview on HN

Comments

MadVikingGodtoday at 4:05 PM

This is all possible and quite neat to dive into the specifics, but if you really want to be able swap a std lib call, just turn it into a variable and change it.

  // code.go
  var now = time.Now

  // code_test.go
  func TestCode(t *testing.T) {
      nowSwap := now
      t.Cleanup (func() {
          now = nowSwap
      }
      now = func() time.Time {
          return time.Date(...)
      }
  }

Examples Code: https://github.com/open-telemetry/opentelemetry-go/blob/main... Test: https://github.com/open-telemetry/opentelemetry-go/blob/490f...
show 3 replies
croneliustoday at 7:24 PM

This is cool, just don't let Rob Pike see this, he will have a conniption. Glad you called out that it shouldn't be used because this is about the most magical thing I have ever seen in Go

show 1 reply
nasretdinovtoday at 5:11 PM

I've used a different approach to this: there's no real need to modify the compiled binary code because Go compiles everything from source, so you can patch the functions at the source level instead: https://github.com/YuriyNasretdinov/golang-soft-mocks

The way it works is that at the start of every function it adds an if statement that atomically checks whether or not the function has been intercepted, and if it did, then executes the replacement function instead. This also addresses the inlining issue.

My tool no longer works since it was rewriting GOPATH, and Go since effectively switched to Go Modules, but if you're persistent enough you can make it work with Go modules too — all you need to do is rewrite the Go module cache instead of GOPATH and you're good to go.

dveeden2today at 7:28 PM

> There you go. It’s 5PM. It’s always 5PM.

That reminded me of the Go Playground, where it is always 2009

https://go.dev/play/p/VrWYHGbtc6m

draxiltoday at 9:55 PM

Spirit of Perl is still alive

pstuarttoday at 3:39 PM

Yikes, I don't see any legitimate use for this, other than hacking for the sake of hacking. Interesting read though.

show 4 replies