GO语言基础之net/http

内置包net/http。

// 服务端
package main import (
"fmt" "net/http" ) // http server func sayHello(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello World!") } func main() { http.HandleFunc("/", sayHello) err := http.ListenAndServe(":8080", nil) if err != nil { fmt.Printf("http server failed, err:%v\n", err) return } }

编译启动之后浏览器输入:127.0.0.1:8080

// 客户端
package main

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

func main() {
    resp, err := http.Get("http://127.0.0.1:8080/")
    if err != nil {
        fmt.Println("get failed, err:", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("read from resp.Body failed,err:", err)
        return
    }
    fmt.Print(string(body))
}

 

你可能感兴趣的:(GO语言基础之net/http)