我有这个接口,需要实现两次通话
1. req, err := http.NewRequest("GET", "http://example.com/healthz", nil)
2. req, err := http.NewRequest("GET", "http://localhost:8082/rest/foos/9", nil)
但是接口使用的是req
类型的*http.Request
方法,我应该怎么做?
type HealthChecker interface {
Name() string
Check(req *http.Request) error
}
type ping struct{}
func (p ping) Check(req *http.Request) error {
}
func (ping) Name() string {
return "check1"
}
答案 0 :(得分:1)
根据我的评论,请不要使用interface
来使问题复杂化。
一个简单的struct
就足够了:
type HealthChecker struct {
URL string
}
func (h HealthChecker) Check() error {
resp, err := http.Get(h.URL)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("got http status %d instead of %d", resp.StatusCode, http.StatusOK)
}
return nil
}
要使用:
ex := HealthChecker{"http://example.com/healthz"}
log.Println(ex.URL, ex.Check()) // http://example.com/healthz got http status 404 instead of 200
g := HealthChecker{"http://google.com/"}
log.Println(g.URL, g.Check()) // http://google.com/ <nil>