如何在Golang的http.Request对象中读取自定义的ajaxParams?

huangapple go评论78阅读模式
英文:

How to read custom ajaxParams in Golang http.Request object

问题

我们有以下的ajaxParams:

   var ajaxParams = {
        type: 'POST',
        url: '/golang_endpoint',
        dataType: 'json',
        customParam: 'customParam',
        success: onResponse,
        error: onError,
    };

在相关的Golang处理程序中,Golang是否可以读取自定义属性,就像它以*http.Request对象的形式出现一样?

英文:

We have the following ajaxParams:

   var ajaxParams = {
        type: 'POST',
        url: '/golang_endpoint',
        dataType: 'json',
        customParam: 'customParam',
        success: onResponse,
        error: onError,
    };

Is it possible for Golang to read the custom attribute as it appears in the form of an *http.Request object in the associated Golang handler?

答案1

得分: 1

这些参数用于执行AJAX请求,它们并不是实际发送到服务器的内容。你应该将它们作为POST请求的数据传递,如下所示:

var ajaxParams = {
    type: 'POST',
    url: '/golang_endpoint',
    dataType: 'json',
    data: {customParam: 'customParam'},
    success: onResponse,
    error: onError,
};
$.ajax(ajaxParams);

然后,在Go端,你可以按照你想要的方式处理数据,例如:

type MyStruct struct {
    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)
}

假设你希望参数是一个字符串。无论如何,你都可以将其转换为你想要的类型。

英文:

Those parameters are used to do the AJAX request, they are not what actually gets to the server. You should pass it as the data of the POST request, as in:

var ajaxParams = {
    type: 'POST',
    url: '/golang_endpoint',
    dataType: 'json',
    data: {customParam: 'customParam'},
    success: onResponse,
    error: onError,
};
$.ajax(ajaxParams);

Then, on the Go side, you just handle the data as you want it, like in:

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

Assuming you want your param to be a string. Either way you could convert it to the type you want.

huangapple
  • 本文由 发表于 2023年1月31日 06:58:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75291045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定