gpt4 book ai didi

go - 在 Go Lang 中避免 http.ResponseWriter 等类型重复

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:08 27 4
gpt4 key购买 nike

我正在学习 Go 并开始了一个小型网络应用程序。

太棒了。但我已经掌握了最基本的知识。

那么,您认为真正的 Go web 应用程序的良好文档源是什么?

例如,现在我有 15 个方法获取“http.ResponseWriter”等作为参数(我的意思是大量重复)。

我想有更好的方法。

但我不想以其他语言(Python、Ruby、Perl 等)的确切思维方式(解决方案)开始编程 Go。

不是因为它是错误的,而是因为它可能是(我不知道,这就是重点)错误。

这是一个例子:

func newStudentHandler(w http.ResponseWriter, r *http.Request) {
p := studentPage{Title:"New Student"}
t, _ := template.ParseFiles("new_student.html")
t.Execute(w, p)
}

func newTeacherHandler(w http.ResponseWriter, r *http.Request) {
p := teacherPage{Title:"New Teacher"}
t, _ := template.ParseFiles("new_teacher.html")
t.Execute(w, p)

}

func newClassHandler(w http.ResponseWriter, r *http.Request) {
p := classPage{Title:"New Class"}
t, _ := template.ParseFiles("new_class.html")
t.Execute(w, p)
}

[]秒吉奥

最佳答案

这就是处理程序通常用 Go 编写的方式,因为它们必须具有特定的签名才能接受处理请求所需的两个参数值。

现在,如果您打算减少打字量,您肯定可以解决这个问题。可能有很多方法可以做到这一点,但我想到的一种看起来像这样。

type H struct {
w http.ResponseWriter
r *http.Request
}

type HF func(H)

func (f HF) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f(H{w:w, r:r})
}

func (h H) newStudent() {
p := studentPage{Title:"New Student"}
t, _ := template.ParseFiles("new_student.html")
t.Execute(h.w, p)
}

func (h H) newTeacher() {
p := teacherPage{Title:"New Teacher"}
t, _ := template.ParseFiles("new_teacher.html")
t.Execute(h.w, p)

}

func (h H) newClass() {
p := classPage{Title:"New Class"}
t, _ := template.ParseFiles("new_class.html")
t.Execute(h.w, p)
}

// ...

http.Handle("/students", HF(H.newStudent))
http.Handle("/teachers", HF(H.newTeacher))
http.Handle("/classes", HF(H.newClass))

我个人不建议更改您的标准处理程序,因为这样做时您可能会失去一些清晰度,例如,其他开发人员在阅读您的代码并看到非标准处理程序时可能会感到困惑。

关于go - 在 Go Lang 中避免 http.ResponseWriter 等类型重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47114392/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com