pink_fox/pink_fox_app/src/app/http_server/response.go
Michael Makarochkin f7a4ad6cdb Отображение html страницы
- Добавлен шаблонизатор jet

- Сделан views для html страниц

- Переработано отображение ошибок, теперь они корректно отображаются
2025-03-14 02:53:36 +03:00

96 lines
2.0 KiB
Go

package http_server
import (
"fmt"
"github.com/CloudyKit/jet/v6"
"github.com/gin-gonic/gin"
"net/http"
"pink_fox/src/app/types"
)
type Response interface {
Render()
}
type StringResponse struct {
str string
ctx *gin.Context
}
func NewStringResponse(s string, ctx *gin.Context) *StringResponse {
return &StringResponse{str: s, ctx: ctx}
}
func (it *StringResponse) Render() {
it.ctx.String(http.StatusOK, it.str)
}
type HtmlErrorResponse struct {
code int
msg string
ctx *gin.Context
}
func NewHtmlErrorResponse(code int, ctx *gin.Context) *HtmlErrorResponse {
return &HtmlErrorResponse{code: code, ctx: ctx}
}
func (it *HtmlErrorResponse) Msg(msg string) *HtmlErrorResponse {
it.msg = msg
return it
}
func (it *HtmlErrorResponse) Render() {
message := ""
if it.msg != "" {
message = fmt.Sprintf("<p>%s</p>", it.msg)
}
it.ctx.Header("Content-Type", "text/html; charset=utf-8")
it.ctx.String(it.code, fmt.Sprintf("<h1>%d %s</h1>\n%s\n", it.code, http.StatusText(it.code), message))
}
type RedirectResponse struct {
code int
to string
ctx *gin.Context
}
func NewRedirectResponse(to string, ctx *gin.Context) *RedirectResponse {
return &RedirectResponse{code: 302, to: to, ctx: ctx}
}
func (it *RedirectResponse) SetCode(code int) *RedirectResponse {
it.code = code
return it
}
func (it *RedirectResponse) Render() {
it.ctx.Redirect(it.code, it.to)
}
type ViewResponse struct {
ctx *gin.Context
makeViewObject types.MakeViewObject
id int16
file string
data any
}
func NewViewResponse(ctx *gin.Context, makeViewObject types.MakeViewObject, id int16, file string, data any) *ViewResponse {
return &ViewResponse{
ctx: ctx,
makeViewObject: makeViewObject,
id: id,
file: file,
data: data,
}
}
func (it *ViewResponse) Render() {
data := make(jet.VarMap)
data.Set("vi", it.makeViewObject(it.id))
data.Set("it", it.data)
it.ctx.HTML(http.StatusOK, it.file, data)
}