• This repository has been archived on 17/Jun/2020
  • Stars
    star
    3,235
  • Rank 13,269 (Top 0.3 %)
  • Language
    Go
  • License
    Other
  • Created about 9 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Monkey patching in Go

Go monkeypatching 🐡 πŸ’

Actual arbitrary monkeypatching for Go. Yes really.

Read this blogpost for an explanation on how it works: https://bou.ke/blog/monkey-patching-in-go/

I thought that monkeypatching in Go is impossible?

It's not possible through regular language constructs, but we can always bend computers to our will! Monkey implements monkeypatching by rewriting the running executable at runtime and inserting a jump to the function you want called instead. This is as unsafe as it sounds and I don't recommend anyone do it outside of a testing environment.

Make sure you read the notes at the bottom of the README if you intend to use this library.

Using monkey

Monkey's API is very simple and straightfoward. Call monkey.Patch(<target function>, <replacement function>) to replace a function. For example:

package main

import (
	"fmt"
	"os"
	"strings"

	"bou.ke/monkey"
)

func main() {
	monkey.Patch(fmt.Println, func(a ...interface{}) (n int, err error) {
		s := make([]interface{}, len(a))
		for i, v := range a {
			s[i] = strings.Replace(fmt.Sprint(v), "hell", "*bleep*", -1)
		}
		return fmt.Fprintln(os.Stdout, s...)
	})
	fmt.Println("what the hell?") // what the *bleep*?
}

You can then call monkey.Unpatch(<target function>) to unpatch the method again. The replacement function can be any function value, whether it's anonymous, bound or otherwise.

If you want to patch an instance method you need to use monkey.PatchInstanceMethod(<type>, <name>, <replacement>). You get the type by using reflect.TypeOf, and your replacement function simply takes the instance as the first argument. To disable all network connections, you can do as follows for example:

package main

import (
	"fmt"
	"net"
	"net/http"
	"reflect"

	"bou.ke/monkey"
)

func main() {
	var d *net.Dialer // Has to be a pointer to because `Dial` has a pointer receiver
	monkey.PatchInstanceMethod(reflect.TypeOf(d), "Dial", func(_ *net.Dialer, _, _ string) (net.Conn, error) {
		return nil, fmt.Errorf("no dialing allowed")
	})
	_, err := http.Get("http://google.com")
	fmt.Println(err) // Get http://google.com: no dialing allowed
}

Note that patching the method for just one instance is currently not possible, PatchInstanceMethod will patch it for all instances. Don't bother trying monkey.Patch(instance.Method, replacement), it won't work. monkey.UnpatchInstanceMethod(<type>, <name>) will undo PatchInstanceMethod.

If you want to remove all currently applied monkeypatches simply call monkey.UnpatchAll. This could be useful in a test teardown function.

If you want to call the original function from within the replacement you need to use a monkey.PatchGuard. A patchguard allows you to easily remove and restore the patch so you can call the original function. For example:

package main

import (
	"fmt"
	"net/http"
	"reflect"
	"strings"

	"bou.ke/monkey"
)

func main() {
	var guard *monkey.PatchGuard
	guard = monkey.PatchInstanceMethod(reflect.TypeOf(http.DefaultClient), "Get", func(c *http.Client, url string) (*http.Response, error) {
		guard.Unpatch()
		defer guard.Restore()

		if !strings.HasPrefix(url, "https://") {
			return nil, fmt.Errorf("only https requests allowed")
		}

		return c.Get(url)
	})

	_, err := http.Get("http://google.com")
	fmt.Println(err) // only https requests allowed
	resp, err := http.Get("https://google.com")
	fmt.Println(resp.Status, err) // 200 OK <nil>
}

Notes

  1. Monkey sometimes fails to patch a function if inlining is enabled. Try running your tests with inlining disabled, for example: go test -gcflags=-l. The same command line argument can also be used for build.
  2. Monkey won't work on some security-oriented operating system that don't allow memory pages to be both write and execute at the same time. With the current approach there's not really a reliable fix for this.
  3. Monkey is not threadsafe. Or any kind of safe.
  4. I've tested monkey on OSX 10.10.2 and Ubuntu 14.04. It should work on any unix-based x86 or x86-64 system.

