1
0
This repository has been archived on 2024-02-27. You can view files and clone it, but cannot push or open issues or pull requests.
chatgpt-to-api/main.go

97 lines
2.1 KiB
Go
Raw Normal View History

2023-04-02 03:30:03 +00:00
package main
2023-04-02 05:40:07 +00:00
import (
2023-04-02 14:53:33 +00:00
"freechatgpt/internal/chatgpt"
2023-04-02 15:15:09 +00:00
typings "freechatgpt/internal/typings"
"io"
"os"
"github.com/gin-gonic/gin"
2023-04-02 05:40:07 +00:00
_ "github.com/r3labs/sse/v2"
)
var HOST string
var PORT string
var PUID string
2023-04-02 14:23:40 +00:00
var ACCESS_TOKENS []string
func init() {
HOST = os.Getenv("SERVER_HOST")
PORT = os.Getenv("SERVER_PORT")
PUID = os.Getenv("PUID")
if HOST == "" {
HOST = "127.0.0.1"
}
if PORT == "" {
PORT = "8080"
}
}
func main() {
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
/// Admin routes
router.PATCH("/admin/puid", admin_check, func(c *gin.Context) {
// Get the PUID from the request and update the PUID
puid := c.Query("puid")
if puid != "" {
PUID = puid
} else {
c.String(400, "puid not provided")
return
}
c.String(200, "puid updated")
})
router.PATCH("/admin/password", admin_check, func(c *gin.Context) {
// Get the password from the request and update the password
password := c.Query("password")
if password != "" {
ADMIN_PASSWORD = password
} else {
c.String(400, "password not provided")
return
}
c.String(200, "password updated")
})
2023-04-02 14:23:40 +00:00
router.PATCH("/admin/tokens", admin_check, func(c *gin.Context) {
// Get the tokens from the request (json) and update the tokens
var tokens []string
err := c.BindJSON(&tokens)
if err != nil {
c.String(400, "tokens not provided")
return
}
ACCESS_TOKENS = tokens
c.String(200, "tokens updated")
})
2023-04-02 14:53:33 +00:00
/// Public routes
router.POST("/v1/chat/completions", func(c *gin.Context) {
2023-04-02 15:15:09 +00:00
var chat_request typings.APIRequest
2023-04-02 14:53:33 +00:00
err := c.BindJSON(&chat_request)
if err != nil {
c.String(400, "chat request not provided")
return
}
// Convert the chat request to a ChatGPT request
chatgpt_request := chatgpt.ConvertAPIRequest(chat_request)
2023-04-02 15:15:09 +00:00
// c.JSON(200, chatgpt_request)
response, err := chatgpt.SendRequest(chatgpt_request, PUID)
if err != nil {
c.String(500, "error sending request")
return
}
defer response.Body.Close()
c.Stream(func(w io.Writer) bool {
// Write data to client
io.Copy(w, response.Body)
return false
})
2023-04-02 14:53:33 +00:00
})
router.Run(HOST + ":" + PORT)
}