56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
/*
|
|
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
*/
|
|
|
|
package http
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
const (
|
|
HxLocation = "HX-Location"
|
|
HxRedirect = "HX-Redirect"
|
|
HxRequest = "HX-Request"
|
|
)
|
|
|
|
func Relocate(w http.ResponseWriter, r *http.Request, url string, code int) {
|
|
if IsHTMxRequest(r) {
|
|
w.Header().Set(HxLocation, MustMarshalHTMxLocation(&HTMxLocation{
|
|
Path: url,
|
|
Target: "main",
|
|
}))
|
|
w.WriteHeader(http.StatusNoContent)
|
|
} else {
|
|
http.Redirect(w, r, url, code)
|
|
}
|
|
}
|
|
|
|
func Redirect(w http.ResponseWriter, r *http.Request, url string, code int) {
|
|
if IsHTMxRequest(r) {
|
|
w.Header().Set(HxRedirect, url)
|
|
w.WriteHeader(http.StatusNoContent)
|
|
} else {
|
|
http.Redirect(w, r, url, code)
|
|
}
|
|
}
|
|
|
|
func IsHTMxRequest(r *http.Request) bool {
|
|
return r.Header.Get(HxRequest) == "true"
|
|
}
|
|
|
|
type HTMxLocation struct {
|
|
Path string `json:"path"`
|
|
Target string `json:"target"`
|
|
}
|
|
|
|
func MustMarshalHTMxLocation(location *HTMxLocation) string {
|
|
data, err := json.Marshal(location)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return string(data)
|
|
}
|