{"id":13472987,"url":"https://github.com/bouk/monkey","last_synced_at":"2025-03-26T17:31:36.622Z","repository":{"id":29517359,"uuid":"33055762","full_name":"bouk/monkey","owner":"bouk","description":"Monkey patching in Go","archived":true,"fork":false,"pushed_at":"2020-06-17T09:49:36.000Z","size":30,"stargazers_count":3341,"open_issues_count":2,"forks_count":370,"subscribers_count":46,"default_branch":"master","last_synced_at":"2024-10-30T05:26:24.518Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://bou.ke","language":"Go","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bouk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-03-29T00:26:32.000Z","updated_at":"2024-10-29T12:37:56.000Z","dependencies_parsed_at":"2022-07-07T22:15:19.488Z","dependency_job_id":null,"html_url":"https://github.com/bouk/monkey","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bouk%2Fmonkey","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bouk%2Fmonkey/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bouk%2Fmonkey/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bouk%2Fmonkey/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bouk","download_url":"https://codeload.github.com/bouk/monkey/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245096308,"owners_count":20560263,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T16:00:59.765Z","updated_at":"2025-03-26T17:31:36.347Z","avatar_url":"https://github.com/bouk.png","language":"Go","funding_links":[],"categories":["开源类库","Test","Misc","Go","Open source library","Exploit Development"],"sub_categories":["测试","Test"],"readme":"# Go monkeypatching :monkey_face: :monkey:\n\nActual arbitrary monkeypatching for Go. Yes really.\n\nRead this blogpost for an explanation on how it works: https://bou.ke/blog/monkey-patching-in-go/\n\n## I thought that monkeypatching in Go is impossible?\n\nIt'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.**\n\nMake sure you read the notes at the bottom of the README if you intend to use this library.\n\n## Using monkey\n\nMonkey's API is very simple and straightfoward. Call `monkey.Patch(\u003ctarget function\u003e, \u003creplacement function\u003e)` to replace a function. For example:\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"bou.ke/monkey\"\n)\n\nfunc main() {\n\tmonkey.Patch(fmt.Println, func(a ...interface{}) (n int, err error) {\n\t\ts := make([]interface{}, len(a))\n\t\tfor i, v := range a {\n\t\t\ts[i] = strings.Replace(fmt.Sprint(v), \"hell\", \"*bleep*\", -1)\n\t\t}\n\t\treturn fmt.Fprintln(os.Stdout, s...)\n\t})\n\tfmt.Println(\"what the hell?\") // what the *bleep*?\n}\n```\n\nYou can then call `monkey.Unpatch(\u003ctarget function\u003e)` to unpatch the method again. The replacement function can be any function value, whether it's anonymous, bound or otherwise.\n\nIf you want to patch an instance method you need to use `monkey.PatchInstanceMethod(\u003ctype\u003e, \u003cname\u003e, \u003creplacement\u003e)`. 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:\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"reflect\"\n\n\t\"bou.ke/monkey\"\n)\n\nfunc main() {\n\tvar d *net.Dialer // Has to be a pointer to because `Dial` has a pointer receiver\n\tmonkey.PatchInstanceMethod(reflect.TypeOf(d), \"Dial\", func(_ *net.Dialer, _, _ string) (net.Conn, error) {\n\t\treturn nil, fmt.Errorf(\"no dialing allowed\")\n\t})\n\t_, err := http.Get(\"http://google.com\")\n\tfmt.Println(err) // Get http://google.com: no dialing allowed\n}\n\n```\n\nNote 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(\u003ctype\u003e, \u003cname\u003e)` will undo `PatchInstanceMethod`.\n\nIf you want to remove all currently applied monkeypatches simply call `monkey.UnpatchAll`. This could be useful in a test teardown function.\n\nIf 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:\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"bou.ke/monkey\"\n)\n\nfunc main() {\n\tvar guard *monkey.PatchGuard\n\tguard = monkey.PatchInstanceMethod(reflect.TypeOf(http.DefaultClient), \"Get\", func(c *http.Client, url string) (*http.Response, error) {\n\t\tguard.Unpatch()\n\t\tdefer guard.Restore()\n\n\t\tif !strings.HasPrefix(url, \"https://\") {\n\t\t\treturn nil, fmt.Errorf(\"only https requests allowed\")\n\t\t}\n\n\t\treturn c.Get(url)\n\t})\n\n\t_, err := http.Get(\"http://google.com\")\n\tfmt.Println(err) // only https requests allowed\n\tresp, err := http.Get(\"https://google.com\")\n\tfmt.Println(resp.Status, err) // 200 OK \u003cnil\u003e\n}\n```\n\n## Notes\n\n1. 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.\n2. 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.\n3. Monkey is not threadsafe. Or any kind of safe.\n4. 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.\n\n© Bouke van der Bijl\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbouk%2Fmonkey","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbouk%2Fmonkey","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbouk%2Fmonkey/lists"}