在Go中处理JSON发布请求 [英] Handling JSON Post Request in Go

查看:139
本文介绍了在Go中处理JSON发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有以下几点,这看起来非常难以置信,我一直在想,Go比这个更好地设计了库,但是我找不到Go处理JSON数据的POST请求的示例。他们都是表单POST。



下面是一个示例请求: curl -X POST -d{\test \:\that\ }http:// localhost:8082 / test



这里是嵌入日志的代码:

  package main 

import(
encoding / json
log
net / http


类型test_struct结构{
测试字符串
}

func测试(rw http.ResponseWriter,req * http.Request){
req.ParseForm()
log.Println(req.Form)
// LOG:map [{test:that}:[]]
var t test_struct
for key,_:= range req.Form {
log.Println(key)
// LOG:{test:that}
err:= json.Unmarshal([] byte(key),& t)
if err!= nil {
log.Println(err.Error())
}

log.Println(t.Test)
// LOG:that
}

func main(){
http。 HandleFunc(/ test,test)
log.Fatal(http.Li stenAndServe(:8082,nil))
}

方式,对吗?我只是难以找到最佳做法。

(Go也被称为Golang到搜索引擎,并且在这里提到所以其他人可以找到它。)

json.Decoder 而不是 json.Unmarshal

  func test(rw http.ResponseWriter,req * http.Request){
decoder:= json.NewDecoder req.Body)
var t test_struct
err:= decoder.Decode(& t)
if err!= nil {
panic(err)
}
defer req.Body.Close()
log.Println(t.Test)
}


So I have the following, which seems incredibly hacky, and I've been thinking to myself that Go has better designed libraries than this, but I can't find an example of Go handling a POST request of JSON data. They are all form POSTs.

Here is an example request: curl -X POST -d "{\"test\": \"that\"}" http://localhost:8082/test

And here is the code, with the logs embedded:

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type test_struct struct {
    Test string
}

func test(rw http.ResponseWriter, req *http.Request) {
    req.ParseForm()
    log.Println(req.Form)
    //LOG: map[{"test": "that"}:[]]
    var t test_struct
    for key, _ := range req.Form {
        log.Println(key)
        //LOG: {"test": "that"}
        err := json.Unmarshal([]byte(key), &t)
        if err != nil {
            log.Println(err.Error())
        }
    }
    log.Println(t.Test)
    //LOG: that
}

func main() {
    http.HandleFunc("/test", test)
    log.Fatal(http.ListenAndServe(":8082", nil))
}

There's got to be a better way, right? I'm just stumped in finding what the best practice could be.

(Go is also known as Golang to the search engines, and mentioned here so others can find it.)

解决方案

Please use json.Decoder instead of json.Unmarshal.

func test(rw http.ResponseWriter, req *http.Request) {
    decoder := json.NewDecoder(req.Body)
    var t test_struct
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }
    defer req.Body.Close()
    log.Println(t.Test)
}

这篇关于在Go中处理JSON发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