登录
首页 >  Golang >  Go问答

实现HTTP请求的两种途径

来源:stackoverflow

时间:2024-02-20 11:18:25 465浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《实现HTTP请求的两种途径》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我需要实现两个调用的接口,

1.   req, err := http.newrequest("get", "http://example.com/healthz", nil)
2. req, err := http.newrequest("get", "http://localhost:8082/rest/foos/9", nil)

但是接口使用的是 *http.request 类型的 req 方法,我该怎么办?

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

https://play.golang.org/p/pvpkd-_mfrs


解决方案


根据我的评论,不要使用 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/ 

https://play.golang.org/p/ktb2xX7DHKI

到这里,我们也就讲完了《实现HTTP请求的两种途径》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>