【问题标题】:Need to query Json data in Golang using url parametersGolang中需要使用url参数查询Json数据
【发布时间】: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} 参数,然后将其插入到查询中。我问的可能吗?

【问题讨论】:

  • 您可以使用gorilla等第三方路由器解析URL参数,也可以手动拆分request.URL.Path
  • 我知道如何解析 url 参数,但是我如何将它应用到 json 中?
  • 您可以将 JSON 解析为 map,然后使用键检索 JSON 值。
  • 或者你可以看看this。通过使用不安全的解析器,您可以尽可能快地查询键。

标签: json go server


【解决方案1】:

按照 Parham Alvani 的建议,将您的游戏加载到地图中,但使用指针值,如下所示:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多