golang如何覆盖http包方法?

tom*_*l18 -1 go

我想覆盖下面的方法(在 request.go 中)以应用转义字符串(例如:template.HTMLEscapeString(r.FormValue("some_param"))。

我想覆盖,因为我不想在每次 FormValue 调用时都进行转义。

有没有办法这样做?

func (r *Request) FormValue(key string) string{
    if r.Form == nil {
        r.ParseMultipartForm(defaultMaxMemory)
    }
    if vs := r.Form[key]; len(vs) > 0 {
        return vs[0]
    }
    return ""
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*arc 6

你不能在 Go 中覆盖任何东西。

这里最简单的解决方案是按照以下方式定义一个小的辅助函数:

func EscapeFormValue(req *http.Request, key string) string {
    return template.HTMLEscapeString(req.FormValue(key))
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你真的想要一个具有相同方法的自定义结构,你可以使用嵌入来包装http.Request并使用新的包装类型:

type newReq struct {
    *http.Request
}

func (n *newReq) FormValue(key string) string {
    return fmt.Sprintf("value: %s", n.Request.FormValue(key))
}

func main() {
    req := &http.Request{Method: "GET"}
    req.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar")
    n := newReq{req}
    fmt.Println(n.FormValue("q"))
}
Run Code Online (Sandbox Code Playgroud)

这输出:

value: foo
Run Code Online (Sandbox Code Playgroud)

请注意,这仅有效,因为我们正在使用newReq它自己。在 a 上运行的任何东西(包括 http 包)http.Request都需要嵌入的结构,而不会看到newReq.FormValue. 这就是它与覆盖不同的地方