[GO]简单的http服务器和客户端的实现

package main

import (
    "net/http"
    "fmt"
)

func Hello(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("handle hello")
    fmt.Fprintf(w, "hello")
}

func main() {
    http.HandleFunc("/", Hello)
    err := http.ListenAndServe("0.0.0.0:8000", nil)
    if err != nil {
        fmt.Println("http listen failed")
    }
}

然后使用浏览器浏览本地的8000端口就可以看到相应的网页内容

 再来个客户端的小样

package main

import (
    "net/http"
    "fmt"
    "io/ioutil"
)

func main() {
    //res, err := http.Get("https://www.baidu.com/")
    res, err := http.Get("http://localhost:8000")
    if err != nil {
        fmt.Println("get err:", err)
        return
    }

    data, _ := ioutil.ReadAll(res.Body)
    fmt.Println(string(data))
}

 

posted @ 2018-10-24 16:04  蟒城贝勒爷  阅读(736)  评论(0编辑  收藏  举报