gpt4 book ai didi

json - 需要使用url参数在Golang中查询Json数据

转载 作者:IT王子 更新时间:2023-10-29 02:35:04 26 4
gpt4 key购买 nike

我在 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} 参数,然后将其插入到查询中。我问的可能吗?

最佳答案

正如 Parham Alvani 所建议的那样,将您的游戏加载到 map 中,但使用指针值,如下所示:

gameMap := make(map[string]*Game)
for _, game := range games{
gameMap[game.ID] = &game
}

在您的 GET/game-route 中,您可以将游戏的 ID 传递给 map ,并以您喜欢的任何方式返回其结果,如果它不存在,指针值将为 nil,您可以返回 404 :

game := gameMap[id]
if game == nil{ // return 404}

关于json - 需要使用url参数在Golang中查询Json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56894396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com