Golang踩坑录 两种方式来读取文件一行所导致的问题

关键词: Golang, 读写

前两天零零碎碎看完了golang的基础,想着找个小项目练练手,可是出现了一个十分棘手的问题
我要做的东西是网站路径爆破
所以我会从文本字典中把一行行路径读取然后与域名拼接,但是我在跑起程序后出现了问题

下面是一个小片段


400 Bad Request-----http://www.xxx.com/channel.asp
400 Bad Request-----http://www.xxx.com/index.asp
404 Not Found-----http://www.xxx.com/admin.asp

程序本身并没有错误,但是运行结果就比较怪了
Bad Request?
这并不是我要说的重点,我发现的问题是,除了最后一个地址,前面所有的地址都会显示位400 Bad Request
经过几轮测试,我觉得应该是网址拼接上出了问题

我的拼接函数是这样


func ReturnBurstURL(fURL *os.File, baseurl string) (urlList []string) {
	allURLTxt := bufio.NewReader(fURL)
	for {
		urlpath, readerError := allURLTxt.ReadString('\n')
		newurl := baseurl + strings.Replace(urlpath, "\n", "", -1)
		urlList = append(urlList, newurl)
		if readerError == io.EOF {
			fmt.Printf("\n读取字典完成,准备开始,请等待...\n")
			return urlList
		}
	}
}

我把取一行的方式换成bufio.NewScanner就正常了


func ReturnBurstURL(fURL *os.File, baseurl string) (urlList []string) {
	allURLTxt := bufio.NewScanner(fURL)
	for allURLTxt.Scan() {
		newurl := baseurl + allURLTxt.Text()
		urlList = append(urlList, newurl)
	}
	fmt.Printf("\n读取字典完成,准备开始,请等待...\n")
	return urlList
}

网上读取文件一行很多人写的文章是第一种方法,但是我也不知道什么问题导致这种情况的发生
我特地去查了查api文档


func NewReader(rd io.Reader) *Reader
//NewReader returns a new Reader whose buffer has the default size. 
func (b *Reader) ReadString(delim byte) (string, error)
//ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient. 
func NewScanner(r io.Reader) *Scanner
//NewScanner returns a new Scanner to read from r. The split function defaults to ScanLines. 
func (s *Scanner) Scan() bool
//Scan advances the Scanner to the next token, which will then be available through the Bytes or Text method. It returns false when the scan stops, either by reaching the end of the input or an error. After Scan returns false, the Err method will return any error that occurred during scanning, except that if it was io.EOF, Err will return nil. Scan panics if the split function returns 100 empty tokens without advancing the input. This is a common error mode for scanners. 
func (s *Scanner) Text() string
//Text returns the most recent token generated by a call to Scan as a newly allocated string holding its bytes. 

按照上面的api文档,这两个的区别就是两者在返回string的时候,一个是数据+分隔符,一个是一行的数据,不带分隔符
虽说我第一种方法也用strings.Replace方法把"\n"替换成了""空字符,但是可能还是有点奇奇怪怪的东西

喜欢本文?求鼓励,求支持!

创作时间: 2017.02.04 22:55
最后修改: 2017.03.27 18:40

本文版权:Akkuman's   共享协议:署名-非商业使用-禁止演绎


随机推荐:



Title - Artist
0:00
TOP