본문 바로가기

GoLang

GIN POST 테스트

검색을 누르면 localhost:3030/posts/ 의 dbApi를 호출해

호출된 json값

A,B,C,D에 값을 넣는 코드

1.main.html

<head>
    <title>메인 페이지</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>

<body>
    <h2>>메인 페이지</h2>
    <form  id="viewData_form" method="post">
        <p><label for="name">A</label> <input id="fieldA" name="fieldA" size="15" type="text" readonly="true" /></p>
        <p><label for="name">B</label> <input id="fieldB" name="fieldB" size="15" type="text" readonly="true" /></p>
        <p><label for="name">C</label> <input id="fieldC" name="fieldC" size="15" type="text" readonly="true" /></p>
        <p><label for="name">D</label> <input id="fieldD" name="fieldD" size="15" type="text" readonly="true" /></p>
    </form>
    <input  type="button" onclick="viewDataBtnClick()" value="조회" >
    <input  type="button" onclick="viewApiBtnClick()" value="검색" >
</body>

<script>
    function viewApiBtnClick() {
        $.ajax({
            url:"/api",
            type:"POST",
            contentType: "application/json; charset=utf-8",
            success: function(resData) { 
               $("#fieldA").val(resData.E)
               $("#fieldB").val(resData.F)
               $("#fieldC").val(resData.G)
               $("#fieldD").val(resData.G)
            },
            error: function() {
                alert("조회 처리 중 에러가 발생했습니다");
            }
        })
    }



</script>

1. route.go에 라우팅 추가

server.route.POST("/api", handler.APIBlogSearchHandler)

2.등록한 핸들러 패키지에서 호출된 function

func APIBlogSearchHandler(c *gin.Context) {
	c.Header("Content-Type", "application/json charset=utf-8")

	//TODO: 해당주소에 API호출 프로토콜 가져와보기
	resp, err := http.Get("http://localhost:3030/posts/")

	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
    
	//json값 전부 읽어온 후 출력하기
	respBody, err := ioutil.ReadAll(resp.Body)
	if err == nil {
		str := string(respBody)
		println(str)
		fmt.Printf("%s\n", str)
	}
    
	var datas []Board
	json.Unmarshal([]byte(respBody), &datas)

	idValue := datas[0].ID
	titleValue := datas[0].Title
	contentValue := datas[0].Content

	c.JSON(200, gin.H{
		"E": idValue,
		"F": titleValue,
		"G": contentValue,
	})
}

검색을 누르면 api값이 들어간다.

 

'GoLang' 카테고리의 다른 글

GIN 그래프 그리기  (0) 2020.11.19
GIN MongoDB Test  (0) 2020.11.17
GIN POST TEST2  (0) 2020.11.14
리눅스 서버에 GIN 포팅하기  (0) 2020.11.11
GoLang  (0) 2020.11.05