Go를 사용하여 JSON 응답을 제공하려면 어떻게 해야 합니까?
질문:현재 응답 내용을 인쇄 중입니다.func Index이것처럼.fmt.Fprintf(w, string(response)) 그러나 JSON을 뷰에서 소비할 수 있도록 요청에서 JSON을 올바르게 보내려면 어떻게 해야 합니까?
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"log"
"encoding/json"
)
type Payload struct {
Stuff Data
}
type Data struct {
Fruit Fruits
Veggies Vegetables
}
type Fruits map[string]int
type Vegetables map[string]int
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
response, err := getJsonResponse();
if err != nil {
panic(err)
}
fmt.Fprintf(w, string(response))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
log.Fatal(http.ListenAndServe(":8080", router))
}
func getJsonResponse()([]byte, error) {
fruits := make(map[string]int)
fruits["Apples"] = 25
fruits["Oranges"] = 10
vegetables := make(map[string]int)
vegetables["Carrats"] = 10
vegetables["Beets"] = 0
d := Data{fruits, vegetables}
p := Payload{d}
return json.MarshalIndent(p, "", " ")
}
클라이언트가 json을 기대하는 것을 알 수 있도록 컨텐츠 유형 헤더를 설정할 수 있습니다.
w.Header().Set("Content-Type", "application/json")
구조체를 json에 정렬하는 또 다른 방법은 concoder를 사용하여 인코더를 구축하는 것입니다.http.ResponseWriter
// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)
다른 사용자는 다음과 같이 코멘트하고 있었습니다.Content-Type이plain/text를 지정합니다.
콘텐츠 유형을 다음과 같이 설정해야 합니다.w.Header().Set()먼저 HTTP 응답 코드를 작성합니다.w.WriteHeader().
전화하시면w.WriteHeader()먼저, 다음에 전화한다.w.Header().Set()얻은 후에plain/text.
핸들러의 예는 다음과 같습니다.
func SomeHandler(w http.ResponseWriter, r *http.Request) {
data := SomeStruct{}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(data)
}
이런 것도 할 수 있어getJsonResponse기능 -
jData, err := json.Marshal(Data)
if err != nil {
// handle error
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
gobuffalo.io 프레임워크에서는 다음과 같이 동작합니다.
// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
return c.Render(200, r.JSON(user))
} else {
// Make user available inside the html template
c.Set("user", user)
return c.Render(200, r.HTML("users/show.html"))
}
그런 다음 해당 리소스에 대한 JSON 응답을 받으려면 "Content-type"을 "application/json"으로 설정해야 합니다.
Rails가 여러 응답 타입에 대응하는 것이 편리하다고 생각합니다만, 지금까지 Gobufalo에서는 같은 것을 볼 수 없었습니다.
이 패키지 렌더러를 사용하셔도 됩니다.이러한 문제를 해결하기 위해 작성했습니다.JSON, JSONP, XML, HTML 등을 지원하는 래퍼입니다.
다음은 적절한 예시를 포함한 보완적인 답변입니다.
func (ch captureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, fmt.Sprintf("error reading request body, %v", err), http.StatusInternalServerError)
return
}
...do your stuff here...
case http.MethodGet:
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode( ...put your object here...)
if err != nil {
http.Error(w, fmt.Sprintf("error building the response, %v", err), http.StatusInternalServerError)
return
}
default:
http.Error(w, fmt.Sprintf("method %s is not allowed", r.Method), http.StatusMethodNotAllowed)
}
}
언급URL : https://stackoverflow.com/questions/31622052/how-to-serve-up-a-json-response-using-go
'programing' 카테고리의 다른 글
| AngularJs ng-include는 $scope로 전달되지 않는 한 뷰를 포함하지 않습니다. (0) | 2023.03.31 |
|---|---|
| 아티팩트 com.microsoft.sqlserver:sqljdbc4:jar:4.0 누락 (0) | 2023.03.31 |
| 여러 데이터 소스를 구성한 후 JPA 명명 전략을 설정할 수 없음 (Spring 1.4.1 / Hibernate 5.x) (0) | 2023.03.31 |
| WooCommerce에서만 현재 제품의 제품 태그를 가져옵니다. (0) | 2023.03.31 |
| Airbnb 스타일 가이드는 왜 함수 이름 추론에 의존하지 말라고 하는가? (0) | 2023.03.26 |