public function getComponent($res){ $url = 'https://ad.oceanengine.com/open_api/2/assets/creative_component/get/'; if($res['component_id']){ $filtering['component_id'] = intval($res['component_id']); } if($res['component_name']){ $filtering['component_name'] = $res['component_name']; } if($res['status']){ $filtering['status'] = explode(',',$res['status']); }else{ $filtering['status'] = []; } $data = [ 'advertiser_id'=>1763116030427144, 'page'=>intval($res['page']), 'page_size'=>$res['page_size'], 'filtering'=>json_decode(json_encode($filtering)), ]; foreach ($data as $k=>$v){ if(!is_string($v)){ $data[$k] = json_encode($v); } } $request_url = $url.'?'.http_build_query($data); $token = '96f8ef5c3baccff7dbea9316051a0352940ab69e'; $list = $this->getClient($request_url,$token); $list = json_decode($list,true); return $list; }这段代码怎么改成使用goframe2.4.3框架重写?goframe2.4.3框架使用了"github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/gclient" "github.com/gogf/gf/v2/net/ghttp"扩展,请详细一点
时间: 2024-04-18 07:32:21 浏览: 190
在GoFrame 2.4.3框架中,你可以重写代码如下:
```go
package controller
import (
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
type ComponentController struct{}
func (c *ComponentController) GetComponent(r *ghttp.Request) {
url := "https://ad.oceanengine.com/open_api/2/assets/creative_component/get/"
filtering := g.Map{}
if componentID := r.Get("component_id"); componentID != "" {
filtering["component_id"] = gconv.Int(componentID)
}
if componentName := r.Get("component_name"); componentName != "" {
filtering["component_name"] = componentName
}
if status := r.Get("status"); status != "" {
filtering["status"] = strings.Split(status, ",")
} else {
filtering["status"] = []string{}
}
data := g.Map{
"advertiser_id": 1763116030427144,
"page": r.GetInt("page"),
"page_size": r.Get("page_size"),
"filtering": filtering,
}
for k, v := range data {
if !gconv.IsString(v) {
data[k] = gjson.New(v).MustToJsonString()
}
}
requestURL := url + "?" + ghttp.BuildQuery(data)
token := "96f8ef5c3baccff7dbea9316051a0352940ab69e"
client := ghttp.NewClient()
response, err := client.SetHeader("Authorization", "Bearer "+token).Get(requestURL)
if err != nil {
g.Log().Error(err)
r.Response.WriteJson(g.Map{
"code": -1,
"message": "Request failed",
"data": nil,
})
return
}
list := gjson.New(response.ReadAllString()).MustToJson()
r.Response.WriteJson(g.Map{
"code": 0,
"message": "Request success",
"data": list,
})
}
```
以上代码是一个ComponentController的示例,你可以将其添加到goframe2.4.3框架的控制器中。在该示例中,我们使用`ghttp`包发送HTTP请求,`gjson`包处理JSON数据,`g`包提供了日志记录功能。
请注意,你可能需要根据实际情况调整代码中的导入语句和其他细节,以适应你的项目。
阅读全文