Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

Code Habit

[Go언어] HTTP 웹 서버 ( json 데이터 전송 ) 본문

카테고리 없음

[Go언어] HTTP 웹 서버 ( json 데이터 전송 )

코드베어 2022. 11. 22. 21:07

Go언어는 "net/http" 패키지를 통해 편리하게 HTTP서버를 만들 수 있다.

  • func ListenAndServe(addr string, handler Handler) error : 웹 서버를 시작한다. 
  • func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) : 경로별로 요청을 처리할 핸들러 함수 등록
type Employee struct {
	No   int
	Age  int
	Name string
}

func MakeWebHandler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("/Employee", EmployeeHandler)
	return mux
}

func EmployeeHandler(w http.ResponseWriter, r *http.Request) {
	var employee = Employee{1, 32, "진숙이"}
	data, _ := json.Marshal(employee)                  // Employee객체를 []byte로 변환
	w.Header().Add("content-type", "application/json") // header에 문서타입 json 정의
	w.WriteHeader(http.StatusOK)
	fmt.Fprint(w, string(data)) // []byte형 data를 응답데이터로 보낸다
}

func main() {
	http.ListenAndServe(":3000", MakeWebHandler())
}

객체 데이터를 json 포맷으로 변환 하기 위해 json.Marshal()함수를 사용했다. 구조체 데이터나 map 데이터등을 json.Marshal()의 매개변수로 전달하면 JSON으로 인코딩된 바이트배열과 에러객체를 리턴한다.

 

 

위 코드를 빌드하고 실행하면 포트 3000번에서 http웹서버가 열리게 되고 /Employee 경로로 요청이 들어오면 다음과 같이 출력된다.