繁体   English   中英

GoLang WebServer在Json Response上发送对param结构的描述

[英]GoLang WebServer sends description of param's struct on Json Response

因此,这很重要:我已经在大型系统(PHP)上工作了两年,现在,我决定放弃部分繁重的Golang脚本工作。

到目前为止,我将一些php脚本复制到了go版本。 然后,我可以对哪个选项进行基准测试(好的,我知道go会更快,但是我需要使用curl或socket进行通信,因此,我必须检查它是否仍然值得)。

其中一个脚本只是生成一个随机代码,检查该新代码是否已在使用(在mysql db上),否则,记录新代码并返回它(如果已使用),只需再次递归调用该函数,直到找到专属代码。 很简单的一个。

我已经在php中拥有此代码生成器,因此,用json参数将新代码生成器称为http / post。 使用linux终端,我称它为

curl -H [headers] -d [jsondata] [host]

然后我得到一个非常简单的json

{"locator" : "XXXXXX"}

之后,我编写了一个简单的PHP脚本来调用这些脚本,并检查每个脚本完成所需的时间,例如:

<?php
public function indexAction()
    {
    $phpTime = $endPHP = $startPHP =
    $goTime = $endGO = $startGO = 0;

// my standard function already in use


    ob_start();

    $startPHP = microtime(true);
    $MyCodeLocator =  $this->container->get('MyCodeLocator')->Generate(22, 5);
    $endPHP = microtime(true);

    ob_end_clean();


    sleep(1);
    // Lets call using curl
    $data = array("comon" => "22", "lenght" => "5");
    $data_string = json_encode($data);

    ob_start();
    $startGO = microtime(true);



    $ch = curl_init('http://localhost:8888/dev/fibootkt/MyCodeGenerator');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
    );

    $result = curl_exec($ch);
    curl_close($ch);
    $endGO = microtime(true);
    ob_end_clean();

    $result_rr = json_decode($result);

    // tst just echo the variable in a nice way, second parameter means no kill execution
    tst($result, 1); // HERE IS MY PROBLEM, please read below
    tst($result_rr, 1); // IT SHOW NULL

    sleep(1);

// just to have params for comparision, always try by shell script
    ob_start();
    $startShell = microtime(true);;

    $exec =  "curl -H \"Content-Type: application/json\" -d '{\"comon\":\"22\"}' http://localhost:8888/dev/fibootkt/MyCodeGenerator";
    $output = shell_exec($exec);
    $endShell  = microtime(true);
    ob_end_clean();

    tst(json_decode($output),1); // here show a stdclass with correct value
    tst($output,1); // here shows a json typed string ready to be converted

    // and here it is just for show the execution time ...
    $phpTime = $endPHP - $startPHP;
    $goTime = $endGO - $startGO ;
    $shellTime = $endShell - $startShell;

    tst("php " . $phpTime, 1);
    tst("curl ". $goTime, 1);
    tst("shell " . $shellTime, 1);

我从GO获得结果:通过Shell Script:

{"locator" : "DPEWX22"} 

因此,这很容易解码为stdobj。

但是,使用curl可以加快操作速度! 所以,我想使用它。 但是,curl请求响应如下:

{"Value":"string","Type":{},"Offset":26,"Struct":"CodeLocatorParams","Field":"lenght"}
{"locator":"DPEWX22"}

当我尝试对其进行解码时,结果为空!

CodeLocatorParams我用于获取帖子参数的结构类型,如下所示

因此,这是我的问题:为什么GO会返回此? 如何避免。

我有另一个相似的go脚本,它不带参数,并且响应相似的json(但在这种情况下,它是一个qrcode图像路径),并且运行良好!

我的go函数:

type CodeLocatorParams struct {
    Comon string `json:"comon"`
    Lenght int  `json:"lenght"`
}

func Generate(w http.ResponseWriter, r *http.Request) {


    data, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
    if err != nil {
        fmt.Println(err)
        panic(err)

    }
    if err := r.Body.Close(); err != nil {
        panic(err)
    }

// retrieve post data  and set it to params which is CodeLocatorParams type
    var params CodeLocatorParams
    if err := json.Unmarshal(data, &params ); err != nil {
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
        w.WriteHeader(422) // unprocessable entity
        if err := json.NewEncoder(w).Encode(err); err != nil {
            fmt.Println(err)
            panic(err)
        }
    }





    var result struct{
        Locator string `json:"locator"`
    }
// here actually comes the func that generates random code and return it as string, but for now, just set it static
    result.Locator = "DPEWX22"

    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    json.NewEncoder(w).Encode(result)


}

解析传入的JSON时出错。 该错误将以{"Value":"string","Type":{},"Offset":26,"Struct":"CodeLocatorParams","Field":"lenght"} 处理程序将继续执行并写入正常响应{"locator":"DPEWX22"}

解决方法如下:

  • 写入错误响应后,从处理程序中返回。
  • 输入的JSON具有长度作为字符串值。 可以将struct字段从int更改为string,或者修改输入以传递整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM