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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教