使用 Golang 的 JSON 响应示例
Example JSON response with Golang
我正在尝试使用 golang 构建一个 API。首先,我只是想在访问 http://localhost:8085/search 时发送一些 json 数据,但我在浏览器中看到的只是 null
.
我从 Medium post
那里得到这个例子
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))
}
您的 "place" 变量没有赋值。我想你正试图通过 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)
}
Working command line program。您可以根据自己的需要进行调整。
我正在尝试使用 golang 构建一个 API。首先,我只是想在访问 http://localhost:8085/search 时发送一些 json 数据,但我在浏览器中看到的只是 null
.
我从 Medium post
那里得到这个例子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))
}
您的 "place" 变量没有赋值。我想你正试图通过 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)
}
Working command line program。您可以根据自己的需要进行调整。