2 Star 0 Fork 0

ledao/go-openai

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server.go 1.59 KB
一键复制 编辑 原始数据 按行查看 历史
package test
import (
"log"
"net/http"
"net/http/httptest"
"regexp"
"strings"
)
const testAPI = "this-is-my-secure-token-do-not-steal!!"
func GetTestToken() string {
return testAPI
}
type ServerTest struct {
handlers map[string]handler
}
type handler func(w http.ResponseWriter, r *http.Request)
func NewTestServer() *ServerTest {
return &ServerTest{handlers: make(map[string]handler)}
}
func (ts *ServerTest) RegisterHandler(path string, handler handler) {
// to make the registered paths friendlier to a regex match in the route handler
// in OpenAITestServer
path = strings.ReplaceAll(path, "*", ".*")
ts.handlers[path] = handler
}
// OpenAITestServer Creates a mocked OpenAI server which can pretend to handle requests during testing.
func (ts *ServerTest) OpenAITestServer() *httptest.Server {
return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("received a %s request at path %q\n", r.Method, r.URL.Path)
// check auth
if r.Header.Get("Authorization") != "Bearer "+GetTestToken() && r.Header.Get("api-key") != GetTestToken() {
w.WriteHeader(http.StatusUnauthorized)
return
}
// Handle /path/* routes.
// Note: the * is converted to a .* in register handler for proper regex handling
for route, handler := range ts.handlers {
// Adding ^ and $ to make path matching deterministic since go map iteration isn't ordered
pattern, _ := regexp.Compile("^" + route + "$")
if pattern.MatchString(r.URL.Path) {
handler(w, r)
return
}
}
http.Error(w, "the resource path doesn't exist", http.StatusNotFound)
}))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ledao/go-openai.git
git@gitee.com:ledao/go-openai.git
ledao
go-openai
go-openai
v1.0.10

搜索帮助