1
0
Fork 0
Learning-GoLang/simple-blog/server/web/app.go

64 lines
1.5 KiB
Go
Raw Normal View History

2024-07-19 22:13:45 +02:00
package web
import (
"encoding/json"
"log"
"net/http"
"simple-blog/db"
)
type App struct {
d db.DB
handlers map[string]http.HandlerFunc
}
func NewApp(d db.DB, cors bool) App {
app := App{
d: d,
handlers: make(map[string]http.HandlerFunc),
}
techHandler := app.GetTechnologies
if !cors {
techHandler = disableCors(techHandler)
}
app.handlers["/api/technologies"] = techHandler
app.handlers["/"] = http.FileServer(http.Dir("/webapp")).ServeHTTP
return app
}
func (a *App) Serve() error {
for path, handler := range a.handlers {
http.Handle(path, handler)
}
log.Println("Web server is available on port 8080")
return http.ListenAndServe(":8080", nil)
}
func (a *App) GetTechnologies(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
technologies, err := a.d.GetTechnologies()
if err != nil {
sendErr(w, http.StatusInternalServerError, err.Error())
return
}
err = json.NewEncoder(w).Encode(technologies)
if err != nil {
sendErr(w, http.StatusInternalServerError, err.Error())
}
}
func sendErr(w http.ResponseWriter, code int, message string) {
resp, _ := json.Marshal(map[string]string{"error": message})
http.Error(w, string(resp), code)
}
// Needed in order to disable CORS for local development
func disableCors(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
h(w, r)
}
}