ServeMux 是go自带的http请求处理器,是一个路由表,存放key-value。根据请求路径(key)在路由表中查找,(按照最长匹配原则)并将请求交给对应的处理函数(value).
导入http包,介绍几个方法:
-
http.ListenAndServe (addr string, handler Handler) //传入请求路径和路由表的handler
-
handler :=http.NewServeMux() //创建 一个路由表的handler
-
handler.HandleFunc("/api/", handle_func)//注册路由表,HandleFunc会将函数转为实现了ServeHTTP接口的新类型,但是需要保证传入的handle_func是符合 func(ResponseWriter,*Request)类型的。
上代码啦:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func requ(w http.ResponseWriter, r *http.Request){
fmt.Println(r.Body)
fmt.Println(r.Header)
resp :=map[string]interface{}{"status": 0, "msg": "ok", "data": "get it!"}
rr,_ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusBadRequest)
w.Write(rr)
}
func print_hello(w http.ResponseWriter, r *http.Request){
resp :=map[string]interface{}{"data": "hello !"}
rr,_ := json.Marshal(resp)
w.WriteHeader(http.StatusOK)
w.Write(rr)
}
func main(){
address :="127.0.0.1:8080"
mux:=http.NewServeMux()
mux.HandleFunc("/", requ)
mux.HandleFunc("/api/hi/",print_hello)
//HandleFunc(pattern string, handler func(ResponseWriter, *Request))
http.ListenAndServe(address, mux)
//func ListenAndServe(addr string, handler Handler) error
}
现在在入门级基础上 加一下东西,判断请求的方法,和拿到请求中body体,上代码:
//server 端
func requ(w http.ResponseWriter, r *http.Request){
if r.Method!="POST"{
resp :=map[string]interface{}{"status": -1, "msg": "请求方法错误", "data": ""}
rr,_ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusBadRequest)
w.Write(rr)
return
}
body := make([]byte, r.ContentLength)
r.Body.Read(body)
//fmt.Println(body)
var data interface{}
err:=json.Unmarshal(body,&data)
//解析失败会报错,如json字符串格式不对,缺"号,缺}等。
if err!=nil{
fmt.Println(err)
}
fmt.Println(data)//获取到的就是body体内容
//对于请求给出响应
resp :=map[string]interface{}{"status": 0, "msg": "ok", "data": "get it!"}
rr,_ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
w.Write(rr)
}
func print_hello(w http.ResponseWriter, r *http.Request){
resp :=map[string]interface{}{"data": "hello !"}
rr,_ := json.Marshal(resp)
w.WriteHeader(http.StatusOK)
w.Write(rr)
}
func main(){
address :="127.0.0.1:8080"
http.HandleFunc("/", requ)
http.HandleFunc("/api/hi/",print_hello)
//HandleFunc(pattern string, handler func(ResponseWriter, *Request))
http.ListenAndServe(address, nil)
//func ListenAndServe(addr string, handler Handler) error
}
// client 端
func Post(url string, data interface{}, contentType string) {
// 超时时间:5秒
client := &http.Client{}
jsonStr, _ := json.Marshal(data)
fmt.Println(jsonStr)
resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode==200{
fmt.Println("调用成功")
//或者可以处理服务端返回的数据
result, _ := ioutil.ReadAll(resp.Body)
fmt.Pringln( string(result))
}
}
func main() {
url:="http://127.0.0.1:8080"
var data map[int]string=map[int]string{1:"chen",2:"tian"}
fmt.Println(Post(url,data,"application/json"))
}