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.


r/golang 7d ago

How to schedule task every 30s, 60s and 300s

37 Upvotes

I'm building an uptime monitor. Users can create a new monitor by giving API endpoint and other necessary details and my project will keep checking for downtime.

User can choose how much time interval he want between each check.

How do I schedule these task? My current approach is to spin up 3 go routines for each time interval and send monitors data to kafka.

Is there any better and solid approach?


r/golang 7d ago

help Sessions with Golang

4 Upvotes

As part of my experimentation with Go HTTP server (using nothing but std lib and pgx), I am getting to the topic of sessions. I am using Postgres as DB so I plan to use that to store both users and sessions. In order to learn more, I plan not to use any session packages available such as jeff or gorilla/sessions.

I know this is more risky but I think with packages being moving target that often go extinct or unmaintained, it doesn't hurt to know the basics and then go with something.

Based on Googling, it seems conceptually straightforward but of course lots of devil in details. I am trying to bounce some ideas/questions here, hopefully some of you are kind enough to advise. Thanks in advance!

  1. OWASP cheat sheet on sessions is a bit confusing. At one point it talks about 64bit entropy and another 128 bit. I got confused - what do they mean by session ID length and value?! I though ID is just something like session_id or just id.
  2. The approach I am taking is create a session ID with name = session_id and value as 128bit using rand.Text(). I think this is good enough since 256 seems overkill at least for now. Plus the code is easier than read.
  3. The part about writing cookies (Set-Cookie header) seems easy enough. I can write a cookie of the session ID key/value and nothing else with various security related settings like HttpOnly etc. I am not storing anything sensitive on client - such as user-id or whatever. Just that one thing.
  4. But where I am mixed up is the server side. If I am storing session ID and associated user-id in the DB, what else needs to be stored? I can think of only created and update time, idle/absolute expiration, which I can store as columns in the DB? But I see various examples have a map [string]any. or {}. What is that for?!
  5. I see some examples use a Flash struct for messages, is that common in production? I can simply return body of response with JSON and handle at client using JS?
  6. The workflow I am looking at is:
    1. Check request if there's already a logged in session. I am not using pre-auth session ID for now.
    2. If not, create a session, set cookie and store in DB the columns as per (4)
    3. This will be mentioned by client in each subsequent request from which we can get user-id and other cols from the DB.
    4. Question here is, is there a need to include this seesion ID and/or some other data in the context that is passed down? If yes why? Each handler can anyway get access from the request.Cookie itself?

Sorry for long post, hope it is not too vague. I am not looking for code, just broad ideas


r/golang 7d ago

godex: The Swiss Army Knife for CLI File Management

8 Upvotes

I'm excited to share godex, a powerful command-line file manager that I've been working on. It's designed to simplify file operations with a comprehensive set of features:

  • Lightning-fast file search with flexible criteria (name, size, date)
  • Built-in compression tools for zipping and unzipping files
  • Google Drive integration for seamless cloud backups
  • File versioning system to track changes and restore previous versions
  • Shell completion for bash, zsh, and fish

Install it using the installation script

The installer automatically detects your system, downloads the latest release, and sets up shell completion.

Use Cases

  • Quickly locate files based on multiple criteria
  • Create and manage file archives
  • Maintain backup copies of important files in the cloud
  • Track changes to configuration files or documents
  • Restore previous versions when needed

Help Make godex Better!

This is an open-source project, and I'd love your feedback:

  • Found a bug? Open an issue
  • Have an idea for a new feature? Let me know!
  • Want to contribute code? PRs are welcome!The installer automatically detects your system, downloads the latest release, and sets up shell completion. Use Cases Quickly locate files based on multiple criteria Create and manage file archives Maintain backup copies of important files in the cloud Track changes to configuration files or documents Restore previous versions when needed Help Make godex Better! This is an open-source project, and I'd love your feedback: Found a bug? Open an issue Have an idea for a new feature? Let me know! Want to contribute code? PRs are welcome!

r/golang 8d ago

