-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
62 lines (48 loc) · 1.16 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
package main
import (
"bufio"
"danhenderson95/websockets/openai"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func getUserOpenAIKey() string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your OpenAI API key: ")
input, _ := reader.ReadString('\n')
return strings.TrimSpace(input)
}
func setOpenAIKeyEnvVar(key string) {
os.Setenv("OPENAI_API_KEY", key)
}
func chatHandler(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}
openAIResponse := openai.MakeOpenAICall(string(msg))
if err = conn.WriteMessage(msgType, []byte(openAIResponse)); err != nil {
return
}
}
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "websockets.html")
}
func main() {
key := getUserOpenAIKey()
setOpenAIKeyEnvVar(key)
http.HandleFunc("/chat", chatHandler)
http.HandleFunc("/", homeHandler)
fmt.Printf("Starting frontend at: http://localhost:%d\n", 8080)
log.Fatal(http.ListenAndServe(":8080", nil))
}