49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/url"
|
|
|
|
"github.com/forgeo/forgebucket/internal/config"
|
|
)
|
|
|
|
type InstanceHandler struct {
|
|
cfg *config.Config
|
|
}
|
|
|
|
func NewInstanceHandler(cfg *config.Config) *InstanceHandler {
|
|
return &InstanceHandler{cfg: cfg}
|
|
}
|
|
|
|
// Get returns the public instance configuration needed by the frontend to
|
|
// construct clone URLs (SSH host, SSH port, instance name).
|
|
func (h *InstanceHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|
sshHost := h.sshHost(r)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{ //nolint:errcheck
|
|
"sshHost": sshHost,
|
|
"sshPort": h.cfg.SSHPort,
|
|
"instanceName": h.cfg.InstanceName,
|
|
})
|
|
}
|
|
|
|
// sshHost resolves the SSH hostname to display in clone URLs.
|
|
// Priority: SSH_HOST env var > InstanceURL hostname > request Host header > localhost.
|
|
func (h *InstanceHandler) sshHost(r *http.Request) string {
|
|
if h.cfg.SSHHost != "" {
|
|
return h.cfg.SSHHost
|
|
}
|
|
if h.cfg.InstanceURL != "" {
|
|
if u, err := url.Parse(h.cfg.InstanceURL); err == nil && u.Hostname() != "" {
|
|
return u.Hostname()
|
|
}
|
|
}
|
|
// Strip port from Host header if present.
|
|
host := r.Host
|
|
if u, err := url.Parse("http://" + host); err == nil {
|
|
return u.Hostname()
|
|
}
|
|
return "localhost"
|
|
}
|