普通网友 2019-07-03 21:11
浏览 168

如何在Golang服务器中通过ID参数返回特定的JSON数据

I am working on a project I've tasked to myself.

I'm trying to set up a Golang server that displays JSON data from a remote json file based on a parameter (ID) passed by the user.

I can find plenty of guides that show how to consume ALL the data from the json API, but I don't know how to pass a parameter to the function so it only returns the required data.

Here is what I have so far:

Setting up the basic server and routes

func main() {

    //Initialises basic router and endpoints
    r := mux.NewRouter()
    r.HandleFunc("/", home).Methods("GET")
    r.HandleFunc("/games/all", getAll).Methods("GET")
    r.HandleFunc("/games/{id}", getGame).Methods("POST")
    r.HandleFunc("/games/report", getReport).Methods("GET")

    fmt.Println("Listening on port 8080")
    http.ListenAndServe(":8080", r)

}

This is my getAll method that sends the GET request (Using the pokedex api for now until i host my json file).

func getAll(w http.ResponseWriter, r *http.Request) {
    response, err := http.Get("http://pokeapi.co/api/v2/pokedex/kanto/")

    if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
    }

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(responseData))
}

Have also built the structs for the data. But i cant, for the life of me, find a way to pass the parameter to do the getGame method to handle that route. Please, if anybody could point me in the right direction.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看