<p>Often I just want to send a request to an URL and get the response, I find myself repeating a lot of lines with regards to setting headers, parsing the response body, etc... So I am wondering is it ok to create my own wrapper to act as syntactic sugar?</p>
<hr/>**评论:**<br/><br/>joncalhoun: <pre><p>I wrap packages all the time. I do this with the hash packages, rand, context, and others to remove things I repeat a lot. So long as you understand you may need to make changes later and don't make that impossible I find it works well and recommend it.</p>
<p>Here is an older article I wrote that discussed it a bit more. It might help give you some ideas or even reasons not to listen to me :). <a href="https://www.calhoun.io/wrapping-packages-to-isolate-code-responsibility/" rel="nofollow">https://www.calhoun.io/wrapping-packages-to-isolate-code-responsibility/</a></p></pre>iroflmaowtf: <pre><blockquote>
<p>Does it make sense to create your own http request wrapper?</p>
</blockquote>
<p>I like to think so</p>
<p>even http request wrapper wrapper, depending on your use cases, imagine if you need an additional parameter/flag/etc., would you copy-paste a ton of times, or would you update the request maker func and be done with it?</p>
<p>food for thought</p>
<pre><code>type httpReqSetupFn func(r *http.Request)
func mkreq(url, setupFuncs...) (*http.Request, error) { ... }
</code></pre>
<p>now you can do the following</p>
<pre><code>req, err := mkreq("reddit.com", func(r *http.Request) {
r.Header.Set("foo", "bar")
}, func(r *http.Request) {
r.Header.Set("something", "else")
})
</code></pre>
<p>this could be your generic maker func, then, you can grow on top</p>
<pre><code>func setupAuth(r *http.Request) {
// ...
}
func setupHdrs(r *http.Request) {
// ...
}
func mkRedditAuthReq(url) {
return mkreq(url, setupAuth, setupHdrs/*, etc.*/)
}
</code></pre></pre>Ploobers: <pre><p>Like <a href="/u/joncalhoun" rel="nofollow">/u/joncalhoun</a>, we often wrap other packages to make our specific use cases simpler, but for this specific case, we have helper functions to help build requests, rather than a wrapper object. Here's one example:</p>
<pre><code>// NewJSONRequest marshals the payload to JSON, adds default JSON headers, allows KeepAlive
func NewJSONRequest(c *ctx.Context, method, url string, payload interface{}) (*http.Request, error) {
var data []byte
var err error
if payload != nil {
data, err = json.Marshal(payload)
if err != nil {
return nil, logger.Error(c, err, "NewJSONRequest - json.Marshal Failed")
}
}
req, err := http.NewRequest(method, url, bytes.NewReader(data))
if err != nil {
return nil, logger.Error(c, err, "http.NewRequest failed")
}
req.Close = false
req.Header.Set("Accept", contentTypeJSON)
req.Header.Set("Content-Type", contentTypeJSON)
return req, nil
}
</code></pre></pre>tmornini: <pre><p>It makes sense to wrap ALL non-application packages in your own, IMHO.</p></pre>Loves_Portishead: <pre><p>A little repetition is better than a little dependency. Extract it to a function for a start. Or write a function factory that gives you back a preconfigured "client"</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传