登录
首页 >  Golang >  Go问答

JSON 正文中缺少引号的HTTP服务器问题

来源:stackoverflow

时间:2024-03-01 22:00:24 470浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《JSON 正文中缺少引号的HTTP服务器问题》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我尝试了 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 数组中的正文时,我看不到字符串中的引号 (")。如何使服务器不会错过请求正文中的引号?


解决方案


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

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

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

本篇关于《JSON 正文中缺少引号的HTTP服务器问题》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>