Skip to content

Commit

Permalink
自定义开启https、自定义端口号和证书位置
Browse files Browse the repository at this point in the history
  • Loading branch information
aaakoako committed Mar 9, 2023
1 parent 4d4cfa8 commit 60568ee
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 47 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,4 @@ docker.md
# Mac OS
.DS_Store
**/.DS_Store
*.pem
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ COPY --from=golang /build/config.example.yaml /dist/config.yaml
COPY --from=golang /build/feishu_chatgpt /dist
ADD entrypoint.sh /dist/entrypoint.sh

EXPOSE 9001
EXPOSE 9000
CMD /dist/entrypoint.sh
7 changes: 7 additions & 0 deletions code/config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,10 @@ OPENAI_KEY:
- sk-xxx
- sk-xxx

# 服务器配置
HTTP_PORT: 9000
HTTPS_PORT: 9001
USE_HTTPS: false
CERT_FILE: /cert.pem
KEY_FILE: /key.pem

6 changes: 3 additions & 3 deletions code/handlers/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"strings"
)

//func sendCard
// func sendCard
func msgFilter(msg string) string {
//replace @到下一个非空的字段 为 ''
regex := regexp.MustCompile(`@[^ ]*`)
Expand Down Expand Up @@ -50,14 +50,14 @@ func processQuote(msg string) string {
return strings.Replace(msg, "\\\"", "\"", -1)
}

//将字符中 \u003c 替换为 < 等等
// 将字符中 \u003c 替换为 < 等等
func processUnicode(msg string) string {
regex := regexp.MustCompile(`\\u[0-9a-fA-F]{4}`)
return regex.ReplaceAllStringFunc(msg, func(s string) string {
r, _ := regexp.Compile(`\\u`)
s = r.ReplaceAllString(s, "")
i, _ := strconv.ParseInt(s, 16, 32)
return string(i)
return strconv.Itoa(int(i))
})
}

Expand Down
6 changes: 3 additions & 3 deletions code/handlers/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
)

