Development Tip

Go를 사용하여 JSON 응답을 제공하는 방법은 무엇입니까?

yourdevel 2020. 11. 23. 20:17
반응형

Go를 사용하여 JSON 응답을 제공하는 방법은 무엇입니까?


질문 : 현재 다음 func Index과 같이 내 응답을 인쇄하고 fmt.Fprintf(w, string(response)) 있지만 요청에서 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으로 마샬링하는 또 다른 방법은 다음을 사용하여 인코더를 빌드하는 것입니다. http.ResponseWriter

// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)

다른 사용자 Content-Typeplain/text인코딩 할 때가 있다고 언급합니다 . Content-Type먼저 w.Header().SetHTTP 응답 코드 를 설정해야 합니다 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"))
}

and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.

I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.


You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

참고URL : https://stackoverflow.com/questions/31622052/how-to-serve-up-a-json-response-using-go

반응형