• Go web编程实例


    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+"
    ")
    	}
    }
    
    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
    ", res)
    	}
    }
    

    4. 参考

  • 相关阅读:
    JavaScript Eval 函数使用
    WPFToolkit Calendar & DatePicker 使用介绍
    Windows Mobile 6.5 配置环境,数据库访问,部署简单实例
    ThreadPool.QueueUserWorkItem 方法 (WaitCallback)
    Windws Mobile 6.5 Professional ADO.NET数据访问
    WPF调用Web Services
    c#中Interface的理解
    PagesSection.MaintainScrollPositionOnPostBack 属性
    EclipseRCP中文语言包版本不一致,导致导出错误
    SWT美化开源控件网站
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/10014915.html
Copyright © 2020-2023  润新知