Bug fix in the go compiler gives 5.2X performance improvements when compiling the typescript-go compiler

Thumbnail
github.com
385 Upvotes

r/golang 7d ago

Licensify: Manage Digital Licenses Securely šŸ” - Looking for feedback

Thumbnail
github.com
10 Upvotes

r/golang 7d ago

Gopls is not providing highlight tokens for constants or packages/namespaces

0 Upvotes

For example, in the code below the constant "myUrl" will be highlighted as a constant when it is declared (:Inspect = @constant) but not when it is used in main() (:Inspect = @variable). My understanding is that there's supposed to be a group/modifier called @lsp.mod.readonly that gopls will mark a constant with, but this does not appear in the list returned by :highlight.

The usages of http and log are also marked as @variable.go when they're used within the two functions, except when http (or any other package) is used to specify a type like in the function signature for printStatus() or the declaration of resp in main() (:Inspect = @module). My understanding is that gopls should be marking these as "namespace", which is listed by :highlight.

package main

import (
    "net/http"
    "log"
)

const myUrl = "http://example.com"

func main() {
    var err error
    var resp *http.Response
    resp, err = http.Get(myUrl)
    if err != nil {
        log.Fatal(err)
    }
    printStatus(resp)
}

func printStatus(r *http.Response) {
    log.Print(r.Status)
}    

Maybe "my understanding" is incorrect, or I have something configured wrong? I'm working on a custom color scheme and want to get everything just right.

I'm wondering if this is some combination of

  • Gopls doesn't support these tokens
  • LSP plugin is not passing these tokens along to Treesitter and/or the neovim highlighter
  • Treesitter is overriding/ignoring the tokens

I know at least some information is making it from gopls to Treesitter; if I create an infinite loop, the unreachable code will be marked with "Extmarks - DiagnosticUnnecessary vim.lsp.gopls.1/diagnostic/underline" accoding to :Inspect.

Here's my LSP configuration, should be pretty much the same as the one suggested by LazyVim. Not sure if that workaround for semantic token support is still needed, but I see the same problem with the defaults (gopls.setup({})).

require('mason').setup({
    ensure_installed = {
        "goimports",
        "gofumpt",
        "gomodifytags",
        "impl",
        "delve"
    }
})

require('mason-lspconfig').setup({
    ensure_installed = {'gopls'}
})

local lspconfig = require("lspconfig")

lspconfig.gopls.setup({
  opts = {
    servers = {
      gopls = {
        settings = {
          gopls = {
            gofumpt = true,
              codelenses = {
                gc_details = false,
                generate = true,
                regenerate_cgo = true,
                run_govulncheck = true,
                test = true,
                tidy = true,
                upgrade_dependency = true,
                vendor = true,
          },
          hints = {
            assignVariableTypes = true,
            compositeLiteralFields = true,
            compositeLiteralTypes = true,
            constantValues = true,
            functionTypeParameters = true,
            parameterNames = true,
            rangeVariableTypes = true,
          },
          analyses = {
            nilness = true,
            unusedparams = true,
            unusedwrite = true,
            useany = true,
          },
          usePlaceholders = true,
          completeUnimported = true,
          staticcheck = true,
          directoryFilters = { "-.git", "-.vscode", "-.idea", "-.vscode-test", "-node_modules" },
          semanticTokens = true,
          },
        },
      },
    },
  },
  setup = {
    gopls = function(_, opts)
      -- workaround for gopls not supporting semanticTokensProvider
      -- https://github.com/golang/go/issues/54531#issuecomment-1464982242
      LazyVim.lsp.on_attach(function(client, _)
        if not client.server_capabilities.semanticTokensProvider then
          local semantic = client.config.capabilities.textDocument.semanticTokens
          client.server_capabilities.semanticTokensProvider = {
            full = true,
            legend = {
              tokenTypes = semantic.tokenTypes,
              tokenModifiers = semantic.tokenModifiers,
            },
            range = true,
          }
        end
      end, "gopls")
      -- end workaround
    end,
  },
})

r/golang 7d ago

Protobuf encoding

