惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
F
Fortinet All Blogs
小众软件
小众软件
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
有赞技术团队
有赞技术团队
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
V
Visual Studio Blog
A
About on SuperTechFans
I
InfoQ
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
罗磊的独立博客
C
Check Point Blog
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
MyScale Blog
MyScale Blog

blag

SQLite prefixes its temp files with `etilqs_` - blag Setsum - order agnostic, additive, subtractive checksum - blag Oldest recorded transaction - blag Replacing a cache service with a database - blag SQLite commits are not durable under default settings - blag PSA: SQLite WAL checksums fail silently and may lose data - blag Rickrolling Turso DB (SQLite rewrite in Rust) - blag Collection of insane and fun facts about SQLite - blag How bloom filters made SQLite 10x faster - blag In search of a faster SQLite - blag Galloping Search - blag Building a distributed log using S3 (under 150 lines of Go) - blag Zero Disk Architecture - blag PSA: Most databases do not do checksums by default - blag PSA: SQLite does not do checksums - blag Disaggregated Storage - a brief introduction - blag Why does SQLite (in production) have such a bad rep? - blag SQLite Slaps - blag Now - blag Learning C - blag Snapshot Testing - blag Win: contribution to libSQL (SQLite) codebase - blag Errata in Hekaton MVCC paper - blag Internet is wholesome: MVCC edition - blag It is becoming difficult for me to be productive in Python - blag MongoDB secondary only index - blag Introducing CaskDB – a project to teach you writing a key-value store - blag Recurse Center: Winter Break - blag Recurse Center Day 24: Hacking Go compiler to add a new keyword - blag Recurse Center Day 20: Django v4 upgrade (from v1) - blag
Marshaling Struct with Special Fields to JSON in Golang -...
2021-05-01 · via blag

I needed to marshal http.Request to json, but this struct contains few fields which are not serialise-able. Here is some sample code:

// imports and error handling is omitted for brevity
func main() {
    req, _ := http.NewRequest("GET", "http://example.com", nil)
    _, err := json.Marshal(req)
    fmt.Println(err)
}

When you run the above code, we get an error:

json: unsupported type: func() (io.ReadCloser, error)

So I inspected the struct, found out that it has two fields which json doesn’t know how to serialize:

// in net/http
type Request struct {
    // snipped
    GetBody func() (io.ReadCloser, error)
    Cancel <-chan struct{}
}

I wrote a wrapper struct in which I embedded the http.Request object, redefined these fields. Do note that the json struct tags need to match with the corresponding fields from http.Request:

type RequestWrapper struct {
    // the types of variables `GetBody` and `Cancel` do not
    // really matter since I don't want them in my final json output
    GetBody string `json:"GetBody,omitempty"`
    Cancel  string `json:"Cancel,omitempty"`
    *http.Request
}

func main() {
    req, _ := http.NewRequest("GET", "http://example.com", nil)
    reqWrapper := &RequestWrapper{req}
    out, _ := json.Marshal(reqWrapper)
    fmt.Println(string(out))
}

This works nicely! Since we don’t care about GetBody, Cancel fields, you might be tempted to use - struct tag instead of explicit mention of omitempty:

type RequestWrapper struct {
    GetBody string `json:"-"`
    Cancel  string `json:"-"`
    *http.Request
}

Unfortunately, this doesn’t work and we ran into the same error which we had encountered earlier. That is because, the wrapper struct fields gets ignored for json marshaling, but embedded struct’s fields get considered.

Now, lets test our code with an HTTP request containing body:

func main() {
    req, _ := http.NewRequest("POST", "http://example.com", strings.NewReader("Hello, World!"))
    reqWrapper := &RequestWrapper{Request: req}
    out, _ := json.Marshal(reqWrapper)
    fmt.Println(string(out))
}

Uh oh! we see that request body isn’t marshaled correctly:

{
    "Body": {"Reader": {}},
    // snipped
}

Body field is of type io.ReadCloser. While serialising JSON doesn’t throw any error, but it doesn’t know how to serialise it either. So, we will slightly modify our struct:

type RequestWrapper struct {
    // this assumes Body is always a string
    Body    string `json:"Body,omitempty"`
    // the types of variables `GetBody` and `Cancel` do not
    // really matter since I don't want them in my final json output
    GetBody string `json:"GetBody,omitempty"`
    Cancel  string `json:"Cancel,omitempty"`
    *http.Request
}

Then we read the body, assign it to this newly added field:

func main() {
    req, _ := http.NewRequest("POST", "http://example.com", strings.NewReader("Hello, World!"))
    body, _ := ioutil.ReadAll(req.Body)
    reqWrapper := &RequestWrapper{Request: req, Body: string(body)}
    out, _ := json.Marshal(reqWrapper)
    fmt.Println(string(out))
}

This works perfectly!

Bonus

The same can be achieved by implementing MarshalJSON() on the RequestWrapper, which I find it to be cleaner:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

type RequestWrapper struct {
    *http.Request
}

func (r *RequestWrapper) MarshalJSON() ([]byte, error) {
    body, _ := ioutil.ReadAll(r.Request.Body)
    return json.Marshal(&struct {
        Body    string `json:"Body,omitempty"`
        GetBody string `json:"GetBody,omitempty"`
        Cancel  string `json:"Cancel,omitempty"`
        *http.Request
    }{
        Body:  string(body),
        Request: r.Request,
    })
}

func main() {
    req, _ := http.NewRequest("POST", "http://example.com", strings.NewReader("Hello, World!"))
    reqWrapper := &RequestWrapper{Request: req}
    out, _ := json.Marshal(reqWrapper)
    fmt.Println(string(out))
}

Note

If you are passing around this request object, then the next method won’t be able to read the body. In that case, buffer needs to be refilled:

body, _ := ioutil.ReadAll(req.Body)
// then assign an `io.ReadCloser` back to it
req.Body = ioutil.NopCloser(bytes.NewBuffer(body))