[英]Example JSON response with Golang
我正在尝试使用 golang 构建 API。 首先,当我访问http://localhost:8085/search时,我只是尝试发送一些 json 数据,但我在浏览器中查看的所有数据都是null
。
我从一个Medium 帖子中得到了这个例子
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))
}
没有分配给您的“位置”变量的值。 我想您正在尝试通过 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)
}
工作命令行程序。 您可以根据自己的需要进行调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.