相关疑难解决方法(0)

在Go中处理JSON Post请求

所以我有以下,看起来非常h​​acky,我一直在想自己Go有比这更好的设计库,但是我找不到Go处理JSON数据的POST请求的例子.它们都是POST形式.

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

这是代码,嵌入了日志:

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))
}
Run Code Online (Sandbox Code Playgroud)

必须有更好的方法,对吗?我很难找到最好的做法.

(Go也被称为搜索引擎的Golang,并在此处提到,以便其他人可以找到它.)

json go

230
推荐指数
6
解决办法
23万
查看次数

在Golang中,json编码和编组之间有什么区别

JSON'编码/解码'和JSON'编组/解组'之间有什么区别?

试着学习如何在golang中编写RESTFUL api并且不确定JSON'encoding'和'marshalling'之间的区别是什么?或者它们是否相同?

go

35
推荐指数
3
解决办法
1万
查看次数

如何利用 enconding/json 的 UnmarshalTypeError 中的偏移值来更好地处理错误?

一年多前,GoOffset向类型添加了一个值(请参阅此处json.UnmarshalTypeError已关闭的问题以了解上下文)。偏移值背后的目的是有道理的,但我不确定在读取类型为 的 go http 响应正文时如何使用它。io.ReadCloser

// An UnmarshalTypeError describes a JSON value that was
// not appropriate for a value of a specific Go type.
type UnmarshalTypeError struct {
    Value  string       // description of JSON value - "bool", "array",   "number -5"
    Type   reflect.Type // type of Go value it could not be assigned to
    Offset int64        // error occurred after reading Offset bytes
}
Run Code Online (Sandbox Code Playgroud)

例如:

var body CustomType
decoderErr := json.NewDecoder(response.Body).Decode(&body)

if decoderErr != …
Run Code Online (Sandbox Code Playgroud)

json go

3
推荐指数
1
解决办法
2451
查看次数

标签 统计

go ×3

json ×2