最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】go代码中直接使用http返回的body赋值给string结果出错:cannot use body (type []byte) as type string in assignment

GO crifan 11061浏览 0评论

【问题】

折腾:

【记录】用go语言实现模拟登陆百度

期间,使用代码:

package main

import (
    "fmt"
    "log"
    "os"
    "io/ioutil"
    "net/http"
    "runtime"
    "path"
    "strings"
)

// GetCurFilename
// Get current file name, without suffix
func GetCurFilename() string {
    _, fulleFilename, _, _ := runtime.Caller(0)
    //fmt.Println(fulleFilename)
    var filenameWithSuffix string
    filenameWithSuffix = path.Base(fulleFilename)
    //fmt.Println("filenameWithSuffix=", filenameWithSuffix)
    var fileSuffix string
    fileSuffix = path.Ext(filenameWithSuffix)
    //fmt.Println("fileSuffix=", fileSuffix)
    
    var filenameOnly string
    filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix)
    //fmt.Println("filenameOnly=", filenameOnly)
    
    return filenameOnly
}

//get url response html
func GetUrlRespHtml(url string) string{
    var respHtml string = "";
    
    resp, err := http.Get(url)
    if err != nil {
        fmt.Printf("http get response errror=%s\n", err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    //fmt.Printf("body=%s\n", body)
    
    respHtml = body

    return respHtml
}

func main() {
    fmt.Printf("this is EmulateLoginBaidu.go\n")
    
    var filenameOnly string
    filenameOnly = GetCurFilename()
    fmt.Println("filenameOnly=", filenameOnly)
    
    var logFilename string =  filenameOnly + ".log";
    fmt.Println("logFilename=", logFilename)
    //logfile,err: = os.OpenFile("/Users/cybercare/tmp/test.log",os.O_RDWR|os.O_CREATE,0666)
    //logFile, err: = os.OpenFile(logFilename, os.O_RDWR | os.O_CREATE, 0777)
    //logFile, err: = os.OpenFile(logFilename, os.O_RDWR | os.O_CREATE, 0777);
    logFile, err := os.OpenFile(logFilename, os.O_RDWR | os.O_CREATE, 0777)
    if err != nil {
        fmt.Printf("open file error=%s\r\n", err.Error())
        os.Exit(-1)
    }

    defer logFile.Close()
    //logger:=log.New(logFile,"\r\n", log.Ldate | log.Ltime | log.Llongfile)
    logger:=log.New(logFile,"\r\n", log.Ldate | log.Ltime | log.Lshortfile)
    logger.Println("normal log 1")
    logger.Println("normal log 2")
    //【已解决】go代码出错退出:exit status 1
    //https://www.crifan.com/go_language_can_printf_info_and_exit_status_1/
    //logger.Panic("panic 1")
    //logger.Fatal("fatal 1")
    
    var baiduMainUrl string
    baiduMainUrl = "http://www.baidu.com/";
    //baiduMainUrl := "http://www.baidu.com/";
    //var baiduMainUrl string = "http://www.baidu.com/";
    fmt.Printf("baiduMainUrl=%s", baiduMainUrl)
    respHtml := GetUrlRespHtml(baiduMainUrl)
    logger.Printf("respHtml=%s", respHtml)
}

结果出错:

D:\tmp\tmp_dev_root\go\src\github.com\user\EmulateLoginBaidu>go run EmulateLoginBaidu.go
# command-line-arguments
.\EmulateLoginBaidu.go:45: cannot use body (type []byte) as type string in assignment

如图:

cannot use body type byte as type string in assignment

即:

cannot use body (type []byte) as type string in assignment

【解决过程】

1.很明显,此处:

body, err := ioutil.ReadAll(resp.Body)

中的的body,不是string,所以不能直接赋值。

因为之前听说了,go中是强类型,不同类型,无法直接赋值。

2.然后就是要去搞懂,此处的body,具体是什么类型的。

然后找到:

func ReadAll

中是:

func ReadAll(r io.Reader) ([]byte, error)

ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

即,此处的body是:[]byte 的类型。

所以,此处,去直接强制将[]byte转换为string:

respHtml = string(body)

试试是否可以,结果是可以的,可以正常运行的:

D:\tmp\tmp_dev_root\go\src\github.com\user\EmulateLoginBaidu>go run EmulateLoginBaidu.go
this is EmulateLoginBaidu.go
filenameOnly= EmulateLoginBaidu
logFilename= EmulateLoginBaidu.log
baiduMainUrl=http://www.baidu.com/
D:\tmp\tmp_dev_root\go\src\github.com\user\EmulateLoginBaidu>

如图:

after byte array cast to string go run ok

 

【总结】

此处,是ioutil.ReadAll获得了[]byte的字节数组,不能直接赋值给string变量。

所以去强制转换:

respHtml = string(body)

后,就可以了。

转载请注明:在路上 » 【已解决】go代码中直接使用http返回的body赋值给string结果出错:cannot use body (type []byte) as type string in assignment

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.184 seconds, using 22.14MB memory