RenderJson/RenderXml 메서드 추가
컨텍스트에 JSON 포맷으로 데이터를 렌더링하는 RenderJson 메서드와 XML 포맷으로 데이터를 렌더링하는 RenderXml 메서드를 추가해 보자. 그리고 에러 상태를 적절한 HTTP Status로 렌더링하는 RenderErr 메서드도 추가하자.
▼ context.go
func (c *Context) RenderJson(v interface{}) { // HTTP Status를 StatusOK로 지정 c.ResponseWriter.WriteHeader(http.StatusOK) // Content-Type을 application/json으로 지정 c.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8") // v 값을 json으로 출력 if err := json.NewEncoder(c.ResponseWriter).Encode(v); err != nil { // 에러 발생 시 RenderErr 메서드 호출 c.RenderErr(http.StatusInternalServerError, err) } } func (c *Context) RenderXml(v interface{}) { // HTTP Status를 StatusOK로 지정 c.ResponseWriter.WriteHeader(http.StatusOK) // Content-Type을 application/json으로 지정 c.ResponseWriter.Header().Set("Content-Type", "application/xml; charset=utf-8") // v 값을 xml로 출력 if err := xml.NewEncoder(c.ResponseWriter).Encode(v); err != nil { // 에러 발생 시 RenderErr 메서드 호출 c.RenderErr(http.StatusInternalServerError, err) } } func (c *Context) RenderErr(code int, err error) { if err != nil { if code > 0 { // 정상적인 code를 전달하면 HTTP Status를 해당 code로 지정 http.Error(c.ResponseWriter, http.StatusText(code), code) } else { // 정상적인 code가 아니면 HTTP Status를 StatusInternalServerError로 지정 defaultErr := http.StatusInternalServerError http.Error(c.ResponseWriter, http.StatusText(defaultErr), defaultErr) } } }
이 메서드는 Json 인코더와 Xml 인코더를 통해 ResponseWriter에 데이터를 정해진 포맷으로 구조화해서 전달한다. JSON 또는 XML로 변환할 때 에러가 발생하면 RenderErr 메서드로 에러 상태를 전달한다.