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

huangapple go评论71阅读模式
英文:

Passing API Request Function To Another Function GoLang

问题

背景 -

我将这个函数移动到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) 
    }
}

问题 -

如何将响应数据设置为可以在代码的其他地方访问到?

英文:

Background -

I am moving this function to main() so the response data is accessible to the rest of my code.

Example -

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) 
    }
}

Question -

How do I set the response data to be accessible to other places in my code?

答案1

得分: 2

RequestTopMovies是一个http.Handler类型,它将自动作为处理函数(也称为控制器)被调用。

要访问接收到的数据,可以使用类似上下文(请检查gorilla/context)的东西,或者只需创建一个切片或映射来保存数据结构,以便您可以从代码的其他位置访问它,例如:

var Temp = map[string]Payload{}

一旦解组数据,就可以像这样存储它:

Temp[key] = p

然后在其他地方,比如另一个处理程序中,可以像这样获取数据:

func SomeHandler(rw http.ResponseWriter, *http.Request) {
        p := Temp[key]
        // ...
}
英文:

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]
        // ...
} 

huangapple
  • 本文由 发表于 2016年3月13日 21:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/35970960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定