Haystack/main.go

86 lines
1.8 KiB
Go

package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
panic(err)
}
openAiClient, err := CreateOpenAiClient()
if err != nil {
panic(err)
}
mux := http.NewServeMux()
mux.HandleFunc("OPTIONS /image/{name}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Credentials", "*")
w.Header().Add("Access-Control-Allow-Headers", "*")
})
mux.HandleFunc("POST /image/{name}", func(w http.ResponseWriter, r *http.Request) {
imageName := r.PathValue("name")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Credentials", "*")
w.Header().Add("Access-Control-Allow-Headers", "*")
if len(imageName) == 0 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "You need to provide a name in the path")
return
}
image, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Couldnt read the image from the request body")
return
}
file, err := os.Create("./db/" + imageName)
defer file.Close()
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Couldnt create the file")
return
}
_, err = file.Write(image)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Couldnt write the image")
return
}
resp, err := openAiClient.GetImageInfo(imageName, image)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "some shit happened")
return
}
log.Printf("%+v\n", resp)
})
log.Println("Listening and serving.")
http.ListenAndServe(":3040", mux)
}