Golang 使用net/http下载文件

简单例子
package main

import (
    "io"
    "net/http"
    "os"
)

var (
    url = "https://blog.csdn.net/LU_ZHAO/article/details/104935957"
)

func main() {
    res, err := http.Get(url)
    if (res != nil) {
    	defer resp.Body.Close()
    }
    if err != nil {
        panic(err)
    }
    
    f, err := os.Create("TheSerenityPrayer.html")
    if (f != nil) {
    	defer f.Close()
    }
    if err != nil {
        panic(err)
    }
    
    io.Copy(f, res.Body)
}

运行:

:go run main.go
:ls
The_Serenity_Prayer.html	main.go
:head The_Serenity_Prayer.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <link rel="canonical" href="https://blog.csdn.net/LU_ZHAO/article/details/104935957"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="renderer" content="webkit"/>
    <meta name="force-rendering" content="webkit"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
:

你可能感兴趣的:(Golang)