2023-04-19 01:30:23 +01:00
|
|
|
package target
|
|
|
|
|
|
|
|
import (
|
2023-04-19 01:30:38 +01:00
|
|
|
"fmt"
|
2023-04-19 01:30:23 +01:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2023-04-19 01:30:38 +01:00
|
|
|
"path"
|
2023-04-19 01:30:23 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type Redirect struct {
|
2023-04-19 01:30:38 +01:00
|
|
|
Pre bool
|
|
|
|
Host string
|
|
|
|
Port int
|
|
|
|
Path string
|
|
|
|
Abs bool
|
2023-04-19 01:30:23 +01:00
|
|
|
Code int
|
|
|
|
}
|
|
|
|
|
2023-04-19 01:30:38 +01:00
|
|
|
func (r Redirect) FullHost() string {
|
|
|
|
if r.Port == 0 {
|
|
|
|
return r.Host
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s:%d", r.Host, r.Port)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r Redirect) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|
|
|
p := r.Path
|
|
|
|
if !r.Abs {
|
|
|
|
p = path.Join(r.Path, req.URL.Path)
|
|
|
|
}
|
|
|
|
u := url.URL{
|
|
|
|
Scheme: req.URL.Scheme,
|
|
|
|
Host: r.FullHost(),
|
|
|
|
Path: p,
|
|
|
|
}
|
|
|
|
if u.Path == "/" {
|
|
|
|
u.Path = ""
|
|
|
|
}
|
|
|
|
http.Redirect(rw, req, u.String(), r.Code)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r Redirect) String() string {
|
|
|
|
return fmt.Sprintf("%#v", r)
|
2023-04-19 01:30:23 +01:00
|
|
|
}
|