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

推荐订阅源

T
The Exploit Database - CXSecurity.com
S
Secure Thoughts
A
Arctic Wolf
V
Vulnerabilities – Threatpost
S
Schneier on Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threat Research - Cisco Blogs
AWS News Blog
AWS News Blog
NISL@THU
NISL@THU
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Palo Alto Networks Blog
L
Lohrmann on Cybersecurity
Schneier on Security
Schneier on Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Scott Helme
Scott Helme
L
LINUX DO - 最新话题
L
LangChain Blog
量子位
T
Threatpost
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
W
WeLiveSecurity
Last Week in AI
Last Week in AI
美团技术团队
The GitHub Blog
The GitHub Blog
The Last Watchdog
The Last Watchdog
C
CERT Recently Published Vulnerability Notes
月光博客
月光博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Troy Hunt's Blog
Webroot Blog
Webroot Blog
云风的 BLOG
云风的 BLOG
博客园 - 叶小钗
V2EX - 技术
V2EX - 技术
雷峰网
雷峰网
Security Latest
Security Latest
小众软件
小众软件
J
Java Code Geeks
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Spread Privacy
Spread Privacy
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Recent Commits to openclaw:main
Recent Commits to openclaw:main
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
The Blog of Author Tim Ferriss
M
MIT News - Artificial intelligence

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 Recurse Center Day 19 - blag Recurse Center Day 18 - blag Recurse Center Day 17 - blag Recurse Center Day 16: Open Source - blag Recurse Center Day 15: B Tree Algorithms - blag Recurse Center Day 14: NoSQL Transactions - blag Recurse Center Day 13: Why 'Raft'? - blag Recurse Center Day 12: Isolation Anomalies - blag Recurse Center Day 11: B Tree Insertions - blag Recurse Center Day 10: Learning Distributed Systems - blag Recurse Center Day 9: Papers We Love - blag Recurse Center Day 8: B Tree Fill Factor (Part 2) - blag Recurse Center Day 7: Basics of ncurses - blag Recurse Center Day 6: B Tree Root - blag Recurse Center First Week - blag Recurse Center Day 5: Garbage Collection Algorithms - blag Recurse Center Day 4: B Tree fill factor - blag Recurse Center Day 3: Hammock Driven Development - blag Recurse Center Day 2: BTree Node - blag Recurse Center Day 1: init - blag What I want to do at Recurse Center - blag Accepted to the Recurse Center! - blag Towards Inserting One Billion Rows in SQLite Under A Minute - blag I ended up adding duplicate records on a unique index in MongoDB - blag Setting up Github Actions for Hugo - blag Moving to Hugo - blag Catching SIGTERM in Python - blag Git/Github fork-pull request-update cycle - blag Using uWSGI with Python 3 - blag When is my Cake Day? - blag Staying Ahead of Amazon, in Amazon Treasure Hunt Contest - blag How I Am Maintaining Multiple Emails For Git On A Same Machine - blag An exploit on Gaana.com gave me access to their entire User Database - blag Flashing Asus-WRT Merlin by XVortex on NetGear NightHawk R7000 - blag Install Windows 8 UEFI on Legacy BIOS with Clover (and Dual boot with Yosemite) - blag Scraping Javascript page using Python - blag Installing Transmission (remote and CLI) client on Raspberry Pi - blag About - blag Projects - blag
Marshaling Struct with Special Fields to JSON in Golang - blag
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))