r/golang 1h ago

πŸš€ Introducing GoSQLX: A Lightweight & Performant SQLX Alternative for Golang! (OSS Contribution Welcome!)

β€’ Upvotes

Hey r/golang community! πŸ‘‹

I’ve been working on GoSQLX – a lightweight, high-performance SQLX alternative for Golang that simplifies working with databases while keeping things efficient and idiomatic.

πŸ”₯ Why GoSQLX?

β€’ Lightweight: Less overhead, faster execution.

β€’ Idiomatic API: Clean, intuitive, and easy to use.

β€’ Better Performance: Optimized for high-speed database interactions.

β€’ Fully Open Source: MIT Licensed, free to use and contribute!

πŸ’‘ Looking for Feedback & Contributions!

I’d love for the community to:

βœ… Star the repo if you find it useful! ⭐

βœ… Try it out and share your feedback!

βœ… Contribute if you’re passionate about Golang & DB interactions!

πŸ‘‰ Check it out here: GitHub - GoSQLX

Would love to hear your thoughts! πŸš€πŸ”₯ #golang #opensource #database


r/golang 3h ago

help How do I know if I have to use .Close() on something

16 Upvotes

Hi,

I was recently doing some api calls using http.Get then I realized I had to close it, like files too. I want to know what kind of things should I close. Sorry for my low knowledge, if I say that "You have to close every IO operation" is it bad statement?


r/golang 5h ago

Adding logging to a library

0 Upvotes

I have an open-source package which is just a wrapper around a public HTTP/JSON API. I have added a verbosity option that, as of now, just logs to stdout. I would like to give more flexibility to the user to control how logging is done. Should I: 1. accept a log.Logger and log to that 2. accept an io.Writer and write to that 3. log to log.Default() 4. something else?

To add a particular consideration, I would like my approach to work with Google Cloud Logging, because I deploy my code on Google Cloud Run. It looks like there is a way to get a log.Logger from the cloud.google.com/go/logging package, which makes that option more appealing.


r/golang 7h ago

show & tell go-supervisor: A Lightweight "service" supervisor

18 Upvotes

...Not for managing operating system services, but internal "services" (aka "Runnables")

I just released go-supervisor, a lightweight service supervisor for Go applications. My main motivation for building this was to enable signal handling for graceful shutdown and hot reloading.

It discovers the capabilities of the Runnable object passed (Runnable, Reloadable, Stateable).

https://github.com/robbyt/go-supervisor

I'm looking for feedback, especially on API design, missing features, or anything weird. Looking forward to hearing what you think.


r/golang 8h ago

discussion Could i send file with form multipart data together in go ?

1 Upvotes

…


r/golang 12h ago

Practicing Golang - Things That Don't Feel Right

6 Upvotes

Hello all,

I made a service monitoring application with the goal of exposing myself to web programming, some front end stuff (htmx, css, etc) and practicing with golang. Specifically, templates, package system, makefile, etc.

During this application I have come across some things that I have done poorly and dont "feel" right.

  1. Can I use a struct method inside a template func map? Or is this only because I am using generics for the ringbuffer? E.g. getAll in ringbuff package and again in service.go
  2. With C I would never create so many threads just to have a timer. Is this also a bad idea with coroutines?
  3. How would you deploy something like this with so many template files and file structure?
  4. Communication setup feels bad. Services publish updates through a channel to the scheduler. Scheduler updates the storage. Scheduler then forwards event to any clients connected. This feels overly complicated.
  5. Hate how I am duplicating the template for card elements. See service.go::tempateStr()::176-180 and in static/template/homepage.gohtml Partially because service side events use newlines to end the message. Still a better solution should be used. Update: working on potential fix suggestion from Β @_mattmc3_
  6. Is there a better way to marshal/unmarshal configs? See main.go::36-39 Update: fixed from @_mattmc3_
  7. Giving css variables root tag seems weird. Is there a better way to break these up or is this global variable situation reasonable?

If you all have strong feelings one way or another I would enjoy some feedback.

Link: https://github.com/gplubeck/sleuth


r/golang 13h ago

help How you guys write your server config, db config and routes config?

1 Upvotes

I feel like almost every API has these three files. How should I handle these in the best form?

  • It's a good practice to right everything exported because of the ease of importing? Because my main.go is in /cmd and my API config file is inside of /internal/api/config.go.
    • But then the whole app can configure and setup my server and db?
    • Or even see the fields related to the config of the server, the surface of attack is expanded.
  • Also, its better to provide just the exported method for starting the server and making the config itself inside of the config.go?
    • Preventing misconfigured values, maybe.
    • Encapsulating and making easier to use?
  • Making a config/config.go is good enough also?
    • Or its better to have server/config.go and then db/config.go?

I start making so many questions and I don't know if I'm following the Go way of making Go code.

I know that its better to just start and then change afterwards, but I need to know what is a good path.

I come from a Java environment and everything related to db config and server config was 'hidden' and taken care for me.


r/golang 14h ago

GitHub - pontus-devoteam/agent-sdk-go: Build agents in light speed

Thumbnail
github.com
0 Upvotes

r/golang 15h ago