//责任链
// 责任链
func chain(data *ActionInfo, actions ...Action) bool {
for _, v := range actions {
if !v.Execute(data) {
Expand All @@ -26,7 +26,7 @@ func chain(data *ActionInfo, actions ...Action) bool {
type MessageHandler struct {
sessionCache services.SessionServiceCacheInterface
msgCache services.MsgCacheInterface
gpt services.ChatGPT
gpt *services.ChatGPT
config initialization.Config
}

Expand Down Expand Up @@ -153,7 +153,7 @@ func (m MessageHandler) msgReceivedHandler(ctx context.Context, event *larkim.P2

var _ MessageHandlerInterface = (*MessageHandler)(nil)

func NewMessageHandler(gpt services.ChatGPT,
func NewMessageHandler(gpt *services.ChatGPT,
config initialization.Config) MessageHandlerInterface {
return &MessageHandler{
sessionCache: services.GetSessionCache(),
Expand Down
2 changes: 1 addition & 1 deletion code/handlers/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const (
// handlers 所有消息类型类型的处理器
var handlers MessageHandlerInterface

func InitHandlers(gpt services.ChatGPT, config initialization.Config) {
func InitHandlers(gpt *services.ChatGPT, config initialization.Config) {
handlers = NewMessageHandler(gpt, config)
}

Expand Down
86 changes: 76 additions & 10 deletions code/initialization/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package initialization

import (
"fmt"
"os"
"strconv"

"github.com/spf13/viper"
)
Expand All @@ -13,36 +15,100 @@ type Config struct {
FeishuAppVerificationToken string
FeishuBotName string
OpenaiApiKeys []string
HttpPort int
HttpsPort int
UseHttps bool
CertFile string
KeyFile string
}

func LoadConfig(cfg string) *Config {
viper.SetConfigFile(cfg)
viper.ReadInConfig()
viper.AutomaticEnv()

httpPort := getViperIntValue("HTTP_PORT", 9000)
httpsPort := getViperIntValue("HTTPS_PORT", 9001)
useHttps := getViperBoolValue("USE_HTTPS", false)
certFile := getViperStringValue("CERT_FILE", "cert.pem")
keyFile := getViperStringValue("KEY_FILE", "key.pem")

return &Config{
FeishuAppId: getViperStringValue("APP_ID"),
FeishuAppSecret: getViperStringValue("APP_SECRET"),
FeishuAppEncryptKey: getViperStringValue("APP_ENCRYPT_KEY"),
FeishuAppVerificationToken: getViperStringValue("APP_VERIFICATION_TOKEN"),
FeishuBotName: getViperStringValue("BOT_NAME"),
OpenaiApiKeys: getViperStringValueTable("OPENAI_KEY"),
FeishuAppId: getViperStringValue("APP_ID", ""),
FeishuAppSecret: getViperStringValue("APP_SECRET", ""),
FeishuAppEncryptKey: getViperStringValue("APP_ENCRYPT_KEY", ""),
FeishuAppVerificationToken: getViperStringValue("APP_VERIFICATION_TOKEN", ""),
FeishuBotName: getViperStringValue("BOT_NAME", ""),
OpenaiApiKeys: getViperStringValueTable("OPENAI_KEY", nil),
HttpPort: httpPort,
HttpsPort: httpsPort,
UseHttps: useHttps,
CertFile: certFile,
KeyFile: keyFile,
}

}

func getViperStringValue(key string) string {
func getViperStringValue(key string, defaultValue string) string {
value := viper.GetString(key)
if value == "" {
panic(fmt.Errorf("%s MUST be provided in environment or config.yaml file", key))
return defaultValue
}
return value
}

func getViperStringValueTable(key string) []string {
func getViperStringValueTable(key string, defaultValue []string) []string {
value := viper.GetStringSlice(key)
if len(value) == 0 {
panic(fmt.Errorf("%s MUST be provided in environment or config.yaml file", key))
return defaultValue
}
return value
}

func getViperIntValue(key string, defaultValue int) int {
value := viper.GetString(key)
if value == "" {
return defaultValue
}
intValue, err := strconv.Atoi(value)
if err != nil {
fmt.Printf("Invalid value for %s, using default value %d\n", key, defaultValue)
return defaultValue
}
return intValue
}

func getViperBoolValue(key string, defaultValue bool) bool {
value := viper.GetString(key)
if value == "" {
return defaultValue
}
boolValue, err := strconv.ParseBool(value)
if err != nil {
fmt.Printf("Invalid value for %s, using default value %v\n", key, defaultValue)
return defaultValue
}
return boolValue
}

func (config *Config) GetCertFile() string {
if config.CertFile == "" {
return "cert.pem"
}
if _, err := os.Stat(config.CertFile); err != nil {
fmt.Printf("Certificate file %s does not exist, using default file cert.pem\n", config.CertFile)
return "cert.pem"
}
return config.CertFile
}

func (config *Config) GetKeyFile() string {
if config.KeyFile == "" {
return "key.pem"
}
if _, err := os.Stat(config.KeyFile); err != nil {
fmt.Printf("Key file %s does not exist, using default file key.pem\n", config.KeyFile)
return "key.pem"
}
return config.KeyFile
}
46 changes: 27 additions & 19 deletions code/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func main() {

gpt := &services.ChatGPT{ApiKeys: config.OpenaiApiKeys}
gpt.StartApiKeyAvailabilityCheck()
handlers.InitHandlers(*gpt, *config)
handlers.InitHandlers(gpt, *config)

eventHandler := dispatcher.NewEventDispatcher(
config.FeishuAppVerificationToken, config.FeishuAppEncryptKey).
Expand All @@ -57,25 +57,33 @@ func main() {
sdkginext.NewCardActionHandlerFunc(
cardHandler))

// 加载证书和密钥文件
cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
panic(err)
}
if config.UseHttps {
certFile := config.GetCertFile()
keyFile := config.GetKeyFile()

// 创建HTTPS服务器
server := &http.Server{
Addr: ":9001",
Handler: r,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
panic(err)
}

server := &http.Server{
Addr: fmt.Sprintf(":%d", config.HttpsPort),
Handler: r,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
}

// 启动HTTPS服务器
fmt.Println("https server started", "https://localhost:9001/webhook/event")
err = server.ListenAndServeTLS("", "")
if err != nil {
panic(err)
fmt.Printf("https server started: https://localhost:%d/webhook/event\n", config.HttpsPort)
err = server.ListenAndServeTLS("", "")
if err != nil {
panic(err)
}
} else {
fmt.Printf("http server started: http://localhost:%d/webhook/event\n", config.HttpPort)
err := r.Run(fmt.Sprintf(":%d", config.HttpPort))
if err != nil {
panic(err)
}
}
}
2 changes: 1 addition & 1 deletion code/services/gpt3.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ type ChatGPT struct {
currentApiKeyIndex int
apiKeyUsage map[string]int
apiKeyWeights []int
apiKeyUsageMutex sync.Mutex
apiKeyUsageMutex sync.RWMutex
}

func (gpt *ChatGPT) Completions(msg []Messages) (resp Messages, err error) {
Expand Down
16 changes: 8 additions & 8 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@ mv config.example.yaml config.yaml

//测试部署
go run main.go
cpolar http 9001
cpolar http 9000

//正式部署
nohup cpolar http 9001 -log=stdout &
nohup cpolar http 9000 -log=stdout &

//查看服务器状态
https://dashboard.cpolar.com/status
Expand Down Expand Up @@ -200,7 +200,7 @@ s deploy

```bash
docker build -t feishu-chatgpt:latest .
docker run -d --name feishu-chatgpt -p 9001:9001 \
docker run -d --name feishu-chatgpt -p 9000:9000 \
--env APP_ID=xxx \
--env APP_SECRET=xxx \
--env APP_ENCRYPT_KEY=xxx \
Expand All @@ -217,7 +217,7 @@ feishu-chatgpt:latest
- docker 地址: https://hub.docker.com/r/leizhenpeng/feishu-chatgpt

```bash
docker run -d --restart=always --name feishu-chatgpt2 -p 9001:9001 -v /etc/localtime:/etc/localtim:ro \
docker run -d --restart=always --name feishu-chatgpt2 -p 9000:9000 -v /etc/localtime:/etc/localtim:ro \
--env APP_ID=xxx \
--env APP_SECRET=xxx \
--env APP_ENCRYPT_KEY=xxx \
Expand All @@ -227,8 +227,8 @@ docker run -d --restart=always --name feishu-chatgpt2 -p 9001:9001 -v /etc/local
dockerproxy.com/leizhenpeng/feishu-chatgpt:latest
```

事件回调地址: http://IP:9001/webhook/event
卡片回调地址: http://IP:9001/webhook/card
事件回调地址: http://IP:9000/webhook/event
卡片回调地址: http://IP:9000/webhook/card

把它填入飞书后台
<br>
Expand All @@ -243,8 +243,8 @@ dockerproxy.com/leizhenpeng/feishu-chatgpt:latest
2. 解压安装包,修改 config.example.yml 中配置信息,另存为 config.yml
3. 运行程序入口文件 `feishu-chatgpt`

事件回调地址: http://IP:9001/webhook/event
卡片回调地址: http://IP:9001/webhook/card
事件回调地址: http://IP:9000/webhook/event
卡片回调地址: http://IP:9000/webhook/card

</details>

Expand Down
2 changes: 1 addition & 1 deletion s.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ services:
name: "feishu-chatgpt"
description: 'a simple feishubot by serverless devs'
codeUri: './code'
cAPort: 9001
cAPort: 9000
customRuntimeConfig:
command:
- ./target/main
Expand Down

0 comments on commit 60568ee

Please sign in to comment.