你们在使用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后再使用,否则将会报错