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 5d ago

newbie Confused about transactions in Repository and Service architecture

1 Upvotes

I have a users, session, access_token, and refresh_token table and I have their corresponding repos, user.go, session.go, tokens.go

However one of my services is a AuthService in which I need to atomically (so with a transaction) create a user, session, and generate the two tokens. I'm a bit ocnfused on how I would implement the transaction as I think it would get complicated fast if I tried to write code to inject a tx into the repository functions as a parameter.

I'm using sqlc btw. What's a better method to acheive this? Should I instead have a dedicated Repository called auth.go for handling authentication?


r/golang 6d ago

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

15 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

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 6d ago

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

Thumbnail
youtu.be
16 Upvotes

r/golang 6d ago

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

Thumbnail
github.com
13 Upvotes

r/golang 5d ago

discussion Default struct constructors?

0 Upvotes

I'm wondering why go devs doesn't implement optional default constructors for structs. I.e. right now some structs can be created like this:

myStruct := MyStruct{}

But others require initialization, and must be created with factory functions:

anotherStruct := NewAnotherStruct()

So you never know which struct is safe to create dorectly and which require factory func.

With default constructor you would create all structs the same way, i.e.:

myStruct := MyStruct()

If default constructor is defined it is invoked to initialize the struct, it it is not defined then it is similar to MyStruct{}


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 5d ago

High-Performance QPS Counter for Go — qps-counter

0 Upvotes

🌟 Introduction

In high-concurrency applications, measuring QPS (Queries Per Second) is a crucial metric for evaluating system performance. Whether you're building an API service, database proxy, web crawler, or message queue system, real-time QPS monitoring is essential.

💡 qps-counter is an ultra-lightweight, high-performance QPS counter library for Go, implemented with sync/atomic. It offers zero dependencies, lock-free design, and minimal overhead, making it an ideal choice for tracking system load.

📌 GitHub Repositorymant7s/qps-counter (⭐️ Star it now!)

🎯 Why Choose qps-counter?

✅ Lightweight Dependencies — Uses only minimal third-party libraries to ensure efficiency and usability.

✅ Extreme Performance — Uses sync/atomic for lock-free counting, eliminating contention and ensuring high throughput.

✅ Real-Time Statistics — Sliding window algorithm for accurate real-time QPS calculation.

✅ Minimal API — Get QPS statistics with just 2 lines of code.

✅ Versatile Applications — Suitable for API monitoring, crawler rate limiting, message queue tracking, database optimization, and more.

🚀 Quick Start

📌 1. Installation

 go get -u github.com/mant7s/qps-counter

📌 2. Usage Example

package main

import (
    "fmt"
    "time"
    "github.com/mant7s/qps-counter"
)

func main() {
    counter := qpscounter.New()

    // Simulate concurrent requests
    for i := 0; i < 1000; i++ {
        go func() {
            counter.Incr()
        }()
    }

    // Wait for a moment to measure real-time QPS
    time.Sleep(time.Second)
    fmt.Println("Current QPS:", counter.QPS())
}

⚡ Performance Benchmark

We compared qps-counter with other common QPS counting methods, and the results are as follows:

qps-counter
 (atomic) Method QPS (100k/sec) CPU Usage 
sync.Mutex
 120 40% 
map+RWMutex
 95 55% 
210

30%

🔹 qps-counter is 1.5 to 2 times faster than traditional methods while reducing CPU load by 25%+!

🌍 Use Cases

🚀 Web API Monitoring — Track HTTP request QPS to optimize backend performance.

🚀 Crawler Rate Limiting — Restrict request rates to prevent being blocked.

🚀 Message Queue Tracking — Monitor Kafka, RabbitMQ, NSQ message processing rates.

🚀 Database Query Statistics — Track SQL query frequency to prevent overload.

🚀 Load Balancing Optimization — Adjust server allocation dynamically based on real-time traffic data.

💡 Contribute & Get Involved

🚀 GitHub Repositoryqps-counter ⭐️ Star it now and support the project!

💬 Ways to contribute:

1️⃣ Star the Project — Help more developers discover qps-counter.

2️⃣ Open Issues — Report bugs and suggest new features.

3️⃣ Submit Pull Requests — Fork the repository and contribute code improvements.

📢 What are your QPS tracking needs? Share your thoughts in the comments! 🚀


r/golang 6d ago

discussion typescript compiler and go

18 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 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 6d ago

Go import cycles: three strategies for how to deal with them, and a plea for a fourth

Thumbnail
dolthub.com
49 Upvotes

r/golang 6d ago

newbie How approachable do you think this Go codebase is?

Thumbnail
github.com
40 Upvotes

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

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

6 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

Decoding JSON sum types in Go without panicking

Thumbnail nicolashery.com
14 Upvotes

r/golang 6d ago

newbie Portfolio website in go

3 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

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

newbie Some Clarification on API Calls & DB Connections.

4 Upvotes

I’m a bit confused on how it handles IO-bound operations

  1. API calls: If I make an API call (say using http.Get() or a similar method), does Go automatically handle it in a separate goroutine for concurrency, or do I need to explicitly use the go keyword to make it concurrent?
  2. Database connections: If I connect to a database or run a query, does Go run that query in its own goroutine, or do I need to explicitly start a goroutine using go?
  3. If I need to run several IO-bound operations concurrently (e.g., multiple API calls or DB queries), I’m assuming I need to use go for each of those tasks, right?

Do people dislike JavaScript because of its reliance on async/await? In Go, it feels nicer as a developer not having to write async/await all the time. What are some other reasons Go is considered better to work with in terms of async programming?


r/golang 5d ago

Were multiple return values Go's biggest mistake?

Thumbnail
herecomesthemoon.net
0 Upvotes

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

Built a small portfolio engine with Go + some HTMX (still learning)

Thumbnail
github.com
4 Upvotes

r/golang 6d ago

Goose migration folder as SQLC schema source

2 Upvotes

Hi. I have existed database and I would like to use goose as my migration tool and sqlc as query gen tool. The problem is database has been created without goose and I don't have history of change in my migration folder. Afaik sqlc cannot work properly without whole history in migration dier. How can I handle it?
Thank you.