chttp

package module
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2025 License: MIT Imports: 11 Imported by: 0

README

chttp

This library is a tool to more conveniently obtain the required content in the corresponding set from the request of the go-chi library.

Usage

type BaseReq struct {
    TraceId  *string `header:"traceId,omitempty" v:"required"`
    Platform *string `header:"platform,omitempty" default:"whatsapp"`
    ReqId    *string `header:"reqId,omitempty" `
}
type TranferStoreReq struct {
    BaseReq      `cv:"true"`
    Origin       *string `url:"origin" v:"required"`
    StoreId      *string `url:"storeId" v:"required"`
    UserId       *string `json:"userId,omitempty"  v:"required"`
    TransferType *string `json:"transferType,omitempty"  v:"required"`
}

Tags Definitions

Value
`json:"<field>"` // value fetch from json body
`header:"<field>"` // value fetch from header
`param:"<field>"` // value fetch from url param
`url:"<field>"` // value fetch from url (only support for go-chi lib)
Func
`v:"required"`// to tell chttp to validate this field != nill
`cv:"true"` // to tell chttp to perform recursion with this struct
`default:"<value: string|int|float|bool>"` // to set the default value

Handle

package cthttp

import (
	"github.com/kuah/chttp"
	"net/http"
)
// this is a sample to show you that I just need to know valid or not in my business
func Valid[T any](r *http.Request, w http.ResponseWriter) (T, bool) {
	req, validation, err := chttp.Valid[T](r)
	switch validation {
	case chttp.ParserResultError, chttp.ParserResultNotVerified:
		// you can log error here || use w to response
		return req, false
	case chttp.ParserResultSuccess:
		return req, true
	default:
		return req, false
	}
}

func ReadRequestBody[T any](r *http.Request) (*T, error) {
	return chttp.ReadRequestBody[T](r)
}

Further Usage

func TransferStore(w http.ResponseWriter, r *http.Request) {
    req, isPassed := cthttp.Valid[vo.TranferStoreReq](r, w)
    if isPassed == false {
    return
    }
    // your code ...
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReadRequestBody

func ReadRequestBody[T any](r *http.Request) (*T, error)

Types

type ParamValidation

type ParamValidation struct {
	Valid        *bool
	ValidMessage *string
}

func ParseWithValidation

func ParseWithValidation[T any](r *http.Request) (T, *ParamValidation, error)

type ParserResult

type ParserResult int
const (
	ParserResultSuccess     ParserResult = 1
	ParserResultNotVerified ParserResult = 0
	ParserResultError       ParserResult = -1
)

func Valid

func Valid[T any](r *http.Request) (T, ParserResult, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL