2024-01-25 17:58:55 +01:00
|
|
|
package httpServer
|
|
|
|
|
|
|
|
import (
|
2024-02-16 22:36:13 +01:00
|
|
|
"embed"
|
2024-01-25 17:58:55 +01:00
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.gnous.eu/gnouseu/plakken/internal/constant"
|
|
|
|
"git.gnous.eu/gnouseu/plakken/internal/web/plak"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ServerConfig struct {
|
|
|
|
HTTPServer *http.Server
|
|
|
|
UrlLength uint8
|
|
|
|
DB *redis.Client
|
2024-02-16 22:36:13 +01:00
|
|
|
Static embed.FS
|
|
|
|
Templates embed.FS
|
|
|
|
}
|
|
|
|
|
2024-02-24 01:26:27 +01:00
|
|
|
func (config ServerConfig) home(w http.ResponseWriter, _ *http.Request) {
|
2024-02-16 22:36:13 +01:00
|
|
|
index, err := config.Static.ReadFile("static/index.html")
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
_, err = w.Write(index)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
2024-01-25 17:58:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Configure HTTP router
|
2024-02-16 22:41:29 +01:00
|
|
|
func (config ServerConfig) router() {
|
2024-01-25 17:58:55 +01:00
|
|
|
WebConfig := plak.WebConfig{
|
|
|
|
DB: config.DB,
|
|
|
|
UrlLength: config.UrlLength,
|
2024-02-16 22:36:13 +01:00
|
|
|
Templates: config.Templates,
|
2024-01-25 17:58:55 +01:00
|
|
|
}
|
2024-02-16 22:36:13 +01:00
|
|
|
staticFiles := http.FS(config.Static)
|
2024-01-25 17:58:55 +01:00
|
|
|
|
2024-02-16 22:36:13 +01:00
|
|
|
http.HandleFunc("GET /{$}", config.home)
|
|
|
|
http.Handle("GET /static/{file}", http.FileServer(staticFiles))
|
2024-01-25 17:58:55 +01:00
|
|
|
http.HandleFunc("GET /{key}/{settings...}", WebConfig.View)
|
2024-02-24 01:26:27 +01:00
|
|
|
http.HandleFunc("POST /{$}", WebConfig.CurlCreate)
|
|
|
|
http.HandleFunc("POST /create/{$}", WebConfig.Create)
|
2024-01-25 17:58:55 +01:00
|
|
|
http.HandleFunc("DELETE /{key}", WebConfig.Delete)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Config Configure HTTP server
|
|
|
|
func Config(listenAddress string) *http.Server {
|
|
|
|
server := &http.Server{
|
|
|
|
Addr: listenAddress,
|
|
|
|
ReadTimeout: constant.HTTPTimeout,
|
|
|
|
WriteTimeout: constant.HTTPTimeout,
|
|
|
|
}
|
|
|
|
|
|
|
|
return server
|
|
|
|
}
|
|
|
|
|
|
|
|
// Server Start HTTP server
|
|
|
|
func (config ServerConfig) Server() {
|
|
|
|
log.Println("Listening on " + config.HTTPServer.Addr)
|
|
|
|
|
2024-02-16 22:41:29 +01:00
|
|
|
config.router()
|
2024-01-25 17:58:55 +01:00
|
|
|
|
|
|
|
log.Fatal(config.HTTPServer.ListenAndServe())
|
|
|
|
}
|