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

I'm studying Go and started a small web application.

Amazing. But I've already got the very basics.

So, what do you think would be a good documentation source for Go web application for real?

For example, now I have 15 methods that get "http.ResponseWriter" and etc as parameter (tons of repetition I mean).

I guess there's a better way of doing that.

But I don't want to start programming Go with the exact mindset (solutions) of other languages (Python, Ruby, Perl etc).

Not because it's wrong but because it can be (I don't know, that's the point) a mistake.

Here's an example:

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)
}

[]s Gio

This is how handlers are usually written in Go since they have to have that specific signature to be able to accept the two parameter values that you need to be able to handle a request.

Now if you're intent on reducing the amount of typing you can certainly get around this. There are probably many ways how to do that but one that comes to mind would look something like this.

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))

Personally I wouldn't recommend to change your handlers from the standard ones because you may loose some clarity when you do that, for example other developers might be confused when reading your code and seeing a non-standard handler.