extract JSON from golang's echo request

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

extract JSON from golang's echo request

问题

我正在使用Echo在Golang中构建一个简约的服务器。

在Echo中,可以在内部将传入的JSON请求有效负载绑定到一个结构体,并访问该有效负载。

然而,我有一个场景,在这种情况下,我只知道传入的JSON请求有效负载的3个字段,而绑定在这种情况下不起作用。

我如何仍然访问我关心的这3个字段?如果在Echo中无法实现这一点,你能推荐一个与Echo的上下文结构兼容的JSON解码器吗?

英文:

I'm using Echo to build a minimalist server in Golang.

In, Echo one can bind an incoming JSON request payload to a struct internally and access the payload.

However I have a scenario wherein I know only 3 fields of the incoming JSON request payload, and the bind doesn't work in this case.

How do I still access the 3 fields that I care about ? If I cannot do this in Echo, can you recommend me a JSON decoder that works with Echo's context structure?

答案1

得分: 20

这是我是如何做的:

json_map := make(map[string]interface{})
err := json.NewDecoder(c.Request().Body).Decode(&json_map)
if err != nil {
    return err
} else {
    // json_map中已解码为映射的JSON有效负载
    cb_type := json_map["type"]
    challenge := json_map["challenge"]
英文:

This is how I did it:

json_map := make(map[string]interface{})
err := json.NewDecoder(c.Request().Body).Decode(&json_map)
if err != nil {
	return err
} else {
	//json_map has the JSON Payload decoded into a map
	cb_type := json_map["type"]
	challenge := json_map["challenge"]

答案2

得分: 3

我创建了一个自定义函数,它获取原始的 JSON 数据并返回一个空值(nil),如果没有值存在的话,否则返回一个 map[string]interface{}。

import (
    "encoding/json"
    "github.com/labstack/echo/v4"
    "github.com/labstack/gommon/log"
)


func GetJSONRawBody(c echo.Context) map[string]interface{} {

    jsonBody := make(map[string]interface{})
    err := json.NewDecoder(c.Request().Body).Decode(&jsonBody)
    if err != nil {

        log.Error("empty json body")
        return nil
    }

    return jsonBody
}
英文:

I created a custom function that retrieves raw json body and returns a nil if no values present otherwise in returns a map[string]interface{}

import (
   "encoding/json"
   "github.com/labstack/echo/v4"
   "github.com/labstack/gommon/log"
)
 
 
func GetJSONRawBody(c echo.Context) map[string]interface{}  {

     jsonBody := make(map[string]interface{})
     err := json.NewDecoder(c.Request().Body).Decode(&jsonBody)
     if err != nil {

	     log.Error("empty json body")
	     return nil
     }

    return jsonBody
}

答案3

得分: 2

我对Echo并不是很有经验,但据我所知,在这种情况下,绑定(bind)可能不起作用。@elithar在另一个线程中提供了一个可能对你的问题有用的答案:

从:https://stackoverflow.com/questions/35822102/golang-json-single-value-parsing

你可以解码为map[string]interface{},然后通过键获取元素。

data := make(map[string]interface{})
err := json.Unmarshal(content, &data)
if err != nil {
   return nil, err
}

price, ok := data["ask_price"].(string); !ok {
    // ask_price不是字符串
    return nil, errors.New("wrong type")
}

// 根据需要使用price

通常情况下,结构体更受青睐,因为它们对类型更明确。你只需要声明你关心的JSON字段,而不需要像使用map那样进行类型断言(encoding/json会隐式处理)。

你应该能够以这种方式获取上下文数据并提取你想要的字段。

英文:

I'm not the most experienced with Echo, but to my knowledge the bind won't work in this case. @elithar provided what may be a good answer to your question in another thread:


From: https://stackoverflow.com/questions/35822102/golang-json-single-value-parsing

You can decode into a map[string]interface{} and then get the element by key.

data := make(map[string]interface{})
err := json.Unmarshal(content, &data)
if err != nil {
   return nil, err
}

price, ok := data["ask_price"].(string); !ok {
    // ask_price is not a string
    return nil, errors.New("wrong type")
}

// Use price as you wish

Structs are often preferred as they are more explicit about the type. You only have to declare the fields in the JSON you care about, and you don't need to type assert the values as you would with a map (encoding/json handles that implicitly).


You should be able to grab your context's data and extract the fields you want in this manner.

答案4

得分: 1

使用Golang的Echo框架,你可以像这样从JSON中提取数据:

示例JSON

{
	"username": "超级用户",
    "useremail": "super@user.email"
}

代码


import (
	"github.com/labstack/echo"
)

func main() {
	my_data := echo.Map{}
	if err := echoCtx.Bind(&my_data); err != nil {
		return err
	} else {

		username := fmt.Sprintf("%v", my_data["username"])
		useremail := fmt.Sprintf("%v", my_data["useremail"])
	}
}
英文:

Using Golang's Echo framework, you extract data from JSON like this

Sample Json

{
	"username": "Super User",
    "useremail": "super@user.email"
}

Code


import (
	"github.com/labstack/echo"
)

func main() {
	my_data := echo.Map{}
	if err := echoCtx.Bind(&my_data); err != nil {
		return err
	} else {

		username := fmt.Sprintf("%v", my_data["username"])
		useremail := fmt.Sprintf("%v", my_data["useremail"])
	}
}

答案5

得分: 0

这是一个简单的解决方案:

func UnwantedJSONHandler(c echo.Context){
    b, _ := io.ReadAll(c.Request().Body)
    var r RequestDataAssumedStruct
    if err := json.Unmarshal(b, &r); err != nil {
        log.Println(err.Error())
        return err
    }
    log.Println(r)
}

我们只是从请求体中获取了字节数据,并将其解析为JSON格式。
我看到其他人提供了一些解决方案,但似乎是一种冗长的方式,所以即使它被标记为已解决,我仍然提供了答案。

英文:

here is the simple solution

func UnwantedJSONHandler(c echo.Context){
    b, _ := io.ReadAll(c.Request().Body)
    var r RequestDataAssumedStruct
    if err := json.Unmarshal(b, &r); err != nil {
    	log.Println(err.Error())
        return err
    }
    log.Println(r)
}

We just took the byte data from the request body and unmarshaled the JSON.
I have seen some solution given by the others but it seems that's a log way so i still put the answer even though it is marked as solved

huangapple
  • 本文由 发表于 2017年1月1日 02:04:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/41410655.html
匿名

发表评论

匿名网友

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

确定