본문 바로가기
Programming Language/golang

Echo 로 JSON POST DATA 처리하기

by 단북 2020. 8. 28.

Redfish 이벤트 모니터링을 위한 Hook Server를 하나 만들어야 하는 상황이 생겼다.
POST DATA를 받아서 엘라스틱 서치로 로그나 다른 메신저로 보내 보려는 중이다.

일단 POST DATA를 어떻게 처리할지를 잘 모르기 때문에, 간단한 POST DATA를 다루는 법만 알아내 끄적여본다.

## POST 소스 코드 작성

  1. 먼저 받을 데이터 필드 구조체를 만든다. (type Redfish struct)
  2. POST DATA를 받아서 처리할 redfish 함수를 만들고 echo.Context를 이용해 JSON 응답을 해줄 수 있다. 서버에서도 올바르게 찍힌 것인지 json marshaling을 이용해 print로 찍어 보았다.
  3. e.POST 구문으로 POST 경로 라우팅과 데이터가 들어오면 처리할 함수를 맵핑해준다.
     
package main

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

//Redfish struct
type Redfish struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Context string `json:"context"`
}

func redfish(c echo.Context) (err error) {
	u := new(Redfish)
	if err = c.Bind(u); err != nil {
		return
	}
	b, _ := json.Marshal(u)
	fmt.Println(string(b))
	return c.JSON(http.StatusOK, u)
}

func main() {
	e := echo.New()
	
    // GET / Response
    e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, alinos World!\n")
	})

    // POST /redfish Response
	e.POST("/redfish", redfish)

    // Logging
	e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Format: "method=${method}, uri=${uri}, status=${status}\n",
	}))

	e.Logger.Fatal(e.Start(":1323"))
}

## Json Post data 보내보기

- curl 로 json post data를 보내본다. 원하는 id/name/context 필드로 응답을 받았고, 서버에서도 print로 json을 찍게끔 해놨기 때문에, 올바르게 데이터가 들어온 걸 확인할 수 있다.
- 세번째 요청엔 context 키 대신 messages 란 없는 키로 요청을 보내보았다.
혹시나 에러가 날까 싶었지만, 없는 키로 보낸 건 버리고 context 필드만 없는 값으로 찍혀서 잘 나온다.

## Client
alinos@DESKTOP-A52MBHK:~/go/src/github.com/alinos/alinosweb$ curl -X POST http://localhost:1323/redfish \
> -H 'Content-Type: application/json' \
> -d '{"id":"alinos","name":"KIH","context":"test" }'
{"id":"alinos","name":"KIH","context":"test"}
alinos@DESKTOP-A52MBHK:~/go/src/github.com/alinos/alinosweb$ curl -X POST http://localhost:1323/redfish \
-H 'Content-Type: application/json' \
-d '{"id":"ickhyun33","name":"Second_KIH","context":"Second test" }'
{"id":"ickhyun33","name":"Second_KIH","context":"Second test"}
alinos@DESKTOP-A52MBHK:~/go/src/github.com/alinos/alinosweb$ curl -X POST http://localhost:1323/redfish \
-H 'Content-Type: application/json' \
-d '{"id":"alinos","name":"KIH","messages":"test" }'
{"id":"alinos","name":"KIH","context":""}


## Server
alinos@DESKTOP-A52MBHK:~/go/src/github.com/alinos/alinosweb$ go run main.go

   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.1.16
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on [::]:1323
{"id":"alinos","name":"KIH","context":"test"}
method=POST, uri=/redfish, status=200
{"id":"ickhyun33","name":"Second_KIH","context":"Second test"}
method=POST, uri=/redfish, status=200
{"id":"alinos","name":"KIH","context":""}
method=POST, uri=/redfish, status=200

 

## 참조

- https://echo.labstack.com/guide/response

 

Echo - High performance, minimalist Go web framework

Echo is a high performance, extensible, minimalist web framework for Go (Golang).

echo.labstack.com

- https://forum.labstack.com/t/how-to-get-the-json-from-the-body-of-a-request/15

 

How to get the JSON from the Body of a Request?

I’m a newbie with Go, but so far I’m liking it very much. I have a problem I can’t figure out. I’m migrating an API from Node to Go and there is this log where I have to capture the Body of a POST AS IT IS and save it to a jsonb type column in a Po

forum.labstack.com