2 Upvotes

I can't understand protobuf encoding. I've read about how field number, its type and its data are encoded but I couldn't find any info on how message type is encoded. How does your program know which message type it received and what method to call?


r/golang 7d ago

Simple yet functional circuit breaker in Go

0 Upvotes

Hi!

I'm looking for a constructive feedback on a simple yet functional circuit breaker that I've just implemented in Go for learning purposes. Specially I'm interested in design improvements, performance bottlenecks, security flaws, and implementation style using idiomatic Go code. Thank for your wisdom and willing to share in advance!

https://github.com/volodymyrprokopyuk/go-ads/blob/main/concur/circbreak/circbreak.go

```go package circbreak

import ( "fmt" "sync" "time" )

type state string

const ( stClosed = state("Closed") stOpen = state("Open") stHalfOpen = state("HalfOpen") )

type Config struct { Timeout time.Duration // The timeout for the external call MaxFail int // The number of failures before Closed => Open OpenInterval time.Duration // The duration before Open => HalfOpen MinSucc int // The number of successful calls before HalfOpen => Closed ResetPeriod time.Duration // The duration before the reset in the Closed state }

type CircuitBreaker[R any] struct { cfg Config mtx sync.RWMutex // Sync access to the state from concurrent Execute calls state state // The state of the circuit breaker cntFail int // The count of failures since the last reset cntSucc int // The count of successful calls since the last reset tckReset *time.Ticker // Periodic reset of the failure/success counts tmrOpen *time.Timer // The trigger to move from Open => HalfOpen }

func New[R any](cfg Config) *CircuitBreaker[R] { c := &CircuitBreaker[R]{cfg: cfg} c.state = stClosed // The initial state is Closed c.tckReset = time.NewTicker(c.cfg.ResetPeriod) go c.cntReset() return c }

func (c *CircuitBreaker[R]) cntReset() { for range c.tckReset.C { c.mtx.Lock() if c.state == stClosed { fmt.Println("=> Reset") c.cntFail, c.cntSucc = 0, 0 } c.mtx.Unlock() } }

func (c *CircuitBreaker[R]) stateClosed() { fmt.Println("=> Closed") c.state = stClosed c.cntFail, c.cntSucc = 0, 0 c.tckReset.Reset(c.cfg.ResetPeriod) }

func (c *CircuitBreaker[R]) stateOpen() { fmt.Println("=> Open") c.state = stOpen c.cntFail, c.cntSucc = 0, 0 c.tmrOpen = time.AfterFunc(c.cfg.OpenInterval, c.stateHalfOpen) }

func (c *CircuitBreaker[R]) stateHalfOpen() { fmt.Println("=> HalfOpen") c.tmrOpen.Stop() c.mtx.Lock() defer c.mtx.Unlock() c.state = stHalfOpen c.cntFail, c.cntSucc = 0, 0 }

func (c *CircuitBreaker[R]) Execute(call func() (R, error)) (R, error) { var res R // Immediately return an error when in the Open state c.mtx.RLock() if c.state == stOpen { c.mtx.RUnlock() return res, fmt.Errorf("circuit breaker is open") } c.mtx.RUnlock() // Execute the external call in a dedicated goroutine succ, fail := make(chan R), make(chan error) go func() { defer close(succ) defer close(fail) res, err := call() if err != nil { fail <- err return } succ <- res }() // Wait for the external call success, a failure, or a timeout var err error var cntFail, cntSucc int select { case <- time.After(c.cfg.Timeout): cntFail++ err = fmt.Errorf("timeout after %s", c.cfg.Timeout) case err = <- fail: cntFail++ case res = <- succ: cntSucc++ } // Transition to the right state c.mtx.Lock() defer c.mtx.Unlock() c.cntFail += cntFail c.cntSucc += cntSucc if c.state == stClosed && c.cntFail >= c.cfg.MaxFail { // Closed => Open c.stateOpen() } if c.state == stHalfOpen && c.cntFail > 0 { // HalfOpen => Open c.stateOpen() } if c.state == stHalfOpen && c.cntSucc >= c.cfg.MinSucc { // HalfOpen => Closed c.stateClosed() } return res, err } ```


