学習備忘ログ

よく使うコードや設定のメモ

go

【Golang + Echo + go-playground/validator】アップロードした画像の幅や高さのバリデーションを実装

go

課題 アップロードした画像の幅や高さのバリデーションしたい サンプル実装 画像の幅が1000以下でない場合はエラーを出す。 type SampleRequest struct { File File } type File struct { Width int `json:"width" validate:"lt=1000"` Height int `json:"he…

【Golang + go-playground/validator】DBを含めたバリデーションの実装

go

課題 DBを含めたバリデーションを実装したい サンプル実装 userテーブルのemailに同じemailがあったらバリデートする。 type DBAbstraction struct { db interface{} //ここは実際のコードの型に合わせる } func (a *DBAbstraction) ValidateExistsEmail(fl …

【Golang + go-playground/validator】他のフィールドの値を含めたカスタムバリデーションの実装

go

課題 他のフィールドの値を含めたカスタムバリデーションの実装をしたい サンプル実装 AフィールドとBフィールドの値を比較してバリデーションする方法。こちらはそもそもカスタムせずに gtecsfieldを使用すれば実現できる。 type SampleStruct struct { A i…

【Golang + Sqlx】リレーション先も含めて構造体へのbindを一度でする方法

go

前提 groupテーブルとcategoryテーブルがあり、groupテーブルにcategoryを参照する外部キーが存在してる。 構造体定義 package model type Group struct { ID int `json:"id" db:"id"` Name string `json:"name" db:"name"` GroupCategoryId uint64 `json:"g…

【Golang + http/test】リクエストのbodyにjsonを渡す方法

go

サンプルコード bodyJsonにjsonの文字列を代入し、strings.NewReaderで読み込んであげる。 package handler_test import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func…