补丁标准包

I want to replace some function from standard Go library (os.Exit specifically). Can I do that? I tried:

myExitValue := reflect.ValueOf(func() {
    fmt.Println("exiting")
})
reflect.ValueOf(os.Exit).Set(myExitValue)

But it panics: reflect: reflect.Value.Set using unaddressable value

Thanks to mkopriva.

package main

import (
    "fmt"
    "os"

    "github.com/bouk/monkey"
)

func myExit(code int) {
    _ = code
    fmt.Println(`I think you shouldn't exit.`)
}

func init() {
    monkey.Patch(os.Exit, myExit)
}

func main() {
    os.Exit(1)
    fmt.Println(`But why?`)
}

I don't think what you are trying to do is achievable even with help of Reflect library. By calling Go's function/method from another package, you are calling a copy of the original code.

You would have to either make wrapper function which somehow changes original behavior, which is cleaner and better way of handling for this kind of purposes. E.g.:

// Do stuff what you need.
func ExitLog(message string) {
   fmt.Printf("an error occured with message: '%s'", message)
   os.Exit(1)
}

and call the function instead of the original one.

Edit: Someone in the comments mentioned a library for doing such a thing, but please reconsider your intention. Rewriting package's behavior by hacking it is not considered clean and/or good practice.

Edit2: If you are trying to send a message whenever an error occurs, take a look at publish-subscribe pattern: