0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Go json.Marshalとencoder.Encodeの違い

Last updated at Posted at 2025-06-08

json.Marshal

  • 単純にgoの構造体をバイト列に変換する
    • レスポンスを返却する場合は、レスポンスに別途書き込む必要がある。
    marshalHandler(w http.ResponseWriter, r *http.Request){
        response := getResponseStruct()
        data, err := json.Marshal(response)
        if err!=nil{
         panic("error")
        }
    
        fmt.Fprint(w, string(data))
    }
    

encoder.Encode

  • レスポンスに直接バイト列を書き込める
    • メモリ使用量が減る
    encodeHandler(w http.ResponseWriter, r *http.Request){
       response := getResponseStruct()
       encoder := json.NewEncoder(w)
       encoder.Encode(&response)
    }
    
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?