golang如何重写http包方法?

时间:2018-01-24 11:17:06

标签: 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 ""
}

1 个答案:

答案 0 :(得分:0)

您无法覆盖Go中的任何内容。

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

func EscapeFormValue(req *http.Request, key string) string {
    return template.HTMLEscapeString(req.FormValue(key))
}

但是,如果您确实需要使用相同方法的自定义结构,则可以使用embedding来包装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"))
}

输出:

value: foo

请注意,这仅适用,因为我们自己使用newReq。在http.Request上运行的任何内容(包括http包)都需要嵌入式结构,而不会看到newReq.FormValue。这就是与覆盖不同的原因。