htmgo/examples/chat/partials/index.go

74 lines
1.7 KiB
Go
Raw Permalink Normal View History

package partials
import (
2024-10-01 01:32:42 +00:00
"chat/chat"
"chat/components"
"github.com/maddalax/htmgo/framework/h"
2024-10-01 03:08:52 +00:00
"net/http"
2024-10-01 17:09:22 +00:00
"time"
)
2024-10-01 01:32:42 +00:00
func CreateOrJoinRoom(ctx *h.RequestContext) *h.Partial {
locator := ctx.ServiceLocator()
service := chat.NewService(locator)
2024-10-01 03:08:52 +00:00
chatRoomId := ctx.Request.FormValue("join-chat-room")
username := ctx.Request.FormValue("username")
if username == "" {
return h.SwapPartial(ctx, components.FormError("Username is required"))
}
2024-10-01 17:42:01 +00:00
if len(username) > 15 {
return h.SwapPartial(ctx, components.FormError("Username is too long"))
}
2024-10-01 03:08:52 +00:00
user, err := service.CreateUser(username)
if err != nil {
return h.SwapPartial(ctx, components.FormError("Failed to create user"))
}
var redirect = func(path string) *h.Partial {
cookie := &http.Cookie{
2024-10-01 17:09:22 +00:00
Name: "session_id",
Value: user.SessionID,
Path: "/",
Expires: time.Now().Add(24 * 30 * time.Hour),
2024-10-01 03:08:52 +00:00
}
2024-10-01 22:19:38 +00:00
return h.RedirectPartialWithHeaders(
path,
2024-10-01 03:08:52 +00:00
h.NewHeaders(
"Set-Cookie", cookie.String(),
),
)
}
2024-10-01 01:32:42 +00:00
if chatRoomId != "" {
room, _ := service.GetRoom(chatRoomId)
if room == nil {
return h.SwapPartial(ctx, components.FormError("Room not found"))
} else {
2024-10-01 03:08:52 +00:00
return redirect("/chat/" + chatRoomId)
2024-10-01 01:32:42 +00:00
}
}
2024-10-01 03:08:52 +00:00
chatRoomName := ctx.Request.FormValue("new-chat-room")
2024-10-01 17:42:01 +00:00
if len(chatRoomName) > 20 {
return h.SwapPartial(ctx, components.FormError("Chat room name is too long"))
}
2024-10-01 01:32:42 +00:00
if chatRoomName != "" {
2024-10-01 03:08:52 +00:00
room, _ := service.CreateRoom(chatRoomName)
if room == nil {
return h.SwapPartial(ctx, components.FormError("Failed to create room"))
} else {
return redirect("/chat/" + room.ID)
}
2024-10-01 01:32:42 +00:00
}
2024-10-01 01:32:42 +00:00
return h.SwapPartial(ctx, components.FormError("Create a new room or join an existing one"))
}