go http client, http server
Posted 翔云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go http client, http server相关的知识,希望对你有一定的参考价值。
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数据
以上是关于go http client, http server的主要内容,如果未能解决你的问题,请参考以下文章