如何提取Golang http.Request对象中的自定义ajaxParams
时间:2024-03-09
浏览:306
作者:佚名
大家好,今天本人给大家带来文章《如何提取Golang http.Request对象中的自定义ajaxParams》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
问题内容
我们有以下ajaxparams:
var ajaxParams = {
type: 'POST',
url: '/golang_endpoint',
dataType: 'json',
customParam: 'customParam',
success: onResponse,
error: onError,
};
golang 是否可以读取关联 golang 处理程序中以 *http.request 对象形式出现的自定义属性?
正确答案
这些参数用于执行 ajax 请求,它们并不是实际到达服务器的参数。您应该将其作为 post 请求的数据传递,如下所示:
var ajaxparams = {
type: 'post',
url: '/golang_endpoint',
datatype: 'json',
data: {customparam: 'customparam'},
success: onresponse,
error: onerror,
};
$.ajax(ajaxparams);
然后,在 go 方面,您只需按照需要处理数据即可,如下所示:
type MyStruct {
customParam string `json:"customParam"`
}
func HandlePost(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
var ms MyStruct
err := dec.Decode(&ms)
if err != nil {
panic(err)
}
fmt.Println(ms.customParam)
}
假设您希望参数是字符串。无论哪种方式,您都可以将其转换为您想要的类型。
到这里,我们也就讲完了《如何提取Golang http.Request对象中的自定义ajaxParams》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
