前言
本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/108971807
未经博主允许不得转载。
博主CSDN地址是:https://blog.csdn.net/freewebsys
博主掘金地址是:https://juejin.cn/user/585379920479288
博主知乎地址是:https://www.zhihu.com/people/freewebsystem
1,关于goframe
最近在使用goframe的框架,发现集成了很多新的方法,特别的好用。
组件也是十分的丰富了。
开源项目地址:
项目地址:https://goframe.org/
GoFrame是一款模块化、低耦合设计的开发框架,包含了常用的基础组件和开发工具,既可以作为完整的业务项目框架使用也可以作为独立的组件库使用。我们为大家提供的快速开始章节,主要以完整的业务项目介绍框架的基本入门和使用。关于独立组件库使用,可以查看独立的组件章节介绍。
https://blog.csdn.net/freewebsys/article/details/129698017
2,使用goframe客户的方法
接口文档:
https://goframe.org/pages/viewpage.action?pageId=59864757
使用类型转换:
https://goframe.org/pages/viewpage.action?pageId=17203726
c := g.Client()
就可以访问了,使用的是流式处理方法。
可以直接获得结果的内容。
// 返回content为string类型
content := g.Client().GetContent(ctx, “https://goframe.org”)
以Bytes及Content后缀结尾的请求方法为直接获取返回内容的快捷方法,这些方法将会自动读取服务端返回内容并自动关闭请求连接。*Bytes方法用于获取[]byte类型结果,*Content方法用于获取string类型结果。需要注意的是,如果请求执行失败,返回内容将会为空。
其实很多看着很重复的工作需要封装下,就像。
直接返回字符串即可。
调用chatgpt 代码就变得非常简单了:
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/gconv"
)
// 接口文档:
// https://goframe.org/pages/viewpage.action?pageId=59864757
// 使用类型转换:
// https://goframe.org/pages/viewpage.action?pageId=17203726
type ChatChoiceMsg struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatChoice struct {
Message ChatChoiceMsg `json:"message"`
}
type ChatRes struct {
Id string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []ChatChoice `json:"choices"`
}
var ApiKey string = "xxxx"
func main() {
c := g.Client()
c.SetHeader("Accept", "text/event-stream")
c.SetHeader("Content-Type", "application/json")
c.SetHeader("Authorization", "Bearer " + ApiKey)
question := "介绍大众汽车"
params := `{
"model": "gpt-3.5-turbo",
"messages": [{
"role": "user", "content": "` + question + `"}]
}`
fmt.Println(params)
// /v1/chat/completions
url := "https://api.openai.com/v1/chat/completions"
// 发送数据
out := c.ContentJson().PostContent(gctx.New(), url, params)
fmt.Println(out)
var chatRes ChatRes
if err := gconv.Structs(out, &chatRes); err == nil {
fmt.Println(chatRes)
if len(chatRes.Choices) > 0 {
fmt.Println(chatRes.Choices[0].Message.Content)
}
}else{
panic(err)
}
}
同时还将结果反序列化了。gconv.Structs 方法可以把json 转换成对象。
然后直接使用对象的属性就可以了。代码还是非常的少的。
3,总结
goframe里面有很多非常实用的工具类,可以非常方便的解决开发中遇到的问题。
类似spring 库和 apache 库,都哟非常丰富的基础类,同时文档非常强大。
可以直接使用即可。
本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/108971807