Go 패키지 시리즈 2 바인딩(mholt/binding) 사용하기

net

소개

Go의 net/http 패키지를 위한 데이터 바인딩 유틸리티로서 http.Request를 Go 구조체로 바인딩 한다.

설치

1
go get github.com/mholt/binding

사용법

1
2
3
4
5
myStruct := new(MyStruct)
errs := binding.Bind(req, myStruct)
if errs.Handle(response) {
return
}

이렇게 바인딩하기 위해서는 구조체 MyStruct를 binding.FieldMap 인터페이스로 만들어야 한다. 이 과정은 간단히 func (s *MyStruct) FieldMap() binding.FieldMap 메소드를 구현하기만 하면 된다.

1
2
3
4
5
6
7
8
9
10
func (s *MyStruct) FieldMap() binding.FieldMap {
return binding.FieldMap{
&s.Name: "name", // 구조체 필드: 폼이름
&s.Email: "email",
&s.Message: binding.Field{
Form: "message",
Required: true, // validation
},
}
}

More

(http://mholt.github.io/binding/)[http://mholt.github.io/binding/]