75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/lucaslorentz/caddy-docker-proxy/v2/caddyfile"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
func generateConfig(labels map[string]string, upstreams string) []byte {
|
|
UpstreamsFunc := map[string]any{
|
|
"upstreams": func() string {
|
|
return upstreams
|
|
},
|
|
}
|
|
|
|
container, err := caddyfile.FromLabels(labels, nil, UpstreamsFunc)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return container.Marshal()
|
|
}
|
|
|
|
func main() {
|
|
// CLI Flavor
|
|
labels := map[string]string{
|
|
"caddy": "example.com",
|
|
"caddy.reverse_proxy": "{{upstreams}}",
|
|
}
|
|
config := generateConfig(labels, "localhost")
|
|
fmt.Print(string(config[:]))
|
|
}
|
|
|
|
func configHandler(w http.ResponseWriter, r *http.Request) {
|
|
// Parse query parameters
|
|
upstreams := r.URL.Query().Get("upstreams")
|
|
if upstreams == "" {
|
|
upstreams = "example.com"
|
|
}
|
|
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, "Unable to read request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
defer r.Body.Close()
|
|
|
|
// Decode the JSON body into the labels map
|
|
var labels map[string]string
|
|
if err := json.Unmarshal(body, &labels); err != nil {
|
|
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Generate config
|
|
config := generateConfig(labels, upstreams)
|
|
|
|
// Respond with the generated config
|
|
w.Header().Set("Content-Type", "application/text")
|
|
|
|
w.Write(config)
|
|
}
|
|
|
|
//func main() {
|
|
// API flavor
|
|
// http.HandleFunc("/generate-config", configHandler) // Set up the route
|
|
// fmt.Println("Starting server on port 8080...")
|
|
// err := http.ListenAndServe(":8080", nil) // Start the HTTP server on port 8080
|
|
// if err != nil {
|
|
// fmt.Println("Error starting server:", err)
|
|
// }
|
|
//}
|