golang <-> javascript json통신

2022. 1. 27. 14:20기타

* 웹알못의 기록

* 예제 1

 

* 서버

mux.HandleFunc("/get-time", func(rw http.ResponseWriter, r *http.Request) {
    ctime := Response{
        CurrentTime: time.Now().Format(time.RFC3339),
    }
    byteArray, err := json.Marshal(ctime)
    if err != nil {
        fmt.Println(err)
    }
    rw.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
    rw.Header().Set("Access-Control-Allow-Origin", "*")
    rw.WriteHeader(http.StatusOK)
    rw.Write(byteArray)
})

 

* 클라이언트

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
	<button id="gt">get time1</button>
    <div id="res"></div>
    <script>
        document.getElementById("gt").onclick = async (e) => {
            var req = await fetch("http://localhost:3000/get-time").then(r => r.json())
            document.getElementById("res").innerHTML = req.CurrentTime
			//alert(req.CurrentTime)
        }
    </script>
</body>
</html>

 

* 창로드

* 버튼을 누르면

* 예제 2

 

* 서버

func testHandler(w http.ResponseWriter, r *http.Request) {
	html := `<!DOCTYPE html>
	<html>
	<head>Title</head>
	<body>
	<fieldset style="width:670px">
	<legend>param1</legend>
	<label for="param1_id"  style="width:80px ">parameter1</label>
	<input id="param1_id" name="param1_id" type="text" style="width:550px"
	value="parameter1_value"/>
	<br/>
	<label for="param2_id"  style="width:80px ">parameter2</label>
	<input id="param2_id" name="param2_id" type="text" style="width:550px"
	value="parameter2_value"/>
	<br/>
	<button id="btn_send">send</button>
	<script>
	document.getElementById("btn_send").onclick = async (e) => {
		var obj = new Object();
		obj.argument1 = param1_id.value;
		obj.argument2 = param2_id.value;
		
		//alert(JSON.stringify(obj));
		
		var req = await fetch("test_send_func", {
			method: 'post',
			headers: {	'Content-Type': 'application/json;charset=utf-8', },
			body: JSON.stringify(obj)
		}).then(r => r.json())
		.then(function(json){
			//alert(JSON.stringify(json));
			document.getElementById("res").innerHTML = JSON.stringify(json)
		})
		


	}

	</script>
	</fieldset>

	<div id="res"></div>
	
	</body>
	</html>
	`

	fmt.Fprint(w, html)
}

type TestRecvObj struct {
	Arg1 string `json:"argument1"`
	Arg2 string `json:"argument2"`
}

func testSendHandler(w http.ResponseWriter, r *http.Request) {
	sendObj := new(TestRecvObj)
	//Client가 보낸 User
	err := json.NewDecoder(r.Body).Decode(sendObj)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, err)
		return
	}

	w.Header().Add("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	data, _ := json.Marshal(sendObj)
	fmt.Fprint(w, string(data))
}

//서버 등록
func NewHandler() http.Handler {
	mux := mux.NewRouter()
	mux.HandleFunc("/test_send_func", testSendHandler)
	mux.HandleFunc("/test", testHandler)
	return mux

}

 

* 화면 접속

* parameter 값을 바꾸고 버튼을 누르면

'기타' 카테고리의 다른 글

WPF 따라하기 - BackgroundWorker  (0) 2022.07.09
go언어 - Cross Compile (Windows -> Linux Arm)  (0) 2022.01.25
[javascript] 벽돌깨기 게임  (0) 2022.01.14
go언어 따라해보기(3) - slice  (0) 2021.12.13
go - web 따라해보기(1)  (0) 2021.12.12