第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

語義方式Go 中的響應(yīng)接收器函數(shù)

語義方式Go 中的響應(yīng)接收器函數(shù)

Go
動(dòng)漫人物 2022-10-04 15:59:33
我剛剛開始學(xué)習(xí)GO并編寫了這段代碼,用于編寫文件或文件,但我對它的語義不滿意。http.Response.Bodyos.Stdout我希望結(jié)構(gòu)具有這些接收器功能,以便我可以在整個(gè)應(yīng)用程序中更輕松地使用它。http.Response我知道答案可能會(huì)被標(biāo)記為固執(zhí)己見,但我仍然想知道,有沒有更好的方法來寫這個(gè)?是否有某種最佳實(shí)踐?package mainimport (    "fmt"    "io"    "io/ioutil"    "net/http"    "os")type httpResp http.Responsefunc main() {    res, err := http.Get("http://www.stackoverflow.com")    if err != nil {        fmt.Println("Error: ", err)        os.Exit(1)    }    defer res.Body.Close()    response := httpResp(*res)    response.toFile("stckovrflw.html")    response.toStdOut()}func (r httpResp) toFile(filename string) {    str, err := ioutil.ReadAll(r.Body)    if err != nil {        panic(err)    }    ioutil.WriteFile(filename, []byte(str), 0666)}func (r httpResp) toStdOut() {    _, err := io.Copy(os.Stdout, r.Body)    if err != nil {        panic(err)    }}順便說一句,有沒有辦法讓該方法吐出一個(gè)已經(jīng)可以訪問這些接收器函數(shù)的自定義類型,而無需強(qiáng)制轉(zhuǎn)換?所以我可以做這樣的事情:http.Getfunc main() {    res, err := http.Get("http://www.stackoverflow.com")    if err != nil {        fmt.Println("Error: ", err)        os.Exit(1)    }    defer res.Body.Close()    res.toFile("stckovrflw.html")    res.toStdOut()}謝謝!
查看完整描述

1 回答

?
拉丁的傳說

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊

您不必實(shí)現(xiàn)這些功能。 已經(jīng)實(shí)現(xiàn)了 io。作者*http.Response

以 HTTP/1.x 服務(wù)器響應(yīng)格式寫入 r 到 w,包括狀態(tài)行、標(biāo)頭、正文和可選的尾部。

package main


import (

    "net/http"

    "os"

)


func main() {

    r := &http.Response{}

    r.Write(os.Stdout)

}

在上面的示例中,零值打?。?/p>

HTTP/0.0 000 狀態(tài)代碼 0

內(nèi)容長度: 0

游樂場: https://play.golang.org/p/2AUEAUPCA8j


如果在編寫方法中需要其他業(yè)務(wù)邏輯,則可以嵌入到定義的類型中:*http.Response

type RespWrapper struct {

    *http.Response

}


func (w *RespWrapper) toStdOut() {

    _, err := io.Copy(os.Stdout, w.Body)

    if err != nil {

        panic(err)

    }

但是,您必須使用 構(gòu)造一個(gè)類型的變量:RespWrapper*http.Response


func main() {

    // resp with a fake body

    r := &http.Response{Body: io.NopCloser(strings.NewReader("foo"))}

    // or r, _ := http.Get("example.com")


    // construct the wrapper

    wrapper := &RespWrapper{Response: r}

    wrapper.toStdOut()

}

有沒有辦法使網(wǎng)址。獲取方法吐出自定義類型

不可以,返回類型是 ,這是函數(shù)簽名的一部分,您無法更改它。http.Get(resp *http.Response, err error)


查看完整回答
反對 回復(fù) 2022-10-04
  • 1 回答
  • 0 關(guān)注
  • 70 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號