Golang高效解码xml文件

xml处理需要引用encoding/xml包.一般推荐使用 xml.Decoder 替代 xml.Unmarshal。 xml.Decoder 是一个流式 XML 解码器,它可以边读取边解码,而不需要将整个 XML 文档加载到内存中。相比之下,xm1.Unmarshal 会将整个 XML 文档加载到内存中然后再进行解码。因此,对于大型 XML 文件,使用xml.Decoder 可以节省内存并提高性能。 小的Xml文件 下面是一个例子 package main import ( "encoding/xml" "os" "testing" ) type UserData struct { Name string `xml:"name"` Age int32 `xml:"age"` } type Pocket struct { Data []UserData `xml:"users"` } func TestXmlDecode(t *testing.T) { file, err := os.Open("testdata/userdata.xml") if err != nil { t.Fatal(err) } var pocket Pocket if err := xml.NewDecoder(file).Decode(&pocket); err != nil { t....

Golang 防火墙编程

非编程方式 Windows 使用netsh方式进行防火墙规则的维护 Linux 编程方式 Windows Tailscale开发了一个应用WFP的库inet.af/wf 。参考参考链接。在tailscale中的封装代码如下(源链接): // Copyright (c) Tailscale Inc & AUTHORS // SPDX-License-Identifier: BSD-3-Clause //go:build windows package wf import ( "fmt" "net/netip" "os" "golang.org/x/sys/windows" "inet.af/wf" "tailscale.com/net/netaddr" ) // Known addresses. var ( linkLocalRange = netip.MustParsePrefix("ff80::/10") linkLocalDHCPMulticast = netip.MustParseAddr("ff02::1:2") siteLocalDHCPMulticast = netip.MustParseAddr("ff05::1:3") linkLocalRouterMulticast = netip.MustParseAddr("ff02::2") ) type direction int const ( directionInbound direction = iota directionOutbound directionBoth ) type protocol int const ( protocolV4 protocol = iota protocolV6 protocolAll ) // getLayers returns the wf....

使用aws go-sdk访问cloudflare R2文件

准备 需要准备Cloudflare的accountId,相应的R2 ak sk 和bucketName等信息. var ( accountId = "xxxxx" accessKeyId = "cbdade718b2ca877882csssssfcf" accessKeySecret = "04917c7d745422022e266f6b06" bucketName = "gopher" ) 完整代码 package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" "log" ) func main() { var ( accountId = "xxxxx" accessKeyId = "cbdade718b2ca877882csssssfcf" accessKeySecret = "04917c7d745422022e266f6b06" bucketName = "gopher" ) var r2Resolver = aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { return aws.Endpoint{ URL: fmt.Sprintf("https://%s.r2.cloudflarestorage.com", accountId), }, nil }) cfg, err := config....

在树莓派3b上部署minio服务

安装 我的树莓派安装的是manjaro,直接执行如下命令即可 yay -S minio 官方的安装文档开源参考 https://min.io/docs/minio/linux/operations/install-deploy-manage/deploy-minio-single-node-single-drive.html 启用服务 systemctl enable minio 修改配置 主要修改mino的设置文件,文件位置为/etc/minio/minio.conf # Local export path. MINIO_VOLUMES="/srv/minio/data/" # Server user. MINIO_ROOT_USER=gopher # Server password. MINIO_ROOT_PASSWORD=gopher # Use if you want to run Minio on a custom port. MINIO_OPTS="--console-address :8888" MINIO_SERVER_URL="https://minio.xxx.org" MINIO_BROWSER_REDIRECT_URL="https://minio-console.xxx.org" 修改 MINIO_OPTS 主要是为了自定义Console的端口,而这个参数主要是在service定义中使用,安装软件后自动使用的service(路径为/usr/lib/systemd/system/minio.service)定义如下 [Unit] Description=Minio Documentation=https://docs.minio.io Wants=network-online.target After=network-online.target AssertFileIsExecutable=/usr/bin/minio [Service] # Specifies the maximum file descriptor number that can be opened by this process LimitNOFILE=65536 Type=simple User=minio Group=minio EnvironmentFile=/etc/minio/minio....

【译】如何使用 http.ResponseController 类型

本文原文地址 https://www.alexedwards.net/blog/how-to-use-the-http-responsecontroller-type,使用chatGPT翻译 One of my favorite things about the recent Go 1.20 release is the new http.ResponseController type, which brings with it three nice benefits: 关于最近的 Go 1.20 版本,我最喜欢的事情之一是新的 http.ResponseController 类型,它带来了三个好处: You can now override your server-wide read and write deadlines on a per request basis. 您现在可以根据每个请求覆盖服务器范围内的读取和写入截止日期。 The pattern for using the http.Flusher and http.Hijacker interfaces is clearer and feels less hacky. No more type assertions necessary! 使用 http.Flusher 和 http....

golang CGO参考

开源项目 https://github.com/dolthub/go-library-sample https://github.com/draffensperger/go-interlang https://github.com/kbehouse/go_call_cxx_so https://github.com/tailscale/libtailscale https://github.com/iikira/golang-msvc https://github.com/vladimirvivien/go-cshared-examples https://github.com/tailscale/libtailscale/tree/main 文档 Embedding Go in C Calling C code from go C? Go? Cgo! CGO编程(Go语言高级编程) https://stackoverflow.com/questions/14581063/golang-cgo-converting-union-field-to-go-type https://sunzenshen.github.io/tutorials/2015/05/09/cgotchas-intro.html https://totallygamerjet.hashnode.dev/the-smallest-go-binary-5kb 代码片段 Convert ‘C’ array to golang slice func carray2slice(array *C.int, len int) []C.int { var list []C.int sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&list))) sliceHeader.Cap = len sliceHeader.Len = len sliceHeader.Data = uintptr(unsafe.Pointer(array)) return list }

Golang Web框架Buffalo 简单使用

官方文档 https://gobuffalo.io 安装 安装要求 Before installing make sure you have the required dependencies installed: A working Go environment Go version v1.16.0. Frontend Requirements# The following requirements are optional. You don’t need them if you want to build an API or if you prefer to build your app in an old-fashioned way. node version 8 or greater either yarn or npm for the asset pipeline built upon webpack. Database Specific Requirements# Again, if you don’t need a database, you won’t need these....

从Golang的开源项目中学习不同的功能实现

缘起 最近看到有些go开源项目中的代码,看到其中的功能,故整理备用。 密码 阈值解密(Threshold Decryption) 来源 取自公众号文章 package main import ( "crypto/rand" "fmt" "github.com/hashicorp/vault/shamir" ) func main() { // 1. 生成一个随机密钥(如AES-256密钥) secretKey := make([]byte, 32) _, err := rand.Read(secretKey) if err != nil { panic(err) } fmt.Printf("原始密钥: %x\n", secretKey) // 2. 分片为3份,至少需要2份恢复(阈值k=2,总分片n=3) shards, err := shamir.Split(secretKey, 3, 2) if err != nil { panic(err) } // 3. 模拟分片存储(实际中分发给不同机构) shard1, shard2, shard3 := shards[0], shards[1], shards[2] fmt.Printf("分片1: %x\n分片2: %x\n分片3: %x\n", shard1, shard2, shard3) // 4....

使用protoc-gen-star编写protoc插件

预备知识 需要安装的软件 protoc golang go 软件包 github.com/lyft/protoc-gen-star 插件调用步骤 protoc,PB编译器,使用一组标志(记录在protoc -h下)进行配置,并将一组文件作为参数交给它。在这种情况下,I标志可以被多次指定,是它在proto文件中用于导入依赖关系的查找路径。默认情况下,官方描述符protos已经被包含在内。 myplugin_out 告诉 protoc 使用 protoc-gen-myplugin protoc-plugin。这些插件会从系统的 PATH 环境变量中自动解析,或者可以用另一个标志明确指定。官方的protoc-plugins (例如,protoc-gen-python) 已经在protoc注册了。该标志的值是特定于特定插件的,但 :…/generated 后缀除外。这个后缀表示protoc将把该包生成的文件放在哪个根目录下(相对于当前工作目录)。然而,这个生成的输出目录不会传播给 protoc-gen-myplugin,所以它需要在标志的左边重复。PG* 通过一个 output_path 参数支持这一点。 protoc 解析传入的 proto 文件,确保它们在语法上是正确的,并加载任何导入的依赖项。它将这些文件和依赖关系转换成描述符 (它们本身就是 PB 消息),并创建一个 CodeGeneratorRequest (又是一个 PB)。protoc 将这个请求序列化,然后执行每个配置的 protoc-plugin,通过 stdin 发送有效载荷。 protoc-gen-myplugin 启动,接收请求的有效载荷,并将其解密。一个基于 PG* 的 protoc-plugin 有两个阶段。首先,PG* 对从 protoc 收到的 CodeGeneratorRequest 进行解密,并为每个文件和其包含的所有实体创建一个完全连接的抽象语法树 (AST)。为这个插件指定的任何参数也会被解析,以便以后使用。 当这一步完成后,PG*就会执行任何注册的模块,把构建的AST交给它。模块可以被写成生成人工制品(例如,文件),或者只是对所提供的图进行某种形式的验证而没有任何其他副作用。模块在针对PB的操作方面提供了极大的灵活性。 一旦所有的模块都被运行,PG*会将任何自定义的工件写入文件系统,或者将生成器特定的工件序列化为CodeGeneratorResponse并将数据发送到其stdout。这整个流程看起来像这样。 foo.proto → protoc → CodeGeneratorRequest → protoc-gen-myplugin → CodeGeneratorResponse → protoc → foo.pb.go 假设插件名称为diy,则需要编译程序为protoc-gen-diy,并将程序加入系统Path变量,通过下面的命令调用插件。 protoc -I ....

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....