• Go基础编程实践(九)—— 网络编程


    下载网页

    package main
    
    import (
        "io/ioutil"
        "net/http"
        "fmt"
    )
    
    func main() {
        url := "http://www.cnblogs.com/GaiheiluKamei"
        response, err := http.Get(url)
        if err != nil {
            panic(err)
        }
        defer response.Body.Close()
        html, err2 := ioutil.ReadAll(response.Body)
        if err2 != nil {
            panic(err2)
        }
        // ReadAll返回[]byte
        fmt.Println(string(html))
    }
    // 这种直接下载下来的网页用处不大,旨在提供思路
    

    下载文件

    package main
    
    import (
        "net/http"
        "io"
        "os"
        "fmt"
    )
    
    func main() {
        // 获取文件
        imageUrl := "http://pic.uzzf.com/up/2015-7/20157816026.jpg"
        response, err := http.Get(imageUrl)
        if err != nil {
            panic(err)
        }
        defer response.Body.Close()
        // 创建保存位置
        file, err2 := os.Create("pic.jpg")
        if err2 != nil {
            panic(err2)
        }
        // 保存文件
        _, err3 := io.Copy(file, response.Body)
        if err3 != nil {
            panic(err3)
        }
    
        file.Close()
        fmt.Println("Image downloading is successful.")
    }
    

    创建Web服务器

    // 运行程序,打开浏览器,根据输入的查询参数将返回不同的值
    // 例如:"http://localhost:8000/?planet=World" 将在页面显示"Hello, World"
    package main
    
    import (
        "net/http"
        "log"
    )
    
    func sayHello(w http.ResponseWriter, r *http.Request) {
        // Query方法解析RawQuery字段并返回其表示的Values类型键值对。
        planet := r.URL.Query().Get("planet")
        w.Write([]byte("Hello, " + planet))
    }
    
    func main() {
        http.HandleFunc("/", sayHello)
        log.Fatalln(http.ListenAndServe(":8000", nil)) 
    }
    

    创建文件服务器

    // 在本程序同目录下创建images文件夹,放入一些文件
    // 打开浏览器访问"http://localhost:5050"将会看到文件
    package main
    
    import "net/http"
    
    func main() {
        http.Handle("/", http.FileServer(http.Dir("./images")))
        http.ListenAndServe(":5050", nil)
    }
    
  • 相关阅读:
    zoj-3433-Gu Jian Qi Tan
    优先队列详解(转载)
    HDU-3661-Assignments
    hdu-1052-Tian Ji -- The Horse Racing(经典)
    POJ-1456-Supermarket
    UVA-11292Dragon of Loowater
    UVA-11729-Commando War
    循环日程表 问题(递归分治)
    八数码问题
    POJ-3273 Monthly Expense (最大值最小化问题)
  • 原文地址:https://www.cnblogs.com/GaiHeiluKamei/p/11154026.html
Copyright © 2020-2023  润新知