-
慕姐4208626
正如Not_a_Golfer和JimB所建议的:io.ReadCloser是一个接口,当 astruct实现Read和Close函数时满足。幸运的是,有ioutil.NopCloser,它接受 aio.Reader并将其包装在nopCloser结构中,该结构同时实现Read和Close。然而,它的Close功能并没有从名字中暗示出来。下面是一个例子:package mainimport ( "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)}
-
当年话下
除了最上面的答案,我发现为了让客户将响应视为真品,它需要更完整地形成。对于正常 (200) 响应,我执行以下操作:body := "Hello world"t := &http.Response{ Status: "200 OK", StatusCode: 200, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Body: ioutil.NopCloser(bytes.NewBufferString(body)), ContentLength: int64(len(body)), Request: req, Header: make(http.Header, 0),}然后你可以,例如,添加标题(带有 401 状态代码,请求授权,比如说)。req是http.Request您为其生成响应的 。
-
吃鸡游戏
这应该工作..func main(){ go serveHTTP(*port, *host) select {}}func serveHTTP(port int, host string) { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { requestHandler(w, r) }) addr := fmt.Sprintf("%v:%d", host, port) server := &http.Server { Addr: addr, Handler: mux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } err := server.ListenAndServe() log.Println(err.Error())}func requestHandler(w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, `Success!`)}