【发布时间】:2019-07-04 21:33:52
【问题描述】:
我正在用 Golang 构建一个从本地 json 文件返回数据的服务器。我已经构建了相关的结构,并且可以让服务器从 json 文件中返回所有信息,但是如果我只希望它返回某些条目呢?
有没有办法查询数据。我希望用户能够在 url、ID 中输入参数,并为具有该 ID 的相应条目返回相关的 json。
查看代码了解更多信息:
func main() {
//Initialises basic router and endpoints
r := mux.NewRouter()
r.HandleFunc("/", getAll).Methods("GET")
r.HandleFunc("/games/{id:[0-9]+}", getGame).Methods("GET")
r.HandleFunc("/games/report/{id}", getReport).Methods("GET")
fmt.Println("Listening on port 8080")
http.ListenAndServe(":8080", r)
}
从 Json 文件中检索所有数据的当前代码。
func getAll(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Open jsonFile and handle the error
jsonFile, err := os.Open("./data/games.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened games.json")
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// read the opened file as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// initialize our Games array
var games models.Games
// unmarshal our byteArray which contains our
// jsonFile's content into 'games' which we defined above
json.Unmarshal(byteValue, &games)
json.NewEncoder(w).Encode(games)
}
相关结构:
type Games struct {
Games []Game `json:"games"`
}
type Comment struct {
User string `json:"user"`
Message string `json:"message"`
DateCreated string `json:"dateCreated"`
Like int `json:"like"`
}
type Game struct {
ID int `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
By string `json:"by"`
Platform string `json:"platform"`
AgeRating string `json:"age_rating"`
Likes int `json:"likes"`
Comment Comment `json:"comments"`
}
正如您应该能够从路由器看到的那样,我希望用户传入 {id} 参数,然后将其插入到查询中。我问的可能吗?
【问题讨论】: