【问题标题】:HTTP server missing quotes in JSON body? [closed]HTTP 服务器在 JSON 正文中缺少引号? [关闭]
【发布时间】:2020-12-11 09:10:17
【问题描述】:

我尝试了一些来自 github 的示例:

package main

import(
    "bytes"
    "fmt"
    "net/http"
    "encoding/json"
    "time"
)

//User defines model for storing account details in database
type User struct {
    Username string
    //Password string `json:"-"`
    //IsAdmin bool
    CreatedAt time.Time
}

func main(){
    mux := http.NewServeMux()

    mux.HandleFunc("/echo", echoHandler)

    http.ListenAndServe(":5000", mux)
}

func echoHandler(w http.ResponseWriter, r *http.Request){
    user := User{} //initialize empty user
    var bodyBuffer = new(bytes.Buffer)
    bodyBuffer.ReadFrom(r.Body)
    bodyBytes := bodyBuffer.Bytes()
    fmt.Println("Received Body: ", string(bodyBytes[:]))
    err := json.Unmarshal(bodyBytes, &user)
    if err != nil{
        panic(err)
    }
    fmt.Println(userJson)
    w.Header().Set("Content-Type","application/json")
    w.WriteHeader(http.StatusOK)
}

当我从 powershell 调用 curl 时:

curl -d '{"Username":"noname"}' localhost:5000/echo

输出来自控制台:

Received Body:  {Username:noname}
2020/12/11 12:00:15 http: panic serving [::1]:52684: invalid character 'U' looking for beginning of object key string
goroutine 6 [running]:
net/http.(*conn).serve.func1(0xc00005caa0)
    C:/Go/src/net/http/server.go:1801 +0x147
panic(0xa2b0a0, 0xc000004820)
    C:/Go/src/runtime/panic.go:975 +0x499
main.echoHandler(0xacb5e0, 0xc0001340e0, 0xc000144000)
    W:/projects/snippets/golang/parsing.go:39 +0x4ec
net/http.HandlerFunc.ServeHTTP(0xa8abf8, 0xacb5e0, 0xc0001340e0, 0xc000144000)
    C:/Go/src/net/http/server.go:2042 +0x4b
net/http.(*ServeMux).ServeHTTP(0xc00001c300, 0xacb5e0, 0xc0001340e0, 0xc000144000)
    C:/Go/src/net/http/server.go:2417 +0x1b7
net/http.serverHandler.ServeHTTP(0xc000134000, 0xacb5e0, 0xc0001340e0, 0xc000144000)
    C:/Go/src/net/http/server.go:2843 +0xaa
net/http.(*conn).serve(0xc00005caa0, 0xacba60, 0xc00001c380)
    C:/Go/src/net/http/server.go:1925 +0x8ad
created by net/http.(*Server).Serve
    C:/Go/src/net/http/server.go:2969 +0x36d

方法:err := json.NewDecoder(r.Body).Decode(&user)也不行。 可能,错误是当我在 []byte 数组中读取正文时,我看不到字符串中的引号 (")。如何使服务器不会错过请求正文中的引号?

【问题讨论】:

  • 您的代码无法编译:./main.go:37:14: undefined: userJson
  • 看起来像是 curl/powershell 的问题,而不是您的服务器代码。
  • 尝试转义双引号:stackoverflow.com/a/59182698/965900
  • 我认为@super 是对的,因为在我删除代码中的第 37 行并成功运行之后。当我运行curl -d '{"Username":"noname"}' localhost:5000/echo 时,服务器并没有恐慌。

标签: powershell go


【解决方案1】:

非常感谢您的回答。问题出在PowerShell中:

使用带引号的json body的正确方法是:

curl -d '{\"Username\":\"noname\"}' localhost:5000/echo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 2014-11-04
    • 2011-03-08
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多