-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
98 lines (83 loc) · 1.99 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/soulteary/yi-openai-proxy/define"
"github.com/soulteary/yi-openai-proxy/yi"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
var (
version = ""
buildDate = ""
gitCommit = ""
)
func main() {
viper.AutomaticEnv()
parseFlag()
err := yi.GetInstance()
if err != nil {
panic(err)
}
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
registerRoute(r)
srv := &http.Server{
Addr: viper.GetString("listen"),
Handler: r,
}
runServer(srv)
}
// registerRoute registers all routes
func registerRoute(r *gin.Engine) {
// https://platform.openai.com/docs/api-reference
r.HEAD("/", func(c *gin.Context) {
c.Status(200)
})
r.Any("/health", func(c *gin.Context) {
c.Status(200)
})
stripPrefixConverter := yi.NewStripPrefixConverter(define.REST_API_VERSION)
apiRouter := r.Group(define.REST_API_VERSION)
{
apiRouter.Any("/completions", yi.ProxyWithConverter(stripPrefixConverter))
apiRouter.Any("/chat/completions", yi.ProxyWithConverter(stripPrefixConverter))
}
}
func runServer(srv *http.Server) {
go func() {
log.Printf("Server listening at %s\n", srv.Addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(errors.Errorf("listen: %s\n", err))
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Server Shutdown...")
if err := srv.Shutdown(context.Background()); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}
func parseFlag() {
pflag.StringP("listen", "l", ":8080", "listen address")
pflag.BoolP("version", "v", false, "version information")
pflag.Parse()
if err := viper.BindPFlags(pflag.CommandLine); err != nil {
panic(err)
}
if viper.GetBool("v") {
fmt.Println("version:", version)
fmt.Println("buildDate:", buildDate)
fmt.Println("gitCommit:", gitCommit)
os.Exit(0)
}
}