go语言的net/http包的使用非常的简单优雅
1)服务端
package main
import (
"flag"
"fmt"
"net/http"
)
func main() {
host := flag.String("host", "127.0.0.1", "listen host")
port := flag.String("port", "80", "listen port")
http.HandleFunc("/hello", Hello)
err := http.ListenAndServe(*host+":"+*port, nil)
if err != nil {
panic(err)
}
}
func Hello(w http.ResponseWriter, req *http.Request) {
<p> w.Write([]byte("Hello World"))</p>}
http.HandleFunc
http.ListenAndSercerhttp.ListenAndSercer(“:8080”, nil)
http.ResponseWriterreq *http.Request
测试结果:成功
2)客户端
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
response, _ := http.Get("http://localhost:80/hello")
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
response, _ := http.Get("http://localhost:80/hello")
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}
测试结果:成功!