使用 Golang 的 JSON 响应示例

我正在尝试使用 golang 构建一个 API。首先,当我访问http://localhost:8085/search时,我只是尝试发送一些 json 数据,但我在浏览器中看到的只是null.


package main


import (

    "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 []Place


func 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))

}


慕田峪9158850
浏览 74回答 1
1回答

噜噜哒

没有为您的“地点”变量分配任何值。我想您正在尝试通过 json 标签分配值,但是此标签是为了通知 json 文件中的 json 属性的名称,而不是属性的值。将您的代码调整为以下内容,它应该可以工作type Place struct {  Location string `json:"location"`  Name string `json:"name"`  Body string `json:"body"`}var place []Placefunc 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
打开App,查看更多内容
随时随地看视频慕课网APP