Web/GoLang

[golang] interface to sturct 인터페이스를 구조체로 변경하는 방법

벨포트조던 2022. 6. 7.
반응형

배경

- 컨택스트에 데이터 넣고 받으려고 하니.. interface로 반환된다. 반환된 interface를 구조체로 만들 필요가 생김

 

참고기사

https://research.swtch.com/interfaces

 

For conversion of interface{} to a struct, we will use the library – https://github.com/mitchellh/mapstructure . Let’s understand how to convert the interface to a struct by an example:

 

위 라이브러리를 사용하자

 

package main

import (
	"fmt"

	"github.com/mitchellh/mapstructure"
)

type NewCustomerEvent struct {
	Name  string
	Phone string
	Email string
}

func main() {
	newCustomer := NewCustomerEvent{Name: "x", Phone: "082213909101", Email: "xyz@gmail.com"}
	convert(newCustomer)
}

func convert(event interface{}) {
	c := NewCustomerEvent{}
	mapstructure.Decode(event, &c)
	fmt.Printf("Event is: %v", c)
}

 

output

 

Event is: {x 082213909101 xyz@gmail.com}

 

 


user := c.Locals("user") 
 details, ok :=user.(*models.User)
 fmt.Println("checking for locals -----------",details.Name)

요렇게도 쓰는거같다

 

반응형

댓글