doujichan1399 2015-11-29 00:57
浏览 223
已采纳

在golang中使用示例主体字符串创建http.Response实例

I am willing to create a sample http.Response instance in golang with a sample body string.

Problem is, its body property accepts ReadCloser instance. But as its a dummy response instance, I was wondering if there is some trick to set it easily without setting up all that stream read/close parts.

  • 写回答

3条回答 默认 最新

  • doulianglou0898 2015-11-29 15:24
    关注

    As suggested by Not_a_Golfer and JimB:

    io.ReadCloser is an interface that is satisfied when a struct implements both the Read and the Close functions.

    Fortunately, there is ioutil.NopCloser, which takes a io.Reader and wraps it in the nopCloser struct, which implements both Read and Close. However, its Close function does nothing as implied from the name.

    Here is an example:

    package main
    
    import (
        "bytes"
        "fmt"
        "io/ioutil"
        "net/http"
    )
    
    func main() {
        t := http.Response{
            Body: ioutil.NopCloser(bytes.NewBufferString("Hello World")),
        }
    
        buff := bytes.NewBuffer(nil)
        t.Write(buff)
    
        fmt.Println(buff)
    }
    

    To play with the code, click here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?