🚧 Trying to setup redirect middleware for Telegram IV

This commit is contained in:
Maxim Lebedev 2023-11-13 10:29:25 +06:00
parent aa7cba5e14
commit 0558cf72d2
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
1 changed files with 120 additions and 83 deletions

49
main.go
View File

@ -13,8 +13,10 @@ import (
"log"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"path/filepath"
"runtime"
"runtime/pprof"
@ -28,6 +30,7 @@ import (
"source.toby3d.me/toby3d/home/internal/common"
"source.toby3d.me/toby3d/home/internal/domain"
"source.toby3d.me/toby3d/home/internal/middleware"
"source.toby3d.me/toby3d/home/internal/page"
pagefsrepo "source.toby3d.me/toby3d/home/internal/page/repository/fs"
pageucase "source.toby3d.me/toby3d/home/internal/page/usecase"
@ -80,13 +83,10 @@ func NewApp(ctx context.Context, config *domain.Config) (*App, error) {
pages := pagefsrepo.NewFileSystemPageRepository(contentDir)
pager := pageucase.NewPageUseCase(pages, resources)
server := &http.Server{
Addr: config.AddrPort().String(),
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// TODO(toby3d): use exists static use case or split that on static and resource modules?
// INFO(toby3d): any static file is public and unprotected by design, so it's safe to search it
// first before deep down to any page or it's resource which might be secured by middleware or
// something else.
// INFO(toby3d): any static file is public and unprotected by design, so it's safe to search it first
// before deep down to any page or it's resource which might be secured by middleware or something else.
static, err := statics.Get(r.Context(), strings.TrimPrefix(r.URL.Path, "/"))
if err == nil {
http.ServeContent(w, r, static.Name(), domain.ResourceModTime(static), static)
@ -190,7 +190,44 @@ func NewApp(ctx context.Context, config *domain.Config) (*App, error) {
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
mw := middleware.Chain{
middleware.Redirect(middleware.RedirectConfig{
Code: http.StatusSeeOther,
Skipper: func(r *http.Request) bool {
return r.UserAgent() != "TelegramBot (like TwitterBot)"
},
}, func(u *url.URL) (string, bool) {
s, err := siter.Do(ctx, domain.LanguageUnd)
if err != nil {
return "", false
}
if ivHash, ok := s.Params["instantViewHash"].(string); ok {
target := &url.URL{
Scheme: "https",
Host: "t.me",
Path: path.Join("/share", "url"),
}
q := target.Query()
q.Set("url", u.String())
q.Set("hash", ivHash)
target.RawQuery = q.Encode()
return target.String(), ok
}
return "", false
}),
}
server := &http.Server{
Addr: config.AddrPort().String(),
Handler: mw.Handler(handler),
ErrorLog: logger,
BaseContext: func(ln net.Listener) context.Context { return ctx },
WriteTimeout: 500 * time.Millisecond,