1. go web編程入門
記錄個web編程例子方便以后使用。
主要有:
- chan的使用(帶緩存,不帶緩存)
- client發起get/post請求
- server解析get/post請求參數
- http.HandleFunc 根據請求uri設置對應處理func
2. server.go, 參數解析返回
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)
}
3. client.go, 發起http get/post請求
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)
}
}
