記錄個web編程例子方便之後使用。
主要有:golang
package main import ( "fmt" "io" "net/http" "os" "os/signal" "strings" ) func getHandler(w http.ResponseWriter, req *http.Request) { vars := req.URL.Query() //解析參數 for _, v := range vars { //遍歷每一個參數 res := fmt.Sprintf("%v", v) io.WriteString(w, "par val:"+res+"\n") } } func postHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析參數,默認是不會解析的 fmt.Println(r.Form) //這些信息是輸出到服務器端的打印信息 fmt.Println("path", r.URL.Path) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "postHandler") //這個寫入到w的是輸出到客戶端的 } func main() { //channel 用於優雅退出 c := make(chan os.Signal) signal.Notify(c, os.Interrupt, os.Kill) //定義2個處理函數 http.HandleFunc("/get", getHandler) http.HandleFunc("/test", postHandler) //服務啓動 http.ListenAndServe(":12365", nil) //阻塞等待信號 s := <-c fmt.Println("退出信號", s) }
package main import ( "fmt" "io/ioutil" "net/http" "net/url" ) func exec_http_get(res chan string) { resp, err := http.Get("http://127.0.0.1:12365/get?url_long=long&id=12") if err != nil { //err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { //err } res <- string(body) } func exec_http_post(res chan string) { resp, err := http.PostForm("http://127.0.0.1:12365/test", url.Values{"key": {"Value"}, "id": {"123"}}) if err != nil { //request err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } res <- string(body) } func main() { c := make(chan string, 2) //發送get/post請求 go exec_http_get(c) go exec_http_post(c) //查看結果 for i := 0; i < 2; i=i+1{ res := <-c fmt.Printf("結果: %v\n", res) } }