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

How to read custom ajaxParams in Golang http.Request object

PHPz
Release: 2024-02-08 23:48:08
forward
650 people have browsed it

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

php editor Xiaoxin will introduce to you how to read the custom ajaxParams in the Golang http.Request object. In Golang, we often use the http package to handle HTTP requests. When we use AJAX to send requests, sometimes custom parameters are carried in the request. How to read these custom parameters on the server side? This article will give you a detailed answer and provide concise and effective code examples. Don’t miss this tutorial to make your Golang development more convenient!

Question content

We have the following ajaxparams:

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

Is it possible for golang to read custom properties that appear as *http.request objects in associated golang handlers?

Solution

These parameters are used to perform ajax requests, they are not the parameters that actually reach the server. You should pass it as data for the post request like this:

var ajaxparams = {
    type: 'post',
    url: '/golang_endpoint',
    datatype: 'json',
    data: {customparam: 'customparam'},
    success: onresponse,
    error: onerror,
};
$.ajax(ajaxparams);
Copy after login

Then, on the go side, you just process the data as needed, like this:

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)
}
Copy after login

Assume you want the parameter to be a string. Either way, you can convert it to the type you want.

The above is the detailed content of How to read custom ajaxParams in Golang http.Request object. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template