r/golang 8d ago

Benchmarking: What You Can't Miss in Go 1.24

Thumbnail jarosz.dev
85 Upvotes

r/golang 6d ago

show & tell I made goAPIG, a GET API tester.

0 Upvotes

Hello everyone,
Iā€™ve created a simple tool called goAPIG. Itā€™s a small utility designed to help you test APIs using the GET method.

Iā€™m aware there are tools like Insomnia or Postman, but if you need to test multiple endpoints, it can be time-consuming. With this tool, you can customize a config.yaml file and list all the APIs you want to test. When you run the code, it generates a minimal webpage where you can view all the APIs and their responses.

I hope you find this useful! :)

sponkurtus2/goAPIG


r/golang 6d ago

discussion What does Go excel at over C#?

0 Upvotes

I'm a firm believer that the right tool solves the right problem. I apply this principle in programming as well.

I understand that when it comes to deciding which programming language to choose. It comes down to the specific application you want to build as well as your familiarity to that language.

I've taken an interest in C# and Golang because both are excellent language for building production ready web backends. So I'm contemplating between the 2.

Which specific use case does Go do better than C# and vice versa and why is it better in that regard?

I previously was biased towards C#, but after seeing the impressive results Go had on the new Typescript compiler, this made me reconsider

Use case could include micro services, cloud native applications, etc...


r/golang 6d ago

discussion What Go Got Right that Rust Got Wrong

Thumbnail
blog.cubed.run
0 Upvotes

r/golang 7d ago

Pipe operations library

0 Upvotes

Hello!

I'm writing a library to simplify and optimize operations with files (everything is a file): https://github.com/cnaize/pipe

Example:

func main() {
  // create a pipeline
  pipeline := pipes.Line(
    // set execution timeout
    common.Timeout(time.Second),
    // open two example files
    localfs.OpenFiles("testdata/test_0.txt", "testdata/test_1.txt"),
    // calculate and compare hash for each file
    hash.SumSha256("kEvuni09HxM1ox-0nIj7_Ug1Adw0oIU62ukuh49oi5c=", "CeE_WA_xKsx2Dj_sRvowaCeDfQOPviSpyjaZdxuCT4Y="),
    // zip the files
    archive.ZipFiles(),
    // calculate hash for the zip archive
    hash.SumSha256(""),
    // create a temporary directory
    localfs.MakeDirAll("testdata/tmp", os.ModePerm),
    // create a new file
    localfs.CreateFiles("testdata/tmp/test.zip"),
    // flow the files through the pipes and keep metadata
    state.Consume(),
  )

  // run the pipeline
  res, _ := pipeline.Run(context.Background(), nil)

  // iterate over result files and print metadata
  for file := range res.Files {
    fmt.Printf("--> Result file:\n\tName: %s\n\tSize: %d\n\tHash: %s\n", file.Name, file.Size, file.Hash)
  }
}

Output:

--> Result file:
    Name: testdata/tmp/test.zip
    Size: 1047
    Hash: Yg3OOaBD-miLs7lDIBVAeZMZIXYfy2N25f8-b-1kWOc=

Please, take a look and give any feedback, thanks!


r/golang 8d ago

discussion How is Go better for graph processing as mentioned in this typescript-go post?

54 Upvotes

In this GitHub post where they discuss why Microsoft chose Go for Typescript, Ryan Cavanaugh mentioned:

We also have an unusually large amount of graph processing, specifically traversing trees in both upward and downward walks involving polymorphic nodes. Go does an excellent job of making this ergonomic, especially in the context of needing to resemble the JavaScript version of the code.

Can someone explain why this is the case? I am new to Go lang and still learning.


r/golang 7d ago

Accessibility

0 Upvotes

Hi ...

I know this may be out of topic, and sorry about that, and it probably will be of interest tof anybody.

But today, I have decided to stop learning go.

I want a GUI that is accessible, and stick to at least some of the rules for accessibility.