Β© Bouke van der Bijl

More Repositories

1

staticfiles

staticfiles compiles a directory of files into an embeddable .go file
Go
505
star
2

extractdata

Live at http://extractdata.club
Go
169
star
3

dark-mode-notify

Run a script whenever dark mode changes in macOS
Swift
158
star
4

babelfish

Translate bash scripts to fish
Go
122
star
5

gonerics

Generics for go
Go
114
star
6

statictemplate

Statictemplate is a code generator for Go's text/template and html/template.
Go
76
star
7

go-faster

You can always Go faster
Go
49
star
8

HTTPS4All

Rewrite HTTP hosts to HTTPS whenever possible
Swift
33
star
9

b

My setup
Nix
30
star
10

kubectl-dashboard

Instantly get a Kubernetes dashboard
Go
14
star
11

https-everywhere-host-list

Tool to convert HTTPS Everywhere rules to a list of hosts that support HTTPS.
HTML
12
star
12

memorizationbot

Source code for https://memorizationbot.com/
Go
10
star
13

arduino-nix

Manage your arduino-cli with Nix
Nix
9
star
14

deoplete-markdown-links

Complete wiki links and tags in Markdown.
Python
7
star
15

esbuild-ruby

Ruby
6
star
16

unsafer

This is a bad idea
Go
4
star
17

proxy-now

Use Tasker to add custom voice commands to Google Now
Java
4
star
18

gameboy-emu

Go
3
star
19

go-lisp

A lisp interpreter in go
Go
3
star
20

objfile

Go
3
star
21

splendimax

Splendor AI that uses minimax to play
Rust
3
star
22

elfie

Package elfie takes an 'ELF-selfie' of the current process.
Go
3
star
23

file2const

Generates a Go file containing the given files as strings
Go
3
star
24

rust-sysv-ipc

Implementation of Sysv IPC for Rust
Rust
2
star
25

symme

Retrieve the symbol table for the current process
Go
2
star
26

boggle-solver

Show all possible words given a boggle board
C++
2
star
27

procmaps

Package procmaps provides a parser for the /proc maps format
Go
2
star
28

uva

My various uva solutions
C++
1
star
29

whoamits

Service that tells you who you are based on Tailscale
Go
1
star
30

hyves-stats

Track Hyves' users' stats
PHP
1
star
31

cross-chain-nix

Binutils cross-compilation toolchains for nix
Nix
1
star
32

tempdb

Go
1
star
33

orm

An ORM for Go that's good. WIP
Go
1
star
34

gotre

Go Tail Recursion Eliminator
Go
1
star
35

rayray

Rust
1
star
36

putio

This is a webOS application that immediately redirects to tv.put.io
HTML
1
star
37

esbuilder

Integrate esbuild into Rails
Ruby
1
star
38

fast-postgres

Fast postgres Docker image for tests
1
star
39

motion-pong

Motion controlled pong game for school project
Python
1
star
40

ctxdb

ctxdb provides access to the database through a Context
Go
1
star
41

webgl-sand

A falling sand game completely implemented in webgl
JavaScript
1
star
42

tools

Misc command line utilities
Go
1
star
43

skype-db

Ruby
1
star
44

txdriver

txdriver provides transaction isolation for Go SQL tests
Go
1
star
45

go-template-parser

Go
1
star
46

watch-dragonball-xbmc

An addon that makes it possible to watch all Dragonball series through XBMC
Python
1
star
47

terraform-provider-ejson

A Terraform provider that can decrypt ejson on-the-fly
Go
1
star
48

exhaustive-enum

Exhaustive-enum is an exhaustive enum checker for Go. It can be used to make sure you don't miss any cases when switching over an enumeration.
Go
1
star