duanguo7021 2016-03-13 13:41
浏览 51


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 {
      defer res.Body.Close()

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

      err = json.Unmarshal(body, &p)
      if err != nil {
      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]
            // ...
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥30 STK matlab python仿真
  • ¥15 关于IMageEnView 图标定位问题
  • ¥20 求解答(matlab)
  • ¥30 ffmpeg库使用过程中遇到的问题
  • ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
  • ¥15 关于HTML中title获取xml内容的问题
  • ¥15 fanuc机器人PRIO083数字信号未复原错误,如何解决?
  • ¥20 如何为现有电路板增加远程控制功能
  • ¥15 UE5打包失败,求解决
  • ¥15 请问STM32G431的CANOPEN协议函数怎么写