登录
首页 >  Golang >  Go问答

Golang httptest 服务器循环引用

来源:stackoverflow

时间:2024-02-29 22:54:20 254浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Golang httptest 服务器循环引用》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我想为一个函数编写一个测试

  1. 向 url1 发出 get 请求,该请求检索 url2
  2. 向 url2 发出 get 请求,并返回结果

但是我不确定如何模拟 url2 的返回值,因为我无法在服务器启动之前获取 server.url。但是服务器启动后我无法更改处理程序。例如,运行以下命令会出现错误 get /url2: 不支持的协议方案 ""

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/http/httptest"
)

func myFunc(client *http.Client, url1 string) string {
    url2 := get(client, url1)
    return get(client, url2)
}

func get(client *http.Client, url string) string {
    resp, err := client.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    body, err := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    if err != nil {
        fmt.Println(err)
    }
    return string(body)
}

// test myFunc
func main() {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        switch r.URL.String() {
        case "/url1":
            w.Write([]byte("/url2")) // how to specify srv.URL+"/url2" here?
        case "/url2":
            w.Write([]byte("return data"))
        }
    }))
    defer srv.Close()

    myFunc(srv.Client(), srv.URL+"/url1")
}

来源:https://onlinegdb.com/upklxfw45


正确答案


使用变量之前先声明 srv 变量。

var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    switch r.URL.String() {
    case "/url1":
        w.Write([]byte(srv.URL + "/url2")) 
    case "/url2":
        w.Write([]byte("return data"))
    }
}))

到这里,我们也就讲完了《Golang httptest 服务器循环引用》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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