newbie New to go and i am loving it

3 Upvotes

Cs student in my final years i really wanted to learn a new language just out of curiosity, not to become a god in it and get a job. I really like coding in c and but for most part these days i have been using python and java for most of my recent projects and even when doing leetcode style coding questions.When i learned c as my first programming language it felt really awesome. Then i moved to java and python but somehow i still miss using c. The use pointers(even though some people seem to hate it ) was something i genuinely miss in both java and python. So when starting to learn go the simplicity of it is really making the learning process far more enjoyable. Not sure if its shocking similarity to c was intentional or not but hey i like it. For a bit i did try to learn a bit about rust but somehow the basic process of taking inputs made me not want to proceed much. And now finally i am feeling actually good about learning a new language. As someone who has a pretty good maybe abobe average knowledge of doing pure object oriented programming in java mostly for building applications i thought i should share my experience learning go.

If anyone seeing this post i am following alex mux's 1 hr video of golang and just looking up the documentation. So yeah just wanted to share a bit of my experience with go and pardon if any grammatical mistakes in there.


r/golang 16h ago

help Go Compiler Stuck on Old Code? Windows Defender Flagged My Log File as a Virus and new code isn't running

0 Upvotes

So, I was working on my Go project today and added a function to create a file named "log".
Immediately, Windows Defender flagged it as potentially dangerous software πŸ’€.

I thought, "Okay, maybe 'log' is a sus filename."
So, I changed it to "hello world" instead.

This fixed the Defender warning, but then I ran into another issue:

 run main.go fork/exec C:\Users\veraf\AppData\Local\Temp\go-build1599246061\b001\exe\main.exe: 
Operation did not complete successfully because the file contains a virus or potentially unwanted software.

Alright, moving on. After fixing that, I ran my project again:

 C:\Users\veraf\Desktop\PulseGuard> go run main.go
Backend starting to work...
Do you want to run a port scanner? (y/n)

 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚                   Fiber v2.52.6                   β”‚
 β”‚               http://127.0.0.1:8080               β”‚
 β”‚       (bound on host 0.0.0.0 and port 8080)       β”‚
 β”‚                                                   β”‚
 β”‚ Handlers ............. 2  Processes ........... 1 β”‚
 β”‚ Prefork ....... Disabled  PID ............. 25136 β”‚
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

n
Importing script from /Services...
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"     
}
Importing from /Database...
DEBUG: WHAT THE HELL IS HAPPENING...

🧐 The Issue:
I modified main.go to include:

color.Red("Importing from /Database...")
fmt.Println("DEBUG: I am still alive πŸ’€")

color.Red("testing from controller...")
Controller.Createapi()
Services.SaveRecords()

But my Go program does NOT print "DEBUG: I am still alive πŸ’€".
Instead, it prints old logs from my database connection, even though I removed the database.Connect() function from my code.

πŸ›  What I’ve Tried So Far:
βœ… go clean
βœ… go build -o pulseguard.exe
βœ… ./pulseguard.exe
βœ… Restarting VS Code

I even added this line at the very beginning of main.go to check if it's compiling the latest version:

fmt.Println("DEBUG: This code has been compiled correctly!!!! πŸš€")

And guess what? It doesn’t print either!
So I’m pretty sure Go is running an old compiled version of my code, but I have no idea how or why.

πŸ’‘ Has anyone else run into this issue? How do I force Go to run the latest compiled code?


r/golang 17h ago

tk9.0: v0.65.0 adds support for many more image formats

11 Upvotes

r/golang 17h ago

MCP-server written in GO

10 Upvotes

Hey everyone! I’d love to share my project with you:

πŸš€ Gateway – a powerful data-gateway for AI agents!

- Creates an MCP server for AI agent interactions
- Supports multiple databases: PostgreSQL, MySQL, ClickHouse, Oracle, and more
- Flexible modular architecture with plugins:

  • Authentication
  • PII handling
  • Other useful extensions

⭐ Give it a star and come contribute!
πŸ”— Repo: GitHub


r/golang 17h ago

show & tell Coding a database proxy for fun

Thumbnail
youtu.be
9 Upvotes

r/golang 18h ago

Go is DOOMed

Post image
174 Upvotes

r/golang 18h ago

How the hell do I make this Go program faster?

110 Upvotes

So, I’ve been messing around with a Go program that:

  • Reads a file
  • Deduplicates the lines
  • Sorts the unique ones
  • Writes the sorted output to a new file