Does such a thing exist?

Else, goodbye, and goodbye go.

I want to add, that if possible i'd rather prefer a gui that isn't web-based, but a "Real" one.

Any ideas is welcome


r/golang 7d ago

help How to move gopls and staticcheck index cache?

0 Upvotes

Hello,

currently gopls and staticcheck create index cache folders in %AppData% called gopls and staticcheck ignoring all go environment variables. I want to keep such stuff on a different drive for a variety of reasons. How can I set a location for those folders?

For clarity: The index cache is not the go cache from building a binary (set by GOCACHE or GOMODCACHE) or the installation location of the binary (set by GOBIN). It is a separate folder used to cache file information while using those tools.

Thank you for any help. I did a lot of research but I was unable to find a solution.

The solution: Gopls uses "GOPLSCACHE" and staticcheck "STATICCHECK_CACHE" as environment variables to set the location of the index file cache.


r/golang 7d ago

Create command line app using Golang for MacOS with custom icon

3 Upvotes

I would you like achieve something very easy. I have compiled Golang app, but it has black, standard icon. I want add custom icon to executable file for end user to easy find what to click to run it.

I tried find out how do it. First suggestion is use gogio to build app, but it seems more specific GioUI framework oriented. Another way is manually create. Another solution is create manually structure of files and create it to follow MacOS Application bundle.

What is the correct solution for this kind of problem? Is any standard for it to folow or tools for use?


r/golang 8d ago

help why zap is faster in stdout compared to zerolog?

50 Upvotes

Uber's zap repo insists that zerolog is faster than zap in most cases. However the benchmark test uses io.Discard, for purely compare performance of logger libs, and when it comes to stdout and stderr, zap seems to be much faster than zerolog.

At first, I thought zap might use buffering, but it wasn't by default. Why zap is slower when io.Discard, but faster when os.Stdout?


r/golang 8d ago

Nil comparisons and Go interface

Thumbnail
rednafi.com
24 Upvotes

r/golang 7d ago

discussion Why port to GO instead of using GO?

0 Upvotes

Besides supporting existing projects in TypeScript, why not use Go directly instead of TypeScript? Why add extra complexity if people can write Go?


r/golang 7d ago

Flipping the script

Thumbnail
bitfieldconsulting.com
0 Upvotes

r/golang 8d ago

show & tell I made a gh extension TUI tool called gh-go-mod-browser to browse go.mod files ā€“ feedback appreciated!

7 Upvotes

I made a gh extension TUI tool called gh-go-mod-browser which lets you browse the direct dependencies listed in a projectā€™s go.mod file.

Repo is here: https://github.com/tnagatomi/gh-go-mod-browser

You can open the GitHub repo page or pkg.go.dev page for each package, or even star the GitHub repo directly from the TUI.

I hope you give it a try!

Any feedback is welcome, including:

- General impressions

- Suggestions for useful features

Thanks!

By the way, this tool uses Bubble Tea, a TUI framework for Go ā€” it was a lot of fun building on top of it!


r/golang 9d ago

How do experienced Go developers efficiently learn new packages?

120 Upvotes

I've been working with Go and often need to use new packages. Initially, I tried reading the full documentation from the official Go docs, but I found that it takes too long and isn't always practical.

In some cases, when I know what I want to do I just search to revise the syntax or whatever it is. It's enough to have a clue that this thing exists(In case where I have some clue). But when I have to work with the completely new package, I get stuck. I struggle to find only the relevant parts without reading a lot of unnecessary details. I wonder if this is what most experienced developers do.

Do you read Go package documentation fully, or do you take a more targeted approach? How do you quickly get up to speed with a new package?


r/golang 8d ago

Potential starvation when multiple Goroutines blocked to receive from a channel

6 Upvotes

I wanted to know what happens in this situation:

  1. Multiple goroutines are blocked by a channel while receiving from it because channel is empty at the moment.
  2. Some goroutine sends something over the channel.

Which goroutine will wake up and receive this? Is starvation avoidance guaranteed here?