在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.默认的常规方法 //默认多路复用器 import ( "fmt" "net/http" ) func IndexHand (w http.ResponseWriter,r *http.Request) { content:="this is test info" fmt.Fprint(w,content) } func main(){ http.HandleFunc("/test",IndexHand) http.ListenAndServe("127.0.0.1:8005",nil) } 2.多路复用器 //个性化多路复用器 func IndexFucn(w http.ResponseWriter,r * http.Request) { content:="this is content" fmt.Fprint(w,content) } func secondFun(w http.ResponseWriter,r * http.Request){ content:="this is second" fmt.Fprint(w,content) } func main(){ mux:=http.NewServeMux() mux.HandleFunc("/aa",IndexFucn) mux.HandleFunc("/bb",secondFun) server:=&http.Server{ Addr: "0.0.0.0:8099", Handler: mux, } err:=server.ListenAndServe() if err!=nil { log.Fatal(err) } } 3.接收Http传递参数 GET 和 POST 是我们最常用的两种请求方式,今天讲一讲如何在 golang 服务中,正确接收这两种请求的参数信息 1.1 接收GET请求 package main import ( "encoding/json" "fmt" "net/http" ) func hello( w http.ResponseWriter, r * http.Request){ params:=make(map[string]string) query := r.URL.Query() id:= query.Get("id") name:= query.Get("name") age:= query.Get("age") params["id"]=id params["name"]=name params["age"]= age strParams,_:= json.Marshal(params) w.Write(strParams) } func main() { http.HandleFunc("/",hello) err:= http.ListenAndServe(":9007",nil) if err != nil { fmt.Print(err) } } 1.2 接收POST请求 func helloPost(w http.ResponseWriter, request * http.Request){ request.ParseForm() id:= request.FormValue("id") name:= request.FormValue("name") age:=request.FormValue("age") params:=make(map[string]string) params["id"] = id params["name"] = name params["age"] = age strParams,_:= json.Marshal(params) w.Write(strParams) } func main() { http.HandleFunc("/",helloPost) err:= http.ListenAndServe(":9007",nil) if err != nil { fmt.Print(err) } }
|
请发表评论