亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號