상세 컨텐츠

본문 제목

[Nomad Coin] Rest API - #6.0 Setup

Go/Blockchain

by Gopythor 2022. 7. 19. 03:16

본문

728x90
반응형

#6.0 Setup

  • explorer보다 더 유용할 것이다. 왜냐하면 HTML explorer은 단지 template로 작업하는 방법만 보여주고, 라우트들을 만드는 기본적인 방법만 보여준다.
  • 블록체인에 기능을 더 추가하면서 REST API를 확장할 것이다.
  • transaction을 추가하는 순간에 transaction을 보낼 건데 REST API를 사용해서 transactino을 만들 것이다.
  • 특정한 블록이나 transaction을 찾고 싶을 때, 블록을 채굴하거나, address에 balance를 보고 싶을 때, 이 모든 것들이 REST API를 통해서 보여지게 될 것이다.
  • 블록체인과 상호작용하는 것이다.
  • Go에서 JSON을 사용하는 연습을 해보자. 자바스크립트에서 했던 거와는 다르다.
const port string = ":4000"

func main() {
	fmt.Printf("Listening on http://localhost%s", port)
	log.Fatal(http.ListenAndServe(port, nil))
}
  • 일단 원래하던대로 서버를 시작한다.
  • http.ListenAndServe()를 입력하고, 포트를 입력한다. const port string = ":4000"
  • 그리고 handler를 바꿀 것이다.보통은 nil이라고 되있다.
/
GET
See Documentation

/blocks
POST
create a block
  • API를 어떻게 디자인 해야 할까?
  • documentation은 기본적으로 route(/)를 의미한다.
  • 이곳으로 가면 API에서 할 수 있는 일들의 목록을 볼 수 있다.
  • 예를들어, url은 이거(/) method는 GET
  • URL 설명은 See Documentation 목록이다.
  • 아니면 /blocks, POST 요청, Create a Block.
  • 이것이 API에서 보고 싶은 것이다.
func documentation(rw http.ResponseWriter, r *http.Request){

}

func main() {
	http.HandleFunc("/", documentation)
	fmt.Printf("Listening on http://localhost%s", port)
	log.Fatal(http.ListenAndServe(port, nil))
}
  • 우선, http.HandleFunc("/")을 입력하고, 함수를 만들자.
  • 이름은 documentation, ResponseWriter인 rw가 필요하고, http.Request의 포인터인 r이 필요하다.
  • 이제 여기에 documentation을 넣어주자.
  • 먼저 유저에게 JSON을 보내는 것부터 시작할 것이다.
  • JSON을 보낸다는 건 GO에서 뭔가를 받아서, 유효한 JSON으로 변환한다는 것이다.
  • 먼저 변환 시킬 GO data를 만들어야 한다.
type URLDescription struct{
	URL string
	Method string
	Description string
}
  • 여기에 모든 URL의 리스트를 갖고 싶다.
  • 먼저 type URLDescription struct를 쓰고 대문자 아니여도 되는데 URL이 줄임말이라 대문자로 썼다.
func documentation(rw http.ResponseWriter, r *http.Request) {
	data := []URLDescription{
		{
			URL:         "/",
			Method:      "GET",
			Description: "See Documentation",
		},
	}
}
  • 이제 여기에는, 내 페이지를 위한 data를 만들 것이다.
  • URLDescription slice를 만들고, 첫 URLDescription을 만들 것이다.
  • 이제 URLDescription slice가 생겼다. 이게 유저한테 보여주고 싶은 것이다.
  • 이 data는 Go의 세계에 있는 slice이다. struct의 slice.

  • 이걸 JSON으로 바꿔야 한다. 이걸 하려면 Marshal이라는 걸 사용해야 한다.
  • Marshal은 JSON으로 encoding한 interface(v)를 return해준다.
  • Marshal은 메모리 형식으로 저장된 객체를, 저장/송신 할 수 있도록 변환해준다.
  • Marshal이랑 Unmarshal을 자주 보게 될 것이다.
  • Marshal은 Go에서 Interface를 받아서 JSON으로 바꿔주는 거고, Unmarshal은 반대로 JSON을 받아서 Go읠 물건으로 바꿔준다.
  • Marshal부터 해 볼 것이다.
func documentation(rw http.ResponseWriter, r *http.Request) {
	data := []URLDescription{
		{
			URL:         "/",
			Method:      "GET",
			Description: "See Documentation",
		},
	}
	b, err := json.Marshal(data)
	if err != nil{
		log.Panic(err)
	}
}
  • Marshal은 이런 식의 data를 갖고 json.Marshal만 해주면 된다. 여기에 interface만 넣어주면 된다. data.
  • 이렇게 해주면 Marshal이 data를 byte slice 아님 error을 retrun해줄 것이다.
  • 그 말은 여기에 byte(b), error(err) := 라고 해주고 error 처리를 해줘야 한다.
  • 만약 err가  nil이 아니라면, log.Panic(err).
  • 전에 template에선s template helper가 있었지만 이걸 많이 쓸 것이다. Marshal, Unmarshal 할때난 DB작업할 때

 

package utils

func HandelErr(err error) {
	if err != nil {
		log.Panic(err)
	}
}
  • utility package 을 만들때가 온 것 같다. utils 폴더에 utils.go 파일을 만들 것이다.
  • 이 파일에는 계속해서 사용할 몇 개의 함수만 만들어 놓을 것이다.
  • 먼저 package utils하고 HandelErr함수를 만들자.
func documentation(rw http.ResponseWriter, r *http.Request) {
	data := []URLDescription{
		{
			URL:         "/",
			Method:      "GET",
			Description: "See Documentation",
		},
	}
	b, err := json.Marshal(data)
	utils.HandelErr(err)
	fmt.Print(b)
}
  • 이제 여기에 utils.HandleErr(err)라고 하면 된다.
  • 여기에 byte slice가 있는데, 이 byte는 JSON바뀐 data이다.
  • fmt.Print(b)하면 뭐가 나오는지 보자.

  • byte slice가 생겼다.
func documentation(rw http.ResponseWriter, r *http.Request) {
	data := []URLDescription{
		{
			URL:         "/",
			Method:      "GET",
			Description: "See Documentation",
		},
	}
	b, err := json.Marshal(data)
	utils.HandelErr(err)
	fmt.Printf("%s", b)
}
  • 이걸 유저한테 보낼 수도 있고, string으로 변환시킬 수도 있다.
  • 원래 byte slice인데 string으로 바궈서 사람의 방식으로 볼 수 있다. 이래서 formatting을 사용하는 것이다.

  • 우리 data이지만 친근한 JSON으로 변환 되었다.
  • string으로 바꿔주고, 이 JSON을 유저가 보게 될 것이다.
  • 어렵진 않지만 꼭 해줘야 한다.
  • struct를 JSON으로 바꿔서 string이나 원하는 포맷으로 보여줄 수 있다.
  • 자바스크립트에서는 익숙하지 않은 절차이다.
  • 자바스크립트에서는 그냥 JSON을 return 해주기만 하면 된다.
  • 이게 첫 번째 파트이다.

 

강의 : 노마드코더 노마드코인

 

 

728x90
반응형

관련글 더보기

댓글 영역