go 实现一个http服务是很简单的
1,特点:不需要依赖容器, 不同于java 与 php
2,可以使用进程的内存, 对于配置文件就不需要第三方存储
服务端代码:
package main import "fmt" import ( "net/http" "time" ) func MyHandle(res http.ResponseWriter, req *http.Request){ fmt.Println("MyHanle") req.ParseForm() for key, v:=range req.Form{ fmt.Println("key:", key, "value:", v) } res.Write([]byte("name: "+ req.Form["age"][0])) } func MyTest(res http.ResponseWriter, req *http.Request){ fmt.Println("MyTest") req.ParseForm() for key, v:=range req.Form{ fmt.Println("key:", key, "value:", v) } res.Write([]byte("name: "+ req.Form["age"][0])) } func main(){ fmt.Println("main start") http.HandleFunc("/root", MyHandle) http.HandleFunc("/test", MyTest) http.ListenAndServe("127.0.0.1:9999", nil) for{ time.Sleep(1e9) } }
客户端代码:
package main import "fmt" import ( "net/http" "io/ioutil" ) func main(){ fmt.Println("main start") rsp, _ := http.Get("http://127.0.0.1:9999/root?name=for&age=56") data, _:=ioutil.ReadAll(rsp.Body) p:= string(data) fmt.Println(p) }
有疑问加站长微信联系(非本文作者)