r/golang • u/bogdanelcs • 5h ago
A Go cheat sheet that can be useful to beginners
r/golang • u/AutoModerator • 2d ago
This is the weekly thread for Small Projects.
The point of this thread is to have looser posting standards than the main board. As such, projects are pretty much only removed from here by the mods for being completely unrelated to Go. However, Reddit often labels posts full of links as being spam, even when they are perfectly sensible things like links to projects, godocs, and an example. r/golang mods are not the ones removing things from this thread and we will allow them as we see the removals.
Please also avoid posts like "why", "we've got a dozen of those", "that looks like AI slop", etc. This the place to put any project people feel like sharing without worrying about those criteria.
This is a monthly recurring post. Clicking the flair will allow you to see all previous posts.
Please adhere to the following rules when posting:
Rules for individuals:
Rules for employers:
COMPANY: [Company name; ideally link to your company's website or careers page.]
TYPE: [Full time, part time, internship, contract, etc.]
DESCRIPTION: [What does your team/company do, and what are you using Go for? How much experience are you seeking and what seniority levels are you hiring for? The more details the better.]
LOCATION: [Where are your office or offices located? If your workplace language isn't English-speaking, please specify it.]
ESTIMATED COMPENSATION: [Please attempt to provide at least a rough expectation of wages/salary.If you can't state a number for compensation, omit this field. Do not just say "competitive". Everyone says their compensation is "competitive".If you are listing several positions in the "Description" field above, then feel free to include this information inline above, and put "See above" in this field.If compensation is expected to be offset by other benefits, then please include that information here as well.]
REMOTE: [Do you offer the option of working remotely? If so, do you require employees to live in certain areas or time zones?]
VISA: [Does your company sponsor visas?]
CONTACT: [How can someone get in touch with you?]
r/golang • u/bogdanelcs • 5h ago
I wanted to show how machine learning actually works in mobile ad tech, using Go for the bidder, so I wrote a free, open-source book with a working DSP you can run locally.
The bidder answers OpenRTB bid requests from a simulated ad market (written in Python, so it knows the true click and install rates to check the models against) and serves its models right in the bid path: LightGBM trees and a small deep model, both in pure Go with no cgo.
Book: https://bgweber.github.io/AdtechBook/
Code: https://github.com/bgweber/AdtechBook (bidder in code/dsp)
You don't need Rust for low-latency ML serving. In my experience, Go is on par with Rust for a bid path: with zero allocations per prediction, the GC stays out of the latency budget. And with GoMLX, Go now has an XLA backend for fast CPU inference, ONNX model loading, and online fine-tuning inside a Go service, something ONNX Runtime can't do. The book covers it in the deep-model serving chapter.
Happy to answer questions about the Go side or ad tech in general.
r/golang • u/mamjamnika • 1d ago
r/golang • u/thecodearcher • 21h ago
A few months ago, I shared Limen’s Organization and API Key plugins here. Since then, I’ve continued expanding the library and recently released v0.2.5.
The main additions are:
Repo: https://github.com/thecodearcher/limen
Docs: https://limenauth.dev
errortype is a linter that finds inconsistent uses of Go error types. v0.0.12 can rename errors to follow the naming conventions, checks %w operands of fmt.Errorf, and prepares you for a new go vet check in Go 1.27.
gopls v0.24 ships a new analyzer, ptrtoerror, that reports when an error type is used both as a value E and as a pointer *E. That's the idea errortype is built around. Because ptrtoerror is on by default, a lot of Go developers will now see these bugs while they write code. Kudos to the gopls team!
The two analyzers complement each other. ptrtoerror asks you to declare which form you mean, and errortype already uses these declarations and checks more places, like %w operands and errors.As targets. More on that below.
The Go conventions say sentinel errors start with Err (ErrNotFound) and error types end with Error (ParseError). The name tells readers and tools whether to match with errors.Is or query with errors.AsType.
-naming checks this. On a large codebase nobody wants to rename errors by hand, so -fix renames the declarations and their uses in the package. You can run it on a whole module, or fix new names as you write them:
-var NotFound = errors.New("not found")
+// Deprecated: Use [ErrNotFound] instead.
+var NotFound = ErrNotFound
+
+var ErrNotFound = errors.New("not found")
-type ErrParse struct{ Line int }
+// Deprecated: Use [ParseError] instead.
+//
+//go:fix inline
+type ErrParse = ParseError
+
+type ParseError struct{ Line int }Exported declarations keep the old name with a // Deprecated: comment so other packages keep compiling. Deprecated type aliases get //go:fix inline, so go fix ./... migrates their uses, while uses of renamed var sentinels in other packages are left to you. You can preview the names with -fix -diff.
-naming is off by default. Try it during development (included in -recommended), and turn it on in CI once you're compliant.
The following program sums up numbers, one per line, but never hits its ParseError branch, printing the generic fallback instead (full version on the Go Playground):
type ParseError struct {
Line int
Err error
}
func (e ParseError) Error() string { return fmt.Sprintf("line %d: %v", e.Line, e.Err) }
// in sumLines:
return 0, fmt.Errorf("sum: %w", ParseError{Line: line, Err: err}) // wrapped as a value
// in printError:
if perr, ok := errors.AsType[*ParseError](err); ok { // never matches
$ go run .
unexpected error: sum: line 3: strconv.Atoi: parsing "3x": invalid syntax
$ errortype .
.../main.go:48:17: Error type "ParseError" should be queried as a value ("errors.AsType[ParseError]"), not a pointer. (et:ast)The program compiles, and nothing complains. The %w operand is passed as any, and *ParseError implements error just like ParseError. errortype now counts %w operands as evidence for the intended form, so it tells you to fix the query. When a pointer Unwrap method already settles the form, it reports the %w operand instead.
In files at go 1.27 or later, go vet's printf check now reports %w on *E whenever E itself implements error. Because this depends on the file's Go version (usually the go directive in go.mod) rather than the toolchain, go vet stays quiet even with a Go 1.27 toolchain, until you bump go.mod to 1.27. At that point it starts flagging working code, like an error type with a value receiver that is consistently used as a pointer (Go Playground, try editing the go.mod part at the bottom):
type StatusError struct{ Code int }
func (e StatusError) Error() string { return fmt.Sprintf("status %d", e.Code) }
func get() error {
// go vet at go 1.27: %w wants operand of error type StatusError, not pointer type *StatusError (defeats errors.Is)
return fmt.Errorf("get: %w", &StatusError{404})
}errortype -receivers flags the receiver. At go 1.27 or later, it's reported by default:
.../main.go:10:6: Method "Error" should be implemented with a pointer receiver ("func (*StatusError) Error"), not a value receiver (et:rcv+)With a pointer receiver, only *StatusError implements error. go vet has nothing to report, and the compiler rejects returning StatusError{...}.
Fix these while you're still on go 1.26, and you won't have to when you upgrade. After raising the go directive, go vet can still report types that only embed an error or come from a dependency.
Pre-Go 1.13 helpers like func IsNotFound(err error) bool with a plain type assertion ignore wrapped errors. -legacy reports them, and -fix rewrites them to errors.AsType (or errors.As on files below Go 1.26), correcting the pointer or value form at the same time. It's off by default for now and might be turned on later.
errortype recognizes wrapper functions around the errors package, and that's how it found bugs in Grafana Loki, Canonical Juju and Chromium's LUCI: error handlers passed invalid targets to errors.As through github.com/pkg/errors, github.com/juju/errors and LUCI's own errors package, and would have panicked the first time they ran. All three are fixed upstream.
The latest one is in Grafana Mimir, and this time every conversion used the same form. The compactor counts failed block uploads by file type, using UploadError:
type UploadError struct {
cause error
fileType FileType
}
func (e UploadError) Error() string { return fmt.Sprintf("failed to upload %s: %v", e.fileType, e.cause) }
func (e *UploadError) Unwrap() error { return e.cause }Every return in the package used the value UploadError{...}. The compactor checked for a *UploadError with errors.As, which never matched, so every known failure was counted as type="unknown". The pointer Unwrap also hid the cause from errors.Is.
#12477 fixed the bug by returning &UploadError{...}. errortype reports those value returns on the old code, and on current main it still reports the root cause:
$ errortype ./pkg/storage/tsdb/block
.../block/block.go:66:6: Method "Error" should be implemented with a pointer receiver ("func (*UploadError) Error"), like "Unwrap" (et:rcv+)
...It also reports three places in the tests that still use the value form, one of which ptrtoerror flags as well. With a pointer receiver, a value return no longer compiles, so the bug can't come back. I've sent that fix upstream as #17467. The README has a minimal version of this pattern.
ptrtoerror is strict about types where both E and *E implement error. When the defining package doesn't show which form it means, gopls asks you to add var _ error = ... and offers that as a quick fix.
Each of these declarations helps errortype. It has recommended them from the start, because then it doesn't have to infer the form. With gopls asking, far more packages will declare their intent.
errortype covers code without declarations as well, since it infers the form from how a type is used. None of the bugs above involved an inconsistent conversion. I run errortype before I commit and in CI, and as a golangci-lint plugin in my editor.
go install fillmore-labs.com/errortype@v0.0.12
errortype -recommended ./...Feedback is very welcome.
r/golang • u/alexedwards • 1d ago
I've just finished a new blog post running through Go's available tooling in 2026 – covering helpful dev tools, code quality tools, testing, profiling, tracing and a bunch more. Hopefully it's a useful one to read and bookmark!
r/golang • u/hasen-judi • 2d ago
Delivered by Gemini 4 Neon!
I don't know what other frameworks do this, but I think this makes Shirei the only non-browser based GUI framework to support video playback across platforms.
r/golang • u/mariiiiiiiiiiiiiiiel • 2d ago
i want to have an automatic report store at midnight in a backend service, this is what i roughly made but im pretty sure is kinda bad; i am aware of cron jobs and those might be the right solution, but if using a cronjob it would mean i have to send credentials because the endpoint version of this requires authentication (im willing to take it away just to make the cronjob simpler, is not that big of a deal if that endpoint is public cause it has no payload) but got really curious about if there is a way to do this in the language itself
func (app *Application) storeReport() error {
loc, err := time.LoadLocation("America/Mazatlan")
if err != nil {
return err
}
year, month, day := time.Now().In(loc).Date()
t := time.Date(year, month, day, 23, 00, 0, 0, loc)
ctx := context.Background()
for {
time.Sleep(time.Until(t))
year, month, day := time.Now().In(loc).Date()
ctx = context.WithValue(ctx, "storeReport:time", t.String())
_, err := app.Handlers.aweta.history.report.SaveTodaysReport(ctx)
if err != nil {
fmt.Printf("[error]: %v\n", err)
}
time.Sleep(time.Hour)
year, month, day = time.Now().In(loc).Date()
t = time.Date(year, month, day, 23, 00, 0, 0, loc)
}
}r/golang • u/fischerville • 1d ago
I'm a long time professional Java dev but I spent some time learning Go and building out some web services, websites and other architecture for small personal projects in Go. Good news and bad news I suppose is that I started doing this just on the cusp of AI coding tools getting useful. So I feel like it has stunted my trajectory to really learning it deeply, but on the other hand I find that Claude Code (and I've played with GLM and Kimi too) is really really good at building what I need quickly in Go.
My question is: what are the pitfalls you have found with writing Go with AI tools? What does it trip up on? What do you look for in a human review? What do you use for baseline instructions for your own quality of life?
r/golang • u/eatonphil • 2d ago
r/golang • u/DanKegel • 3d ago
the little gophers have been very busy lately, see e.g. https://github.com/tinygo-org/tinygo/pull/6507
r/golang • u/ianchen0119 • 3d ago
I'm writing a userspace Linux scheduler in Go using eBPF and sched_ext. Go receives runnable tasks from eBPF, decides what should run next, and sends the decisions back for dispatch. This repeats every scheduling round.
The hot loop makes lots of short, nonblocking C calls to exchange task and dispatch records with the eBPF program. The problem wasn't just the cost of calling C. I also wanted to avoid runtime scheduling delays in the middle of a round.
With regular cgo, the runtime enters syscall state. If the P gets handed off while C is running, returning from C can mean waiting for a P before the Go code can continue. That's awkward when the code waiting to resume is responsible for scheduling other tasks.
I ended up using runtime.LockOSThread() together with a small runtime.asmcgocall bridge:
//go:linkname asmcgocall runtime.asmcgocall
//go:noescape
func asmcgocall(fn, arg unsafe.Pointer) int32
// Call invokes a bounded C wrapper. fn must be a C ABI function accepting one
// void pointer, with no blocking, allocation, or callbacks into Go.
func Call(fn, arg unsafe.Pointer) {
asmcgocall(fn, arg)
}LockOSThread keeps the goroutine on the same OS thread; the bridge skips the usual cgo syscall bookkeeping, avoiding that particular P handoff path. Linux can still preempt the thread.
I only use this path for bounded memory operations. Wrappers that perform syscalls go through a separate CallSyscall function using runtime.cgocall.
For a simple 64-bit read microbenchmark, regular cgo took around 220 ns per call versus 21 ns through the bridge. That's only call overhead, not overall scheduler performance.
The wrappers have to stay short and nonblocking, with no allocation or callbacks into Go. This also depends on an internal runtime function, so compatibility across Go versions is part of the trade-off.
r/golang • u/ScoreSouthern56 • 2d ago
Hi all
Has anyone here tested different models for coding tasks in Go?
I’m especially looking for cost-efficient, open models that may not be cutting edge but are good enough to write solid code.
I’m talking about providers like Qwen, Z.ai, DeepSeek and Tencent, and each of them offers several models. The market is crowded, and it’s hard to choose one.
The price difference compared to Anthropic, the current tech leader, is significant.
These are the models currently on my shortlist:
Has anyone actually tested these runner-up models and can share some tips?
Did you have good or bad experiences with them?
Is there a model missing from my list that I should take a look at?
I’m currently using Compare AI Models: Pricing, Context & Benchmarks | OpenRouter and I’m happy with it, but I’m open to alternatives as well.
Best wishes,
Karl
This is an open source project that I have been working on for a few years, It's available on GitHub and also has been deployed live on my Raspberry Pi
GitHub: https://github.com/Anga205/AngaDriveV3
Live deployment: https://drive.anga.codes
Since the primary focus of this project was to achieve production-level performance from the limited hardware that I hosted on (that is, a Raspberry Pi), There are a few architectural and resource related optimizations that I've implemented that I think anyone with a similar project would find interesting.
sync.RWMutex. This gives average O(1) membership checks and key lookups without a separate Redis process or network/protocol communication overhead. The trade-off is that cache consistency and data management become more complex, since the application has to maintain these indexes itself.There are also other several micro-optimizations like personal cache initialization and bounded background workers that I think anyone with dreams of making a big project in home lab infrastructure would find pretty interesting to go through in my codebase.
The general idea is to keep frequently accessed data and communication paths in-process or on persistent connections wherever practical. Many of the fundamental index operations are average-case O(1), although operations involving iteration or database work naturally have different complexity.
Tech stack: Go, Gin, GORM, SQLite, and Gorilla WebSocket. (SolidJS for frontend)
r/golang • u/Gloomy-Ebb7311 • 5d ago
Hello everyone, wanted to share something I’ve been working on for the past year: betterauth-go.
It lets you use Better Auth’s frontend clients React, Vue, Svelte, etc. with a Go backend. Mount the handler in your Go server and point your client at it.
I’ve also been testing it in my clients’ products, and I’d love to get it into more developers’ hands.
It supports email/password auth, social login, sessions, and plugins like 2FA, organizations, and magic links. Storage options include Postgres, SQLite, MySQL, or your own adapter.
It’s MIT licensed, and there’s a Go + React example in the repo to help you get started.
https://github.com/patrickkabwe/betterauth-go
If you try it out, I’d love to hear how it goes. Feedback, issues, and contributions are welcome!
Approximate aggregate window functions for SQLite, using ncruces/go-sqlite3.
TL;DR
If you use Go's default http client without changing MaxIdleConnsPerHost and you happen to use HTTP/1.1 (which is pretty common in service to service communications -- like within a Kubernetes cluster), you might be leaving a lot more throughput on the table and causing increased client side CPU usage.
So MaxIdleConnsPerHost has a default value of 2. That means Go will only keep 2 idle connections per host. So, if you have a high throughput client, it will open a lot lot more connections causing huge performance drop and CPU usage. In my benchmark (probably a worst case scenario), I saw a 8x drop in throughput compared to using MaxIdleConnsPerHost = number of goroutines (requests in flight)
The most interesting finding for me was why it happens - It turns out to be due to the client running out of ports and the Kernel having to do a very long search for free ports.
Fix is of course to set MaxIdleConnsPerHost to whatever max requests in flight you expect. But be mindful and don’t set it too high!
I have a blog post with a lot more details, benchmarks and some kernel level investigations, for those interested - https://newsletter.esc.sh/p/performance-penalty-in-gos-default
Edit: added TLDR
Edit 2: updated the max recommendation
r/golang • u/BrilliantUseful2960 • 4d ago
Sharing a project that has run in production for us for a few weeks. The Go side may interest you:
CGO_ENABLED=0, a distroless image of ~28 MB, ~20 MB idle RSS.net/http with 1.22 route patterns. The database is pgx/v5 with hand-written SQL and goose migrations, so no ORM.internal/auth, internal/ids) instead of JWT or UUID libraries.internal/ with a Mount(a *app.App) registered from init(), so adding one is one package plus a blank import.web/dist and embedded with embed.Tests run with -race against a real Postgres per test (make testdb), and CI also runs govulncheck and gitleaks.
Code review of the architecture is welcome: https://github.com/cdmx-in/kera
r/golang • u/Metal-3d • 6d ago
I know... “yet another GTK binding”—that’s what you’re probably thinking... But let me tell you about my project first.
There are a bunch of bindings for GTK4/Adwaita, either as dynamically linked libraries or as “purego” bindings. But:
dlopen() plus a function map—clearly falls short of my expectations (lots of classes are missing, no `cairo` or `webview`)In short, I’ve had enough. For several months now, I’ve been putting something together locally to have everything I need for the various apps I’m developing. And today, after a major cleanup, I’m releasing it as open source.
What makes it different? Not much in terms of magic, but I’ve worked hard to make sure it covers almost everything:
In short, if you want to test it and report any potential issues to me...
I'll be releasing (in the next day or two) a program I developed using this “Cellule” library—a tool for Matrix that, in my opinion, is much better suited to the GNOME desktop than Element.
And there are more to come :)
Hello there,
I'm working on a project which which should provide at least 2 binaries - a TUI app and an REST API and keep everything under single repository, obviously the dependencies for each are different (bubbletea and friends for TUI and gin for API), thus using separate modules makes sense to make them installable separately, but I have some common packages (for now it's database) which are required for both binaries. With chat gpt help I've made something like this:
. (modname: github.com/<username>/<projectname>)
├── Dockerfile
├── cmd
│ └── tui (modname: github.com/<username>/<projectname>/cmd/tui)
│ ├── accounts.go
│ ├── go.mod
│ ├── go.sum
│ └── main.go
├── database
│ ├── db.go
│ └── migrations
│ └── 001_initial.sql
├── go.mod
├── go.sum
├── go.work
├── go.work.sum
└── tmuxp.yaml
// go.work
go 1.27.3
use (
.
./cmd/tui
)
// cmd/tui/go.mod
module github.com/<username>/<projectname>/cmd/tui
go 1.27.3
require (
charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.1.2
charm.land/lipgloss/v2 v2.1.1
github.com/<username>/<projectname> v0.0.0
)Unfortunately it does not allow me to run tui/main.go, it tries reaching github for <projectname> instead of using the module in local filesystem. Ideally I would like to avoid pushing the code, tagging it and adding/removing replace. As for now nothing was pushed to github, I'd like to work locally until there's actually something to push. How can I make this work?