Go web编程实例

时间:2022-04-17 05:14:13

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)
}
}

4. 参考