Go语言中的HTTP client, server非常简单。具体如下。
HTTP Server
package main
import (
"fmt"
"html"
"io/ioutil"
"log"
"net/http"
)
func main() {
http.HandleFunc("/bar", func (w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
if r.Method == "POST" {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println("Read failed:", err)
}
defer r.Body.Close()
log.Println("b:", string(b))
} else {
log.Println("ONly support Post")
w.Write([]byte("Only support post"))
}
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
HTTP Client
-
GET方式
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "http://127.0.0.1:8080/bar"
resp, err := http.Get(url)
if err != nil {
log.Println("Get failed:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Println("statuscode:", resp.StatusCode)
}
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Read failed:", err)
}
log.Println("content:", string(content))
}
-
POST方式
package main
import (
"bytes"
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "http://127.0.0.1:8080/bar"
contentType := "application/json;charset=utf-8"
b := []byte("Hello, Server")
body := bytes.NewBuffer(b)
resp, err := http.Post(url, contentType, body)
if err != nil {
log.Println("Post failed:", err)
return
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Read failed:", err)
return
}
log.Println("content:", string(content))
}
注意:
response的Body使用后记得close,即:
resp.Body.Close()
关于如何传递json格式数据,可以参考博文go http 传递json数据
|
请发表评论