init(app) moved app code from Lab1

This commit is contained in:
imadev
2026-10-21 16:42:14 +03:00
parent 65003b6119
commit 1db3953226
22 changed files with 1297 additions and 0 deletions
+122
View File
@@ -0,0 +1,122 @@
package common
import (
"errors"
"github.com/gofiber/fiber/v3"
)
const (
ErrorCodeInvalidRequest = "invalid_request"
ErrorCodeUnauthorized = "unauthorized"
ErrorCodeNotFound = "not_found"
ErrorCodeConflict = "conflict"
ErrorCodePayloadTooLarge = "payload_too_large"
ErrorCodeUnsupportedMedia = "unsupported_media_type"
ErrorCodeRateLimited = "rate_limited"
ErrorCodeUnavailable = "unavailable"
ErrorCodeInternal = "internal_error"
)
type APIErrorResponse struct {
Error APIError `json:"error"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
func NewError(code, message, requestID string) APIErrorResponse {
return APIErrorResponse{
Error: APIError{
Code: code,
Message: message,
RequestID: requestID,
},
}
}
type AppError struct {
Status int
Code string
Message string
}
func (e *AppError) Error() string {
return e.Message
}
func NewAppError(status int, code, message string) *AppError {
return &AppError{
Status: status,
Code: code,
Message: message,
}
}
func BadRequest(message string) *AppError {
return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message)
}
func Unauthorized(message string) *AppError {
return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
}
func NotFound(message string) *AppError {
return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message)
}
func Conflict(message string) *AppError {
return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message)
}
func UnsupportedMedia(message string) *AppError {
return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
}
func Internal() *AppError {
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
}
func ErrorCodeFromStatus(status int) string {
switch status {
case fiber.StatusBadRequest:
return ErrorCodeInvalidRequest
case fiber.StatusUnauthorized:
return ErrorCodeUnauthorized
case fiber.StatusNotFound:
return ErrorCodeNotFound
case fiber.StatusConflict:
return ErrorCodeConflict
case fiber.StatusRequestEntityTooLarge:
return ErrorCodePayloadTooLarge
case fiber.StatusUnsupportedMediaType:
return ErrorCodeUnsupportedMedia
case fiber.StatusTooManyRequests:
return ErrorCodeRateLimited
case fiber.StatusServiceUnavailable:
return ErrorCodeUnavailable
default:
return ErrorCodeInternal
}
}
func getRequestID(c fiber.Ctx) string {
return string(c.Response().Header.Peek("X-Request-Id"))
}
func SendError(c fiber.Ctx, status int, code, message string) error {
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
}
func SendAppError(c fiber.Ctx, err error) error {
var appErr *AppError
if errors.As(err, &appErr) {
return SendError(c, appErr.Status, appErr.Code, appErr.Message)
}
return SendError(c, fiber.StatusInternalServerError,
ErrorCodeInternal, "Internal server error")
}
+17
View File
@@ -0,0 +1,17 @@
package common
import (
"encoding/json"
"time"
)
type RFCFormTime time.Time
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
ftime := time.Time(t).UTC().Format(time.RFC3339)
return json.Marshal(ftime)
}
func NowUTC() RFCFormTime {
return RFCFormTime(time.Now().UTC().Truncate(time.Second))
}
+198
View File
@@ -0,0 +1,198 @@
package common
import (
"encoding/base64"
"sort"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
type CursorKeyCtx struct {
Time time.Time
ID uuid.UUID
ContextID uuid.UUID
}
type cursorKey struct {
time time.Time
id uuid.UUID
}
type CreatedAtIDable interface {
GetCreatedAt() time.Time
GetID() uuid.UUID
}
type PaginatedResponse[T any] struct {
Items []T `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
limitStr, exists := c.Queries()["limit"]
if limitStr == "" {
if !exists {
return defaultLimit, nil
}
return 0, BadRequest("limit param declared but empty")
}
limit, ok := validateLimitStr(limitStr)
if !ok {
return 0, BadRequest("limit must be an integer between 1 and 100")
}
return limit, nil
}
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
cursorStr, exists := c.Queries()["cursor"]
if cursorStr == "" {
if !exists {
return nil, nil
}
return nil, BadRequest("cursor param declared but empty")
}
cursor := DecodeCursor(cursorStr)
if cursor == nil {
return nil, BadRequest("invalid cursor format")
}
return cursor, nil
}
func Paginate[T CreatedAtIDable](
items []T,
limit int,
cursor *CursorKeyCtx,
contextID uuid.UUID,
) (*PaginatedResponse[T], error) {
enforceOrder(items)
start := 0
if cursor != nil {
key := cursorKey{time: cursor.Time, id: cursor.ID}
position, found := findAfter(items, key)
if !found {
return nil, BadRequest("cursor invalid")
}
if position == -1 {
position = len(items)
}
start = position
}
end := start + limit
if end > len(items) {
end = len(items)
}
page := items[start:end]
if page == nil {
page = []T{}
}
var nextCursor *string
if end < len(items) {
last := items[end-1]
encoded := encodeCursor(CursorKeyCtx{
Time: last.GetCreatedAt(),
ID: last.GetID(),
ContextID: contextID,
})
nextCursor = &encoded
}
return &PaginatedResponse[T]{
Items: page,
NextCursor: nextCursor,
}, nil
}
func encodeCursor(key CursorKeyCtx) string {
timeStr := key.Time.UTC().Format(time.RFC3339Nano)
raw := timeStr + "|" + key.ID.String() + "|" + key.ContextID.String()
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func DecodeCursor(cursor string) *CursorKeyCtx {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return nil
}
parts := strings.SplitN(string(data), "|", 3)
if len(parts) != 3 {
return nil
}
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
if err != nil {
return nil
}
parsedID, err := uuid.Parse(parts[1])
if err != nil {
return nil
}
parsedContextID, err := uuid.Parse(parts[2])
if err != nil {
return nil
}
return &CursorKeyCtx{
Time: parsedTime,
ID: parsedID,
ContextID: parsedContextID,
}
}
func findAfter[T CreatedAtIDable](items []T, key cursorKey) (position int, keyFound bool) {
for i, item := range items {
itemKey := keyOf(item)
if itemKey == key {
keyFound = true
}
if after(itemKey, key) {
return i, true
}
}
return -1, keyFound
}
func keyOf(item CreatedAtIDable) cursorKey {
return cursorKey{
time: item.GetCreatedAt(),
id: item.GetID(),
}
}
func after(a, b cursorKey) bool {
if !a.time.Equal(b.time) {
return a.time.After(b.time)
}
return a.id.String() > b.id.String()
}
func enforceOrder[T CreatedAtIDable](items []T) {
sort.Slice(items, func(i, j int) bool {
return after(keyOf(items[j]), keyOf(items[i]))
})
}
+139
View File
@@ -0,0 +1,139 @@
package common
import (
"bytes"
"encoding/json"
"io"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/go-playground/validator"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
var (
validate = validator.New()
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
)
func BindJSON(c fiber.Ctx, req any) error {
contentType := c.Get(fiber.HeaderContentType)
if !strings.HasPrefix(contentType, "application/json") {
return UnsupportedMedia("invalid JSON body")
}
body := c.Body()
if len(body) == 0 {
return BadRequest("request body is empty")
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(req); err != nil {
return BadRequest(err.Error())
}
var extra json.RawMessage
if err := decoder.Decode(&extra); err != io.EOF {
return BadRequest("request body has extra trailing bytes")
}
if err := validate.Struct(req); err != nil {
return BadRequest("field validation failed: " + err.Error())
}
return nil
}
func blank(s string) bool {
return strings.TrimSpace(s) == ""
}
func strLenBetween(s string, min, max int) bool {
n := utf8.RuneCountInString(s)
return n >= min && n <= max
}
func ValidateCreateUser(username, displayName string) string {
if !usernameRegex.MatchString(username) {
return "username must match ^[a-z0-9_]{3,32}$"
}
if blank(displayName) {
return "display_name must not be empty or only whitespace"
}
if !strLenBetween(displayName, 1, 100) {
return "display_name must be between 1 and 100 Unicode code points"
}
return ""
}
func ValidateChatTitle(title string) string {
if blank(title) {
return "title must not be empty or only whitespace"
}
if !strLenBetween(title, 1, 100) {
return "title must be between 1 and 100 Unicode code points"
}
return ""
}
func ValidateMessageText(text string) string {
if blank(text) {
return "text must not be empty or only whitespace"
}
if !strLenBetween(text, 1, 4000) {
return "text must be between 1 and 4000 Unicode code points"
}
return ""
}
func validateLimitStr(s string) (int, bool) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, false
}
if n < 1 || n > 100 {
return 0, false
}
return n, true
}
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
if len(ids) < 1 || len(ids) > 100 {
return "member_ids must contain between 1 and 100 members"
}
seen := make(map[uuid.UUID]bool, len(ids))
callerFound := false
for _, id := range ids {
if seen[id] {
return "member_ids must not contain duplicates"
}
seen[id] = true
if id == callerID {
callerFound = true
}
}
if !callerFound {
return "caller must be included in member_ids"
}
return ""
}