Golang获取post、get数据

         你们在使用golang创建web服务器的时候,有时会需要使用到post和get 而go本身是不携带post的,在这里博主写了一套完整的post键值提取,供大家使用

        这里有完整的web代码段 其中get不需自定义函数,而post则需要,这里需要区分一下

        博主在这里踩了不少坑,值得一提的是,在golang中对于数据类型有着非常大的局限性,导致post数据处理代码整体结构复杂化

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
	"strings"
)

func post (name string,str string) (returns string){
    countSplit := strings.Split(str,"&")            //用&切分字符串
    post := countSplit                              //储存至临时变量
    var post_len int = 2020                         //定义post_len变量 类型为int
    post_len = len(post)-1                          //获取数组post中数组的数量
    
    for i:=0;i<=post_len;i++{
         countSplits := strings.Split(post[i],"=")  //用=切分字符串
         if name ==  countSplits[0]{                //判断是否符合条件
             returns =  countSplits[1]              //保存内容至returns
             break                                  //跳出循环
         }else{
             returns = ""
         }
    }

    return returns                                  //返回值
}

func sayHello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello astaxie!")
    
    if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		fmt.Fprintf(w, "invalid_http_method")
		return
	}
	
	query := r.URL.Query()                          //GET数据
	id := query.Get("id")
	fmt.Fprintf(w,id)
	
	defer r.Body.Close()
	con,_ := ioutil.ReadAll(r.Body)                 //获取post的数据
    text := post("cookie",string(con))
    fmt.Fprintf(w,text)
    
    
}
func main() {

                                                    //1.注册一个处理器函数
    http.HandleFunc("/", sayHello)

                                                    //2.设置监听的TCP地址并启动服务
                                                    //参数1:TCP地址(IP+Port)
                                                    //参数2:handler handler参数一般会设为nil,此时会使用DefaultServeMux。
    http.ListenAndServe(":9070", nil)
    fmt.Println("helloworld")
}

以下是get数据获取方式

	query := r.URL.Query()                          //GET数据
	id := query.Get("id")
	fmt.Fprintf(w,id)

以下是post数据获取的调用方式

	defer r.Body.Close()                            //初始化数据
	con,_ := ioutil.ReadAll(r.Body)                 //获取post的数据
    text := post("cookie",string(con))              //储存到临时变量
    fmt.Fprintf(w,text)

注意,要先复制func post后再使用,否则将会报错

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fcch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值