pay/internal/cmd/pay/cmd_pay.go

79 lines
1.9 KiB
Go

package pay
import (
"context"
"fmt"
"io/fs"
"log"
"net/http"
"strconv"
"time"
"source.toby3d.me/toby3d/pay/internal/common"
"source.toby3d.me/toby3d/pay/internal/domain"
paymenthttpdelivery "source.toby3d.me/toby3d/pay/internal/payment/delivery/http"
"source.toby3d.me/toby3d/pay/internal/urlutil"
)
type Service struct {
server *http.Server
}
func New(logger *log.Logger, static fs.FS, config domain.Config) *Service {
handler := paymenthttpdelivery.NewHandler()
fileServer := http.FileServer(http.FS(static))
return &Service{
server: &http.Server{
Addr: config.Bind,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch head, _ := urlutil.ShiftPath(r.URL.Path); head {
default:
parsed, err := strconv.ParseFloat(head, 64)
if err != nil {
fileServer.ServeHTTP(w, r)
return
}
// NOTE(toby3d): Take my money? No way!
if parsed < 0 {
http.Redirect(w, r, fmt.Sprint("/", parsed*-1),
http.StatusMovedPermanently)
return
}
fallthrough
case "":
handler.ServeHTTP(w, r)
case "manifest.webmanifest":
w.Header().Set(common.HeaderContentType,
common.MIMEApplicationManifestJSONCharsetUTF8)
fileServer.ServeHTTP(w, r)
}
}),
DisableGeneralOptionsHandler: false,
TLSConfig: nil,
ReadTimeout: 500 * time.Millisecond,
ReadHeaderTimeout: 500 * time.Millisecond,
WriteTimeout: 500 * time.Millisecond,
IdleTimeout: 0,
MaxHeaderBytes: 0,
TLSNextProto: nil,
ConnState: nil,
ErrorLog: logger,
BaseContext: nil,
ConnContext: nil,
},
}
}
func (s *Service) Run() error {
return s.server.ListenAndServe()
}
func (s *Service) Stop(ctx context.Context) error {
return s.server.Shutdown(ctx)
}