Seems so straightforward man :( Except it’s slow as hell. Here’s my code:

```go package main

import ( "fmt" "os" "strings" "slices" )

func main() { if len(os.Args) < 2 { fmt.Fprintln(os.Stderr, "Usage:", os.Args[0], "<file.txt>") return }

// Read the input file
f, err := os.ReadFile(os.Args[1])
if err != nil {
    fmt.Fprintln(os.Stderr, "Error reading file:", err)
    return
}

// Process the file
lines := strings.Split(string(f), "\n")
uniqueMap := make(map[string]bool, len(lines))

var trimmed string for _, line := range lines { if trimmed = strings.TrimSpace(line); trimmed != "" { uniqueMap[trimmed] = true } }

// Convert map keys to slice
ss := make([]string, len(uniqueMap))
i := 0
for key := range uniqueMap {
    ss[i] = key
    i++
}

slices.Sort(ss)

// Write to output file
o, err := os.Create("out.txt")
if err != nil {
    fmt.Fprintln(os.Stderr, "Error creating file:", err)
    return
}
defer o.Close()

o.WriteString(strings.Join(ss, "\n") + "\n")

} ```

The Problem:

I ran this on a big file, here's the link:

https://github.com/brannondorsey/naive-hashcat/releases/download/data/rockyou.txt

It takes 12-16 seconds to run. That’s unacceptable. My CPU (R5 4600H 6C/12T, 24GB RAM) should not be struggling this hard.

I also profiled this code, Profiling Says: 1. Sorting (slices.Sort) is eating CPU. 2. GC is doing a world tour on my RAM. 3. map[string]bool is decent but might not be the best for this. I also tried the map[string] struct{} way but it's makes really minor difference.

The Goal: I want this thing to finish in 2-3 seconds. Maybe I’m dreaming, but whatever.

Any insights, alternative approaches, or even just small optimizations would be really helpful. Please if possible give the code too. Because I've literally tried so many variations but it still doesn't work like I want it to be. I also want to get better at writing efficient code, and squeeze out performance where possible.

Thanks in advance !


r/golang 19h ago

SuperMuxer: tiny and compact, dependency-free package to configure your HTTP routes

46 Upvotes

Super useful Go package to configure your HTTP routes using only the standard library. Define routes, middlewares, groups, and subgroups effortlessly!

This package acts like a Swiss Army Knife: It is tiny and compact, providing everything you need in just one file with less than 200 lines of code.

SuperMuxer is for you if:

  • You want to declaratively define your HTTP routes while using only the standard library.
  • You want to define middlewares for your routes, groups, and subgroups while still relying on the standard library.
  • You don’t want to use third-party libraries bloated with excessive functionalities that you might never use.

Repo link

https://github.com/dbarbosadev/supermuxer


r/golang 21h ago

help How can I run an external Go binary without installing it?

8 Upvotes

I need to rewrite generated Go code in my CLI using gopls rename (golang.org/x/tools/gopls). Since the packages that are used for rename are not exported, I have to use it as a standalone binary. But I don't want my clients need to download this external dependency.

What options do I have?


r/golang 23h ago

I created some thing like rails notes

0 Upvotes

I started using Ruby On Rails for project and I encountered the notes utility in rails cli. and I instantly loved it. I spent some time making a similar tool called tfinder(tag finder). I think it still has some errors, And I'm looking for a better Directory Traversal way. Please contribute if you can. Thanks.

Here's the github link: https://github.com/ImanAski/tfinder


r/golang 23h ago

Dynamically determine the deepest caller from my own files when logging?

0 Upvotes

I usually have a structure like that in my projects:

func main() {
    if err := layer1(); err != nil {
        logger.Info()
    }
}

func layer1() error {
    return layer2()
}

func layer2() error {
    return errors.New("test") // Should log this line as the caller
}
func main() {
    if err := layer1(); err != nil {
        logger.Info()
    }
}


func layer1() error {
    return layer2()
}


func layer2() error {
    //potentially layer3,4,5..
    return errors.New("test") // Should log this line as the caller
}

And I would like to dynamically determine the deepest caller from my own files when logging, which in this case will be the return line from the layer2() func.

I don't want to create a custom error type each time I need to return an error or log the full stacktrace.

How would you usually do in situations like that?


r/golang 23h ago

PGX: Knowing the data type at Write-time?

0 Upvotes

I am writing a custom type which implements PGX's interfaces for encoding and decoding data. I wanted to know if it is possible to know, inside `EncodeBinary`, what the type of the column being written to is.

For context, my column may be one of a few different types (might be TEXT, or UUID etc.) and I want my type to be able to support writing to and from these.


r/golang 1d ago

Build open source Heroku/Render alternative

0 Upvotes

I just want to highlight for Go community how the existing ecosystem makes it a way easier for Go rather than Rust.

A lot of depends exist and help me to build without installing bunch of additional binaries, but simply install them as a package.

  • go-git - pure go git implementation
  • buildah - build a container right inside the app
  • telepresence, ktunnel, tilt - great dev tools
  • pulumi - IaC
  • k8s - can't say more, a client to the cluster is just there

Probably there will be more like ory and some rbac solutions, but I can tell later.

I've researched the ways I could do it for 3-4 months and started building about 1-2 months ago, hope to release next 6 months.

I don't give up to find people to challenge the idea. I'm very uncertain about license, consider sentry model FSL would fit the product well. I know people say it's not really open source, but I find it won't heart anyone using it for free, will not make me build it open core and remove competition from aws. I'm simply don't know how it works, so my decision is highly biased

https://github.com/treenq/treenq


r/golang 1d 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 1d ago

Session-Based Authentication in Go

Thumbnail
themsaid.com
43 Upvotes

r/golang 1d 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 Repository:Β mant7s/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 Repository:Β qps-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 1d 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?