Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

go - How does ServeHTTP work?

I am studying web development in Golang (Beginner) I came across some code I played around with and I'm not too sure why it works, I looked through the library source code and docs but I only have a vague idea it still isn't clicking. Note the code below:

package main

import (
    "fmt"
    "net/http"
)

type foo int

func (m foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Some text")
}

func main() {
    var bar foo
    http.ListenAndServe(":8080", bar)
}

From what I understand adding ServeHTTP(w http.ResponseWriter, r *http.Request) as a function method, invokes the handler interface (if I'm saying that correctly) and now foo is of type handler as well. I also understand that http.ListenAndServe takes an input of type handler so that is where my variable bar comes into play. When I run the code and go to localhost:8080 on my browser I get "Some Text" appearing.

EDIT: Implements the interface is the proper term NOT invoke.

Question:

How does this exactly work? How is that ServeHTTP function being accessed?

I tried looking at the source code of the libraries but couldn't pinpoint exactly how ServeHTTP worked. I found these two pieces of code (not sure if this is applicable) that sort of gave me the idea it was implementing a function but need clarification:

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

I have never seen a type declaration as the one above with HandlerFunc that has a function after the name of the type. I have also seen how methods are declared but not sure what is happening in the code above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...