12 个改变我生产力的个人go技巧【译】

原文链接https://dev.to/func25/12-personal-go-tricks-that-transformed-my-productivity-mne 作者 我通常在 Devtrovert 分享有关系统设计和 Go 的见解。请随时查看我的 LinkedIn Phuong Le 以获取最新帖子。 在从事生产项目时,我注意到我经常重复代码并利用某些技术,直到后来回顾我的工作时才意识到这一点。 为了解决这个问题,我开发了一个解决方案,事实证明它对我很有帮助,而且我认为它对其他人也可能有用。 下面是从我的实用程序库中随机挑选的一些有用且通用的代码片段,没有任何特定的分类或特定于系统的技巧。 1.跟踪使用时间的技巧 如果您有兴趣跟踪 Go 中函数的执行时间,您可以使用一个简单而有效的技巧,只需使用“defer”关键字的一行代码即可。您所需要的只是一个 TrackTime 函数: // Utility func TrackTime(pre time.Time) time.Duration { elapsed := time.Since(pre) fmt.Println("elapsed:", elapsed) return elapsed } func TestTrackTime(t *testing.T) { defer TrackTime(time.Now()) // <--- THIS time.Sleep(500 * time.Millisecond) } // elapsed: 501.11125ms 1.5.两阶段延迟 Go 延迟的强大之处不仅在于任务完成后的清理工作,还在于任务完成后的清理工作。这也是为了做好准备,请考虑以下事项: func setupTeardown() func() { fmt.Println("Run initialization") return func() { fmt.Println("Run cleanup") } } func main() { defer setupTeardown()() // <-------- fmt....

October 5, 2023 · 4 min · czyt

golang http Reverse Proxy使用备忘

创建 一般使用 使用 httputil.NewSingleHostReverseProxy 即可 返回Response 当我们想实现获取通过ReverseProxy的请求结果时,可以使用自定义的 responsewriter 来实现。参考定义 func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { .... } type ResponseWriter interface { // Header returns the header map that will be sent by // WriteHeader. The Header map also is the mechanism with which // Handlers can set HTTP trailers. // // Changing the header map after a call to WriteHeader (or // Write) has no effect unless the modified headers are // trailers....

September 30, 2022 · 4 min · czyt

golang转换任意长度[] byte为int

package main import ( "encoding/binary" "fmt" ) func main() { slices := [][]byte{ {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6, 7}, {1, 2, 3, 4, 5, 6, 7, 8}, } for _, s := range slices { fmt.Println(getInt1(s), getInt2(s)) } } func getInt1(s []byte) int { var b [8]byte copy(b[8-len(s):], s) return int(binary....

July 30, 2022 · 1 min · czyt