Home > other >  How to read custom ajaxParams in Golang http.Request object
How to read custom ajaxParams in Golang http.Request object

Time:02-01

We have the following ajaxParams:

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

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?

CodePudding user response:

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: one rror,
};
$.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.

  •  Tags:  
  • go
  • Related