duanguo7021 2016-03-13 13:41
浏览 51
已采纳

将API请求函数传递给另一个函数GoLang

I was making an api request on page load of a specific html template. This is causing problems so I would like to make the api call when the program runs so the data is accessible when the html page is viewed.

So I am new to GoLang and am having trouble understanding what arguments to pass to this function when I call it in main.

func RequestTopMovies(w http.ResponseWriter, r *http.Request) {
  res, err := http.Get(url)
      if err != nil {
        panic(err)
      }
      defer res.Body.Close()

      body, err := ioutil.ReadAll(res.Body)
      if err != nil {
        panic(err)
      }
      var p Payload

      err = json.Unmarshal(body, &p)
      if err != nil {
        panic(err)
      }
      for i := 0; i < len(p.Results); i++ {
       fmt.Println(p.Results[i].Overview) // Prints to your terminal
    }
}

So now at this point I have the response in p.Results.

I want to be able to access this data in other places in my program. I was thinking I could just call the function.

So how can I call this function in main?

func main() {
  RequestTopMovies(http.ResponseWriter, http.Request)
  http.HandleFunc("/", mainHandler)
  http.HandleFunc("/about", aboutHandler)
  http.HandleFunc("/TopPicks", TopMoviesHandler)
  http.ListenAndServe(":8080", nil)
}

How can I pass this function to another function to have it return the response as well?

  • 写回答

1条回答 默认 最新

  • douti8321 2016-03-13 14:55
    关注

    RequestTopMovies is a http.Handler type which will get called automatically as a handler function aka controller.

    To access the data received, either use something like context (check gorilla/context) or just create a slice or map to hold the data struct so you can access it from somewhere else in the code, i.e.

    var Temp = map[string]Payload{}
    

    And once you unmarshaled the data, store it like

    Temp[key] = p
    

    Then from else where like another handler you can grab the data like

    func SomeHandler(rw http.ResponseWriter, *http.Request) {
            p := Temp[key]
            // ...
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog