Genericsがある良い時代にGolang使えてよかったhttps://t.co/E4MlH1ikv4
— 優さん (@yuu13n6r2) January 6, 2023
Controller.go
// create birth_days func (controller_birthday BirthDayController) CreateBirthDay(w http.ResponseWriter, r *http.Request) (Response.ApiResponseInterface) { input_data := []usecase_create_birth_day.CreateBirthDayRequest{} Request.JsonDecode(r, &input_data) controller_birthday.i_create_birth_day_interactor.Handle(input_data) return Response.NewCreateSuccessResponse() }
Request/RequestBody.go
package Request import ( "net/http" "encoding/json" "io" "log" ) // Map request body to specified object func JsonDecode[T any](r *http.Request, inputData *T) { body, err := io.ReadAll(r.Body) if err != nil { log.Fatalf("failed JsonDecode when io.ReadAll. %v", err) } // finally must close defer r.Body.Close() err = json.Unmarshal(body, &inputData) if err != nil { log.Fatalf("failed JsonDecode when Unmarshal %v", err) } }
Genericが活躍した😼
https://go.dev/doc/tutorial/generics
もくじ
reflectとforで実装例
@see Teratail
func structToMap(data interface{}) []map[string]string { rv := reflect.ValueOf(data) maps := make([]map[string]string, 0, rv.Len()) for i := 0; i < rv.Len(); i++ { st := rv.Index(i) rt := st.Type() // マップに代入 m := make(map[string]string) for i := 0; i < rt.NumField(); i++ { m[rt.Field(i).Name] = st.Field(i).String() } maps = append(maps, m) } return maps }