附上server代码 package main import( "github.com/urfave/negroni" //安装步骤请看git地址:https://github.com/urfave/negroni, 前提必须装有git工具 "net/http" "fmt" "io/ioutil" )
mux := http.NewServeMux()mux.HandleFunc("/",func(w http.ResponseWriter, req *http.Request){ body,err := ioutil.ReadAll(req.Body) //获取客户端请求参数 if err!=nil{ fmt.Println(err.Error()); return; } // fmt.Println(string(body))//打印客户请求参数 fmt.Fprintf(w, "Welcome to the home page!") //返回客户数据})n := negroni.Classic()n.UseHandler(mux)n.Run(":3000")//端口号}func main(){
附上客户端代码 //模拟request请求 //除了使用Get、Post、PostForm 这三个函数来建立一个简单客户端, //还可以使用: //http.Client和http.NewRequest来模拟请求 package main import( "fmt" "io/ioutil" "net/http" "strings" //"net/url" "encoding/json" ) func main() { client := &http.Client{} //values := url.Values{} //values.Set("name","张三") //values.Add("age","20") request, err:= http.NewRequest("POST","http://localhost:3000", nil) if err !=nil{ fmt.Println(err.Error()); return } request.Header.Set("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") request.Header.Set("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.3") request.Header.Set("Accept-Encoding","gzip,deflate,sdch") request.Header.Set("Accept-Language","zh-CN,zh;q=0.8") request.Header.Set("Cache-Control","max-age=0") request.Header.Set("Connection","keep-alive") request.Header.Set("Content-Type","application/x-www-form-urllencoded; param=value") //网上资料说必须加上此句话,才可接受post参数 //form := url.Values{"name":{"123"}} type Message struct{ //注意因为要转成json所以字段名首字母必须大写,否则不可转成Json Name string Age int Sex string } m := Message{"张三",20,"男"} //拼接客户端请求数据 jsonstr, err := json.Marshal(m); //转换成json fmt.Println(string(jsonstr));//转成字符打印 request.Body = ioutil.NopCloser(strings.NewReader(string(jsonstr))) //将请求参数放入request对象body中 response,err:=client.Do(request) if err != nil{ fmt.Println(err.Error()) return } if response.StatusCode==200{ body,_ := ioutil.ReadAll(response.Body)//成功打印服务器返回数据 bodystr := string(body); fmt.Println(bodystr) } }
golang 使用negroni,实现server
最新推荐文章于 2024-05-24 09:32:42 发布