GoLang的ListenAndServe
go常用env
go env -w GO111MODULE=on
go env -w GOPROXY="https://goproxy.cn,direct"
go env -w GOOS=linux
go env -w GOOS=windows
go-restful的WebService示例
var onceHttpDemo sync.Once
func HttpDemoRun() {
onceHttpDemo.Do(func() {
go HttpDemo()
})
}
func HttpDemo() {
ws := new(restful.WebService)
ws.Path("/test")
ws.Route(ws.POST("/demo").To(func(request *restful.Request, response *restful.Response) {
fmt.Println(fmt.Sprintf("WebService Route: /demo"))
body := "xxxxx"
response.Write([]byte(body + "\n"))
}))
ws.Route(ws.GET("/api/users/{id}").To(func(request *restful.Request, response *restful.Response) {
fmt.Println(fmt.Sprintf("WebService Route: /api/users/{id}"))
id := request.PathParameter("id")
body := map[string]string{"message": fmt.Sprintf("Getting user %s", id)}
response.WriteAsJson(body)
}))
container := restful.NewContainer()
container.Add(ws)
for i := 28080; i < 28090; i++ {
fmt.Println(fmt.Sprintf("start to http.ListenAndServe: [%v]", i))
err := http.ListenAndServe(fmt.Sprintf(":%v", i), container)
fmt.Println(fmt.Sprintf("start to http.ListenAndServe fail: %v", err.Error()))
time.Sleep(time.Second * 5)
}
}