为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Golang 的 JSON 响应示例

使用 Golang 的 JSON 响应示例

Go
慕田峪9158850 2023-08-07 14:49:17
我正在尝试使用 golang 构建一个 API。首先,当我访问http://localhost:8085/search时,我只是尝试发送一些 json 数据,但我在浏览器中看到的只是null.package mainimport (    "log"    "net/http"    "encoding/json"    "github.com/gorilla/mux")type Place struct {  Location string `json:"123 Houston st"`  Name string `json:"Ricks Barber Shop"`  Body string `json:"this is the best barber shop in the world"`}var place []Placefunc search(write http.ResponseWriter, req *http.Request) {    write.Header().Set("Content-Type", "application/json")    json.NewEncoder(write).Encode(place)}func main() {    router := mux.NewRouter().StrictSlash(true)    router.HandleFunc("/search", search).Methods("GET")    log.Fatal(http.ListenAndServe(":8085", router))}
查看完整描述

1 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

没有为您的“地点”变量分配任何值。我想您正在尝试通过 json 标签分配值,但是此标签是为了通知 json 文件中的 json 属性的名称,而不是属性的值。


将您的代码调整为以下内容,它应该可以工作


type Place struct {

  Location string `json:"location"`

  Name string `json:"name"`

  Body string `json:"body"`

}


var place []Place


func search(write http.ResponseWriter, req *http.Request) {


  place = append(place, Place{Location: `123 Houston st`, Name:`Ricks Barber Shop`, Body:`this is the best barber shop in the world`})


   write.Header().Set("Content-Type", "application/json")

   j, err := json.Marshal(&place)


   if err != nil {

        //Your logic to handle Error

   }    


   fmt.Fprint(write, string(j)


}

工作命令行程序。您可以根据您的需要进行调整。

https://play.golang.org/p/yHTcbqjoCjx


查看完整回答
反对 回复 2023-08-07
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信