ServeHTTP方法从何而来

时间:2018-12-20 01:49:55

标签: go

这让我对学习Go的最后一个月感到困惑:

const OtherComponent = React.lazy(() => {
  const x = new Promise((resolve) => {
    setTimeout(() => {
      return resolve(import("./Child"))
    }, 1500)
  })
  return x;
});

class App extends Component {
  render() {
    return (
      <div className="App">
        <Suspense fallback={<div>Loading...</div>}>
          <OtherComponent />
        </Suspense>
      </div>
    );
  }
}

在这里我们可以看到Auth函数返回类型func Auth(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // hmmmm // ... next.ServeHTTP(w, r) } } 。 这种类型只是一个函数。因此,当您调用http.HandlerFunc时,将在何时/何处定义该方法?

1 个答案:

答案 0 :(得分:2)

https://golang.org/src/net/http/server.go?s=59707:59754#L1950

// 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)
}
可以将具有签名func(ResponseWriter, *Request)

任何 any 函数强制转换为HandlerFunc,从而为它提供方法ServeHTTP-然后简单地调用该函数。