74 lines
1.4 KiB
Go
74 lines
1.4 KiB
Go
package api
|
|
|
|
import (
|
|
"downloadhub/pkg/data"
|
|
_ "embed"
|
|
"fmt"
|
|
"html/template"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
)
|
|
|
|
type (
|
|
Server struct {
|
|
r chi.Router
|
|
d data.Service
|
|
port uint16
|
|
}
|
|
)
|
|
|
|
//go:embed templates/index.html
|
|
var index string
|
|
|
|
//go:embed templates/description.html
|
|
var description string
|
|
|
|
func New(port uint16, d data.Service) *Server {
|
|
indexTemplate := template.New("index")
|
|
indexTemplate.Parse(index)
|
|
|
|
descTemplate := template.New("description")
|
|
descTemplate.Parse(description)
|
|
|
|
r := chi.NewRouter()
|
|
r.Use(middleware.Logger)
|
|
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
|
err := indexTemplate.Execute(w, d.Softwares)
|
|
if err != nil {
|
|
slog.Error(fmt.Sprintf("failed to execute template index: %s", err))
|
|
}
|
|
})
|
|
r.Get("/d/{softID}", func(w http.ResponseWriter, r *http.Request) {
|
|
softID := chi.URLParam(r, "softID")
|
|
var soft data.Software
|
|
var found bool
|
|
for _, s := range d.Softwares {
|
|
if s.UUID == softID {
|
|
soft = s
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
w.Header().Add("Location", "/")
|
|
w.WriteHeader(http.StatusTemporaryRedirect)
|
|
return
|
|
}
|
|
err := descTemplate.Execute(w, soft)
|
|
if err != nil {
|
|
slog.Error(fmt.Sprintf("failed to execute template index: %s", err))
|
|
}
|
|
})
|
|
return &Server{
|
|
r: r,
|
|
d: d,
|
|
port: port,
|
|
}
|
|
}
|
|
|
|
func (s *Server) Serve() error {
|
|
return http.ListenAndServe(fmt.Sprintf(":%d", s.port), s.r)
|
|
}
|