2024-01-29 17:52:31 +00:00
|
|
|
package main
|
|
|
|
|
2024-01-29 18:51:23 +00:00
|
|
|
import (
|
|
|
|
"context"
|
2024-01-29 21:23:15 +00:00
|
|
|
_ "embed"
|
2024-01-29 18:51:23 +00:00
|
|
|
"log"
|
|
|
|
"net/http"
|
2024-01-29 18:53:15 +00:00
|
|
|
"os"
|
2024-01-29 20:21:23 +00:00
|
|
|
"strings"
|
2024-01-29 18:51:23 +00:00
|
|
|
|
|
|
|
"github.com/babariviere/short/internal/api"
|
|
|
|
"github.com/babariviere/short/internal/db"
|
|
|
|
"github.com/babariviere/short/internal/oas"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
)
|
2024-01-29 17:52:31 +00:00
|
|
|
|
2024-01-29 21:23:15 +00:00
|
|
|
//go:embed openapi.yaml
|
|
|
|
var openapiFile []byte
|
|
|
|
|
|
|
|
var rapidocHtml = `
|
|
|
|
<!doctype html> <!-- Important: must specify -->
|
|
|
|
<html>
|
|
|
|
<head>
|
|
|
|
<meta charset="utf-8"> <!-- Important: rapi-doc uses utf8 characters -->
|
|
|
|
<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<rapi-doc spec-url="/docs/openapi.yaml" render-style="view"> </rapi-doc>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
`
|
|
|
|
|
2024-01-29 17:52:31 +00:00
|
|
|
func main() {
|
2024-01-29 18:53:15 +00:00
|
|
|
// This is rude but at least we can configure the database URL securely.
|
|
|
|
psqlUrl := os.Getenv("DATABASE_URL")
|
|
|
|
if psqlUrl == "" {
|
|
|
|
log.Fatalln("DATABASE_URL is not configured.")
|
|
|
|
}
|
|
|
|
|
2024-01-29 20:21:23 +00:00
|
|
|
serverUrl := os.Getenv("SERVER_URL")
|
|
|
|
if serverUrl == "" {
|
|
|
|
serverUrl = "http://localhost:8080"
|
|
|
|
}
|
|
|
|
|
|
|
|
serverUrl = strings.TrimSuffix(serverUrl, "/")
|
|
|
|
|
2024-01-29 18:53:15 +00:00
|
|
|
psql, err := pgx.Connect(context.Background(), psqlUrl)
|
2024-01-29 18:51:23 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("cannot connect to database: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
queries := db.New(psql)
|
2024-01-29 20:21:23 +00:00
|
|
|
handler := api.NewHandler(serverUrl, queries)
|
2024-01-29 18:51:23 +00:00
|
|
|
|
|
|
|
srv, err := oas.NewServer(handler)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("failed te create OpenAPI server: %v", err)
|
|
|
|
}
|
|
|
|
|
2024-01-29 21:23:15 +00:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.Handle("/", srv)
|
|
|
|
mux.Handle("/docs", serveContent([]byte(rapidocHtml), "text/html"))
|
|
|
|
mux.Handle("/docs/openapi.yaml", serveContent(openapiFile, "application/yaml"))
|
2024-01-29 18:51:23 +00:00
|
|
|
log.Println("Listening on :8080")
|
2024-01-29 21:23:15 +00:00
|
|
|
if err = http.ListenAndServe(":8080", mux); err != nil {
|
2024-01-29 18:51:23 +00:00
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2024-01-29 17:52:31 +00:00
|
|
|
}
|
2024-01-29 21:23:15 +00:00
|
|
|
|
|
|
|
func serveContent(content []byte, contentType string) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Add("Content-Type", contentType)
|
|
|
|
w.Write(content)
|
|
|
|
})
|
|
|
|
}
|