100 lines
2.1 KiB
Go
100 lines
2.1 KiB
Go
package router
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"html/template"
|
|
"net/http"
|
|
"path/filepath"
|
|
)
|
|
|
|
type Response struct {
|
|
http.ResponseWriter
|
|
}
|
|
|
|
func (resp Response) View(name string, data any) {
|
|
fp := filepath.Join("internal/views", fmt.Sprintf("%s.html", name))
|
|
tmpl, _ := template.ParseFiles(fp)
|
|
|
|
buf := new(bytes.Buffer)
|
|
if err := tmpl.ExecuteTemplate(buf, "index", data); err != nil {
|
|
resp.statusCode(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
resp.html(buf.Bytes(), http.StatusOK)
|
|
}
|
|
|
|
func (resp Response) OK(data any) {
|
|
resp.json(data, http.StatusOK)
|
|
}
|
|
|
|
func (resp Response) NoContent() {
|
|
resp.statusCode(http.StatusNoContent)
|
|
}
|
|
|
|
func (resp Response) BadRequest(err error) {
|
|
resp.error(err, http.StatusBadRequest)
|
|
}
|
|
|
|
func (resp Response) Unauthorized(err error) {
|
|
resp.error(err, http.StatusUnauthorized)
|
|
}
|
|
|
|
func (resp Response) Forbidden(err error) {
|
|
resp.error(err, http.StatusForbidden)
|
|
}
|
|
|
|
func (resp Response) NotFound(err error) {
|
|
resp.error(err, http.StatusNotFound)
|
|
}
|
|
|
|
func (resp Response) Conflict(err error) {
|
|
resp.error(err, http.StatusConflict)
|
|
}
|
|
|
|
func (resp Response) UnsupportedMediaType(err error) {
|
|
resp.error(err, http.StatusUnsupportedMediaType)
|
|
}
|
|
|
|
func (resp Response) InternalServerError(err error) {
|
|
resp.error(err, http.StatusInternalServerError)
|
|
}
|
|
|
|
func (resp Response) error(err error, status int) {
|
|
er := struct {
|
|
Message string `json:"message"`
|
|
}{
|
|
Message: err.Error(),
|
|
}
|
|
resp.json(er, status)
|
|
}
|
|
|
|
func (resp Response) html(content []byte, status int) {
|
|
resp.Header().Add("Content-Type", "text/html; charset=utf-8")
|
|
resp.WriteHeader(status)
|
|
|
|
if _, err := resp.Write(content); err != nil {
|
|
panic("Failed to write HTTP response: " + err.Error())
|
|
}
|
|
}
|
|
|
|
func (resp Response) json(data any, statusCode int) {
|
|
content, err := json.Marshal(data)
|
|
if err != nil {
|
|
panic("Failed to marshal JSON: " + err.Error())
|
|
}
|
|
|
|
resp.Header().Add("Content-Type", "application/json; charset=utf-8")
|
|
resp.WriteHeader(statusCode)
|
|
|
|
if _, err := resp.Write(content); err != nil {
|
|
panic("Failed to write HTTP response: " + err.Error())
|
|
}
|
|
}
|
|
|
|
func (resp Response) statusCode(code int) {
|
|
resp.WriteHeader(code)
|
|
}
|